answer
stringlengths 17
10.2M
|
|---|
package natlab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import beaver.Parser;
import natlab.ast.Root;
public class Interpreter {
private Interpreter() {}
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the Natlab Interpreter!");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
if(line == null) {
break;
}
try {
NatlabScanner scanner = new NatlabScanner(new StringReader(line));
NatlabParser parser = new NatlabParser();
Root original = (Root) parser.parse(scanner);
if(parser.hasError()) {
System.out.println("**ERROR**");
for(String error : parser.getErrors()) {
System.out.println(error);
}
} else {
System.out.println(original.getStructureString());
}
} catch(Parser.Exception e) {
System.out.println("**ERROR**");
System.out.println(e.getMessage());
}
}
System.out.println("Goodbye!");
}
}
|
public class AddBinary {
public static String addBinary(String a, String b) {
int n1 = a.length() - 1, n2 = b.length() - 1, sum, carry = 0;
StringBuilder sb = new StringBuilder();
while (carry > 0 || n1 >=0 || n2 >= 0) {
sum = carry; // reset sum to the value of carry
if (n1 >= 0) sum += a.charAt(n1
if (n2 >= 0) sum += b.charAt(n2
carry = sum / 2;
sb.append(sum % 2);
}
return sb.reverse().toString();
}
public static void main(String[] args) {
System.out.println("addBinary(\"0\", \"0\") = " + addBinary("0", "0"));
System.out.println("addBinary(\"0\", \"1\") = " + addBinary("0", "1"));
System.out.println("addBinary(\"10\", \"0\") = " + addBinary("10", "0"));
System.out.println("addBinary(\"01\", \"0\") = " + addBinary("01", "0"));
System.out.println("addBinary(\"01\", \"10\") = " + addBinary("01", "10"));
System.out.println("addBinary(\"11\", \"1\") = " + addBinary("11", "1"));
}
}
|
package com.jaivox.ui.appmaker;
import com.jaivox.interpreter.Utils;
import com.jaivox.tools.Generator;
import com.jaivox.util.Log;
import java.awt.Point;
import java.io.*;
import java.nio.file.Files;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
public class guiprep {
static String outfile = "test.dlg";
static String questions = "test.quest";
static String errors = "errors.txt";
static boolean overwrite = true;
static String patIndicator = "PAT";
public static void main (String args []) {
generate();
}
static void generate () {
Rule2Fsm rf = new Rule2Fsm ();
Gui2Gram gg = new Gui2Gram ();
try {
PrintWriter out = new PrintWriter (new FileWriter (outfile));
rf.writeRules (out);
gg.writeRules (out);
out.close ();
out = new PrintWriter (new FileWriter (questions));
BufferedReader in = new BufferedReader (new FileReader (errors));
String line;
while ((line = in.readLine ()) != null) {
String s = line.trim ().toLowerCase ();
if (s.length () == 0) continue;
out.println (s+"\t"+s+"\t(_,_,_,_,_,_,_)");
}
gg.writeQuestions (out);
out.close ();
}
catch (Exception e) {
e.printStackTrace ();
}
}
//java 7
public static void copyFile(String s, String t) throws IOException {
File src = new File(s);
File targ = new File(t);
Files.copy(src.toPath(), targ.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
static boolean isRecognizerEnabled(Properties conf, String name) {
return conf.getProperty("recognizer_"+name, "false").equalsIgnoreCase("true");
}
static boolean isSynthesizerEnabled(Properties conf, String name) {
return conf.getProperty("synthesizer_"+name, "false").equalsIgnoreCase("true");
}
static boolean isPlatformEnabled(Properties conf, String name) {
return conf.getProperty("platform_"+name, "false").equalsIgnoreCase("true");
}
public static void generateApp(String conffile) {
try {
Properties conf = new Properties();
conf.load(new FileInputStream(conffile));
String project = conf.getProperty("project");
String destination = conf.getProperty("destination");
String cpsrc = conf.getProperty("cpsrc");
String cfile = conf.getProperty("common_words");
String efile = conf.getProperty("error_dlg");
if(destination == null | cpsrc == null) {
}
if(!destination.endsWith(File.separator)) destination += File.separator;
copyFile(cpsrc +"/"+ cfile, destination +"/"+ cfile);
copyFile(cpsrc +"/"+ efile, destination +"/"+ efile);
errors = cpsrc +"/"+ "errors.txt";
outfile = destination + project +".dlg";
questions = destination + project +".quest";
Gui2Gram.dlgtree = destination + project +".tree";
Rule2Fsm.dir = "";
Rule2Fsm.name = destination + "dialog" +".tree";
Gui2Gram.gram = destination + "dialog" +".tree";
guiprep.generate();
if(conf.getProperty("console", "false").equalsIgnoreCase("true")) {
StringBuffer code = new StringBuffer();
copyFile(cpsrc+ "/console.java", destination + "console.java");
String clz = buildAppCode(code, "console", project);
PrintWriter out = new PrintWriter (new FileWriter (destination + clz + ".java"));
out.println(code.toString());
out.close ();
}
if(isRecognizerEnabled(conf, "google")) {
StringBuffer code = new StringBuffer();
copyFile(cpsrc +"/runapp.java", destination + "runapp.java");
String clz = buildAppCode(code, "runapp", project);
PrintWriter out = new PrintWriter (new FileWriter (destination + clz + ".java"));
out.println(code.toString());
out.close ();
}
if(isRecognizerEnabled(conf, "sphinx")) {
StringBuffer code = new StringBuffer();
doSphinxStuff(Gui2Gram.dlgtree, conf);
copyFile(cpsrc +"/runapp.java", destination + "runapp.java");
copyFile(cpsrc +"/runappsphinx.java", destination + "runappsphinx.java");
String clz = buildAppCode(code, "runappsphinx", project);
PrintWriter out = new PrintWriter (new FileWriter (destination + clz + ".java"));
out.println(code.toString());
out.close ();
//usingJvGen(conffile);
}
System.out.println("Application Generated: Path: "+ destination);
} catch (Exception ex) {
ex.printStackTrace();
}
}
//temp code
static String buildAppCode(StringBuffer code, String type, String appname) {
String clz = Character.toUpperCase(appname.charAt(0)) + appname.substring(1) +
Character.toUpperCase(type.charAt(0)) + type.substring(1);
code.append("import com.jaivox.interpreter.Command;\nimport com.jaivox.interpreter.Interact;\n");
code.append("import com.jaivox.synthesizer.web.Synthesizer;\n\n");
code.append("import java.util.Properties;\nimport java.io.*;\n\n");
code.append("public class ").append(clz);
code.append(" {\n");
code.append("\tpublic static void main(String[] args) {\n");
if(type.equals("runappsphinx")) {
code.append("\t\trunappsphinx.config=\"").append(appname)
.append(".config.xml").append("\";\n");
}
code.append("\t\t").append(type).append(" c = new ").append(type);
code.append("() {\n\t\t\t@Override\n\t\t\tvoid initializeInterpreter () {\n");
code.append("\t\t\ttry {\n");
code.append("\t\t\tProperties kv = new Properties ();\n");
code.append("\t\t\tkv.load(new FileInputStream(\"").append(appname).append(".conf\"));\n");
code.append("\t\t\tCommand cmd = new Command ();\n");
code.append("\t\t\tinter = new Interact (basedir, kv, cmd);\n");
if(!type.equals("console")) code.append("\t\t\tspeaker = new Synthesizer (basedir, kv);\n");
code.append("\t\t\t}catch(Exception e) {e.printStackTrace(); }\n");
code.append("\t\t\t}\n\t\t\t};\n");
code.append("\t}").append("\n}");
return clz;
}
static void doSphinxStuff(String treefile, Properties conf) throws FileNotFoundException, IOException {
new Log ();
Log.setLevelByName ("FINEST");
String project = conf.getProperty("project");
String destination = conf.getProperty("destination");
String cpsrc = conf.getProperty("cpsrc");
String sentfile = treefile.substring(0, treefile.lastIndexOf('.')) + ".sent";
BufferedReader in = new BufferedReader (new FileReader (treefile));
PrintWriter out = new PrintWriter (new FileWriter (sentfile));
String line;
while ((line = in.readLine ()) != null) {
String upper = line.trim ().toUpperCase();
if (upper.length () == 0) continue;
if(upper.charAt(0) == '*') upper = upper.substring(1);
if(!Character.isLetterOrDigit(upper.charAt(upper.length()-1))) upper = upper.substring(0, upper.length()-2);
out.println("<s> " + upper + " </s>");
}
in.close ();
out.close();
generateFile(conf, cpsrc, destination, "project.config.xml");
generateFile(conf, cpsrc, destination, "lmgen.sh");
}
static boolean generateFile (Properties kv, String src, String dest, String name) {
String common = src;
try {
Set keys = kv.stringPropertyNames ();
int n = keys.size ();
String okeys [] = new String [n];
Point op [] = new Point [n];
int pi = 0;
for (Iterator<String> it = keys.iterator (); it.hasNext (); ) {
String key = it.next ();
okeys [pi] = key;
op [pi] = new Point (pi, -key.length ());
pi++;
}
Utils.quicksortpointy(op, 0, n-1);
String filename = common + name;
String destname = dest + name;
if (!okOverwrite (destname)) {
Log.severe (destname+" exists. To overwrite, set overwrite_files to yes");
return true;
}
String text = loadFile (filename);
String changed = text;
// replace longest keys first
for (int i=0; i<n; i++) {
Point p = op [i];
String key = okeys [p.x];
String val = kv.getProperty (key);
if (name.startsWith (key)) {
String newname = name.replaceFirst (key, val);
// Log.fine ("Destination name: "+newname);
destname = dest + newname;
if (!okOverwrite (destname)) {
Log.severe (destname+" exists. To overwrite, set overwrite_files to yes");
return true;
}
}
String pat = patIndicator + key;
if (text.indexOf (pat) != -1) {
// Log.fine ("replacing "+pat+" with "+val+" in "+name);
if (val != null) changed = changed.replace (pat, val);
else {
Log.info ("Missing value for "+pat);
}
}
}
if (changed.indexOf (patIndicator) != -1)
changed = fixmisses (filename, changed);
if (!writeFile (destname, changed)) return false;
Log.info ("wrote: "+destname);
return true;
}
catch (Exception e) {
e.printStackTrace ();
return false;
}
}
static String loadFile (String filename) {
try {
BufferedReader in = new BufferedReader (new FileReader (filename));
String line;
StringBuffer sb = new StringBuffer ();
while ((line = in.readLine ()) != null) {
sb.append (line + "\n");
}
in.close ();
String text = new String (sb);
return text;
}
catch (Exception e) {
e.printStackTrace ();
return null;
}
}
static String fixmisses (String filename, String text) {
try {
Log.info ("Commenting out lines containing missing patterns with
Log.info ("Plese check output for syntax errors.");
StringTokenizer st = new StringTokenizer (text, "\n", true);
StringBuffer sb = new StringBuffer ();
while (st.hasMoreTokens ()) {
String token = st.nextToken ();
if (token.indexOf (patIndicator) != -1 && token.indexOf ("CLASSPATH") == -1) {
Log.warning ("Missing value in "+token+" in file "+filename);
token = "// "+token;
}
sb.append (token);
}
return new String (sb);
}
catch (Exception e) {
e.printStackTrace ();
Log.severe ("Errors while trying to remove missing tags in "+filename);
return text;
}
}
static boolean writeFile (String filename, String text) {
try {
PrintWriter out = new PrintWriter (new FileWriter (filename));
out.print (text);
out.close ();
return true;
}
catch (Exception e) {
e.printStackTrace ();
return false;
}
}
static boolean okOverwrite (String filename) {
try {
File f = new File (filename);
if (f.exists ()) {
if (!overwrite) return false;
}
return true;
}
catch (Exception e) {
e.printStackTrace ();
return false;
}
}
}
|
package org.concord.data;
/**
* @author dima
*
*/
import java.util.Vector;
import org.concord.framework.data.DataDimension;
public final class Unit implements DataDimension{
public int unitCategory = UNIT_CAT_UNKNOWN;
public int code = UNIT_CODE_UNKNOWN;
public int baseUnit = UNIT_CODE_UNKNOWN;
public boolean derived = false;
public String name;
public String abbreviation;
// Powers of the standard units
public byte meter = 0;
public byte kg = 0;
public byte sec = 0;
public byte amper = 0;
public byte kelvin = 0;
public byte candela = 0;
public byte mole = 0;
public byte radian = 0;
public byte steradian = 0;
public float koeffA = 1.0f;
public float koeffB = 0.0f;
public boolean dimLess = false;
public boolean doMetricPrefix = false;
private static final byte NON_ORDER = 0;
final static int METER_INDEX = 0;
final static int KG_INDEX = 1;
final static int SEC_INDEX = 2;
final static int AMPER_INDEX = 3;
final static int KELVIN_INDEX = 4;
final static int CANDELA_INDEX = 5;
final static int MOLE_INDEX = 6;
final static int RADIAN_INDEX = 7;
final static int STERADIAN_INDEX = 8;
public final static int UNIT_CODE_UNKNOWN = 0;
public final static int UNIT_CODE_KG = 1;
public final static int UNIT_CODE_G = 2;
public final static int UNIT_CODE_MT = 3;
public final static int UNIT_CODE_LB = 4;
public final static int UNIT_CODE_OZ = 5;
public final static int UNIT_CODE_AMU = 6;
public final static int UNIT_CODE_METER = 7;
public final static int UNIT_CODE_INCH = 8;
public final static int UNIT_CODE_YARD = 9;
public final static int UNIT_CODE_FEET = 10;
public final static int UNIT_CODE_MILE_ST = 11;
public final static int UNIT_CODE_MICRON = 12;
public final static int UNIT_CODE_S = 13;
public final static int UNIT_CODE_MIN = 14;
public final static int UNIT_CODE_HOUR = 15;
public final static int UNIT_CODE_DAY = 16;
public final static int UNIT_CODE_CELSIUS = 17;
public final static int UNIT_CODE_KELVIN = 18;
public final static int UNIT_CODE_FAHRENHEIT = 19;
public final static int UNIT_CODE_M2 = 20;
public final static int UNIT_CODE_ACRE = 21;
public final static int UNIT_CODE_ARE = 22;
public final static int UNIT_CODE_HECTARE = 23;
public final static int UNIT_CODE_M3 = 24;
public final static int UNIT_CODE_LITER = 25;
public final static int UNIT_CODE_CC = 26;
public final static int UNIT_CODE_BBL_D = 27;
public final static int UNIT_CODE_BBL_L = 28;
public final static int UNIT_CODE_BU = 29;
public final static int UNIT_CODE_GAL_D = 30;
public final static int UNIT_CODE_GAL_L = 31;
public final static int UNIT_CODE_PT_D = 32;
public final static int UNIT_CODE_PT_L = 33;
public final static int UNIT_CODE_QT_D = 34;
public final static int UNIT_CODE_QT_L = 35;
public final static int UNIT_CODE_JOULE = 36;
public final static int UNIT_CODE_CALORIE = 37;
public final static int UNIT_CODE_EV = 38;
public final static int UNIT_CODE_ERG = 39;
public final static int UNIT_CODE_WHR = 40;
public final static int UNIT_CODE_NEWTON = 41;
public final static int UNIT_CODE_DYNE = 42;
public final static int UNIT_CODE_KGF = 43;
public final static int UNIT_CODE_LBF = 44;
public final static int UNIT_CODE_WATT = 45;
public final static int UNIT_CODE_HP_MECH = 46;
public final static int UNIT_CODE_HP_EL = 47;
public final static int UNIT_CODE_HP_METR = 48;
public final static int UNIT_CODE_PASCAL = 49;
public final static int UNIT_CODE_BAR = 50;
public final static int UNIT_CODE_ATM = 51;
public final static int UNIT_CODE_MMHG = 52;
public final static int UNIT_CODE_CMH2O = 53;
public final static int UNIT_CODE_TORR = 54;
public final static int UNIT_CODE_ANG_VEL = 55;
public final static int UNIT_CODE_LINEAR_VEL = 56;
public final static int UNIT_CODE_AMPERE = 57;
public final static int UNIT_CODE_VOLT = 58;
public final static int UNIT_CODE_COULOMB = 59;
public final static int UNIT_CODE_MILLIVOLT = 60;
public final static int UNIT_CODE_LUMEN = 61;
public final static int UNIT_CODE_LUX = 62;
public final static int UNIT_CODE_CENTIMETER = 63;
public final static int UNIT_CODE_MILLISECOND = 64;
public final static int UNIT_CODE_LINEAR_VEL_MILLISECOND = 65;
public final static int UNIT_CODE_KILOMETER = 66;
public final static int UNIT_CODE_LINEAR_VEL_KMH = 67;
public final static int UNIT_TABLE_LENGTH = 68;
public final static int UNIT_CAT_UNKNOWN = 0;
public final static int UNIT_CAT_LENGTH = 1;
public final static int UNIT_CAT_MASS = 2;
public final static int UNIT_CAT_TIME = 3;
public final static int UNIT_CAT_TEMPERATURE = 4;
public final static int UNIT_CAT_AREA = 5;
public final static int UNIT_CAT_VOL_CAP = 6;
public final static int UNIT_CAT_ENERGY = 7;
public final static int UNIT_CAT_FORCE = 8;
public final static int UNIT_CAT_POWER = 9;
public final static int UNIT_CAT_PRESSURE = 10;
public final static int UNIT_CAT_ELECTRICITY = 11;
public final static int UNIT_CAT_LIGHT = 12;
public final static int UNIT_CAT_MISC = 13;
public final static int UNIT_CAT_VELOCITY = 14;
public final static int UNIT_CAT_ACCELERATION = 15;
public final static int UNIT_CAT_TABLE_LENGTH = 16;
public static String[] catNames = {"Unknown",
"Length",
"Mass",
"Time",
"Temperature",
"Area",
"Volumes/Capacity",
"Energy",
"Force",
"Power",
"Pressure",
"Electricity",
"Light",
"Miscellaneous",
"Velocity",
"Acceleration"};
static byte [][]catNumbers = new byte[UNIT_CAT_TABLE_LENGTH][9];
static{
boolean []flags = new boolean[UNIT_CAT_TABLE_LENGTH];
for(int u = 1; u < UNIT_TABLE_LENGTH; u++){
Unit unit = getUnit(u);
if(!flags[unit.unitCategory]){
flags[unit.unitCategory] = true;
catNumbers[unit.unitCategory][METER_INDEX] = unit.meter;
catNumbers[unit.unitCategory][KG_INDEX] = unit.kg;
catNumbers[unit.unitCategory][SEC_INDEX] = unit.sec;
catNumbers[unit.unitCategory][AMPER_INDEX] = unit.amper;
catNumbers[unit.unitCategory][KELVIN_INDEX] = unit.kelvin;
catNumbers[unit.unitCategory][CANDELA_INDEX] = unit.candela;
catNumbers[unit.unitCategory][MOLE_INDEX] = unit.mole;
catNumbers[unit.unitCategory][RADIAN_INDEX] = unit.radian;
catNumbers[unit.unitCategory][STERADIAN_INDEX] = unit.steradian;
}
}
}
public static byte[] getCategoryNumber(int category){
if(category < 0 || category >= UNIT_CAT_TABLE_LENGTH) return null;
return catNumbers[category];
}
public Unit(String name,String abbreviation,boolean derived,int unitCategory,int code,int baseUnit,
byte meter,byte kg,byte sec,byte amper,byte kelvin,byte candela,byte mole,byte radian,byte steradian,
float koeffA,float koeffB,boolean dimLess,boolean doMetricPrefix){
this.name = name;
this.abbreviation = abbreviation;
this.derived = derived;
this.unitCategory = unitCategory;
this.code = code;
this.baseUnit = baseUnit;
this.meter = meter;
this.kg = kg;
this.sec = sec;
this.amper = amper;
this.kelvin = kelvin;
this.candela = candela;
this.mole = mole;
this.radian = radian;
this.steradian = steradian;
this.koeffA = koeffA;
this.koeffB = koeffB;
this.dimLess = dimLess;
this.doMetricPrefix = doMetricPrefix;
}
public String getDimension(){return abbreviation;}
public void setDimension(String dimension){abbreviation = dimension;}
public static Vector getCatUnitAbbrev(int index)
{
Vector abbrevs = new Vector();
for(int i = 1; i < UNIT_TABLE_LENGTH; i++){
Unit u = getUnit(i);
if(u.unitCategory == index){
abbrevs.addElement(u.abbreviation);
}
}
return abbrevs;
}
public static Unit getUnit(int code){
if(code < 0) return null;
switch(code){
case UNIT_CODE_KG :
return new Unit("kilogram","kg",false,UNIT_CAT_MASS,UNIT_CODE_KG,UNIT_CODE_KG,
(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1.0f,0.0f,false,false);
case UNIT_CODE_G :
return new Unit("gram","g",true,UNIT_CAT_MASS,UNIT_CODE_G,UNIT_CODE_KG,
(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.001f,0.0f,false,true);
case UNIT_CODE_MT :
return new Unit("metric ton","tn",true,UNIT_CAT_MASS,UNIT_CODE_MT,UNIT_CODE_KG,
(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1000f,0.0f,false,true);
case UNIT_CODE_LB :
return new Unit("pound","lb",true,UNIT_CAT_MASS,UNIT_CODE_LB,UNIT_CODE_KG,
(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.45359237f,0.0f,false,false);
case UNIT_CODE_OZ :
return new Unit("ounce","oz",true,UNIT_CAT_MASS,UNIT_CODE_OZ,UNIT_CODE_G,
(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.028349523f,0.0f,false,false);
case UNIT_CODE_AMU :
return new Unit("atomic mass unit","amu",true,UNIT_CAT_MASS,UNIT_CODE_AMU,UNIT_CODE_KG,
(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1.66054e-27f,0.0f,false,false);
case UNIT_CODE_KILOMETER :
return new Unit("kilometer","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1000f,0.0f,false,true);
case UNIT_CODE_METER :
return new Unit("meter","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_CENTIMETER :
return new Unit("centimeter","cm",false,UNIT_CAT_LENGTH,code,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.01f,0.0f,false,false);
case UNIT_CODE_INCH :
return new Unit("inch","in",false,UNIT_CAT_LENGTH,UNIT_CODE_INCH,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.0254f,0.0f,false,false);
case UNIT_CODE_YARD :
return new Unit("yard","yd",false,UNIT_CAT_LENGTH,UNIT_CODE_YARD,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.9144f,0.0f,false,false);
case UNIT_CODE_FEET :
return new Unit("feet","ft",false,UNIT_CAT_LENGTH,UNIT_CODE_FEET,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.3048f,0.0f,false,false);
case UNIT_CODE_MILE_ST :
return new Unit("mile (statute)","mi",false,UNIT_CAT_LENGTH,UNIT_CODE_MILE_ST,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1609.344f,0.0f,false,false);
case UNIT_CODE_MICRON :
return new Unit("micron","?",false,UNIT_CAT_LENGTH,UNIT_CODE_MICRON,UNIT_CODE_METER,
(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1e-6f,0.0f,false,false);
case UNIT_CODE_MILLISECOND :
return new Unit("millisecond","ms",false,UNIT_CAT_TIME,UNIT_CODE_MILLISECOND,UNIT_CODE_S,
(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.001f,0.0f,false,true);
case UNIT_CODE_S :
return new Unit("second","s",false,UNIT_CAT_TIME,UNIT_CODE_S,UNIT_CODE_S,
(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_MIN :
return new Unit("minute","min",false,UNIT_CAT_TIME,UNIT_CODE_MIN,UNIT_CODE_S,
(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
60f,0.0f,false,false);
case UNIT_CODE_HOUR :
return new Unit("hour","hr",false,UNIT_CAT_TIME,UNIT_CODE_HOUR,UNIT_CODE_S,
(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
3600f,0.0f,false,false);
case UNIT_CODE_DAY :
return new Unit("day","d",false,UNIT_CAT_TIME,UNIT_CODE_DAY,UNIT_CODE_S,
(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
86400f,0.0f,false,false);
case UNIT_CODE_CELSIUS :
return new Unit("Celsius","degC",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_CELSIUS,UNIT_CODE_CELSIUS,
(byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,false);
case UNIT_CODE_KELVIN :
return new Unit("Kelvin","K",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_KELVIN,UNIT_CODE_CELSIUS,
(byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,
1f,-273.15f,false,true);
case UNIT_CODE_FAHRENHEIT :
return new Unit("Fahrenheit","degF",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_FAHRENHEIT,UNIT_CODE_CELSIUS,
(byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,
.55555555556f,-17.777777778f,false,false);
case UNIT_CODE_M2 :
return new Unit("m2","m2",false,UNIT_CAT_AREA,UNIT_CODE_M2,UNIT_CODE_M2,
(byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,false);
case UNIT_CODE_ACRE :
return new Unit("acre","acre",false,UNIT_CAT_AREA,UNIT_CODE_ACRE,UNIT_CODE_M2,
(byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
4046.8564f,0.0f,false,false);
case UNIT_CODE_ARE :
return new Unit("are","a",false,UNIT_CAT_AREA,UNIT_CODE_ARE,UNIT_CODE_M2,
(byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
100f,0.0f,false,false);
case UNIT_CODE_HECTARE :
return new Unit("hectare","ha",true,UNIT_CAT_AREA,UNIT_CODE_HECTARE,UNIT_CODE_M2,
(byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
10000f,0.0f,false,false);
case UNIT_CODE_M3 :
return new Unit("m3","m3",true,UNIT_CAT_VOL_CAP,UNIT_CODE_M3,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,false);
case UNIT_CODE_LITER :
return new Unit("liter","L",true,UNIT_CAT_VOL_CAP,UNIT_CODE_LITER,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.001f,0.0f,false,true);
case UNIT_CODE_CC :
return new Unit("cc","cc",true,UNIT_CAT_VOL_CAP,UNIT_CODE_CC,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.000001f,0.0f,false,false);
case UNIT_CODE_BBL_D :
return new Unit("barrel","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_D,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.11562712f,0.0f,false,false);
case UNIT_CODE_BBL_L :
return new Unit("barrel (l)","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_L,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.11924047f,0.0f,false,false);
case UNIT_CODE_BU :
return new Unit("bushel","bu",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BU,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.03523907f,0.0f,false,false);
case UNIT_CODE_GAL_D :
return new Unit("gallon","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_D,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.00440476f,0.0f,false,false);
case UNIT_CODE_GAL_L :
return new Unit("gallon (liq)","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_L,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.0037854118f,0.0f,false,false);
case UNIT_CODE_PT_D :
return new Unit("pint","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_D,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
5.505951e-4f,0.0f,false,false);
case UNIT_CODE_PT_L :
return new Unit("pint (liq)","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_L,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
4.731632e-4f,0.0f,false,false);
case UNIT_CODE_QT_D :
return new Unit("quart","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_D,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1.1011901e-3f,0.0f,false,false);
case UNIT_CODE_QT_L :
return new Unit("quart (liq)","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_L,UNIT_CODE_M3,
(byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
9.463264e-4f,0.0f,false,false);
case UNIT_CODE_JOULE :
return new Unit("Joule","J",true,UNIT_CAT_ENERGY,UNIT_CODE_JOULE,UNIT_CODE_JOULE,
(byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_CALORIE :
return new Unit("calorie","cal",true,UNIT_CAT_ENERGY,UNIT_CODE_CALORIE,UNIT_CODE_JOULE,
(byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
4.184f,0.0f,false,true);
case UNIT_CODE_EV :
return new Unit("eV","eV",true,UNIT_CAT_ENERGY,UNIT_CODE_EV,UNIT_CODE_JOULE,
(byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1.60219e-19f,0.0f,false,true);
case UNIT_CODE_ERG :
return new Unit("erg","erg",true,UNIT_CAT_ENERGY,UNIT_CODE_ERG,UNIT_CODE_JOULE,
(byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1e-7f,0.0f,false,true);
case UNIT_CODE_WHR :
return new Unit("Watt-hours","Whr",true,UNIT_CAT_ENERGY,UNIT_CODE_WHR,UNIT_CODE_JOULE,
(byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
3600f,0.0f,false,true);
case UNIT_CODE_NEWTON :
return new Unit("Newton","N",true,UNIT_CAT_FORCE,UNIT_CODE_NEWTON,UNIT_CODE_NEWTON,
(byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_DYNE :
return new Unit("dyne","dyn",true,UNIT_CAT_FORCE,UNIT_CODE_DYNE,UNIT_CODE_NEWTON,
(byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1e-5f,0.0f,false,true);
case UNIT_CODE_KGF :
return new Unit("kilogram-force","kgf",true,UNIT_CAT_FORCE,UNIT_CODE_KGF,UNIT_CODE_NEWTON,
(byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
9.80665f,0.0f,false,false);
case UNIT_CODE_LBF :
return new Unit("pound-force","lbf",true,UNIT_CAT_FORCE,UNIT_CODE_LBF,UNIT_CODE_NEWTON,
(byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
4.448222f,0.0f,false,false);
case UNIT_CODE_WATT :
return new Unit("watt","W",true,UNIT_CAT_POWER,UNIT_CODE_WATT,UNIT_CODE_WATT,
(byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_HP_MECH :
return new Unit("horsepower","hp",true,UNIT_CAT_POWER,UNIT_CODE_HP_MECH,UNIT_CODE_WATT,
(byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
745.7f,0.0f,false,false);
case UNIT_CODE_HP_EL :
return new Unit("horsepower (el)","hp(el)",true,UNIT_CAT_POWER,UNIT_CODE_HP_EL,UNIT_CODE_WATT,
(byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
746f,0.0f,false,false);
case UNIT_CODE_HP_METR :
return new Unit("horsepower (metric)","hp(metric)",true,UNIT_CAT_POWER,UNIT_CODE_HP_METR,UNIT_CODE_WATT,
(byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
735.499f,0.0f,false,false);
case UNIT_CODE_PASCAL :
return new Unit("Pascal","Pa",true,UNIT_CAT_PRESSURE,UNIT_CODE_PASCAL,UNIT_CODE_PASCAL,
(byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_BAR :
return new Unit("bar","bar",true,UNIT_CAT_PRESSURE,UNIT_CODE_BAR,UNIT_CODE_PASCAL,
(byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1e5f,0.0f,false,true);
case UNIT_CODE_ATM :
return new Unit("atmosphere","atm",true,UNIT_CAT_PRESSURE,UNIT_CODE_ATM,UNIT_CODE_PASCAL,
(byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1.01325e5f,0.0f,false,false);
case UNIT_CODE_MMHG :
return new Unit("mm Hg","mmHg",true,UNIT_CAT_PRESSURE,UNIT_CODE_MMHG,UNIT_CODE_PASCAL,
(byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
133.3224f,0.0f,false,false);
case UNIT_CODE_CMH2O :
return new Unit("cm H2O","cmH2O",true,UNIT_CAT_PRESSURE,UNIT_CODE_CMH2O,UNIT_CODE_PASCAL,
(byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
98.0638f,0.0f,false,false);
case UNIT_CODE_TORR :
return new Unit("torr","torr",true,UNIT_CAT_PRESSURE,UNIT_CODE_TORR,UNIT_CODE_PASCAL,
(byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
133.3224f,0.0f,false,true);
case UNIT_CODE_ANG_VEL :
return new Unit("rad/s","rad/s",true,UNIT_CAT_MISC,UNIT_CODE_ANG_VEL,UNIT_CODE_ANG_VEL,
(byte)0,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,
1f,0.0f,false,false);
case UNIT_CODE_LINEAR_VEL :
return new Unit("m/s","m/s",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL,UNIT_CODE_LINEAR_VEL,
(byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_LINEAR_VEL_MILLISECOND :
return new Unit("m/ms","m/ms",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_MILLISECOND,UNIT_CODE_LINEAR_VEL,
(byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1000f,0.0f,false,true);
case UNIT_CODE_LINEAR_VEL_KMH :
return new Unit("km/h","km/h",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_KMH,UNIT_CODE_LINEAR_VEL,
(byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f/3600f,0.0f,false,true);
case UNIT_CODE_AMPERE :
return new Unit("ampere","A",false,UNIT_CAT_ELECTRICITY,UNIT_CODE_AMPERE,UNIT_CODE_AMPERE,
(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_VOLT :
return new Unit("volt","V",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_VOLT,UNIT_CODE_VOLT,
(byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_COULOMB :
return new Unit("coulomb","Q",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_COULOMB,UNIT_CODE_COULOMB,
(byte)0,(byte)0,(byte)1,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
1f,0.0f,false,true);
case UNIT_CODE_MILLIVOLT :
return new Unit("millivolt","mV",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_MILLIVOLT,UNIT_CODE_VOLT,
(byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.001f,0.0f,false,false);
case UNIT_CODE_LUMEN :
return new Unit("lumen","lm",true,UNIT_CAT_POWER,UNIT_CODE_LUMEN,UNIT_CODE_WATT,
(byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.0014641288f,0.0f,false,true);
case UNIT_CODE_LUX :
return new Unit("lux","lx",true,UNIT_CAT_LIGHT,UNIT_CODE_LUX,UNIT_CODE_LUX,
(byte)0,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
0.0014641288f,0.0f,false,true);
}
return null;
}
public static Unit findUnit(String unitAbbreviation)
{
for(int i = 1; i < UNIT_TABLE_LENGTH; i++){
Unit u = getUnit(i);
if(u.abbreviation.equals(unitAbbreviation)) {
return u;
}
}
return null;
}
public static int errorConvertStatus = 0;
public static Unit sourceGlobalUnit = null;
public static Unit destGlobalUnit = null;
public static float unitConvert(Unit unitSrc, float srcValue,Unit unitDest){
float retValue = srcValue;
errorConvertStatus = 0;
if(!isUnitCompatible(unitSrc,unitDest)){
errorConvertStatus = 1;
return retValue;
}
/*
Unit unitSrcBase = Unit.getUnit(unitSrc.baseUnit);
Unit unitDestBase = Unit.getUnit(unitDest.baseUnit);
if(unitSrcBase == null || unitDestBase == null || unitSrcBase != unitDestBase){
errorConvertStatus = 3;
return retValue;
}
*/
retValue = ((srcValue*unitSrc.koeffA + unitSrc.koeffB) - unitDest.koeffB)/ unitDest.koeffA;
return retValue;
}
public static float unitConvert(float srcValue){
return unitConvert(sourceGlobalUnit,srcValue,destGlobalUnit);
}
public boolean setGlobalUnits(int unitIDSrc,int unitIDDest){
sourceGlobalUnit = destGlobalUnit = null;
sourceGlobalUnit = Unit.getUnit(unitIDSrc);
if(sourceGlobalUnit == null) return false;
destGlobalUnit = Unit.getUnit(unitIDDest);
if(destGlobalUnit == null) return false;
return true;
}
public static boolean isUnitCompatible(Unit unitSrc,Unit unitDest){
if(unitSrc == null || unitDest == null) return false;
return ((unitSrc.meter == unitDest.meter) &&
(unitSrc.kg == unitDest.kg) &&
(unitSrc.sec == unitDest.sec) &&
(unitSrc.amper == unitDest.amper) &&
(unitSrc.kelvin == unitDest.kelvin) &&
(unitSrc.candela == unitDest.candela) &&
(unitSrc.mole == unitDest.mole) &&
(unitSrc.radian == unitDest.radian) &&
(unitSrc.steradian == unitDest.steradian));
}
public static boolean isUnitCompatible(int unitIDSrc,int unitIDDest){
return isUnitCompatible(Unit.getUnit(unitIDSrc),Unit.getUnit(unitIDDest));
}
public static float unitConvert(int unitIDSrc, float srcValue,int unitIDDest){
return unitConvert(Unit.getUnit(unitIDSrc),srcValue,Unit.getUnit(unitIDDest));
}
public static String getPrefixStringForUnit(Unit p,int order){
String retValue = null;
if(p == null || !p.doMetricPrefix) return retValue;
switch(order){
case -12: retValue = "p"; break;
case -9: retValue = "n"; break;
case -6: retValue = "?"; break;
case -3: retValue = "m"; break;
case -2: retValue = "c"; break;
case -1: retValue = "d"; break;
case 3: retValue = "k"; break;
case 6: retValue = "M"; break;
case 9: retValue = "G"; break;
}
return retValue;
}
public static float getPrefixKoeffForUnit(Unit p,int order){
float retValue = -1f;
if(p == null || !p.doMetricPrefix) return retValue;
switch(order){
case -12: retValue = 1e-12f; break;
case -9: retValue = 1e-9f; break;
case -6: retValue = 1e-6f; break;
case -3: retValue = 1e-3f; break;
case -2: retValue = 0.01f; break;
case -1: retValue = 0.1f; break;
case 3: retValue = 1000f; break;
case 6: retValue = 1e6f; break;
case 9: retValue = 1e9f; break;
}
return retValue;
}
protected static float calcKoeff0(byte order,float kpart){
float k = 1;
if(order == 0) return k;
int n = Math.abs(order);
for(int i = 0; i < n; i++) k = (order < 0)?(k/kpart):k*kpart;
return k;
}
public static Unit createMechanicUnit(byte meter,byte kg,byte sec,float k){
return new Unit("Custom","",true,UNIT_CAT_UNKNOWN,UNIT_CODE_UNKNOWN,UNIT_CODE_UNKNOWN,meter,kg,sec,NON_ORDER,NON_ORDER,NON_ORDER,NON_ORDER,NON_ORDER,NON_ORDER,k,0,false,false);
}
public static Unit createMechanicUnit(byte meter,byte kg,byte sec,float kmeter,float kkg, float ksec){
float k = calcKoeff0(meter,kmeter)*calcKoeff0(kg,kkg)*calcKoeff0(sec,ksec);
return createMechanicUnit(meter,kg,sec,k);
}
public static Unit findKnownMechanicUnit(int meter,int kg,int sec,float kmeter,float kkg, float ksec){
Unit needUnit = createMechanicUnit((byte)meter,(byte)kg,(byte)sec,kmeter,kkg,ksec);
Unit cat = null;
for(int i = 1; i < UNIT_TABLE_LENGTH; i++){
Unit tunit = getUnit(i);
if(!isUnitCompatible(tunit,needUnit)) continue;
if(needUnit.equals(tunit)){
cat = tunit;
break;
}
}
if(cat == null) return needUnit;
return cat;
}
public static Unit findKnownMechanicUnit(int unitMeter,int nmeter,int unitKg,int nkg,int unitSec,int nsec){
Unit u = getUnit(unitMeter);
if(u == null) return null;
if(u.unitCategory != UNIT_CAT_LENGTH) return null;
int umeter = u.meter*nmeter;
float kmeter = u.koeffA;
u = getUnit(unitKg);
if(u == null) return null;
if(u.unitCategory != UNIT_CAT_MASS) return null;
int ukg = u.kg*nkg;
float kkg = u.koeffA;
u = getUnit(unitSec);
if(u == null) return null;
if(u.unitCategory != UNIT_CAT_TIME) return null;
int usec = u.sec*nsec;
float ksec = u.koeffA;
return findKnownMechanicUnit(umeter,ukg,usec,kmeter,kkg,ksec);
}
public static Unit findKnownMechanicUnit(int category,int unitMeter,int unitKg,int unitSec){
byte []catn = getCategoryNumber(category);
if(catn == null) return null;
return findKnownMechanicUnit(unitMeter,catn[METER_INDEX],unitKg,catn[KG_INDEX],unitSec,catn[SEC_INDEX]);
}
public static Unit getUnitFromBasics(int unitCategory,
int unitMeter, int unitKg, int unitSec, int unitAmper, int unitKelvin,
int unitCandela, int unitMole, int unitRadian, int unitSteradian)
{
float koeffA=1f;
float koeffB=0f;
Unit cat=null, u;
int i;
for(i = 1; i < UNIT_TABLE_LENGTH; i++){
cat = getUnit(i);
if(cat.unitCategory == unitCategory){
break;
}
}
if (i == UNIT_TABLE_LENGTH) return null;
u = getUnit(unitMeter);
if (u!=null){
//System.out.println(u.name + " has koeffA: "+u.koeffA+" "+koeffA + "*" +u.koeffA+"^"+cat.meter);
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.meter);
}
u = getUnit(unitKg);
if (u!=null){
//System.out.println(u.name + " has koeffA: "+u.koeffA+" "+koeffA + "*" +u.koeffA+"^"+cat.kg);
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.kg);
}
u = getUnit(unitSec);
if (u!=null){
//System.out.println(u.name + " has koeffA: "+u.koeffA+" "+koeffA + "*" +u.koeffA+"^"+cat.sec);
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.sec);
}
u = getUnit(unitAmper);
if (u!=null){
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.amper);
}
u = getUnit(unitKelvin);
if (u!=null){
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.kelvin);
}
u = getUnit(unitCandela);
if (u!=null){
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.candela);
}
u = getUnit(unitMole);
if (u!=null){
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.mole);
}
u = getUnit(unitRadian);
if (u!=null){
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.radian);
}
u = getUnit(unitSteradian);
if (u!=null){
koeffA=koeffA*(float)Math.pow(u.koeffA,cat.steradian);
}
System.out.println("koeffA: "+koeffA);
for(i = 1; i < UNIT_TABLE_LENGTH; i++){
u = getUnit(i);
if(u.unitCategory == unitCategory){
if (u.koeffA==koeffA){
return u;
}
}
}
return new Unit("Unknown","?",true,unitCategory,-1,-1,
cat.meter,cat.kg,cat.sec,cat.amper,cat.kelvin,
cat.candela,cat.mole,cat.radian,cat.steradian,
koeffA,koeffB,false,false);
}
public String toString(){
String ret = "Unit: ";
ret += name+":"+abbreviation+": "+meter+":";
ret += kg+":";
ret += sec+":";
ret += amper+":";
ret += kelvin+":";
ret += candela+":";
ret += mole+":";
ret += radian+":";
ret += steradian+": ";
ret += koeffA+":";
ret += koeffB;
return ret;
}
public synchronized boolean equals(Object obj) {
if(!(obj instanceof Unit)) return false;
if(obj == this) return true;
Unit unit = (Unit)obj;
if(unit.meter != meter) return false;
if(unit.kg != kg) return false;
if(unit.sec != sec) return false;
if(unit.amper != amper) return false;
if(unit.kelvin != kelvin) return false;
if(unit.candela != candela) return false;
if(unit.mole != mole) return false;
if(unit.radian != steradian) return false;
if(!MathUtil.equalWithTolerance(unit.koeffA,koeffA,1e-4f)) return false;
if(!MathUtil.equalWithTolerance(unit.koeffB,koeffB,1e-4f)) return false;
return true;
}
}
|
package org.jgroups.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.*;
import org.jgroups.auth.AuthToken;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.FD;
import org.jgroups.protocols.PingHeader;
import org.jgroups.stack.IpAddress;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.security.MessageDigest;
import java.text.NumberFormat;
import java.util.*;
/**
* Collection of various utility routines that can not be assigned to other classes.
* @author Bela Ban
* @version $Id: Util.java,v 1.158 2008/08/20 14:47:54 vlada Exp $
*/
public class Util {
private static NumberFormat f;
private static Map<Class,Byte> PRIMITIVE_TYPES=new HashMap<Class,Byte>(10);
private static final byte TYPE_NULL = 0;
private static final byte TYPE_STREAMABLE = 1;
private static final byte TYPE_SERIALIZABLE = 2;
private static final byte TYPE_BOOLEAN = 10;
private static final byte TYPE_BYTE = 11;
private static final byte TYPE_CHAR = 12;
private static final byte TYPE_DOUBLE = 13;
private static final byte TYPE_FLOAT = 14;
private static final byte TYPE_INT = 15;
private static final byte TYPE_LONG = 16;
private static final byte TYPE_SHORT = 17;
private static final byte TYPE_STRING = 18;
// constants
public static final int MAX_PORT=65535; // highest port allocatable
static boolean resolve_dns=false;
static boolean JGROUPS_COMPAT=false;
/**
* Global thread group to which all (most!) JGroups threads belong
*/
private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") {
public void uncaughtException(Thread t, Throwable e) {
LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e);
}
};
public static ThreadGroup getGlobalThreadGroup() {
return GLOBAL_GROUP;
}
static {
try {
resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();
}
catch (SecurityException ex){
resolve_dns=false;
}
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
try {
String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false");
JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue();
}
catch (SecurityException ex){
}
PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN));
PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE));
PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR));
PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE));
PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT));
PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT));
PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG));
PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT));
PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING));
}
public static void assertTrue(boolean condition) {
assert condition;
}
public static void assertTrue(String message, boolean condition) {
if(message != null)
assert condition : message;
else
assert condition;
}
public static void assertFalse(boolean condition) {
assertFalse(null, condition);
}
public static void assertFalse(String message, boolean condition) {
if(message != null)
assert !condition : message;
else
assert !condition;
}
public static void assertEquals(String message, Object val1, Object val2) {
if(message != null) {
assert val1.equals(val2) : message;
}
else {
assert val1.equals(val2);
}
}
public static void assertEquals(Object val1, Object val2) {
assertEquals(null, val1, val2);
}
public static void assertNotNull(String message, Object val) {
if(message != null)
assert val != null : message;
else
assert val != null;
}
public static void assertNotNull(Object val) {
assertNotNull(null, val);
}
public static void assertNull(String message, Object val) {
if(message != null)
assert val == null : message;
else
assert val == null;
}
public static void assertNull(Object val) {
assertNotNull(null, val);
}
/**
* Verifies that val is <= max memory
* @param buf_name
* @param val
*/
public static void checkBufferSize(String buf_name, long val) {
// sanity check that max_credits doesn't exceed memory allocated to VM by -Xmx
long max_mem=Runtime.getRuntime().maxMemory();
if(val > max_mem) {
throw new IllegalArgumentException(buf_name + "(" + Util.printBytes(val) + ") exceeds max memory allocated to VM (" +
Util.printBytes(max_mem) + ")");
}
}
public static void close(InputStream inp) {
if(inp != null)
try {inp.close();} catch(IOException e) {}
}
public static void close(OutputStream out) {
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
public static void close(Socket s) {
if(s != null) {
try {s.close();} catch(Exception ex) {}
}
}
public static void close(DatagramSocket my_sock) {
if(my_sock != null) {
try {my_sock.close();} catch(Throwable t) {}
}
}
public static void close(Channel ch) {
if(ch != null) {
try {ch.close();} catch(Throwable t) {}
}
}
public static void close(Channel ... channels) {
if(channels != null) {
for(Channel ch: channels)
Util.close(ch);
}
}
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer);
return objectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer, offset, length);
Object retval=null;
InputStream in=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
byte b=(byte)in_stream.read();
try {
switch(b) {
case TYPE_NULL:
return null;
case TYPE_STREAMABLE:
in=new DataInputStream(in_stream);
retval=readGenericStreamable((DataInputStream)in);
break;
case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable
in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=((ContextObjectInputStream)in).readObject();
break;
case TYPE_BOOLEAN:
in=new DataInputStream(in_stream);
retval=Boolean.valueOf(((DataInputStream)in).readBoolean());
break;
case TYPE_BYTE:
in=new DataInputStream(in_stream);
retval=new Byte(((DataInputStream)in).readByte());
break;
case TYPE_CHAR:
in=new DataInputStream(in_stream);
retval=new Character(((DataInputStream)in).readChar());
break;
case TYPE_DOUBLE:
in=new DataInputStream(in_stream);
retval=new Double(((DataInputStream)in).readDouble());
break;
case TYPE_FLOAT:
in=new DataInputStream(in_stream);
retval=new Float(((DataInputStream)in).readFloat());
break;
case TYPE_INT:
in=new DataInputStream(in_stream);
retval=new Integer(((DataInputStream)in).readInt());
break;
case TYPE_LONG:
in=new DataInputStream(in_stream);
retval=new Long(((DataInputStream)in).readLong());
break;
case TYPE_SHORT:
in=new DataInputStream(in_stream);
retval=new Short(((DataInputStream)in).readShort());
break;
case TYPE_STRING:
in=new DataInputStream(in_stream);
if(((DataInputStream)in).readBoolean()) { // large string
ObjectInputStream ois=new ObjectInputStream(in);
try {
return ois.readObject();
}
finally {
ois.close();
}
}
else {
retval=((DataInputStream)in).readUTF();
}
break;
default:
throw new IllegalArgumentException("type " + b + " is invalid");
}
return retval;
}
finally {
Util.close(in);
}
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
if(JGROUPS_COMPAT)
return oldObjectToByteBuffer(obj);
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
if(obj == null) {
out_stream.write(TYPE_NULL);
out_stream.flush();
return out_stream.toByteArray();
}
OutputStream out=null;
Byte type;
try {
if(obj instanceof Streamable) { // use Streamable if we can
out_stream.write(TYPE_STREAMABLE);
out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, (DataOutputStream)out);
}
else if((type=(Byte)PRIMITIVE_TYPES.get(obj.getClass())) != null) {
out_stream.write(type.byteValue());
out=new DataOutputStream(out_stream);
switch(type.byteValue()) {
case TYPE_BOOLEAN:
((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue());
break;
case TYPE_BYTE:
((DataOutputStream)out).writeByte(((Byte)obj).byteValue());
break;
case TYPE_CHAR:
((DataOutputStream)out).writeChar(((Character)obj).charValue());
break;
case TYPE_DOUBLE:
((DataOutputStream)out).writeDouble(((Double)obj).doubleValue());
break;
case TYPE_FLOAT:
((DataOutputStream)out).writeFloat(((Float)obj).floatValue());
break;
case TYPE_INT:
((DataOutputStream)out).writeInt(((Integer)obj).intValue());
break;
case TYPE_LONG:
((DataOutputStream)out).writeLong(((Long)obj).longValue());
break;
case TYPE_SHORT:
((DataOutputStream)out).writeShort(((Short)obj).shortValue());
break;
case TYPE_STRING:
String str=(String)obj;
if(str.length() > Short.MAX_VALUE) {
((DataOutputStream)out).writeBoolean(true);
ObjectOutputStream oos=new ObjectOutputStream(out);
try {
oos.writeObject(str);
}
finally {
oos.close();
}
}
else {
((DataOutputStream)out).writeBoolean(false);
((DataOutputStream)out).writeUTF(str);
}
break;
default:
throw new IllegalArgumentException("type " + type + " is invalid");
}
}
else { // will throw an exception if object is not serializable
out_stream.write(TYPE_SERIALIZABLE);
out=new ObjectOutputStream(out_stream);
((ObjectOutputStream)out).writeObject(obj);
}
}
finally {
Util.close(out);
}
result=out_stream.toByteArray();
return result;
}
/** For backward compatibility in JBoss 4.0.2 */
public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
return oldObjectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Object retval=null;
try { // to read the object as an Externalizable
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=in.readObject();
in.close();
}
catch(StreamCorruptedException sce) {
try { // is it Streamable?
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream);
retval=readGenericStreamable(in);
in.close();
}
catch(Exception ee) {
IOException tmp=new IOException("unmarshalling failed");
tmp.initCause(ee);
throw tmp;
}
}
if(retval == null)
return null;
return retval;
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] oldObjectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
if(obj instanceof Streamable) { // use Streamable if we can
DataOutputStream out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, out);
out.close();
}
else {
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
out.close();
}
result=out_stream.toByteArray();
return result;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static byte[] streamableToByteBuffer(Streamable obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(out_stream);
obj.writeTo(out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(out_stream);
Util.writeAddresses(c, out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static int size(Address addr) {
int retval=Global.BYTE_SIZE; // presence byte
if(addr != null)
retval+=addr.size() + Global.BYTE_SIZE; // plus type of address
return retval;
}
public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{
Util.writeString(token.getName(), out);
token.writeTo(out);
}
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
try{
String type = Util.readString(in);
Object obj = Class.forName(type).newInstance();
AuthToken token = (AuthToken) obj;
token.readFrom(in);
return token;
}
catch(ClassNotFoundException cnfe){
return null;
}
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
if(addr == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if(addr instanceof IpAddress) {
// regular case, we don't need to include class information about the type of Address, e.g. JmsAddress
out.writeBoolean(true);
addr.writeTo(out);
}
else {
out.writeBoolean(false);
writeOtherAddress(addr, out);
}
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Address addr=null;
if(in.readBoolean() == false)
return null;
if(in.readBoolean()) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
int b=in.read();
short magic_number;
String classname;
Class cl=null;
Address addr;
if(b == 1) {
magic_number=in.readShort();
cl=ClassConfigurator.get(magic_number);
}
else {
classname=in.readUTF();
cl=ClassConfigurator.get(classname);
}
addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
short magic_number=ClassConfigurator.getMagicNumber(addr.getClass());
// write the class info
if(magic_number == -1) {
out.write(0);
out.writeUTF(addr.getClass().getName());
}
else {
out.write(1);
out.writeShort(magic_number);
}
// write the data itself
addr.writeTo(out);
}
/**
* Writes a Vector of Addresses. Can contain 65K addresses at most
* @param v A Collection<Address>
* @param out
* @throws IOException
*/
public static void writeAddresses(Collection<Address> v, DataOutputStream out) throws IOException {
if(v == null) {
out.writeShort(-1);
return;
}
out.writeShort(v.size());
for(Address addr: v) {
Util.writeAddress(addr, out);
}
}
public static Collection<Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException {
short length=in.readShort();
if(length < 0) return null;
Collection<Address> retval=(Collection<Address>)cl.newInstance();
Address addr;
for(int i=0; i < length; i++) {
addr=Util.readAddress(in);
retval.add(addr);
}
return retval;
}
/**
* Returns the marshalled size of a Collection of Addresses.
* <em>Assumes elements are of the same type !</em>
* @param addrs Collection<Address>
* @return long size
*/
public static long size(Collection<Address> addrs) {
int retval=Global.SHORT_SIZE; // number of elements
if(addrs != null && !addrs.isEmpty()) {
Address addr=addrs.iterator().next();
retval+=size(addr) * addrs.size();
}
return retval;
}
public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {
if(obj == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
obj.writeTo(out);
}
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Streamable retval=null;
if(in.readBoolean() == false)
return null;
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {
short magic_number;
String classname;
if(obj == null) {
out.write(0);
return;
}
out.write(1);
magic_number=ClassConfigurator.getMagicNumber(obj.getClass());
// write the magic number or the class name
if(magic_number == -1) {
out.writeBoolean(false);
classname=obj.getClass().getName();
out.writeUTF(classname);
}
else {
out.writeBoolean(true);
out.writeShort(magic_number);
}
// write the contents
obj.writeTo(out);
}
public static Streamable readGenericStreamable(DataInputStream in) throws IOException {
Streamable retval=null;
int b=in.read();
if(b == 0)
return null;
boolean use_magic_number=in.readBoolean();
String classname;
Class clazz;
try {
if(use_magic_number) {
short magic_number=in.readShort();
clazz=ClassConfigurator.get(magic_number);
if (clazz==null) {
throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found.");
}
}
else {
classname=in.readUTF();
clazz=ClassConfigurator.get(classname);
if (clazz==null) {
throw new ClassNotFoundException(classname);
}
}
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
catch(Exception ex) {
throw new IOException("failed reading object: " + ex.toString());
}
}
public static void writeObject(Object obj, DataOutputStream out) throws Exception {
if(obj == null || !(obj instanceof Streamable)) {
byte[] buf=objectToByteBuffer(obj);
out.writeShort(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.writeShort(-1);
writeGenericStreamable((Streamable)obj, out);
}
}
public static Object readObject(DataInputStream in) throws Exception {
short len=in.readShort();
Object retval=null;
if(len == -1) {
retval=readGenericStreamable(in);
}
else {
byte[] buf=new byte[len];
in.readFully(buf, 0, len);
retval=objectFromByteBuffer(buf);
}
return retval;
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {
if(buf != null) {
out.write(1);
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.write(0);
}
}
public static byte[] readByteBuffer(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1) {
b=in.readInt();
byte[] buf=new byte[b];
in.read(buf, 0, buf.length);
return buf;
}
return null;
}
public static Buffer messageToByteBuffer(Message msg) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
out.writeBoolean(msg != null);
if(msg != null)
msg.writeTo(out);
out.flush();
Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception {
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
if(!in.readBoolean())
return null;
Message msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
return msg;
}
/**
* Marshalls a list of messages.
* @param xmit_list LinkedList<Message>
* @return Buffer
* @throws IOException
*/
public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
Buffer retval=null;
out.writeInt(xmit_list.size());
for(Message msg: xmit_list) {
msg.writeTo(out);
}
out.flush();
retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {
List<Message> retval=null;
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
int size=in.readInt();
if(size == 0)
return null;
Message msg;
retval=new LinkedList<Message>();
for(int i=0; i < size; i++) {
msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
retval.add(msg);
}
return retval;
}
public static boolean match(Object obj1, Object obj2) {
if(obj1 == null && obj2 == null)
return true;
if(obj1 != null)
return obj1.equals(obj2);
else
return obj2.equals(obj1);
}
public static boolean match(long[] a1, long[] a2) {
if(a1 == null && a2 == null)
return true;
if(a1 == null || a2 == null)
return false;
if(a1 == a2) // identity
return true;
// at this point, a1 != null and a2 != null
if(a1.length != a2.length)
return false;
for(int i=0; i < a1.length; i++) {
if(a1[i] != a2[i])
return false;
}
return true;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void sleep(long timeout, int nanos) {
try {
Thread.sleep(timeout,nanos);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
public static int keyPress(String msg) {
System.out.println(msg);
try {
return System.in.read();
}
catch(IOException e) {
return 0;
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * range) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
return r < cutoff;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
public static String dumpThreads() {
StringBuilder sb=new StringBuilder();
ThreadMXBean bean=ManagementFactory.getThreadMXBean();
long[] ids=bean.getAllThreadIds();
ThreadInfo[] threads=bean.getThreadInfo(ids, 20);
for(int i=0; i < threads.length; i++) {
ThreadInfo info=threads[i];
if(info == null)
continue;
sb.append(info.getThreadName()).append(":\n");
StackTraceElement[] stack_trace=info.getStackTrace();
for(int j=0; j < stack_trace.length; j++) {
StackTraceElement el=stack_trace[j];
sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName());
sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")");
sb.append("\n");
}
sb.append("\n\n");
}
return sb.toString();
}
public static boolean interruptAndWaitToDie(Thread t) {
return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME);
}
public static boolean interruptAndWaitToDie(Thread t, long timeout) {
if(t == null)
throw new IllegalArgumentException("Thread can not be null");
t.interrupt(); // interrupts the sleep()
try {
t.join(timeout);
}
catch(InterruptedException e){
Thread.currentThread().interrupt(); // set interrupt flag again
}
return t.isAlive();
}
/**
* Debugging method used to dump the content of a protocol queue in a
* condensed form. Useful to follow the evolution of the queue's content in
* time.
*/
public static String dumpQueue(Queue q) {
StringBuilder sb=new StringBuilder();
LinkedList values=q.values();
if(values.isEmpty()) {
sb.append("empty");
}
else {
for(Iterator it=values.iterator(); it.hasNext();) {
Object o=it.next();
String s=null;
if(o instanceof Event) {
Event event=(Event)o;
int type=event.getType();
s=Event.type2String(type);
if(type == Event.VIEW_CHANGE)
s+=" " + event.getArg();
if(type == Event.MSG)
s+=" " + event.getArg();
if(type == Event.MSG) {
s+="[";
Message m=(Message)event.getArg();
Map<String,Header> headers=new HashMap<String,Header>(m.getHeaders());
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
Object headerKey=i.next();
Object value=headers.get(headerKey);
String headerToString=null;
if(value instanceof FD.FdHeader) {
headerToString=value.toString();
}
else
if(value instanceof PingHeader) {
headerToString=headerKey + "-";
if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) {
headerToString+="GMREQ";
}
else
if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) {
headerToString+="GMRSP";
}
else {
headerToString+="UNKNOWN";
}
}
else {
headerToString=headerKey + "-" + (value == null ? "null" : value.toString());
}
s+=headerToString;
if(i.hasNext()) {
s+=",";
}
}
s+="]";
}
}
else {
s=o.toString();
}
sb.append(s).append("\n");
}
}
return sb.toString();
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("
}
public static String activeThreads() {
StringBuilder sb=new StringBuilder();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("
for(int i=0; i < threads.length; i++) {
sb.append("#").append(i).append(": ").append(threads[i]).append('\n');
}
sb.append("
return sb.toString();
}
public static String printBytes(long bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
public static String printBytes(double bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) {
byte[] retval[];
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < length) {
if(accumulated_size + frag_size <= length)
tmp_size=frag_size;
else
tmp_size=length - accumulated_size;
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
return fragmentBuffer(buf, frag_size, buf.length);
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static List<Range> computeFragOffsets(int offset, int length, int frag_size) {
List<Range> retval=new ArrayList<Range>();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static List<Range> computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) {
boolean first=true;
StringBuilder sb=new StringBuilder();
for(T el: list) {
if(first) {
first=false;
}
else {
sb.append(delimiter);
}
sb.append(el);
}
return sb.toString();
}
// /**
// Peeks for view on the channel until n views have been received or timeout has elapsed.
// Used to determine the view in which we want to start work. Usually, we start as only
// member in our own view (1st view) and the next view (2nd view) will be the full view
// of all members, or a timeout if we're the first member. If a non-view (a message or
// block) is received, the method returns immediately.
// @param channel The channel used to peek for views. Has to be operational.
// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,
// if there are other members, we start working with them included in our view.
// @param timeout Number of milliseconds to wait until view is forced to return. A value
// of <= 0 means wait forever.
// */
// public static View peekViews(Channel channel, int number_of_views, long timeout) {
// View retval=null;
// Object obj=null;
// int num=0;
// long start_time=System.currentTimeMillis();
// if(timeout <= 0) {
// while(true) {
// try {
// obj=channel.peek(0);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(0);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// else {
// while(timeout > 0) {
// try {
// obj=channel.peek(timeout);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(timeout);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// timeout=timeout - (System.currentTimeMillis() - start_time);
// return retval;
public static String array2String(long[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(short[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(Object[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
/** Returns true if all elements of c match obj */
public static boolean all(Collection c, Object obj) {
for(Iterator iterator=c.iterator(); iterator.hasNext();) {
Object o=iterator.next();
if(!o.equals(obj))
return false;
}
return true;
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector<Address> pickSubset(Vector<Address> members, double subset_percentage) {
Vector<Address> ret=new Vector<Address>(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector<Address>)members.clone();
for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
public static Object pickRandomElement(List list) {
if(list == null) return null;
int size=list.size();
int index=(int)((Math.random() * size * 10) % size);
return list.get(index);
}
public static Object pickRandomElement(Object[] array) {
if(array == null) return null;
int size=array.length;
int index=(int)((Math.random() * size * 10) % size);
return array[index];
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) {
Vector<Address> retval=new Vector<Address>();
Address mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printMembers(Vector v) {
StringBuilder sb=new StringBuilder("(");
boolean first=true;
Object el;
if(v != null) {
for(int i=0; i < v.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
el=v.elementAt(i);
sb.append(el);
}
}
sb.append(')');
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception {
if(length > 1) {
out.write(buf, offset, 1);
out.write(buf, offset+1, length - 1);
}
else {
out.write(buf, offset, 0);
out.write(buf, offset, length);
}
}
/**
* if we were to register for OP_WRITE and send the remaining data on
* readyOps for this channel we have to either block the caller thread or
* queue the message buffers that may arrive while waiting for OP_WRITE.
* Instead of the above approach this method will continuously write to the
* channel until the buffer sent fully.
*/
public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException {
int written = 0;
int toWrite = buf.limit();
while (written < toWrite) {
written += out.write(buf);
}
}
// /* double writes are not required.*/
// public static void doubleWriteBuffer(
// ByteBuffer buf,
// WritableByteChannel out)
// throws Exception
// if (buf.limit() > 1)
// int actualLimit = buf.limit();
// buf.limit(1);
// writeFully(buf,out);
// buf.limit(actualLimit);
// writeFully(buf,out);
// else
// buf.limit(0);
// writeFully(buf,out);
// buf.limit(1);
// writeFully(buf,out);
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
inst=Util.loadClass(classname, null).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static int sizeOf(Streamable inst) {
byte[] data;
ByteArrayOutputStream output;
DataOutputStream out;
try {
output=new ByteArrayOutputStream();
out=new DataOutputStream(output);
inst.writeTo(out);
out.flush();
data=output.toByteArray();
return data.length;
}
catch(Exception ex) {
return -1;
}
}
/**
* Tries to load the class from the current thread's context class loader. If
* not successful, tries to load the class from the current instance.
* @param classname Desired class.
* @param clazz Class object used to obtain a class loader
* if no context class loader is available.
* @return Class, or null on failure.
*/
public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
throw new ClassNotFoundException(classname);
}
public static InputStream getResourceAsStream(String name, Class clazz) {
ClassLoader loader;
InputStream retval=null;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
return retval;
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
* Parses comma-delimited longs; e.g., 2000,4000,8000.
* Returns array of long, or null.
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector<Long> v=new Vector<Long>();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.isEmpty()) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=v.elementAt(i).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static List<String> parseCommaDelimitedStrings(String l) {
return parseStringList(l, ",");
}
/**
* Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of
* IpAddresses
*/
public static List<IpAddress> parseCommaDelimetedHosts(String hosts, int port_range) throws UnknownHostException {
StringTokenizer tok=new StringTokenizer(hosts, ",");
String t;
IpAddress addr;
Set<IpAddress> retval=new HashSet<IpAddress>();
while(tok.hasMoreTokens()) {
t=tok.nextToken().trim();
String host=t.substring(0, t.indexOf('['));
host=host.trim();
int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']')));
for(int i=port;i < port + port_range;i++) {
addr=new IpAddress(host, i);
retval.add(addr);
}
}
return Collections.unmodifiableList(new LinkedList<IpAddress>(retval));
}
public static List<String> parseStringList(String l, String separator) {
List<String> tmp=new LinkedList<String>();
StringTokenizer tok=new StringTokenizer(l, separator);
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t.trim());
}
return tmp;
}
/**
*
* @param s
* @return List<NetworkInterface>
*/
public static List<NetworkInterface> parseInterfaceList(String s) throws Exception {
List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10);
if(s == null)
return null;
StringTokenizer tok=new StringTokenizer(s, ",");
String interface_name;
NetworkInterface intf;
while(tok.hasMoreTokens()) {
interface_name=tok.nextToken();
// try by name first (e.g. (eth0")
intf=NetworkInterface.getByName(interface_name);
// next try by IP address or symbolic name
if(intf == null)
intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name));
if(intf == null)
throw new Exception("interface " + interface_name + " not found");
if(!interfaces.contains(intf)) {
interfaces.add(intf);
}
}
return interfaces;
}
public static String print(List<NetworkInterface> interfaces) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(NetworkInterface intf: interfaces) {
if(first) {
first=false;
}
else {
sb.append(", ");
}
sb.append(intf.getName());
}
return sb.toString();
}
public static String shortName(String hostname) {
int index;
StringBuilder sb=new StringBuilder();
if(hostname == null) return null;
index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
sb.append(hostname.substring(0, index));
else
sb.append(hostname);
return sb.toString();
}
public static String shortName(InetAddress hostname) {
if(hostname == null) return null;
StringBuilder sb=new StringBuilder();
if(resolve_dns)
sb.append(hostname.getHostName());
else
sb.append(hostname.getHostAddress());
return sb.toString();
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static MulticastSocket createMulticastSocket(int port) throws IOException {
return createMulticastSocket(null, port, null);
}
public static MulticastSocket createMulticastSocket(InetAddress mcast_addr, int port, Log log) throws IOException {
if(mcast_addr != null && !mcast_addr.isMulticastAddress()) {
if(log != null && log.isWarnEnabled())
log.warn("mcast_addr (" + mcast_addr + ") is not a multicast address, will be ignored");
return new MulticastSocket(port);
}
SocketAddress saddr=new InetSocketAddress(mcast_addr, port);
MulticastSocket retval=null;
try {
retval=new MulticastSocket(saddr);
}
catch(IOException ex) {
if(log != null && log.isWarnEnabled()) {
StringBuilder sb=new StringBuilder();
String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a";
sb.append("could not bind to " + mcast_addr + " (" + type + " address)");
sb.append("; make sure your mcast_addr is of the same type as the IP stack (IPv4 or IPv6).");
sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " +
"(see http:
sb.append("\nException was: " + ex);
log.warn(sb);
}
}
if(retval == null)
retval=new MulticastSocket(port);
return retval;
}
/**
* Returns the address of the interface to use defined by bind_addr and bind_interface
* @param props
* @return
* @throws UnknownHostException
* @throws SocketException
*/
public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException {
boolean ignore_systemprops=Util.isBindAddressPropertyIgnored();
String bind_addr=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr",
ignore_systemprops, null);
String bind_interface=Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface",
ignore_systemprops, null);
InetAddress retval=null, bind_addr_host=null;
if(bind_addr != null) {
bind_addr_host=InetAddress.getByName(bind_addr);
}
if(bind_interface != null) {
NetworkInterface intf=NetworkInterface.getByName(bind_interface);
if(intf != null) {
for(Enumeration<InetAddress> addresses=intf.getInetAddresses(); addresses.hasMoreElements();) {
InetAddress addr=addresses.nextElement();
if(bind_addr == null) {
retval=addr;
break;
}
else {
if(bind_addr_host != null) {
if(bind_addr_host.equals(addr)) {
retval=addr;
break;
}
}
else if(addr.getHostAddress().trim().equalsIgnoreCase(bind_addr)) {
retval=addr;
break;
}
}
}
}
else {
throw new UnknownHostException("network interface " + bind_interface + " not found");
}
}
if(retval == null) {
retval=bind_addr != null? InetAddress.getByName(bind_addr) : InetAddress.getLocalHost();
}
//check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine
if(NetworkInterface.getByInetAddress(retval) == null) {
throw new UnknownHostException("Invalid bind address " + retval);
}
props.remove("bind_addr");
props.remove("bind_interface");
return retval;
}
public static boolean checkForLinux() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("linux");
}
public static boolean checkForSolaris() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("sun");
}
public static boolean checkForWindows() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("win");
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static int getJavaVersion() {
String version=System.getProperty("java.version");
int retval=0;
if(version != null) {
if(version.startsWith("1.2"))
return 12;
if(version.startsWith("1.3"))
return 13;
if(version.startsWith("1.4"))
return 14;
if(version.startsWith("1.5"))
return 15;
if(version.startsWith("5"))
return 15;
if(version.startsWith("1.6"))
return 16;
if(version.startsWith("6"))
return 16;
}
return retval;
}
public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) {
if(v == null) return null;
return new UnmodifiableVector(v);
}
public static String memStats(boolean gc) {
StringBuilder sb=new StringBuilder();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
// public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
// Enumeration en=NetworkInterface.getNetworkInterfaces();
// while(en.hasMoreElements()) {
// NetworkInterface i=(NetworkInterface)en.nextElement();
// for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
// InetAddress addr=(InetAddress)en2.nextElement();
// if(!addr.isLoopbackAddress())
// return addr;
// return null;
public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
boolean preferIpv4=Boolean.getBoolean(Global.IPv4);
boolean preferIPv6=Boolean.getBoolean(Global.IPv6);
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
if(preferIPv6)
continue;
return addr;
}
if(addr instanceof Inet6Address) {
if(preferIpv4)
continue;
return addr;
}
}
}
}
return null;
}
public static boolean isIPv4Stack() {
return getIpStack()== 4;
}
public static boolean isIPv6Stack() {
return getIpStack() == 6;
}
public static short getIpStack() {
short retval=2;
if(Boolean.getBoolean(Global.IPv4)) {
retval=4;
}
if(Boolean.getBoolean(Global.IPv6)) {
retval=6;
}
return retval;
}
public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
continue;
}
if(addr instanceof Inet6Address) {
return addr;
}
}
}
}
return null;
}
public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10);
NetworkInterface intf;
for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
intf=(NetworkInterface)en.nextElement();
retval.add(intf);
}
return retval;
}
/**
* Returns a value associated wither with one or more system properties, or found in the props map
* @param system_props
* @param props List of properties read from the configuration file
* @param prop_name The name of the property, will be removed from props if found
* @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from
* props (not system_props)
* @param default_value Used to return a default value if the properties or system properties didn't have the value
* @return The value, or null if not found
*/
public static String getProperty(String[] system_props, Properties props, String prop_name,
boolean ignore_sysprops, String default_value) {
String retval=null;
if(props != null && prop_name != null) {
retval=props.getProperty(prop_name);
props.remove(prop_name);
}
if(!ignore_sysprops) {
String tmp, prop;
if(system_props != null) {
for(int i=0; i < system_props.length; i++) {
prop=system_props[i];
if(prop != null) {
try {
tmp=System.getProperty(prop);
if(tmp != null)
return tmp; // system properties override config file definitions
}
catch(SecurityException ex) {}
}
}
}
}
if(retval == null)
return default_value;
return retval;
}
public static boolean isBindAddressPropertyIgnored() {
try {
String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY);
if(tmp == null) {
tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD);
if(tmp == null)
return false;
}
tmp=tmp.trim().toLowerCase();
return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on"));
}
catch(SecurityException ex) {
return false;
}
}
public static MBeanServer getMBeanServer() {
ArrayList servers=MBeanServerFactory.findMBeanServer(null);
if(servers == null || servers.isEmpty())
return null;
// return 'jboss' server if available
for(int i=0; i < servers.size(); i++) {
MBeanServer srv=(MBeanServer)servers.get(i);
if("jboss".equalsIgnoreCase(srv.getDefaultDomain()))
return srv;
}
// return first available server
return (MBeanServer)servers.get(0);
}
public static void main(String args[]) throws Exception {
System.out.println("IPv4: " + isIPv4Stack());
System.out.println("IPv6: " + isIPv6Stack());
}
public static String generateList(Collection c, String separator) {
if(c == null) return null;
StringBuilder sb=new StringBuilder();
boolean first=true;
for(Iterator it=c.iterator(); it.hasNext();) {
if(first) {
first=false;
}
else {
sb.append(separator);
}
sb.append(it.next());
}
return sb.toString();
}
/**
* Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns
* the same string, otherwise a copy of the string with variables substituted
* @param val
* @return A string with vars replaced, or the same string if no vars found
*/
public static String substituteVariable(String val) {
if(val == null)
return val;
String retval=val, prev;
while(retval.contains("${")) { // handle multiple variables in val
prev=retval;
retval=_substituteVar(retval);
if(retval.equals(prev))
break;
}
return retval;
}
private static String _substituteVar(String val) {
int start_index, end_index;
start_index=val.indexOf("${");
if(start_index == -1)
return val;
end_index=val.indexOf("}", start_index+2);
if(end_index == -1)
throw new IllegalArgumentException("missing \"}\" in " + val);
String tmp=getProperty(val.substring(start_index +2, end_index));
if(tmp == null)
return val;
StringBuilder sb=new StringBuilder();
sb.append(val.substring(0, start_index));
sb.append(tmp);
sb.append(val.substring(end_index+1));
return sb.toString();
}
private static String getProperty(String s) {
String var, default_val, retval=null;
int index=s.indexOf(":");
if(index >= 0) {
var=s.substring(0, index);
default_val=s.substring(index+1);
retval=System.getProperty(var, default_val);
}
else {
var=s;
retval=System.getProperty(var);
}
return retval;
}
/**
* Used to convert a byte array in to a java.lang.String object
* @param bytes the bytes to be converted
* @return the String representation
*/
private static String getString(byte[] bytes) {
StringBuilder sb=new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
sb.append(0x00FF & b);
if (i + 1 < bytes.length) {
sb.append("-");
}
}
return sb.toString();
}
/**
* Converts a java.lang.String in to a MD5 hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String md5(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
return null;
}
}
/**
* Converts a java.lang.String in to a SHA hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String sha(String source) {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
/*
* $Id: Tdb.java,v 1.29 2014-09-15 19:34:16 pgust Exp $
*/
package org.lockss.config;
import java.io.*;
import java.util.*;
import org.apache.commons.collections .*;
import org.apache.commons.collections.iterators .*;
import org.lockss.util.*;
/**
* This class represents a title database (TDB). The TDB consists of
* hierarchy of <code>TdbPublisher</code>s, and <code>TdbAu</code>s.
* Special indexing provides fast access to all <code>TdbAu</code>s for
* a specified plugin ID.
*
* @author Philip Gust
* @version $Id: Tdb.java,v 1.29 2014-09-15 19:34:16 pgust Exp $
*/
public class Tdb {
/**
* Set up logger
*/
protected final static Logger logger = Logger.getLogger("Tdb");
/**
* A map of AUs per plugin, for this configuration
* (provides faster access for Plugins)
*/
private final Map<String, Map<TdbAu.Id,TdbAu>> pluginIdTdbAuIdsMap =
new HashMap<String,Map<TdbAu.Id,TdbAu>>(4, 1F);
/**
* Map of publisher names to TdBPublishers for this configuration
*/
private final Map<String, TdbPublisher> tdbPublisherMap =
new HashMap<String,TdbPublisher>(4, 1F);
/**
* Map of provider names to TdBProviders for this configuration
*/
private final Map<String, TdbProvider> tdbProviderMap =
new HashMap<String,TdbProvider>(4, 1F);
/**
* Determines whether more AUs can be added.
*/
private boolean isSealed = false;
/**
* The total number of TdbAus in this TDB (sum of collections in pluginIdTdbAus map
*/
private int tdbAuCount = 0;
/**
* Prefix appended to generated unknown title
*/
private static final String UNKNOWN_TITLE_PREFIX = "Title of ";
/**
* Prefix appended to generated unknown publisher
*/
static final String UNKNOWN_PUBLISHER_PREFIX = "Publisher of ";
/**
* Prefix appended to generated unknown publisher
*/
static final String UNKNOWN_PROVIDER_PREFIX = "Provider of ";
@SuppressWarnings("serial")
static public class TdbException extends Exception {
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public TdbException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* <code>cause</code> is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public TdbException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail
* message of <tt>(cause==null ? null : cause.toString())</tt> (which
* typically contains the class and detail message of <tt>cause</tt>).
* This constructor is useful for exceptions that are little more than
* wrappers for other throwables (for example, {@link
* java.security.PrivilegedActionException}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public TdbException(Throwable cause) {
super(cause);
}
}
/**
* Register the au with this Tdb for its plugin.
*
* @param au the TdbAu
* @return <code>false</code> if already registered,
* otherwise <code>true</code>
* @throws TdbException if adding new TdbAu with duplicate id
*/
private boolean addTdbAuForPlugin(TdbAu au) throws TdbException {
// add AU to list for plugins
String pluginId = au.getPluginId();
Map<TdbAu.Id,TdbAu> auids = pluginIdTdbAuIdsMap.get(pluginId);
if (auids == null) {
auids = new HashMap<TdbAu.Id, TdbAu>(4, 1F);
pluginIdTdbAuIdsMap.put(pluginId, auids);
}
TdbAu otherAu = auids.put(au.getId(),au);
if (otherAu != null) {
// check existing entry
if (au == otherAu) {
// OK if same AU
return false;
}
// restore otherAu and throw exception
auids.put(otherAu.getId(),otherAu);
// throw exception if adding another AU with duplicate au id.
throw new TdbException("New au with duplicate id: " + au.getName());
}
// increment the total AU count;
tdbAuCount++;
return true;
}
/**
* Unregister the au with this Tdb for its plugin.
*
* @param au the TdbAu
* @return <code>false</code> if au was not registered, otherwise <code>true</code>
*/
private boolean removeTdbAuForPlugin(TdbAu au) {
// if can't add au to title, we need to undo the au
// registration and re-throw the exception we just caught
String pluginId = au.getPluginId();
Map<TdbAu.Id, TdbAu> c = pluginIdTdbAuIdsMap.get(pluginId);
if (c.remove(au.getId()) != null) {
if (c.isEmpty()) {
pluginIdTdbAuIdsMap.remove(c);
}
tdbAuCount
return true;
}
return false;
}
/**
* Add TdbProvider to Tdb
* @param provider the TdbProvider
* @return <code>true</code> if a new provider was added, <code>false<code>
* if this providerr is already added
* @throws TdbException if trying to add new provider with duplicate name
*/
public boolean addTdbProvider(TdbProvider provider) throws TdbException {
String providerName = provider.getName();
TdbProvider oldProvider = tdbProviderMap.put(providerName, provider);
if ((oldProvider != null) && (oldProvider != provider)) {
// restore old publisher and report error
tdbProviderMap.put(providerName, oldProvider);
throw new TdbException("New au provider with duplicate name: "
+ providerName);
}
return (oldProvider == null);
}
/**
* Add TdbPublisher to Tdb
* @param publisher the TdbPublisher
* @return <code>true</code> if a new publisher was added, <code>false<code>
* if this publisher is already added
* @throws TdbException if trying to add new publisher with duplicate name
*/
public boolean addTdbPublisher(TdbPublisher publisher) throws TdbException {
String pubName = publisher.getName();
TdbPublisher oldPublisher = tdbPublisherMap.put(pubName, publisher);
if ((oldPublisher != null) && (oldPublisher != publisher)) {
// restore old publisher and report error
tdbPublisherMap.put(pubName, oldPublisher);
throw new TdbException("New au publisher with duplicate name: "
+ pubName);
}
return (oldPublisher == null);
}
/**
* Add a new TdbAu to this title database. The TdbAu must have
* its pluginID, provider, and title set. The TdbAu's title must also
* have its titleId and publisher set. The publisher name must be unique
* to all publishers in this Tdb.
*
* @param au the TdbAu to add.
* @return <code>true</code> if new AU was added, <code>false</code> if
* this AU was previously added
* @throws TdbException if Tdb is sealed, this is a duplicate au, or
* the au's publisher or provider is a duplicate
*/
public boolean addTdbAu(TdbAu au) throws TdbException {
if (au == null) {
throw new IllegalArgumentException("TdbAu cannot be null");
}
// verify not sealed
if (isSealed()) {
throw new TdbException("Cannot add TdbAu to sealed Tdb");
}
// validate title
TdbTitle title = au.getTdbTitle();
if (title == null) {
throw new IllegalArgumentException("TdbAu's title not set");
}
// validate publisher
TdbPublisher publisher = title.getTdbPublisher();
if (publisher == null) {
throw new IllegalArgumentException("TdbAu's publisher not set");
}
// validate provider
TdbProvider provider = au.getTdbProvider();
if (provider == null) {
String pubName = publisher.getName();
// assume the provider is the same as the publisher
provider = tdbProviderMap.get(pubName);
if (provider == null) {
provider = new TdbProvider(pubName);
}
// add publisher provider to the au
provider.addTdbAu(au);
if (logger.isDebug3()) {
logger.debug3("Creating default provider for publisher " + pubName);
}
}
boolean newPublisher = false;
boolean newProvider = false;
boolean newAu = false;
try {
// add au publisher if not already added
newPublisher = addTdbPublisher(publisher);
// add au provider if not already added
newProvider = addTdbProvider(provider);
// add au if not already added
newAu = addTdbAuForPlugin(au);
} catch (TdbException ex) {
// remove new publisher and new provider, and report error
if (newPublisher) {
tdbPublisherMap.remove(publisher.getName());
}
if (newProvider) {
tdbProviderMap.remove(provider.getName());
}
TdbException ex2 = new TdbException("Cannot register au " + au.getName());
ex2.initCause(ex);
throw ex2;
}
return newAu;
}
/**
* Seals a Tdb against further additions.
*/
public void seal() {
isSealed = true;
}
/**
* Determines whether this Tdb is sealed.
*
* @return <code>true</code> if sealed
*/
public boolean isSealed() {
return isSealed;
}
/**
* Determines whether the title database is empty.
*
* @return <code> true</code> if the title database has no entries
*/
public boolean isEmpty() {
return pluginIdTdbAuIdsMap.isEmpty();
}
/**
* Return an object describing the differences between the Tdbs.
* Logically a symmetric operation but currently records only changes and
* addition, not deletions.
* @param newTdb the new Tdb
* @param oldTdb the previous Tdb
* @return a {@link Tdb.Differences}
*/
public static Differences computeDifferences(Tdb newTdb, Tdb oldTdb) {
if (newTdb == null) {
newTdb = new Tdb();
}
return newTdb.computeDifferences(oldTdb);
}
Differences computeDifferences(Tdb oldTdb) {
if (oldTdb == null) {
return new AllDifferences(this);
} else {
return new Differences(this, oldTdb);
}
}
/**
* Adds to the {@link Tdb.Differences} the differences found between
* oldTdb and this Tdb
*
* @param the {@link Tdb.Differences} to which to add items.
* @param otherTdb a Tdb
*/
private void addDifferences(Differences diffs, Tdb oldTdb) {
// process publishers
Map<String, TdbPublisher> oldPublishers = oldTdb.getAllTdbPublishers();
for (TdbPublisher oldPublisher : oldPublishers.values()) {
if (!this.tdbPublisherMap.containsKey(oldPublisher.getName())) {
// add pluginIds for publishers in tdb that are not in this Tdb
diffs.addPublisher(oldPublisher, Differences.Type.Old);
}
}
for (TdbPublisher thisPublisher : tdbPublisherMap.values()) {
TdbPublisher oldPublisher = oldPublishers.get(thisPublisher.getName());
if (oldPublisher == null) {
// add pluginIds for publisher in this Tdb that is not in tdb
diffs.addPublisher(thisPublisher, Differences.Type.New);
} else {
// add pluginIds for publishers in both Tdbs that are different
thisPublisher.addDifferences(diffs, oldPublisher);
}
}
// process providers
Map<String, TdbProvider> oldProviders = oldTdb.getAllTdbProviders();
for (TdbProvider oldProvider : oldProviders.values()) {
if (!this.tdbProviderMap.containsKey(oldProvider.getName())) {
// add pluginIds for providers in tdb that are not in this Tdb
diffs.addProvider(oldProvider, Differences.Type.Old);
}
}
for (TdbProvider thisProvider : tdbProviderMap.values()) {
TdbProvider oldProvider = oldTdb.getTdbProvider(thisProvider.getName());
if (oldProvider == null) {
// add pluginIds for provider in this Tdb that is not in tdb
diffs.addProvider(thisProvider, Differences.Type.New);
} else {
// add pluginIds for providers in both Tdbs that are different
thisProvider.addDifferences(diffs, oldProvider);
}
}
}
/**
* Determines two Tdbs are equal. Equality is based on having
* equal TdbPublishers, and their child TdbTitles and TdbAus.
*
* @param o the other object
* @return <code>true</code> iff they are equal Tdbs
*/
public boolean equals(Object o) {
// check for identity
if (this == o) {
return true;
}
if (o instanceof Tdb) {
try {
// if no exception thrown, there are no differences
// because the method did not try to modify the set
Differences diffs = new Differences.Unmodifiable();
addDifferences(diffs, (Tdb)o);
return true;
} catch (UnsupportedOperationException ex) {
// differences because method tried to add to unmodifiable set
} catch (IllegalArgumentException ex) {
// if something was wrong with the other Tdb
} catch (IllegalStateException ex) {
// if something is wrong with this Tdb
}
}
return false;
}
/**
* Not supported for this class.
*
* @throws UnsupportedOperationException
*/
public int hashCode() {
throw new UnsupportedOperationException();
}
/**
* Merge other Tdb into this one. Makes copies of otherTdb's non-duplicate
* TdbPublisher, TdbTitle, and TdbAu objects and their non-duplicate children.
* The object themselves are not merged.
*
* @param otherTdb the other Tdb
* @throws TdbException if Tdb is sealed
*/
public void copyFrom(Tdb otherTdb) throws TdbException {
// ignore inappropriate Tdb values
if ((otherTdb == null) || (otherTdb == this)) {
return;
}
if (isSealed()) {
throw new TdbException("Cannot add otherTdb AUs to sealed Tdb");
}
// merge non-duplicate publishers of otherTdb
boolean tdbIsNew = tdbPublisherMap.isEmpty();
for (TdbPublisher otherPublisher : otherTdb.getAllTdbPublishers().values()) {
String pubName = otherPublisher.getName();
TdbPublisher thisPublisher;
boolean publisherIsNew = true;
if (tdbIsNew) {
// no need to check for existing publisher if TDB is new
thisPublisher = new TdbPublisher(pubName);
tdbPublisherMap.put(pubName, thisPublisher);
} else {
thisPublisher = tdbPublisherMap.get(pubName);
publisherIsNew = (thisPublisher == null);
if (publisherIsNew) {
// copy publisher if not present in this Tdb
thisPublisher = new TdbPublisher(pubName);
tdbPublisherMap.put(pubName, thisPublisher);
}
}
// merge non-duplicate titles of otherPublisher into thisPublisher
for (TdbTitle otherTitle : otherPublisher.getTdbTitles()) {
String titleName = otherTitle.getName();
String otherId = otherTitle.getId();
TdbTitle thisTitle;
boolean titleIsNew = true;
if (publisherIsNew) {
// no need to check for existing title if publisher is new
thisTitle = otherTitle.copyForTdbPublisher(thisPublisher);
thisPublisher.addTdbTitle(thisTitle);
} else {
thisTitle = thisPublisher.getTdbTitleById(otherId);
titleIsNew = (thisTitle == null);
if (titleIsNew) {
// copy title if not present in this publisher
thisTitle = otherTitle.copyForTdbPublisher(thisPublisher);
thisPublisher.addTdbTitle(thisTitle);
} else if (! thisTitle.getName().equals(otherTitle.getName())) {
// error because it could lead to a missing title -- one probably has a typo
// (what about checking other title elements too?)
logger.error("Ignorning duplicate title entry: \"" + titleName
+ "\" with the same ID as \""
+ thisTitle.getName() + "\"");
}
}
// merge non-duplicate TdbAus of otherTitle into thisTitle
for (TdbAu otherAu : otherTitle.getTdbAus()) {
String auName = otherAu.getName();
String providerName = otherAu.getProviderName();
TdbAu thisAu = getTdbAuById(otherAu);
if (thisAu == null) {
// copy new TdbAu
thisAu = otherAu.copyForTdbTitle(thisTitle);
// add copy to provider of same name
TdbProvider thisProvider = getTdbProvider(providerName);
if (thisProvider == null) {
// add new provider to this Tdb
thisProvider = new TdbProvider(providerName);
tdbProviderMap.put(providerName, thisProvider);
}
thisProvider.addTdbAu(thisAu);
// finish adding this AU
addTdbAuForPlugin(thisAu);
} else {
// ignore and log error if existing AU is not identical
if ( !thisAu.getName().equals(auName)
|| !thisAu.getTdbTitle().getName().equals(titleName)
|| !thisAu.getTdbPublisher().getName().equals(pubName)
|| !thisAu.getTdbProvider().getName().equals(providerName)) {
logger.error("Ignoring duplicate au entry id \"" + thisAu.getId()
+ " for provider \"" + providerName
+ "\" (" + thisAu.getProviderName() + "), publisher \""
+ pubName + "\" (" + thisAu.getPublisherName()
+ "), title \"" + titleName + "\" ("
+ thisAu.getPublicationTitle() + "), name \""
+ auName + "\" (" + thisAu.getName() + ")");
}
}
}
}
}
}
/**
* Get existing TdbAu with same Id as another one.
* @param otherAu another TdbAu
* @return an existing TdbAu already in thisTdb
*/
public TdbAu getTdbAuById(TdbAu otherAu) {
Map<TdbAu.Id,TdbAu> map = pluginIdTdbAuIdsMap.get(otherAu.getPluginId());
return (map == null) ? null : map.get(otherAu.getId());
}
/**
* Get existing TdbAu with the the specified id.
* @param auId the TdbAu.Id
* @return the existing TdbAu or <code>null</code> if not in this Tdb
*/
public TdbAu getTdbAuById(TdbAu.Id auId) {
return getTdbAuById(auId.getTdbAu());
}
/**
* Returns a collection of TdbAus for the specified plugin ID.
* <p>
* Note: the returned collection should not be modified.
*
* @param pluginId the plugin ID
* @return a collection of TdbAus for the plugin; <code>null</code>
* if no TdbAus for the specified plugin in this configuration.
*/
public Collection<TdbAu.Id> getTdbAuIds(String pluginId) {
Map<TdbAu.Id,TdbAu> auIdMap = pluginIdTdbAuIdsMap.get(pluginId);
return (auIdMap != null) ?
auIdMap.keySet() : Collections.<TdbAu.Id>emptyList();
}
/**
* Returns the set of plugin ids for this Tdb.
* @return the set of all plugin ids for this Tdb.
*/
public Set<String> getAllPluginsIds() {
return (pluginIdTdbAuIdsMap != null)
? Collections.unmodifiableSet(pluginIdTdbAuIdsMap.keySet())
: Collections.<String>emptySet();
}
/**
* Get a list of all the TdbAu.Ids for this Tdb
*
* @return a collection of TdbAu objects
*/
public Set<TdbAu.Id> getAllTdbAuIds() {
if (pluginIdTdbAuIdsMap == null) {
return Collections.<TdbAu.Id> emptySet();
}
Set<TdbAu.Id> allAuIds = new HashSet<TdbAu.Id>();
// For each plugin's AU set, add them all to the set.
for (Map<TdbAu.Id,TdbAu> auIdMap : pluginIdTdbAuIdsMap.values()) {
allAuIds.addAll(auIdMap.keySet());
}
return allAuIds;
}
/**
* Return the number of TdbAus in this Tdb.
*
* @return the total TdbAu count
*/
public int getTdbAuCount() {
return tdbAuCount;
}
/**
* Return the number of TdbTitles in this Tdb.
*
* @return the total TdbTitle count
*/
public int getTdbTitleCount() {
int titleCount = 0;
for (TdbPublisher publisher : tdbPublisherMap.values()) {
titleCount += publisher.getTdbTitleCount();
}
return titleCount;
}
/**
* Return the number of TdbPublishers in this Tdb.
*
* @return the total TdbPublisher count
*/
public int getTdbPublisherCount() {
return tdbPublisherMap.size();
}
/**
* Return the number of TdbProviders in this Tdb.
*
* @return the total TdbProvider count
*/
public int getTdbProviderCount() {
return tdbProviderMap.size();
}
/**
* Add a new TdbAu from properties. This method recognizes
* properties of the following form:
* <pre>
* Properties p = new Properties();
* p.setProperty("title", "Air & Space Volume 1)");
* p.setProperty("journalTitle", "Air and Space");
* p.setProperty("plugin", "org.lockss.plugin.smithsonian.SmithsonianPlugin");
* p.setProperty("pluginVersion", "4");
* p.setProperty("issn", "0886-2257");
* p.setProperty("param.1.key", "volume");
* p.setProperty("param.1.value", "1");
* p.setProperty("param.2.key", "year");
* p.setProperty("param.2.value", "2001");
* p.setProperty("param.2.editable", "true");
* p.setProperty("param.3.key", "journal_id");
* p.setProperty("param.3.value", "0886-2257");
* p.setProperty("attributes.publisher", "Smithsonian Institution");
* </pre>
* <p>
* The "attributes.publisher" property is used to identify the publisher.
* If a unique journalID is specified it is used to select among titles
* for a publisher. A journalID can be specified indirectly through a
* "journal_id" param or an "issn" property. If a journalId is not
* specified, the "journalTitle" property is used to select the the title.
* <p>
* Properties other than "param", "attributes", "title", "journalTitle",
* "journalId", and "plugin" are converted to attributes of the AU. Only
* "title" and "plugin" are required properties. If "attributes.publisher"
* or "journalTitle" are missing, their values are synthesized from the
* "title" property.
*
* @param props a map of title properties
* @return the TdbAu that was added
* @throws TdbException if this Tdb is sealed, or the
* AU already exists in this Tdb
*/
public TdbAu addTdbAuFromProperties(Properties props) throws TdbException {
if (props == null) {
throw new IllegalArgumentException("properties cannot be null");
}
// verify not sealed
if (isSealed()) {
throw new TdbException("cannot add au to sealed TDB");
}
// generate new TdbAu from properties
TdbAu au = newTdbAu(props);
// add au for plugin assuming it is not a duplicate
try {
addTdbAuForPlugin(au);
} catch (TdbException ex) {
// au already registered -- report existing au
TdbAu existingAu = getTdbAuById(au);
String titleName = getTdbTitleName(props, au);
if (!titleName.equals(existingAu.getTdbTitle().getName())) {
throw new TdbException(
"Cannot add duplicate au entry: \"" + au.getName()
+ "\" for title \"" + titleName
+ "\" with same definition as existing au entry: \""
+ existingAu.getName() + "\" for title \""
+ existingAu.getTdbTitle().getName() + "\" to title database");
} else if (!existingAu.getName().equals(au.getName())) {
// error because it could lead to a missing AU -- one probably has a typo
throw new TdbException(
"Cannot add duplicate au entry: \"" + au.getName()
+ "\" with the same definition as \"" + existingAu.getName()
+ "\" for title \"" + titleName + "\" to title database");
} else {
throw new TdbException(
"Cannot add duplicate au entry: \"" + au.getName()
+ "\" for title \"" + titleName + "\" to title database");
}
}
// get or create the TdbTitle for this
TdbTitle title = getTdbTitle(props, au);
try {
// add AU to title
title.addTdbAu(au);
} catch (TdbException ex) {
// if we can't add au to title, remove for plugin and re-throw exception
removeTdbAuForPlugin(au);
throw ex;
}
// get or create the TdbProvider for this
TdbProvider provider = getTdbProvider(props, au);
try {
// add AU to title
provider.addTdbAu(au);
} catch (TdbException ex) {
// if we can't add au to provider, remove for plugin and title,
// and re-throw exception
removeTdbAuForPlugin(au);
// TODO: what to do about unregistering with the tdbTitle?
throw ex;
}
// process title links
Map<String, Map<String,String>> linkMap = new HashMap<String, Map<String,String>>();
for (Map.Entry<Object,Object> entry : props.entrySet()) {
String key = ""+entry.getKey();
String value = ""+entry.getValue();
if (key.startsWith("journal.link.")) {
// skip to link name
String param = key.substring("link.".length());
int i;
if ( ((i = param.indexOf(".type")) < 0)
&& ((i = param.indexOf(".journalId")) < 0)) {
logger.warning("Ignoring nexpected link key for au \"" + au.getName() + "\" key: \"" + key + "\"");
} else {
// get link map for linkName
String lname = param.substring(0,i);
Map<String,String> lmap = linkMap.get(lname);
if (lmap == null) {
lmap = new HashMap<String,String>();
linkMap.put(lname, lmap);
}
// add name and value to link map for link
String name = param.substring(i+1);
lmap.put(name, value);
}
}
}
// add links to title from accumulated "type", "journalId" entries
for (Map<String, String> lmap : linkMap.values()) {
String name = lmap.get("type");
String value = lmap.get("journalId");
if ((name != null) && (value != null)) {
try {
TdbTitle.LinkType linkType = TdbTitle.LinkType.valueOf(name);
title.addLinkToTdbTitleId(linkType, value);
} catch (IllegalArgumentException ex) {
logger.warning("Ignoring unknown link type for au \"" + au.getName() + "\" name: \"" + name + "\"");
}
}
}
return au;
}
/**
* Create a new TdbAu instance from the properties.
*
* @param props the properties
* @return a TdbAu instance set built from the properties
*/
private TdbAu newTdbAu(Properties props) {
String pluginId = (String)props.get("plugin");
if (pluginId == null) {
throw new IllegalArgumentException("TdbAu plugin ID not specified");
}
String auName = props.getProperty("title");
if (auName == null) {
throw new IllegalArgumentException("TdbAu title not specified");
}
// create a new TdbAu and set its elements
TdbAu au = new TdbAu(auName, pluginId);
// process attrs, and params
Map<String, Map<String,String>> paramMap = new HashMap<String, Map<String,String>>();
for (Map.Entry<Object,Object> entry : props.entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
if (key.startsWith("attributes.")) {
// set attributes directly
String name = key.substring("attributes.".length());
try {
au.setAttr(name, value);
} catch (TdbException ex) {
logger.warning("Cannot set attribute \"" + name + "\" with value \"" + value + "\" -- ignoring");
}
} else if (key.startsWith("param.")) {
// skip to param name
String param = key.substring("param.".length());
int i;
if ( ((i = param.indexOf(".key")) < 0)
&& ((i = param.indexOf(".value")) < 0)) {
logger.warning("Ignoring unexpected param key for au \"" + auName + "\" key: \"" + key + "\" -- ignoring");
} else {
// get param map for pname
String pname = param.substring(0,i);
Map<String,String> pmap = paramMap.get(pname);
if (pmap == null) {
pmap = new HashMap<String,String>();
paramMap.put(pname, pmap);
}
// add name and value to param map for pname
String name = param.substring(i+1);
pmap.put(name, value);
}
} else if ( !key.equals("title") // TdbAu has "name" property
&& !key.equals("plugin") // TdbAu has "pluginId" property
&& !key.equals("journalTitle") // TdbAu has "title" TdbTitle property
&& !key.startsWith("journal.")) { // TdbAu has "title" TdbTitle property
// translate all other properties into AU properties
try {
au.setPropertyByName(key, value);
} catch (TdbException ex) {
logger.warning("Cannot set property \"" + key + "\" with value \"" + value + "\" -- ignoring");
}
}
}
// set param from accumulated "key", and "value" entries
for (Map<String, String> pmap : paramMap.values()) {
String name = pmap.get("key");
String value = pmap.get("value");
if (name == null) {
logger.warning("Ignoring property with null name");
} else if (value == null) {
logger.warning("Ignoring property \"" + name + "\" with null value");
} else {
try {
au.setParam(name, value);
} catch (TdbException ex) {
logger.warning("Cannot set param \"" + name + "\" with value \"" + value + "\" -- ignoring");
}
}
}
return au;
}
/**
* Get title ID from properties and TdbAu.
*
* @param props the properties
* @param au the TdbAu
* @return the title ID or <code>null</code> if not found
*/
private String getTdbTitleId(Properties props, TdbAu au) {
// get the title ID from one of several props
String titleId = props.getProperty("journalId");
return titleId;
}
/**
* Get or create TdbTitle for the specified properties and TdbAu.
*
* @param props the properties
* @param au the TdbAu
* @return the corresponding TdbTitle
*/
private TdbTitle getTdbTitle(Properties props, TdbAu au) {
TdbTitle title = null;
// get publisher name
String publisherNameFromProps = getTdbPublisherName(props, au);
// get the title name
String titleNameFromProps = getTdbTitleName(props, au);
// get the title ID
String titleIdFromProps = getTdbTitleId(props, au);
String titleId = titleIdFromProps;
if (titleId == null) {
// generate a titleId if one not specified, using the
// hash code of the combined title name and publisher names
int hash = (titleNameFromProps + publisherNameFromProps).hashCode();
titleId = (hash < 0) ? ("id:1" +(-hash)) : ("id:0" + hash);
}
// get publisher specified by property name
TdbPublisher publisher = tdbPublisherMap.get(publisherNameFromProps);
if (publisher != null) {
// find title from publisher
title = publisher.getTdbTitleById(titleId);
if (title != null) {
// warn that title name is different
if (!title.getName().equals(titleNameFromProps)) {
logger.warning("Title for au \"" + au.getName() + "\": \"" + titleNameFromProps
+ "\" is different than existing title \"" + title.getName()
+ "\" for id " + titleId + " -- using existing title.");
}
return title;
}
}
if (publisher == null) {
// warn of missing publisher name
if (publisherNameFromProps.startsWith(UNKNOWN_PUBLISHER_PREFIX)) {
logger.warning("Publisher missing for au \"" + au.getName() + "\" -- using \"" + publisherNameFromProps + "\"");
}
// create new publisher for specified publisher name
publisher = new TdbPublisher(publisherNameFromProps);
tdbPublisherMap.put(publisherNameFromProps, publisher);
}
// warn of missing title name and/or id
if (titleNameFromProps.startsWith(UNKNOWN_TITLE_PREFIX)) {
logger.warning("Title missing for au \"" + au.getName() + "\" -- using \"" + titleNameFromProps + "\"");
}
if (titleIdFromProps == null) {
logger.debug2("Title ID missing for au \"" + au.getName() + "\" -- using " + titleId);
}
// create title and add to publisher
title = new TdbTitle(titleNameFromProps, titleId);
try {
publisher.addTdbTitle(title);
} catch (TdbException ex) {
// shouldn't happen: title already exists in publisher
logger.error(ex.getMessage(), ex);
}
return title;
}
/**
* Get or create TdbProvider for the specified properties and TdbAu.
*
* @param props the properties
* @param au the TdbAu
* @return the corresponding TdbProvider
*/
private TdbProvider getTdbProvider(Properties props, TdbAu au) {
// get publisher name
String providerNameFromProps = getTdbProviderName(props, au);
// get publisher specified by property name
TdbProvider provider = tdbProviderMap.get(providerNameFromProps);
if (provider == null) {
// warn of missing provider name
if (providerNameFromProps.startsWith(UNKNOWN_PROVIDER_PREFIX)) {
logger.warning("Provider missing for au \"" + au.getName()
+ "\" -- using \"" + providerNameFromProps + "\"");
}
// create new publisher for specified publisher name
provider = new TdbProvider(providerNameFromProps);
tdbProviderMap.put(providerNameFromProps, provider);
}
return provider;
}
/**
* Get provider name from properties and TdbAu. Uses the
* pubisher name as the provider name if not specified.
*
* @param props the properties
* @param au the TdbAu
* @return the provider name
*/
private String getTdbProviderName(Properties props, TdbAu au) {
// Use "provider" attribute if specified.
// Otherwise use the publisher name as the provider name.
String providerName = props.getProperty("attributes.provider");
if (providerName == null) {
providerName = au.getPublisherName();
if (providerName == null) {
providerName = getTdbPublisherName(props, au);
if (providerName == null) {
// create provider name from au name as last resort
providerName = UNKNOWN_PROVIDER_PREFIX + "[" + au.getName() + "]";
}
}
}
return providerName;
}
/**
* Get publisher name from properties and TdbAu. Creates a name
* based on title name if not specified.
*
* @param props the properties
* @param au the TdbAu
* @return the publisher name
*/
private String getTdbPublisherName(Properties props, TdbAu au) {
// use "publisher" attribute if specified, or synthesize from titleName.
// proposed to replace with publisher.name property
String publisherName = props.getProperty("attributes.publisher");
if (publisherName == null) {
publisherName = props.getProperty("publisher.name"); // proposed new property
}
if (publisherName == null) {
// create publisher name from title name if not specified
String titleName = getTdbTitleName(props, au);
publisherName = UNKNOWN_PUBLISHER_PREFIX + "[" + titleName + "]";
}
return publisherName;
}
/**
* Get TdbTitle name from properties alone.
*
* @param props a group of properties
* @return
*/
private String getTdbTitleName(Properties props) {
// from auName and one of several properties
String titleName = props.getProperty("journalTitle");
if (titleName == null) {
titleName = props.getProperty("journal.title"); // proposed to replace journalTitle
}
return titleName;
}
/**
* Get the TdbTitle name from the properties. Fall back to a name
* derived from the TdbAU name if not specified.
*
* @param props a group of properties
* @param au the TdbAu
* @return a TdbTitle name
*/
private String getTdbTitleName(Properties props, TdbAu au) {
// use "journalTitle" prop if specified, or synthesize it
// from auName and one of several properties
String titleName = getTdbTitleName(props);
if (titleName == null) {
String year = au.getYear();
String volume = au.getVolume();
String issue = au.getIssue();
String auName = au.getName();
String auNameLC = auName.toLowerCase();
if ((volume != null) && auNameLC.endsWith(" vol " + volume)) {
titleName = auName.substring(0, auName.length()-" vol ".length() - volume.length());
} else if ((volume != null) && auNameLC.endsWith(" volume " + volume)) {
titleName = auName.substring(0, auName.length()-" volume ".length() - volume.length());
} else if ((issue != null) && auNameLC.endsWith(" issue " + issue)) {
titleName = auName.substring(0, auName.length()-" issue ".length() - issue.length());
} else if ((year != null) && auNameLC.endsWith(" " + year)) {
titleName = auName.substring(0, auName.length()-" ".length() - year.length());
} else {
titleName = UNKNOWN_TITLE_PREFIX + "[" + auName + "]";
}
}
return titleName;
}
/**
* Get the linked titles for the specified link type.
*
* @param linkType the link type (see {@link TdbTitle} for description of
* link types)
* @param title the TdbTitle with links
* @return a collection of linked titles for the specified type
*/
public Collection<TdbTitle> getLinkedTdbTitlesForType(
TdbTitle.LinkType linkType, TdbTitle title) {
if (linkType == null) {
throw new IllegalArgumentException("linkType cannot be null");
}
if (title == null) {
throw new IllegalArgumentException("title cannot be null");
}
Collection<String> titleIds = title.getLinkedTdbTitleIdsForType(linkType);
if (titleIds.isEmpty()) {
return Collections.emptyList();
}
ArrayList<TdbTitle> titles = new ArrayList<TdbTitle>();
for (String titleId : titleIds) {
TdbTitle aTitle = getTdbTitleById(titleId);
if (aTitle != null) {
titles.add(aTitle);
}
}
titles.trimToSize();
return titles;
}
/**
* Get the title for the specified titleId. Only the first matchine
* title is returned.
*
* @param titleId the titleID
* @return the title for the titleId or <code>null</code. if not found
*/
public TdbTitle getTdbTitleById(String titleId)
{
if (titleId != null) {
for (TdbPublisher publisher : tdbPublisherMap.values()) {
TdbTitle title = publisher.getTdbTitleById(titleId);
if (title != null) {
return title;
}
}
}
return null;
}
/**
* Get the TdbTitles with the specified titleid.
* @param titleId the title ID
* @return a collection of matching titleids
*/
public Collection<TdbTitle> getTdbTitlesById(String titleId) {
Collection<TdbTitle> tdbTitles = new ArrayList<TdbTitle>();
getTdbTitlesById(titleId, tdbTitles);
return tdbTitles;
}
/**
* Add the TdbTitles with the specified titleid to the collection.
* @param titleId the title ID
* @param matchingTdbTitles the collection of matching TdbTitles
* @return <code>true</code> if items were added, else <code>false></code>
*/
public boolean getTdbTitlesById(String titleId,
Collection<TdbTitle> matchingTdbTitles) {
boolean added = false;
if (titleId != null) {
for (TdbPublisher publisher : tdbPublisherMap.values()) {
// titleId constrained to be unique for a given publisher
TdbTitle title = publisher.getTdbTitleById(titleId);
if (title != null) {
added |= matchingTdbTitles.add(title);
}
}
}
return added;
}
/**
* Get a title for the specified issn. Only the first matching title
* is returned.
*
* @param issn the issn
* @return the title for the titleId or <code>null</code. if not found
*/
public TdbTitle getTdbTitleByIssn(String issn)
{
if (issn != null) {
for (TdbPublisher publisher : tdbPublisherMap.values()) {
TdbTitle title = publisher.getTdbTitleByIssn(issn);
if (title != null) {
return title;
}
}
}
return null;
}
/**
* Return a collection of TdbTitles for this TDB that match the ISSN.
* @param issn the ISSN
* @return a colleciton of TdbTitles that match the ISSN
*/
public Collection<TdbTitle> getTdbTitlesByIssn(String issn) {
Collection<TdbTitle> tdbTitles = new ArrayList<TdbTitle>();
getTdbTitlesByIssn(issn, tdbTitles);
return tdbTitles;
}
/**
* Add a collection of TdbTitles for this TDB that match the ISBN.
* @param issn the ISSN
* @param matchingTdbTitles the collection of TdbTitles
* @return <code>true</code> if titles were added, else <code>false</code>
*/
public boolean getTdbTitlesByIssn(String issn,
Collection<TdbTitle> matchingTdbTitles) {
boolean added = false;
if (issn != null) {
for (TdbPublisher publisher : tdbPublisherMap.values()) {
added |= publisher.getTdbTitlesByIssn(issn, matchingTdbTitles);
}
}
return added;
}
/**
* Return a collection of TdbAus for this TDB that match the ISBN.
*
* @return a colleciton of TdbAus that match the ISBN
*/
public Collection<TdbAu> getTdbAusByIsbn(String isbn) {
Collection<TdbAu> tdbAus = new ArrayList<TdbAu>();
getTdbAusByIsbn(isbn, tdbAus);
return tdbAus;
}
/**
* Add to a collection of TdbAus for this TDB that match the ISBN.
* @param isbn the ISSN
* @param matchingTdbAus
*/
public boolean getTdbAusByIsbn(String isbn,
Collection<TdbAu> matchingTdbAus) {
boolean added = false;
if (isbn != null) {
for (TdbPublisher tdbPublisher : tdbPublisherMap.values()) {
added |= tdbPublisher.getTdbAusByIsbn(matchingTdbAus, isbn);
}
}
return added;
}
/**
* Returns a collection of TdbTitles for the specified title name
* across all publishers.
*
* @param titleName the title name
* @return a collection of TdbTitles that match the title name
*/
public Collection<TdbTitle> getTdbTitlesByName(String titleName)
{
ArrayList<TdbTitle> titles = new ArrayList<TdbTitle>();
getTdbTitlesByName(titleName, titles);
titles.trimToSize();
return titles;
}
/**
* Adds to a collection of TdbTitles for the specified title name
* across all publishers.
*
* @param titleName the title name
* @param titles the collection of TdbTitles to add to
* @return <code>true</code> if TdbTitles were adddthe titles collection
*/
public boolean getTdbTitlesByName(String titleName,
Collection<TdbTitle> titles) {
boolean added = false;
if (titleName != null) {
for (TdbPublisher publisher : tdbPublisherMap.values()) {
added |= publisher.getTdbTitlesByName(titleName, titles);
}
}
return added;
}
/**
* Returns a collection of TdbTitles like (starts with) the
* specified title name across all publishers.
*
* @param titleName the title name
* @return a collection of TdbTitles that match the title name
*/
public Collection<TdbTitle> getTdbTitlesLikeName(String titleName)
{
ArrayList<TdbTitle> titles = new ArrayList<TdbTitle>();
getTdbTitlesLikeName(titleName, titles);
titles.trimToSize();
return titles;
}
/**
* Adds to a collection of TdbTitles like (starts with) the
* specified title name across all publishers.
*
* @param titleName the title name
* @param titles a collection of matching titles
* @return a collection of TdbTitles that match the title name
*/
public boolean getTdbTitlesLikeName(String titleName,
Collection<TdbTitle> titles) {
boolean added = false;
if (titleName != null) {
for (TdbPublisher publisher : tdbPublisherMap.values()) {
added |= publisher.getTdbTitlesLikeName(titleName, titles);
}
}
return added;
}
/**
* Return the TdbAus with the specified TdbAu name (ignoring case).
*
* @param tdbAuName the name of the AU to select
* @return all TdbAus with the specified name
*/
public Collection<TdbAu> getTdbAusByName(String tdbAuName) {
ArrayList<TdbAu> aus = new ArrayList<TdbAu>();
getTdbAusByName(tdbAuName, aus);
return aus;
}
/**
* Add TdbAus with the specified TdbAu name.
*
* @param tdbAuName the name of the AU to select
* @param aus the collection to add to
* @return <code>true</code> if TdbAus were added to the collection
*/
public boolean getTdbAusByName(String tdbAuName, Collection<TdbAu> aus) {
boolean added = false;
for (TdbPublisher publisher : tdbPublisherMap.values()) {
added |= publisher.getTdbAusByName(tdbAuName, aus);
}
return added;
}
/**
* Return the TdbAus like (starts with, ignoring case) the specified
* TdbAu name.
*
* @param tdbAuName initial substring of the name of AUs to return
* @return all TdbAus like the specified name
*/
public List<TdbAu> getTdbAusLikeName(String tdbAuName) {
ArrayList<TdbAu> aus = new ArrayList<TdbAu>();
getTdbAusLikeName(tdbAuName, aus);
return aus;
}
/**
* Add TdbAus for like (starts with) the specified TdbAu name.
*
* @param tdbAuName the name of the AU to select
* @param aus the collection to add to
* @return <code>true</code> if TdbAus were added to the collection
*/
public boolean getTdbAusLikeName(String tdbAuName, Collection<TdbAu> aus) {
boolean added = false;
for (TdbPublisher publisher : tdbPublisherMap.values()) {
added |= publisher.getTdbAusLikeName(tdbAuName, aus);
}
return added;
}
/**
* Get the publisher for the specified name.
*
* @param name the publisher name
* @return the publisher, or <code>null</code> if not found
*/
public TdbPublisher getTdbPublisher(String name) {
return (tdbPublisherMap != null) ? tdbPublisherMap.get(name) : null;
}
/**
* Returns all TdbPubishers in this configuration.
* <p>
* Note: The returned map should not be modified.
*
* @return a map of publisher names to publishers
*/
public Map<String, TdbPublisher> getAllTdbPublishers() {
return (tdbPublisherMap != null)
? tdbPublisherMap : Collections.<String,TdbPublisher>emptyMap();
}
/**
* Get the publisher for the specified name.
*
* @param name the publisher name
* @return the publisher, or <code>null</code> if not found
*/
public TdbProvider getTdbProvider(String name) {
return (tdbProviderMap != null) ? tdbProviderMap.get(name) : null;
}
/**
* Returns all TdbPubishers in this configuration.
* <p>
* Note: The returned map should not be modified.
*
* @return a map of publisher names to publishers
*/
public Map<String, TdbProvider> getAllTdbProviders() {
return (tdbProviderMap != null)
? tdbProviderMap : Collections.<String,TdbProvider>emptyMap();
}
/** ObjectGraphIterator Transformer that descends into collections of
* TdbPublishers and TdbTitles, returning TdbAus */
static Transformer AU_ITER_XFORM = new Transformer() {
public Object transform(Object input) {
if (input instanceof TdbPublisher) {
return ((TdbPublisher)input).tdbTitleIterator();
}
if (input instanceof TdbTitle) {
return ((TdbTitle)input).tdbAuIterator();
}
if (input instanceof TdbAu) {
return input;
}
if (input instanceof TdbProvider) {
return ((TdbProvider)input).tdbAuIterator();
}
throw new
ClassCastException(input+" is not a TdbPublisher, TdbTitle or TdbAu");
}};
/** ObjectGraphIterator Transformer that descends into collections of
* TdbPublishers, returning TdbTitles */
static Transformer TITLE_ITER_XFORM = new Transformer() {
public Object transform(Object input) {
if (input instanceof TdbPublisher) {
return ((TdbPublisher)input).tdbTitleIterator();
}
if (input instanceof TdbTitle) {
return input;
}
throw new
ClassCastException(input+" is not a TdbPublisher or TdbTitle");
}};
/** @return an Iterator over all the TdbProviders in this Tdb. */
public Iterator<TdbProvider> tdbProviderIterator() {
return tdbProviderMap.values().iterator();
}
/** @return an Iterator over all the TdbPublishers in this Tdb. */
public Iterator<TdbPublisher> tdbPublisherIterator() {
return tdbPublisherMap.values().iterator();
}
/** @return an Iterator over all the TdbTitles (in all the TdbPublishers)
* in this Tdb. */
public Iterator<TdbTitle> tdbTitleIterator() {
return new ObjectGraphIterator(tdbPublisherMap.values().iterator(),
TITLE_ITER_XFORM);
}
/** @return an Iterator over all the TdbAus (in all the TdbTitles in all
* the TdbPublishers) in this Tdb. */
public Iterator<TdbAu> tdbAuIterator() {
return new ObjectGraphIterator(tdbPublisherMap.values().iterator(),
AU_ITER_XFORM);
}
/** Print a full description of all elements in the Tdb */
public void prettyPrint(PrintStream ps) {
ps.println("Tdb");
TreeMap<String, TdbPublisher> sorted =
new TreeMap<String, TdbPublisher>(CatalogueOrderComparator.SINGLETON);
sorted.putAll(getAllTdbPublishers());
for (TdbPublisher tdbPublisher : sorted.values()) {
tdbPublisher.prettyPrint(ps, 2);
}
}
/** Differences represents the changes in a Tdb from the previous Tdb,
* primarily oriented toward enumerating the changes (rather than testing
* containment as with {@link Configuration.Differences}). It currently
* retains only additions and changes, as deletions aren't needed (and
* would require holding on to objects that could otherwise be GCed).
*/
public static class Differences {
enum Type {Old, New}
// newly added providers
private final Set<TdbProvider> newProviders
= new HashSet<TdbProvider>();;
// newly added publishers
private final Set<TdbPublisher> newPublishers
= new HashSet<TdbPublisher>();;
// titles that have been added to existing publishers
private final Set<TdbTitle> newTitles = new HashSet<TdbTitle>();;
// AUs that have been added to existing titles
private final Set<TdbAu> newAus = new HashSet<TdbAu>();
// Retained for compatibility with legacy Plugin/TitleConfig mechanism
private final Set<String> diffPluginIds = new HashSet<String>();
private int tdbAuCountDiff;
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[Tdb.Diffa");
if (!newPublishers.isEmpty()) {
sb.append(" newPubs: ");
sb.append(newPublishers);
}
if (!newTitles.isEmpty()) {
sb.append(" newTitles: ");
sb.append(newTitles);
}
if (!newAus.isEmpty()) {
sb.append(" newAus: ");
sb.append(newAus);
}
sb.append("]");
return sb.toString();
}
Differences() {
}
Differences(Tdb newTdb, Tdb oldTdb) {
tdbAuCountDiff =
newTdb.getTdbAuCount()-((oldTdb == null) ? 0 : oldTdb.getTdbAuCount());
newTdb.addDifferences(this, oldTdb);
}
/** Return the ID of every plugin that has at least one changed or
* added or removed AU */
Set<String> getPluginIdsForDifferences() {
return diffPluginIds;
}
/** Return the difference in number of AUs from old to new Tdb. */
public int getTdbAuDifferenceCount() {
return tdbAuCountDiff;
}
/** @return an Iterator over all the newly added TdbPublishers. */
public Iterator<TdbPublisher> newTdbPublisherIterator() {
return newPublishers.iterator();
}
/** @return an Iterator over all the newly added TdbTitles, including
* those belonging to newly added TdbPublishers. */
public Iterator<TdbTitle> newTdbTitleIterator() {
return new IteratorChain(new ObjectGraphIterator(newPublishers.iterator(),
TITLE_ITER_XFORM),
newTitles.iterator());
}
/** @return an Iterator over all the newly added or changed TdbAus, */
public Iterator<TdbAu> newTdbAuIterator() {
return new IteratorChain(new Iterator[] {
new ObjectGraphIterator(newPublishers.iterator(),
AU_ITER_XFORM),
new ObjectGraphIterator(newTitles.iterator(),
AU_ITER_XFORM),
newAus.iterator()
});
}
/** Return the {@link TdbProvider}s that appear in the new Tdb and not
* the old. */
public Set<TdbProvider> rawNewTdbProviders() {
return newProviders;
}
/** Return the {@link TdbPublisher}s that appear in the new Tdb and not
* the old. */
public Set<TdbPublisher> rawNewTdbPublishers() {
return newPublishers;
}
/** Return the {@link TdbTitle}s that have been added to existing
* {@link TdbPublisher}s. To get the entire set of new titles, use
* {@link #newTdbTitleIterator()}. */
public Set<TdbTitle> rawNewTdbTitles() {
return newTitles;
}
/** Return the {@link TdbAu}s that have been added to existing
* {@link TdbTitle}s. To get the entire set of new AUs, use
* {@link #newTdbAuIterator()}. */
public Set<TdbAu> rawNewTdbAus() {
return newAus;
}
void addPluginId(String id) {
diffPluginIds.add(id);
}
void addProvider(TdbProvider provider, Type type) {
switch (type) {
case New:
newProviders.add(provider);
break;
}
provider.addAllPluginIds(this);
}
void addPublisher(TdbPublisher pub, Type type) {
switch (type) {
case New:
newPublishers.add(pub);
break;
}
pub.addAllPluginIds(this);
}
void addTitle(TdbTitle title, Type type) {
switch (type) {
case New:
newTitles.add(title);
break;
}
title.addAllPluginIds(this);
}
void addAu(TdbAu au, Type type) {
switch (type) {
case New:
newAus.add(au);
break;
}
addPluginId(au.getPluginId());
}
static class Unmodifiable extends Differences {
void addProvider(TdbProvider provider, Type type) {
throw new UnsupportedOperationException(
"Can't modify unmodifiable Differences");
}
void addPublisher(TdbPublisher pub, Type type) {
throw new UnsupportedOperationException(
"Can't modify unmodifiable Differences");
}
void addTitle(TdbTitle title, Type type) {
throw new UnsupportedOperationException(
"Can't modify unmodifiable Differences");
}
void addAu(TdbAu au, Type type) {
throw new UnsupportedOperationException(
"Can't modify unmodifiable Differences");
}
void addPluginId(String id) {
throw new UnsupportedOperationException(
"Can't modify unmodifiable Differences");
}
}
}
/** Implements Differences(tdb, null) efficiently */
public static class AllDifferences extends Differences {
private Tdb tdb;
public String toString() {
return "[Tdb.Diffa: all]";
}
AllDifferences(Tdb newTdb) {
tdb = newTdb;
}
/** Return the ID of every plugin that has at least one changed or
* added or removed AU */
Set<String> getPluginIdsForDifferences() {
return tdb.pluginIdTdbAuIdsMap.keySet();
}
/** Return the difference in number of AUs from old to new Tdb. */
public int getTdbAuDifferenceCount() {
return tdb.getTdbAuCount();
}
/** @return an Iterator over all the newly added TdbPublishers. */
public Iterator<TdbProvider> newTdbProviderIterator() {
return tdb.tdbProviderIterator();
}
/** @return an Iterator over all the newly added TdbPublishers. */
public Iterator<TdbPublisher> newTdbPublisherIterator() {
return tdb.tdbPublisherIterator();
}
/** @return an Iterator over all the newly added TdbTitles, including
* those belonging to newly added TdbPublishers. */
public Iterator<TdbTitle> newTdbTitleIterator() {
return tdb.tdbTitleIterator();
}
/** @return an Iterator over all the newly added or changed TdbAus, */
public Iterator<TdbAu> newTdbAuIterator() {
return tdb.tdbAuIterator();
}
/** Return the {@link TdbProvider}s that appear in the new Tdb and not
* the old. */
public Set<TdbProvider> rawNewTdbProviders() {
return SetUtil.fromIterator(newTdbProviderIterator());
}
/** Return the {@link TdbPublisher}s that appear in the new Tdb and not
* the old. */
public Set<TdbPublisher> rawNewTdbPublishers() {
return SetUtil.fromIterator(newTdbPublisherIterator());
}
/** Return the {@link TdbTitle}s that have been added to existing
* {@link TdbPublisher}s. To get the entire set of new titles, use
* {@link #newTdbTitleIterator()}. */
public Set<TdbTitle> rawNewTdbTitles() {
return Collections.emptySet();
}
/** Return the {@link TdbAu}s that have been added to existing
* {@link TdbTitle}s. To get the entire set of new AUs, use
* {@link #newTdbAuIterator()}. */
public Set<TdbAu> rawNewTdbAus() {
return Collections.emptySet();
}
}
}
|
package org.team2168;
import org.team2168.PIDController.sensors.AverageEncoder;
import org.team2168.utils.ConstantsBase;
import edu.wpi.first.wpilibj.CounterBase;
/**
* The RobotMap defines constants that are used throughout the robot classes.
* Things you'll find here:
* - which port all the input/output devices are wired to.
* - control system parameters
*
* This provides a single, centralized, location to make wiring/parameter
* modifications.
*/
public class RobotMap extends ConstantsBase {
public static final Constant debug =
new Constant("debug", 0);
//PWM Channels////////////////////////////////////////////////////
public static final Constant rightDriveMotor =
new Constant("rightDriveMotor", 1);
public static final Constant leftDriveMotor =
new Constant("leftDriveMotor", 2);
public static final Constant winchMotor = new Constant("winchMotor", 3);
public static final Constant intakeMotor = new Constant("intakeMotor", 4);
public static final Constant visionServo = new Constant("visionServo", 10);
//DIO Channels////////////////////////////////////////////////////
public static final Constant driveTrainEncoderRightA =
new Constant("driveTrainEncoderRightA",1);
public static final Constant driveTrainEncoderRightB =
new Constant("driveTrainEncoderRightB",2);
public static final Constant driveTrainEncoderLeftA =
new Constant("driveTrainEncoderLeftA",3);
public static final Constant driveTrainEncoderLeftB =
new Constant("driveTrainEncoderLeftB",4);
public static final Constant winchLimitSwitch =
new Constant("winchLimitSwitch",5);
public static final Constant winchEncoderA =
new Constant("winchEncoderA", 6);
public static final Constant winchEncoderB =
new Constant("winchEncoderB", 7);
public static final Constant intakeDownLimitSwitch =
new Constant("intakeDownLimitSwitch", 8);
public static final Constant pressureSwitch =
new Constant("pressureSwitch", 14);
//Relay Output Channels///////////////////////////////////////////
public static final Constant flashlightRelay =
new Constant("flashlightRelay", 1);
public static final Constant compressorRelay =
new Constant("compressorRelay", 2);
//Solenoid Channels(third slot on cRio)///////////////////////////
public static final Constant intakeExtPort =
new Constant("intakeExtPort", 1);
public static final Constant intakeRetPort =
new Constant("intakeRetPort", 2);
public static final Constant winchExtPort = new Constant("winchExtPort", 3);
public static final Constant winchRetPort = new Constant("winchRetPort", 4);
public static final Constant catExtPort1 = new Constant("catExtPort1", 5);
public static final Constant catRetPort1 = new Constant("catRetPort1", 6);
public static final Constant catExtPort2 = new Constant("catExtPort2", 7);
public static final Constant catRetPort2 = new Constant("catRetPort2", 8);
//Solenoid Channels(fourth slot on cRio)//////////////////////////
//Analog Input Channels///////////////////////////////////////////
public static final Constant gyroPort = new Constant("gyroPort", 1);
public static final Constant ballSensorPort =
new Constant("ballSensorPort", 2);
public static final Constant potentiometerPort =
new Constant("potentiometerPort", 3);
public static final Constant wheelDiameterDrivetrain =
new Constant("wheelDiameterDriveTrain", 3.0330);
public static final Constant ticksPerRevolutionDrivetrain =
new Constant("ticksPerRevolutionDrivetrain", 256);
public static final Constant drivetrainGearRatio =
new Constant("drivetrainGearRatio",(24.0/27.0));
public static final Constant driveRateLimit =
new Constant("driveRateLimit", 0.15);
public static final Constant rotateDriveKP =
new Constant("rotateDriveKP", 0.06);
public static final Constant rotateDriveMaxSpeed =
new Constant("rotateDriveMaxSpeed", 0.8);
private static final int drivePulsePerRotation = 256; //encoder ticks per rotation
private static final double driveGearRatio = 24.0/27.0; //ratio between wheel over encoder
public static final int driveEncoderPulsePerRot = (int) (drivePulsePerRotation*driveGearRatio); //pulse per rotation * gear ratio
public static final double driveEncoderDistPerTick = (Math.PI * wheelDiameterDrivetrain.getDouble())/driveEncoderPulsePerRot;
public static final CounterBase.EncodingType driveEncodingType = CounterBase.EncodingType.k4X; //count rising and falling edges on both channels
public static final AverageEncoder.PositionReturnType drivePosReturnType = AverageEncoder.PositionReturnType.INCH;
public static final AverageEncoder.SpeedReturnType driveSpeedReturnType = AverageEncoder.SpeedReturnType.RPM;
public static final int driveEncoderMinRate = 10;
public static final int driveEncoderMinPeriod = 10;
public static final boolean leftDriveTrainEncoderReverse = false;
public static final boolean rightDriveTrainEncoderReverse = true;
public static final int driveAvgEncoderVal = 5;
public static final Constant tuskIntermediatePositionDelay =
new Constant("tuskIntermediatePositionDelay", 0.1);
public static final Constant wheelDiameterWinch =
new Constant("wheelDiameterWinch", 2);
public static final Constant catapultWinchUp =
new Constant("catapultWinchUp", 4.0);
public static final Constant catapultWinchDown =
new Constant("catapultWinchDown", 1.0);
public static final Constant retractWinchSpeed =
new Constant("retractWinchSpeed", 1.0);
public static final Constant catapultRaiseAngle =
new Constant("catapultRaiseAngle", 44.0);
public static final Constant catapultRaiseVoltage =
new Constant("catapultRaiseVoltage", 2.79);
public static final Constant catapultLowerAngle =
new Constant("catapultLowerAngle", -26.0);
public static final Constant catapultLowerVoltage =
new Constant("catapultLowerVoltage", 3.83);
public static final Constant catapultWaitUntilFiredAngle =
new Constant("catapultWaitUntilFiredAngle", 30.0);
//TODO: Determine appropriate threshold voltage value for ball presence
public static final Constant catapultBallPresentVoltage =
new Constant("catapultBallPresentVoltage", 2.0);
private static final int winchPulsePerRotation = 256; //encoder ticks per rotation
private static final double winchGearRatio = 1.0/1.0; //ratio between wheel over encoder
private static final double winchStrapThickness = 3.0/32.0; //thickness of the strap that winds the winch up
public static final int winchEncoderPulsePerRot = (int) (winchPulsePerRotation*winchGearRatio); //pulse per rotation * gear ratio
public static final double winchEncoderDistPerTick = (Math.PI * wheelDiameterWinch.getDouble())/winchEncoderPulsePerRot;
public static final CounterBase.EncodingType winchEncodingType = CounterBase.EncodingType.k4X; //count rising and falling edges on both channels
public static final AverageEncoder.PositionReturnType winchPosReturnType = AverageEncoder.PositionReturnType.INCH;
public static final AverageEncoder.SpeedReturnType winchSpeedReturnType = AverageEncoder.SpeedReturnType.RPM;
public static final double winchEncoderMinRate = 0.13;
public static final int winchEncoderMinPeriod = 10;
public static final boolean winchEncoderReverse = true;
public static final int winchAvgEncoderVal = 5;
public static final Constant intakeLowerTimeout =
new Constant("intakeLowerTimeout", 2.5);
public static final Constant minDriveSpeed =
new Constant("minDriveSpeed", 0.2);
public static final Constant flashlightOnTime =
new Constant("flashlightOnTime", 15.0);
public static final Constant rotationAngleToHot =
new Constant("rotationAngleToHot", 10.0);
public static final Constant CameraSteadyStateSecs =
new Constant("CameraSteadyStateSecs", 1.1);
public static final Constant VisionTimeOutSecs =
new Constant("VisionTimeOutSecs", 1.5);
public static final Constant autoDriveDistance =
new Constant("autoDriveDistance", 35);
static {
// Set any overridden constants from the file on startup.
readConstantsFromFile();
}
/**
* Prevent instantiation of this class, as it should only be used
* statically.
*/
private RobotMap() {
}
}
|
package ua.com.fielden.platform.entity.query;
import java.util.HashMap;
import java.util.Map;
import ua.com.fielden.platform.entity.AbstractEntity;
public class EntityFromContainerInstantiatorCache {
private Map<EntityContainer<? extends AbstractEntity<?>>, Object> map = new HashMap<>();
private final EntityFromContainerInstantiator instantiator;
public EntityFromContainerInstantiatorCache(final EntityFromContainerInstantiator instantiator) {
this.instantiator = instantiator;
}
public <R extends AbstractEntity<?>> R getEntity(final EntityContainer<R> entityContainer) {
final AbstractEntity<?> existingEntity = (AbstractEntity<?>) map.get(entityContainer);
if (existingEntity == null) {
final R justAddedEntity = instantiator.instantiateInitially(entityContainer);
map.put(entityContainer, justAddedEntity);
return instantiator.instantiateFully(entityContainer, justAddedEntity);
}
return (R) existingEntity;
}
}
|
package org.yakindu.sct.ui.editor.propertysheets;
import org.eclipse.emf.databinding.EMFDataBindingContext;
import org.eclipse.emf.databinding.IEMFValueProperty;
import org.eclipse.emf.databinding.edit.EMFEditProperties;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.jface.databinding.viewers.ViewerProperties;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.yakindu.sct.model.sgraph.ChoiceKind;
import org.yakindu.sct.model.sgraph.SGraphPackage;
import org.yakindu.sct.ui.editor.propertysheets.OrderElementControl.ISourceObjectCallback;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class ChoicePropertySection extends AbstractEditorPropertySection implements ISourceObjectCallback {
private OrderElementControl orderElementControl;
private ComboViewer choiceKindViewer;
@Override
public void createControls(Composite parent) {
Label label = getToolkit().createLabel(parent, "Choice kind:");
GridDataFactory.fillDefaults().applyTo(label);
choiceKindViewer = new ComboViewer(parent);
GridDataFactory.fillDefaults().grab(true, false).applyTo(choiceKindViewer.getControl());
choiceKindViewer.setContentProvider(new ArrayContentProvider());
choiceKindViewer.setLabelProvider(new LabelProvider());
choiceKindViewer.setInput(ChoiceKind.values());
label = getToolkit().createLabel(parent, "Transition Priority:");
GridDataFactory.fillDefaults().applyTo(label);
orderElementControl = new OrderElementControl(parent, SGraphPackage.Literals.VERTEX__OUTGOING_TRANSITIONS, this);
GridDataFactory.fillDefaults().grab(true, false).applyTo(orderElementControl);
}
@Override
public void bindModel(EMFDataBindingContext context) {
orderElementControl.refreshInput();
bindChoiceKind(context);
}
protected void bindChoiceKind(EMFDataBindingContext context) {
IEMFValueProperty property = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject),
SGraphPackage.Literals.CHOICE__KIND);
context.bindValue(ViewerProperties.singleSelection().observe(choiceKindViewer), property.observe(eObject));
}
// Enhance visibility
@Override
public EObject getEObject() {
return super.getEObject();
}
}
|
package com.opengamma.integration.copier.portfolio.rowparser;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import javax.time.calendar.LocalDate;
import javax.time.calendar.format.DateTimeFormatter;
import javax.time.calendar.format.DateTimeFormatterBuilder;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.master.position.ManageableTrade;
import com.opengamma.master.security.ManageableSecurity;
import com.opengamma.util.ArgumentChecker;
/**
* An abstract row parser class, to be specialised for parsing a specific security/trade/position type from a row's data
*/
public abstract class RowParser {
// CSOFF
/** Standard date-time formatter for the input. */
protected DateTimeFormatter CSV_DATE_FORMATTER;
/** Standard date-time formatter for the output. */
protected DateTimeFormatter OUTPUT_DATE_FORMATTER;
/** Standard rate formatter. */
protected DecimalFormat RATE_FORMATTER = new DecimalFormat("0.
/** Standard notional formatter. */
protected DecimalFormat NOTIONAL_FORMATTER = new DecimalFormat("0,000");
// CSON
{
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.appendPattern("yyyy-MM-dd");
CSV_DATE_FORMATTER = builder.toFormatter();
builder = new DateTimeFormatterBuilder();
builder.appendPattern("yyyy-MM-dd");
OUTPUT_DATE_FORMATTER = builder.toFormatter();
}
/**
* Constructs a row from the supplied trade.
* @param trade The trade to convert
* @return The mapping from column names to contents of the current row
*/
public Map<String, String> constructRow(ManageableTrade trade) {
return new HashMap<String, String>();
}
/**
* Constructs a row from the supplied position.
* @param position The position to convert
* @return The mapping from column names to contents of the current row
*/
public Map<String, String> constructRow(ManageablePosition position) {
return new HashMap<String, String>();
}
/**
* Constructs a row from the supplied securities.
* @param securities The securities to convert (securities following the first are assumed to be underlyings)
* @return The mapping from column names to contents of the current row
*/
public Map<String, String> constructRow(ManageableSecurity[] securities) {
return new HashMap<String, String>();
}
/**
* Constructs a row from the supplied security, position and trade.
* @param securities The securities to convert
* @param position The position to convert
* @param trade The trade to convert
* @return The mapping from column names to contents of the current row
*/
public Map<String, String> constructRow(ManageableSecurity[] securities, ManageablePosition position, ManageableTrade trade) {
ArgumentChecker.notNull(securities, "securities");
ArgumentChecker.notNull(position, "position");
ArgumentChecker.notNull(trade, "trade");
Map<String, String> result = new HashMap<String, String>();
Map<String, String> securityRow = constructRow(securities);
Map<String, String> positionRow = constructRow(position);
Map<String, String> tradeRow = constructRow(trade);
if (securityRow != null) {
result.putAll(securityRow);
}
if (positionRow != null) {
result.putAll(positionRow);
}
if (tradeRow != null) {
result.putAll(tradeRow);
}
return result;
}
/**
* Constructs one or more securities associated with the supplied row. As a convention, the underlying security
* is returned at array location 0.
* @param row The mapping between column names and contents for the current row
* @return An array of securities constructed from the current row's data; underlying is at index 0; null or an
* empty array if unable to construct any securities from the row; this will cause the entire row to be
* skipped (constructPosition() won't be called for that row
*/
public abstract ManageableSecurity[] constructSecurity(Map<String, String> row);
/**
* Constructs a position associated with the supplied row.
* @param row The mapping between column names and contents for the current row
* @param security The associated security
* @return The constructed position or null if position construction failed
*/
public ManageablePosition constructPosition(Map<String, String> row, ManageableSecurity security) {
ArgumentChecker.notNull(row, "row");
ArgumentChecker.notNull(security, "security");
return new ManageablePosition(BigDecimal.ONE, security.getExternalIdBundle());
}
/**
* Constructs a trade associated with the supplied row.
* @param row The mapping between column names and contents for the current row
* @param security The associated security
* @param position The associated position
* @return The constructed trade or null if unable to construct a trade
*/
public ManageableTrade constructTrade(Map<String, String> row, ManageableSecurity security, ManageablePosition position) {
return null;
}
/**
* Gets the list of column names that this particular row parser knows of
* @return A string array containing the column names
*/
public abstract String[] getColumns();
public int getSecurityHashCode() {
return 0;
}
public static String getWithException(Map<String, String> fieldValueMap, String fieldName) {
String result = fieldValueMap.get(fieldName);
if (result == null) {
System.err.println(fieldValueMap);
throw new IllegalArgumentException("Could not find field '" + fieldName + "'");
}
return result;
}
public LocalDate getDateWithException(Map<String, String> fieldValueMap, String fieldName) {
return getDateWithException(fieldValueMap, fieldName, CSV_DATE_FORMATTER);
}
public static LocalDate getDateWithException(Map<String, String> fieldValueMap, String fieldName, DateTimeFormatter formatter) {
return LocalDate.parse(getWithException(fieldValueMap, fieldName), formatter);
}
public static void addValueIfNotNull(Map<String, String> map, String key, Object value) {
if (value != null) {
map.put(key, value.toString());
}
}
}
|
package com.evolveum.midpoint.provisioning.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.common.ResourceObjectPattern;
import com.evolveum.midpoint.common.refinery.RefinedAccountDefinition;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.common.refinery.ResourceShadowDiscriminator;
import com.evolveum.midpoint.prism.PrismContainer;
import com.evolveum.midpoint.prism.PrismContainerDefinition;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.delta.ContainerDelta;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.provisioning.api.GenericConnectorException;
import com.evolveum.midpoint.provisioning.ucf.api.Change;
import com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance;
import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException;
import com.evolveum.midpoint.provisioning.ucf.api.Operation;
import com.evolveum.midpoint.provisioning.ucf.api.PropertyModificationOperation;
import com.evolveum.midpoint.provisioning.ucf.api.ResultHandler;
import com.evolveum.midpoint.provisioning.util.ShadowCacheUtil;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttribute;
import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer;
import com.evolveum.midpoint.schema.processor.ResourceAttributeContainerDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceObjectShadowUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.AccountShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ActivationType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.AvailabilityStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ResourceObjectShadowAttributesType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ResourceObjectShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ResourceType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_2.ActivationCapabilityType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_2.ActivationEnableDisableCapabilityType;
@Component
public class ShadowConverter {
// private static final ItemPath ATTRIBUTES_PATH = new ItemPath(ResourceObjectShadowType.F_ATTRIBUTES);
@Autowired
private ConnectorTypeManager connectorTypeManager;
@Autowired
private PrismContext prismContext;
public ShadowConverter() {
}
public ConnectorTypeManager getConnectorTypeManager() {
return connectorTypeManager;
}
public void setConnectorTypeManager(ConnectorTypeManager connectorTypeManager) {
this.connectorTypeManager = connectorTypeManager;
}
private static final Trace LOGGER = TraceManager.getTrace(ShadowConverter.class);
@SuppressWarnings("unchecked")
public <T extends ResourceObjectShadowType> T getShadow(Class<T> type, ResourceType resource,
T repoShadow, OperationResult parentResult) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, GenericConnectorException {
ObjectClassComplexTypeDefinition objectClassDefinition = applyAttributesDefinition(repoShadow.asPrismObject(), resource);
// Let's get all the identifiers from the Shadow <attributes> part
Collection<? extends ResourceAttribute<?>> identifiers = ResourceObjectShadowUtil
.getIdentifiers(repoShadow);
if (identifiers == null || identifiers.isEmpty()) {
//check if the account is not only partially created (exist only in repo so far)
if (repoShadow.getFailedOperationType() != null) {
throw new GenericConnectorException(
"Unable to get account from the resource. Probably it has not been created yet because of previous unavailability of the resource.");
}
// No identifiers found
SchemaException ex = new SchemaException("No identifiers found in the respository shadow "
+ ObjectTypeUtil.toShortString(repoShadow) + " with respect to resource "
+ ObjectTypeUtil.toShortString(resource));
parentResult.recordFatalError(
"No identifiers found in the respository shadow "
+ ObjectTypeUtil.toShortString(repoShadow), ex);
throw ex;
}
//try to apply changes to the account only if the resource if UP
if (repoShadow.getObjectChange() != null && repoShadow.getFailedOperationType() != null
&& resource.getOperationalState() != null
&& resource.getOperationalState().getLastAvailabilityStatus() == AvailabilityStatusType.UP) {
throw new GenericConnectorException(
"Found changes that have been not applied to the account yet. Trying to apply them now.");
}
Collection<? extends ResourceAttribute<?>> attributes = ResourceObjectShadowUtil
.getAttributes(repoShadow);
if (isProtectedShadow(resource, objectClassDefinition, attributes)) {
LOGGER.error("Attempt to fetch protected resource object " + objectClassDefinition + ": "
+ identifiers + "; ignoring the request");
throw new SecurityViolationException("Cannot get protected resource object "
+ objectClassDefinition + ": " + identifiers);
}
ConnectorInstance connector = getConnectorInstance(resource, parentResult);
T resourceShadow = fetchResourceObject(type, objectClassDefinition, identifiers, connector, resource,
parentResult);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Shadow from repository:\n{}", repoShadow.asPrismObject().dump());
LOGGER.trace("Resource object fetched from resource:\n{}", resourceShadow.asPrismObject().dump());
}
// Complete the shadow by adding attributes from the resource object
T resultShadow = ShadowCacheUtil.completeShadow(resourceShadow, repoShadow, resource, parentResult);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Shadow when assembled:\n", ObjectTypeUtil.dump(resultShadow));
}
parentResult.recordSuccess();
return resultShadow;
}
@SuppressWarnings("unchecked")
public ResourceObjectShadowType addShadow(ResourceType resource, ResourceObjectShadowType shadowType,
Set<Operation> additionalOperations, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException,
ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException {
PrismObject<ResourceObjectShadowType> shadow = shadowType.asPrismObject();
// ObjectClassComplexTypeDefinition objectClass =
applyAttributesDefinition(shadow, resource);
Collection<ResourceAttribute<?>> resourceAttributesAfterAdd = null;
if (isProtectedShadow(resource, shadow)) {
LOGGER.error("Attempt to add protected shadow " + shadowType + "; ignoring the request");
throw new SecurityViolationException("Cannot get protected shadow " + shadowType);
}
ConnectorInstance connector = getConnectorInstance(resource, parentResult);
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("PROVISIONING ADD operation on resource {}\n ADD object:\n{}\n additional operations:\n{}",
new Object[] { resource.asPrismObject(), shadowType.asPrismObject().debugDump(),
SchemaDebugUtil.debugDump(additionalOperations,2) });
}
ResourceAttributeContainerDefinition resourceAttributeDefinition = ResourceObjectShadowUtil
.getObjectClassDefinition(shadowType);
checkActivationAttribute(shadowType, resource, resourceAttributeDefinition);
resourceAttributesAfterAdd = connector.addObject(shadow, additionalOperations, parentResult);
if (LOGGER.isDebugEnabled()) {
// TODO: reduce only to new/different attributes. Dump all
// attributes on trace level only
LOGGER.debug("PROVISIONING ADD successful, returned attributes:\n{}",
SchemaDebugUtil.prettyPrint(resourceAttributesAfterAdd));
}
applyAfterOperationAttributes(shadowType, resourceAttributesAfterAdd);
} catch (CommunicationException ex) {
parentResult.recordFatalError(
"Could not create account on the resource. Error communicating with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with the connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (GenericFrameworkException ex) {
parentResult.recordFatalError("Could not create account on the resource. Generic error in connector: " + ex.getMessage(), ex);
throw new GenericConnectorException("Generic error in connector: " + ex.getMessage(), ex);
} catch (ObjectAlreadyExistsException ex){
parentResult.recordFatalError("Could not create account on the resource. Account already exists on the resource: " + ex.getMessage(), ex);
throw new ObjectAlreadyExistsException("Account already exists on the resource: " + ex.getMessage(), ex);
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Shadow being stored:\n{}", shadowType.asPrismObject().dump());
}
parentResult.recordSuccess();
return shadowType;
}
@SuppressWarnings("unchecked")
public void deleteShadow(ResourceType resource, ResourceObjectShadowType shadow,
Set<Operation> additionalOperations, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException {
ConnectorInstance connector = getConnectorInstance(resource, parentResult);
ObjectClassComplexTypeDefinition objectClassDefinition = applyAttributesDefinition(shadow.asPrismObject(), resource);
LOGGER.trace("Getting object identifiers");
Collection<? extends ResourceAttribute<?>> identifiers = ResourceObjectShadowUtil
.getIdentifiers(shadow);
Collection<? extends ResourceAttribute<?>> attributes = ResourceObjectShadowUtil
.getAttributes(shadow);
if (isProtectedShadow(resource, objectClassDefinition, attributes)) {
LOGGER.error("Attempt to delete protected resource object " + objectClassDefinition + ": "
+ identifiers + "; ignoring the request");
throw new SecurityViolationException("Cannot delete protected resource object "
+ objectClassDefinition + ": " + identifiers);
}
//check idetifier if it is not null
if (identifiers.isEmpty() && shadow.getFailedOperationType()!= null){
throw new GenericConnectorException(
"Unable to delete account from the resource. Probably it has not been created yet because of previous unavailability of the resource.");
}
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"PROVISIONING DELETE operation on resource {}\n DELETE object, object class {}, identified by:\n{}\n additional operations:\n{}",
new Object[] { ObjectTypeUtil.toShortString(resource), shadow.getObjectClass(),
SchemaDebugUtil.debugDump(identifiers),
SchemaDebugUtil.debugDump(additionalOperations) });
}
connector.deleteObject(objectClassDefinition, additionalOperations, identifiers, parentResult);
LOGGER.debug("PROVISIONING DELETE successful");
parentResult.recordSuccess();
} catch (ObjectNotFoundException ex) {
parentResult.recordFatalError("Can't delete object " + ObjectTypeUtil.toShortString(shadow)
+ ". Reason: " + ex.getMessage(), ex);
throw new ObjectNotFoundException("An error occured while deleting resource object " + shadow
+ "whith identifiers " + identifiers + ": " + ex.getMessage(), ex);
} catch (CommunicationException ex) {
parentResult.recordFatalError(
"Error communicating with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with the connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (GenericFrameworkException ex) {
parentResult.recordFatalError("Generic error in connector: " + ex.getMessage(), ex);
throw new GenericConnectorException("Generic error in connector: " + ex.getMessage(), ex);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Set<PropertyModificationOperation> modifyShadow(ResourceType resource,
ResourceObjectShadowType shadow, Collection<Operation> operations,
Collection<? extends ItemDelta> objectChanges, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException {
ObjectClassComplexTypeDefinition objectClassDefinition = applyAttributesDefinition(shadow.asPrismObject(), resource);
ResourceAttributeContainerDefinition resourceAttributeDefinition = ResourceObjectShadowUtil
.getObjectClassDefinition(shadow);
Collection<? extends ResourceAttribute<?>> identifiers = ResourceObjectShadowUtil
.getIdentifiers(shadow);
Collection<? extends ResourceAttribute<?>> attributes = ResourceObjectShadowUtil
.getAttributes(shadow);
if (isProtectedShadow(resource, objectClassDefinition, attributes)) {
LOGGER.error("Attempt to modify protected resource object " + objectClassDefinition + ": "
+ identifiers + "; ignoring the request");
throw new SecurityViolationException("Cannot modify protected resource object "
+ objectClassDefinition + ": " + identifiers);
}
getAttributeChanges(objectChanges, operations, resource, shadow, resourceAttributeDefinition);
if (shadow.getFetchResult() != null){
parentResult.addParam("shadow", shadow);
}
if (operations.isEmpty()){
LOGGER.trace("No modifications for connector object specified. Skipping processing of modifyShadow.");
parentResult.recordSuccess();
return new HashSet<PropertyModificationOperation>();
}
//check idetifier if it is not null
if (identifiers.isEmpty() && shadow.getFailedOperationType()!= null){
throw new GenericConnectorException(
"Unable to modify account in the resource. Probably it has not been created yet because of previous unavailability of the resource.");
}
ConnectorInstance connector = getConnectorInstance(resource, parentResult);
if (avoidDuplicateValues(resource)) {
// We need to filter out the deltas that add duplicate values or remove values that are not there
ResourceObjectShadowType currentShadow = fetchResourceObject(ResourceObjectShadowType.class, objectClassDefinition,
identifiers, connector, resource, parentResult);
Collection<Operation> filteredOperations = new ArrayList(operations.size());
for (Operation origOperation: operations) {
if (origOperation instanceof PropertyModificationOperation) {
PropertyDelta<?> propertyDelta = ((PropertyModificationOperation)origOperation).getPropertyDelta();
PropertyDelta<?> filteredDelta = propertyDelta.narrow(currentShadow.asPrismObject());
if (filteredDelta != null && !filteredDelta.isEmpty()) {
if (propertyDelta == filteredDelta) {
filteredOperations.add(origOperation);
} else {
PropertyModificationOperation newOp = new PropertyModificationOperation(filteredDelta);
filteredOperations.add(newOp);
}
}
}
}
if (filteredOperations.isEmpty()){
LOGGER.debug("No modifications for connector object specified (after filtering). Skipping processing.");
parentResult.recordSuccess();
return new HashSet<PropertyModificationOperation>();
}
operations = filteredOperations;
}
Set<PropertyModificationOperation> sideEffectChanges = null;
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"PROVISIONING MODIFY operation on resource {}\n MODIFY object, object class {}, identified by:\n{}\n changes:\n{}",
new Object[] { ObjectTypeUtil.toShortString(resource), shadow.getObjectClass(),
SchemaDebugUtil.debugDump(identifiers), SchemaDebugUtil.debugDump(operations) });
}
// Invoke ICF
sideEffectChanges = connector.modifyObject(objectClassDefinition, identifiers, operations,
parentResult);
LOGGER.debug("PROVISIONING MODIFY successful, side-effect changes {}",
SchemaDebugUtil.debugDump(sideEffectChanges));
} catch (ObjectNotFoundException ex) {
parentResult.recordFatalError("Object to modify not found. Reason: " + ex.getMessage(), ex);
throw new ObjectNotFoundException("Object to modify not found. " + ex.getMessage(), ex);
} catch (CommunicationException ex) {
parentResult.recordFatalError(
"Error communicationg with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error comminicationg with connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (GenericFrameworkException ex) {
parentResult.recordFatalError(
"Generic error in the connector " + connector + ": " + ex.getMessage(), ex);
throw new GenericConnectorException("Generic error in connector connector " + connector + ": "
+ ex.getMessage(), ex);
}
parentResult.recordSuccess();
return sideEffectChanges;
}
public <T extends ResourceObjectShadowType> void searchObjects(ResourceType resourceType, ResourceSchema resourceSchema, QName objectClass,
ResultHandler<T> resultHandler, ObjectQuery query, OperationResult parentResult) throws SchemaException,
CommunicationException, ObjectNotFoundException, ConfigurationException {
ObjectClassComplexTypeDefinition objectClassDef = resourceSchema.findObjectClassDefinition(objectClass);
if (objectClassDef == null) {
String message = "Object class " + objectClass + " is not defined in schema of "
+ ObjectTypeUtil.toShortString(resourceType);
LOGGER.error(message);
parentResult.recordFatalError(message);
throw new SchemaException(message);
}
ConnectorInstance connector = getConnectorInstance(resourceType, parentResult);
try {
connector.search(objectClassDef, query, resultHandler, parentResult);
} catch (GenericFrameworkException e) {
parentResult.recordFatalError("Generic error in the connector: " + e.getMessage(), e);
throw new SystemException("Generic error in the connector: " + e.getMessage(), e);
} catch (CommunicationException ex) {
parentResult.recordFatalError(
"Error communicating with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with the connector " + connector + ": "
+ ex.getMessage(), ex);
}
parentResult.recordSuccess();
}
private boolean avoidDuplicateValues(ResourceType resource) {
if (resource.getConsistency() == null) {
return false;
}
if (resource.getConsistency().isAvoidDuplicateValues() == null) {
return false;
}
return resource.getConsistency().isAvoidDuplicateValues();
}
@SuppressWarnings("rawtypes")
public PrismProperty fetchCurrentToken(ResourceType resourceType, ResourceSchema resourceSchema, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException {
Validate.notNull(resourceType, "Resource must not be null.");
Validate.notNull(resourceSchema, "Resource schema must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
LOGGER.trace("Getting last token");
ConnectorInstance connector = getConnectorInstance(resourceType, parentResult);
// This is a HACK. It should not work only for default account, but also
// for other objectclasses (FIXME)
ObjectClassComplexTypeDefinition objectClass = resourceSchema.findDefaultAccountDefinition();
PrismProperty lastToken = null;
try {
lastToken = connector.fetchCurrentToken(objectClass, parentResult);
} catch (GenericFrameworkException e) {
parentResult.recordFatalError("Generic error in the connector: " + e.getMessage(), e);
throw new CommunicationException("Generic error in the connector: " + e.getMessage(), e);
} catch (CommunicationException ex) {
parentResult.recordFatalError(
"Error communicating with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with the connector " + connector + ": "
+ ex.getMessage(), ex);
}
LOGGER.trace("Got last token: {}", SchemaDebugUtil.prettyPrint(lastToken));
parentResult.recordSuccess();
return lastToken;
}
@SuppressWarnings("rawtypes")
public List<Change> fetchChanges(ResourceType resource, PrismProperty lastToken,
OperationResult parentResult) throws ObjectNotFoundException, SchemaException,
CommunicationException, ConfigurationException {
Validate.notNull(resource, "Resource must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
Validate.notNull(lastToken, "Token property must not be null.");
LOGGER.trace("Shadow converter, START fetch changes");
ConnectorInstance connector = getConnectorInstance(resource, parentResult);
ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext);
// This is a HACK. It should not work only for default account, but also
// for other objectclasses (FIXME)
ObjectClassComplexTypeDefinition objectClass = resourceSchema.findDefaultAccountDefinition();
// get changes from the connector
List<Change> changes = null;
try {
changes = connector.fetchChanges(objectClass, lastToken, parentResult);
// TODO: filter out changes of protected objects
} catch (SchemaException ex) {
parentResult.recordFatalError("Schema error: " + ex.getMessage(), ex);
throw ex;
} catch (CommunicationException ex) {
parentResult.recordFatalError("Communication error: " + ex.getMessage(), ex);
throw ex;
} catch (GenericFrameworkException ex) {
parentResult.recordFatalError("Generic error: " + ex.getMessage(), ex);
throw new GenericConnectorException(ex.getMessage(), ex);
} catch (ConfigurationException ex) {
parentResult.recordFatalError("Configuration error: " + ex.getMessage(), ex);
throw ex;
}
Iterator<Change> iterator = changes.iterator();
while (iterator.hasNext()) {
Change change = iterator.next();
if (isProtectedShadowChange(resource, change)) {
LOGGER.trace("Skipping change to a protected object: {}", change);
iterator.remove();
}
}
parentResult.recordSuccess();
LOGGER.trace("Shadow converter, END fetch changes");
return changes;
}
public ResourceObjectShadowType createNewAccountFromChange(Change change, ResourceType resource, ResourceSchema resourceSchema,
OperationResult parentResult) throws SchemaException, ObjectNotFoundException,
CommunicationException, GenericFrameworkException, ConfigurationException,
SecurityViolationException {
// ResourceAttributeContainer resourceObject = null;
ConnectorInstance connector = getConnectorInstance(resource, parentResult);
// ResourceSchema schema = resourceTypeManager.getResourceSchema(resource, parentResult);
ObjectClassComplexTypeDefinition rod = resourceSchema.findObjectClassDefinition(new QName(ResourceTypeUtil.getResourceNamespace(resource),
"AccountObjectClass"));
ResourceObjectShadowType shadow = null;
try {
shadow = fetchResourceObject(ResourceObjectShadowType.class, rod, change.getIdentifiers(),
connector, resource, parentResult);
} catch (ObjectNotFoundException ex) {
parentResult
.recordPartialError("Object detected in change log no longer exist on the resource. Skipping processing this object.");
LOGGER.warn("Object detected in change log no longer exist on the resource. Skipping processing this object "
+ ex.getMessage());
return null;
}
try {
shadow = ShadowCacheUtil.completeShadow(shadow, null, resource, parentResult);
shadow = ShadowCacheUtil.createRepositoryShadow(shadow, resource);
} catch (SchemaException ex) {
parentResult.recordFatalError("Can't create account shadow from identifiers: "
+ change.getIdentifiers());
throw new SchemaException("Can't create account shadow from identifiers: "
+ change.getIdentifiers());
}
parentResult.recordSuccess();
return shadow;
}
private <T extends ResourceObjectShadowType> T fetchResourceObject(Class<T> type,
ObjectClassComplexTypeDefinition objectClassDefinition,
Collection<? extends ResourceAttribute<?>> identifiers, ConnectorInstance connector,
ResourceType resource, OperationResult parentResult) throws ObjectNotFoundException,
CommunicationException, SchemaException, SecurityViolationException {
if (isProtectedShadow(resource, objectClassDefinition, identifiers)) {
LOGGER.error("Attempt to fetch protected resource object " + objectClassDefinition + ": "
+ identifiers + "; ignoring the request");
throw new SecurityViolationException("Cannot get protected resource object "
+ objectClassDefinition + ": " + identifiers);
}
try {
PrismObject<T> resourceObject = connector.fetchObject(type, objectClassDefinition, identifiers,
true, null, parentResult);
return resourceObject.asObjectable();
} catch (ObjectNotFoundException e) {
parentResult.recordFatalError(
"Object not found. Identifiers: " + identifiers + ". Reason: " + e.getMessage(), e);
// parentResult.getLastSubresult().muteError();
throw new ObjectNotFoundException("Object not found. Identifiers: " + identifiers + ". Reason: "
+ e.getMessage(), e);
} catch (CommunicationException e) {
parentResult.recordFatalError("Error communication with the connector " + connector
+ ": " + e.getMessage(), e);
// parentResult.getLastSubresult().muteError();
throw new CommunicationException("Error communication with the connector " + connector
+ ": " + e.getMessage(), e);
} catch (GenericFrameworkException e) {
parentResult.recordFatalError(
"Generic error in the connector " + connector + ". Reason: " + e.getMessage(), e);
throw new GenericConnectorException("Generic error in the connector " + connector + ". Reason: "
+ e.getMessage(), e);
} catch (SchemaException ex) {
parentResult.recordFatalError("Can't get resource object, schema error: " + ex.getMessage(), ex);
throw new SchemaException("Can't get resource object, schema error: " + ex.getMessage(), ex);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void applyAfterOperationAttributes(ResourceObjectShadowType shadow,
Collection<ResourceAttribute<?>> resourceAttributesAfterAdd) throws SchemaException {
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
for (ResourceAttribute attributeAfter : resourceAttributesAfterAdd) {
ResourceAttribute attributeBefore = attributesContainer.findAttribute(attributeAfter.getName());
if (attributeBefore != null) {
attributesContainer.remove(attributeBefore);
}
attributesContainer.add(attributeAfter);
}
}
private ConnectorInstance getConnectorInstance(ResourceType resource, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException {
return connectorTypeManager.getConfiguredConnectorInstance(resource, false, parentResult);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Operation determineActivationChange(ResourceObjectShadowType shadow, Collection<? extends ItemDelta> objectChange,
ResourceType resource, ResourceAttributeContainerDefinition objectClassDefinition)
throws SchemaException {
PropertyDelta<Boolean> enabledPropertyDelta = PropertyDelta.findPropertyDelta(objectChange,
new ItemPath(ResourceObjectShadowType.F_ACTIVATION, ActivationType.F_ENABLED));
if (enabledPropertyDelta == null) {
return null;
}
Boolean enabled = enabledPropertyDelta.getPropertyNew().getRealValue();
LOGGER.trace("Find activation change to: {}", enabled);
if (enabled != null) {
LOGGER.trace("enabled not null.");
if (!ResourceTypeUtil.hasResourceNativeActivationCapability(resource)) {
// if resource cannot do activation, resource should
// have specified policies to do that
PropertyModificationOperation activationAttribute = convertToActivationAttribute(shadow, resource,
enabled, objectClassDefinition);
return activationAttribute;
} else {
// Navive activation, nothing special to do
return new PropertyModificationOperation(enabledPropertyDelta);
}
}
return null;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void checkActivationAttribute(ResourceObjectShadowType shadow, ResourceType resource,
ResourceAttributeContainerDefinition objectClassDefinition) throws SchemaException {
OperationResult result = new OperationResult("Checking activation attribute in the new shadow.");
if (shadow instanceof AccountShadowType) {
if (((AccountShadowType) shadow).getActivation() != null && shadow.getActivation().isEnabled() != null) {
if (!ResourceTypeUtil.hasResourceNativeActivationCapability(resource)) {
ActivationEnableDisableCapabilityType enableDisable = getEnableDisableFromSimulatedActivation(
shadow, resource, result);
if (enableDisable == null) {
throw new SchemaException("Attempt to change activation/enabled on "+resource+" that has neither native" +
" nor simulated activation capability");
}
ResourceAttribute<?> activationSimulateAttribute = getSimulatedActivationAttribute(shadow, resource,
objectClassDefinition, result);
boolean enabled = shadow.getActivation().isEnabled().booleanValue();
PrismPropertyValue activationValue = null;
if (enabled) {
activationValue = new PrismPropertyValue(getEnableValue(enableDisable));
} else {
activationValue = new PrismPropertyValue(getDisableValue(enableDisable));
}
activationSimulateAttribute.add(activationValue);
PrismContainer attributesContainer =shadow.asPrismObject().findContainer(AccountShadowType.F_ATTRIBUTES);
if (attributesContainer.findItem(activationSimulateAttribute.getName()) == null){
attributesContainer.add(activationSimulateAttribute);
} else{
attributesContainer.findItem(activationSimulateAttribute.getName()).replace(activationSimulateAttribute.getValue());
}
shadow.setActivation(null);
}
}
}
}
// private Operation determinePasswordChange(Collection<? extends ItemDelta> objectChange, ResourceObjectShadowType objectType) throws SchemaException {
// // Look for password change
// PropertyDelta<PasswordType> passwordPropertyDelta = PropertyDelta.findPropertyDelta(objectChange,
// SchemaConstants.PATH_PASSWORD_VALUE);
// if (passwordPropertyDelta == null) {
// return null;
// PasswordType newPasswordStructure = passwordPropertyDelta.getPropertyNew().getRealValue();
// PropertyModificationOperation passwordChangeOp = null;
// if (newPasswordStructure != null) {
// ProtectedStringType newPasswordPS = newPasswordStructure.getValue();
// if (MiscSchemaUtil.isNullOrEmpty(newPasswordPS)) {
// "ProtectedString is empty in an attempt to change password of "
// + ObjectTypeUtil.toShortString(objectType));
// passwordChangeOp = new PropertyModificationOperation(passwordPropertyDelta);
// // TODO: other things from the structure
// // changes.add(passwordChangeOp);
// return passwordChangeOp;
@SuppressWarnings("rawtypes")
private void getAttributeChanges(Collection<? extends ItemDelta> objectChange, Collection<Operation> changes,
ResourceType resource, ResourceObjectShadowType shadow, ResourceAttributeContainerDefinition objectClassDefinition) throws SchemaException {
if (changes == null) {
changes = new HashSet<Operation>();
}
for (ItemDelta itemDelta : objectChange) {
if (new ItemPath(ResourceObjectShadowType.F_ATTRIBUTES).equals(itemDelta.getParentPath()) || SchemaConstants.PATH_PASSWORD.equals(itemDelta.getParentPath())) {
if (itemDelta instanceof PropertyDelta) {
PropertyModificationOperation attributeModification = new PropertyModificationOperation(
(PropertyDelta) itemDelta);
changes.add(attributeModification);
} else if (itemDelta instanceof ContainerDelta) {
// skip the container delta - most probably password change
// - it is processed earlier
continue;
} else {
throw new UnsupportedOperationException("Not supported delta: " + itemDelta);
}
}else if (SchemaConstants.PATH_PASSWORD.equals(itemDelta.getParentPath())){
//processed in the previous if clause
// LOGGER.trace("Determinig password change");
// Operation passwordOperation = determinePasswordChange(objectChange, shadow);
// if (passwordOperation != null){
// changes.add(passwordOperation);
}else if (SchemaConstants.PATH_ACTIVATION.equals(itemDelta.getParentPath())){
Operation activationOperation = determineActivationChange(shadow, objectChange, resource, objectClassDefinition);
LOGGER.trace("Determinig activation change");
if (activationOperation != null){
changes.add(activationOperation);
}
} else {
LOGGER.trace("Skipp converting item delta: {}. It's not account change, but it it shadow change.", itemDelta);
}
}
// return changes;
}
private ActivationEnableDisableCapabilityType getEnableDisableFromSimulatedActivation(ResourceObjectShadowType shadow, ResourceType resource, OperationResult result){
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
if (activationCapability == null) {
result.recordWarning("Resource " + ObjectTypeUtil.toShortString(resource)
+ " does not have native or simulated activation capability. Processing of activation for account "+ ObjectTypeUtil.toShortString(shadow)+" was skipped");
shadow.setFetchResult(result.createOperationResultType());
return null;
}
ActivationEnableDisableCapabilityType enableDisable = activationCapability.getEnableDisable();
if (enableDisable == null) {
result.recordWarning("Resource " + ObjectTypeUtil.toShortString(resource)
+ " does not have native or simulated activation/enableDisable capability. Processing of activation for account "+ ObjectTypeUtil.toShortString(shadow)+" was skipped");
shadow.setFetchResult(result.createOperationResultType());
return null;
}
return enableDisable;
}
private ResourceAttribute<?> getSimulatedActivationAttribute(ResourceObjectShadowType shadow, ResourceType resource, ResourceAttributeContainerDefinition objectClassDefinition, OperationResult result){
ActivationEnableDisableCapabilityType enableDisable = getEnableDisableFromSimulatedActivation(shadow, resource, result);
if (enableDisable == null){
return null;
}
QName enableAttributeName = enableDisable.getAttribute();
LOGGER.trace("Simulated attribute name: {}", enableAttributeName);
if (enableAttributeName == null) {
result.recordWarning("Resource "
+ ObjectTypeUtil.toShortString(resource)
+ " does not have attribute specification for simulated activation/enableDisable capability. Processing of activation for account "+ ObjectTypeUtil.toShortString(shadow)+" was skipped");
shadow.setFetchResult(result.createOperationResultType());
return null;
}
ResourceAttributeDefinition enableAttributeDefinition = objectClassDefinition
.findAttributeDefinition(enableAttributeName);
if (enableAttributeDefinition == null) {
result.recordWarning("Resource " + ObjectTypeUtil.toShortString(resource)
+ " attribute for simulated activation/enableDisable capability" + enableAttributeName
+ " in not present in the schema for objeclass " + objectClassDefinition+". Processing of activation for account "+ ObjectTypeUtil.toShortString(shadow)+" was skipped");
shadow.setFetchResult(result.createOperationResultType());
return null;
}
return enableAttributeDefinition.instantiate(enableAttributeName);
}
private PropertyModificationOperation convertToActivationAttribute(ResourceObjectShadowType shadow, ResourceType resource,
Boolean enabled, ResourceAttributeContainerDefinition objectClassDefinition)
throws SchemaException {
OperationResult result = new OperationResult("Modify activation attribute.");
ResourceAttribute<?> activationAttribute = getSimulatedActivationAttribute(shadow, resource, objectClassDefinition, result);
if (activationAttribute == null){
return null;
}
ActivationEnableDisableCapabilityType enableDisable = getEnableDisableFromSimulatedActivation(shadow, resource, result);
if (enableDisable == null){
return null;
}
PropertyDelta<?> enableAttributeDelta = null;
if (enabled) {
String enableValue = getEnableValue(enableDisable);
LOGGER.trace("enable attribute delta: {}", enableValue);
enableAttributeDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(
ResourceObjectShadowType.F_ATTRIBUTES, activationAttribute.getName()), activationAttribute.getDefinition(), enableValue);
// enableAttributeDelta.setValueToReplace(enableValue);
} else {
String disableValue = getDisableValue(enableDisable);
LOGGER.trace("enable attribute delta: {}", disableValue);
enableAttributeDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(
ResourceObjectShadowType.F_ATTRIBUTES, activationAttribute.getName()), activationAttribute.getDefinition(), disableValue);
// enableAttributeDelta.setValueToReplace(disableValue);
}
PropertyModificationOperation attributeChange = new PropertyModificationOperation(
enableAttributeDelta);
return attributeChange;
}
private String getDisableValue(ActivationEnableDisableCapabilityType enableDisable){
//TODO some checks
String disableValue = enableDisable.getDisableValue().iterator().next();
return disableValue;
// return new PrismPropertyValue(disableValue);
}
private String getEnableValue(ActivationEnableDisableCapabilityType enableDisable){
List<String> enableValues = enableDisable.getEnableValue();
Iterator<String> i = enableValues.iterator();
String enableValue = i.next();
if ("".equals(enableValue)) {
if (enableValues.size() < 2) {
enableValue = "false";
} else {
enableValue = i.next();
}
}
return enableValue;
// return new PrismPropertyValue(enableValue);
}
public <T extends ResourceObjectShadowType> boolean isProtectedShadow(ResourceType resource,
PrismObject<T> shadow) throws SchemaException {
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
if (attributesContainer == null) {
return false;
}
QName objectClass = shadow.asObjectable().getObjectClass();
Collection<ResourceAttribute<?>> attributes = attributesContainer.getAttributes();
return isProtectedShadow(resource, objectClass, attributes);
}
public boolean isProtectedShadow(ResourceType resource,
ObjectClassComplexTypeDefinition objectClassDefinition,
Collection<? extends ResourceAttribute<?>> attributes) throws SchemaException {
return isProtectedShadow(resource, objectClassDefinition.getTypeName(), attributes);
}
private boolean isProtectedShadowChange(ResourceType resource, Change change) throws SchemaException {
PrismObject<? extends ResourceObjectShadowType> currentShadow = change.getCurrentShadow();
if (currentShadow != null) {
return isProtectedShadow(resource, currentShadow);
}
Collection<ResourceAttribute<?>> identifiers = change.getIdentifiers();
return isProtectedShadow(resource, change.getObjectClassDefinition().getTypeName(), identifiers);
}
private boolean isProtectedShadow(ResourceType resource, QName objectClass,
Collection<? extends ResourceAttribute<?>> attributes) throws SchemaException {
// TODO: support also other types except account
RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource, prismContext);
RefinedAccountDefinition refinedAccountDef = refinedSchema
.findAccountDefinitionByObjectClass(objectClass);
LOGGER.trace("isProtectedShadow: {} -> {}, {}", new Object[] { objectClass, refinedAccountDef,
attributes });
if (refinedAccountDef == null) {
return false;
}
Collection<ResourceObjectPattern> protectedAccountPatterns = refinedAccountDef.getProtectedAccounts();
if (protectedAccountPatterns == null) {
return false;
}
return ResourceObjectPattern.matches(attributes, protectedAccountPatterns);
}
public <T extends ResourceObjectShadowType> ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<T> delta,
ResourceShadowDiscriminator discriminator, ResourceType resource) throws SchemaException, ConfigurationException {
ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(discriminator, resource);
return applyAttributesDefinition(delta, objectClassDefinition, resource);
}
public <T extends ResourceObjectShadowType> ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<T> delta,
PrismObject<T> shadow, ResourceType resource) throws SchemaException, ConfigurationException {
ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(shadow, resource);
return applyAttributesDefinition(delta, objectClassDefinition, resource);
}
private <T extends ResourceObjectShadowType> ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<T> delta,
ObjectClassComplexTypeDefinition objectClassDefinition, ResourceType resource) throws SchemaException, ConfigurationException {
if (delta.isAdd()) {
applyAttributesDefinition(delta.getObjectToAdd(), resource);
} else if (delta.isModify()) {
ItemPath attributesPath = new ItemPath(ResourceObjectShadowType.F_ATTRIBUTES);
for(ItemDelta<?> modification: delta.getModifications()) {
if (modification.getDefinition() == null && attributesPath.equals(modification.getParentPath())) {
QName attributeName = modification.getName();
ResourceAttributeDefinition attributeDefinition = objectClassDefinition.findAttributeDefinition(attributeName);
if (attributeDefinition == null) {
throw new SchemaException("No definition for attribute "+attributeName+" in object delta "+delta);
}
modification.applyDefinition(attributeDefinition);
}
}
}
return objectClassDefinition;
}
public <T extends ResourceObjectShadowType> ObjectClassComplexTypeDefinition applyAttributesDefinition(
PrismObject<T> shadow, ResourceType resource) throws SchemaException, ConfigurationException {
ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(shadow, resource);
ResourceAttributeContainerDefinition attributesContainerDefinition = new ResourceAttributeContainerDefinition(ResourceObjectShadowType.F_ATTRIBUTES,
objectClassDefinition, objectClassDefinition.getPrismContext());
PrismContainer<?> attributesContainer = shadow.findContainer(ResourceObjectShadowType.F_ATTRIBUTES);
if (attributesContainer != null) {
if (attributesContainer instanceof ResourceAttributeContainer) {
if (attributesContainer.getDefinition() == null) {
attributesContainer.applyDefinition(attributesContainerDefinition);
}
} else {
// We need to convert <attributes> to ResourceAttributeContainer
ResourceAttributeContainer convertedContainer = ResourceAttributeContainer.convertFromContainer(
attributesContainer, objectClassDefinition);
shadow.getValue().replace(attributesContainer, convertedContainer);
}
}
// We also need to replace the entire object definition to inject correct object class definition here
// If we don't do this then the patch (delta.applyTo) will not work correctly because it will not be able to
// create the attribute container if needed.
PrismObjectDefinition<T> objectDefinition = shadow.getDefinition();
PrismContainerDefinition<ResourceObjectShadowAttributesType> origAttrContainerDef = objectDefinition.findContainerDefinition(ResourceObjectShadowType.F_ATTRIBUTES);
if (origAttrContainerDef == null || !(origAttrContainerDef instanceof ResourceAttributeContainerDefinition)) {
PrismObjectDefinition<T> clonedDefinition = objectDefinition.cloneWithReplacedDefinition(ResourceObjectShadowType.F_ATTRIBUTES,
attributesContainerDefinition);
shadow.setDefinition(clonedDefinition);
}
return objectClassDefinition;
}
private <T extends ResourceObjectShadowType> ObjectClassComplexTypeDefinition determineObjectClassDefinition(PrismObject<T> shadow, ResourceType resource) throws SchemaException, ConfigurationException {
ResourceSchema schema = RefinedResourceSchema.getResourceSchema(resource, prismContext);
if (schema == null) {
throw new ConfigurationException("No schema definied for "+resource);
}
QName objectClass = shadow.asObjectable().getObjectClass();
if (objectClass == null) {
throw new SchemaException("No objectclass definied in "+shadow);
}
ObjectClassComplexTypeDefinition objectClassDefinition = schema.findObjectClassDefinition(objectClass);
if (objectClassDefinition == null) {
// Unknown objectclass
throw new SchemaException("Object class " + objectClass
+ " defined in the repository shadow is not known in schema of " + resource);
}
return objectClassDefinition;
}
private <T extends ResourceObjectShadowType> ObjectClassComplexTypeDefinition determineObjectClassDefinition(
ResourceShadowDiscriminator discriminator, ResourceType resource) throws SchemaException {
ResourceSchema schema = RefinedResourceSchema.getResourceSchema(resource, prismContext);
ObjectClassComplexTypeDefinition objectClassDefinition = schema.findAccountDefinition(discriminator.getIntent());
if (objectClassDefinition == null) {
// Unknown objectclass
throw new SchemaException("Account type " + discriminator.getIntent()
+ " is not known in schema of " + resource);
}
return objectClassDefinition;
}
}
|
package uk.ac.ebi.quickgo.rest.search.request.config;
import uk.ac.ebi.quickgo.common.SearchableField;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import com.google.common.base.Preconditions;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Takes care of providing {@link FilterConfig} instances for {@link FilterRequest}
* signatures that are searchable via the provided{@link SearchableField} instance.
*
* @author Ricardo Antunes
*/
@Component class InternalFilterConfigRetrieval implements FilterConfigRetrieval {
private final Map<Set<String>, FilterConfig> executionConfigs;
@Autowired
public InternalFilterConfigRetrieval(SearchableField searchableField) {
Preconditions
.checkArgument(searchableField != null, "SearchableField instance cannot be null.");
executionConfigs = populateExecutionConfigs(searchableField);
}
@Override public Optional<FilterConfig> getBySignature(Set<String> signature) {
Preconditions
.checkArgument(signature != null && !signature.isEmpty(), "Signature cannot be null or empty");
return Optional.ofNullable(executionConfigs.get(signature));
}
private Map<Set<String>, FilterConfig> populateExecutionConfigs(SearchableField searchableField) {
final FilterConfig.ExecutionType executionType = FilterConfig.ExecutionType.SIMPLE;
return searchableField.searchableFields()
.map(field -> createRequestConfig(field, executionType))
.collect(Collectors.toMap(FilterConfig::getSignature, Function.identity()));
}
private FilterConfig createRequestConfig(String signature, FilterConfig.ExecutionType type) {
FilterConfig config = new FilterConfig();
config.setSignature(signature);
config.setExecution(type);
return config;
}
@Override public String toString() {
return "InternalFilterConfigRetrieval{" +
"executionConfigs=" + executionConfigs +
'}';
}
}
|
package org.sakaiproject.tool.assessment.ui.listener.delivery;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Iterator;
import java.util.Set;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc;
import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
public class SaCharCountListener implements ActionListener
{
private static Log log = LogFactory.getLog(SaCharCountListener.class);
public void processAction(ActionEvent ae) throws AbortProcessingException
{
DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery");
String itemId = ContextUtil.lookupParam("itemId");
if (itemId == null) {
return;
}
StringBuffer redrawAnchorName = new StringBuffer("p");
Iterator iter = delivery.getPageContents().getPartsContents().iterator();
while (iter.hasNext()) {
SectionContentsBean part = (SectionContentsBean) iter.next();
String partSeq = part.getNumber();
redrawAnchorName.append(partSeq);
Iterator iter2 = part.getItemContents().iterator();
while (iter2.hasNext()) {
ItemContentsBean item = (ItemContentsBean) iter2.next();
ItemDataIfc itemData = item.getItemData();
ArrayList itemGradingDataArray = item.getItemGradingDataArray();
if (itemGradingDataArray != null && itemGradingDataArray.size() != 0) {
Iterator iter3 = itemGradingDataArray.iterator();
while (iter3.hasNext()) {
ItemGradingData itemGrading = (ItemGradingData) iter3.next();
if (itemData != null) {
if (itemId.equals(itemData.getItemIdString()) && itemGrading.getAnswerText() != null) {
if (itemGrading.getAnswerText() != null) {
String processedAnswerText = itemGrading.getAnswerText().replaceAll("\r", "").replaceAll("\n", "");
int saCharCount = processedAnswerText.length();
String formattedCount = String.format("%,d\n",saCharCount);
item.setSaCharCount(formattedCount);
if (saCharCount > 60000) {
item.setIsInvalidSALengthInput(true);
}
else {
item.setIsInvalidSALengthInput(false);
}
}
else {
item.setSaCharCount("0");
item.setIsInvalidSALengthInput(false);
}
redrawAnchorName.append("q");
String itemSeq = itemData.getSequence().toString();
redrawAnchorName.append(itemSeq);
delivery.setRedrawAnchorName(redrawAnchorName.toString());
}
}
}
}
else {
if (itemId.equals(itemData.getItemIdString())) {
item.setSaCharCount("0");
redrawAnchorName.append("q");
String itemSeq = itemData.getSequence().toString();
redrawAnchorName.append(itemSeq);
delivery.setRedrawAnchorName(redrawAnchorName.toString());
}
}
}
}
delivery.syncTimeElapsedWithServer();
}
}
|
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.canvas.core.codegen;
import java.util.LinkedHashSet;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.swt.graphics.RGB;
import phasereditor.assetpack.core.AssetModel;
import phasereditor.canvas.core.AssetSpriteModel;
import phasereditor.canvas.core.BaseObjectModel;
import phasereditor.canvas.core.CanvasModel;
import phasereditor.canvas.core.PhysicsType;
import phasereditor.canvas.core.StateSettings;
import phasereditor.canvas.core.StateSettings.LoadPack;
import phasereditor.project.core.ProjectCore;
/**
* @author arian
*
*/
public abstract class BaseStateGenerator extends JSLikeCanvasCodeGenerator {
protected StateSettings _state;
public BaseStateGenerator(CanvasModel model) {
super(model);
_state = model.getStateSettings();
}
@SuppressWarnings("rawtypes")
protected void generatePreloadMethodBody() {
trim(() -> {
line();
userCode(_settings.getUserCode().getState_preload_before());
});
Set<LoadPack> loadPacks = new LinkedHashSet<>(_state.getLoadPack());
if (!_state.isPreloader()) {
// when the state is a "preloader" we want to have full control of
// what's loading, so let's disable the automatic computation of the
// sections to load.
_world.walk(obj -> {
if (obj instanceof AssetSpriteModel) {
AssetModel asset = ((AssetSpriteModel) obj).getAssetKey().getAsset();
String relpath = asset.getPack().getRelativePath();
LoadPack loadpack = new LoadPack(relpath, asset.getSection().getKey());
loadPacks.add(loadpack);
}
});
}
IProject project = _world.getFile().getProject();
trim(() -> {
line();
for (LoadPack loadpack : loadPacks) {
String filepath = loadpack.getFile();
String url = ProjectCore.getAssetUrl(project.getFile(filepath));
line("this.load.pack('" + loadpack.getSection() + "', '" + url + "');");
}
});
trim(() -> {
line();
generatePreloaderStateCode();
});
trim(() -> {
line();
userCode(_settings.getUserCode().getState_preload_after());
});
}
protected void generatePreloaderStateCode() {
if (_state.isPreloader()) {
trim(() -> {
line();
super.generateObjectCreation();
});
trim(() -> {
line();
super.generatePublicFields();
});
trim(() -> {
String id = _state.getPreloadSpriteId();
if (id != null) {
BaseObjectModel obj = _model.getWorld().findById(id);
if (obj != null) {
line();
line("this.load.setPreloadSprite(" + getLocalVarName(obj) + ", "
+ _state.getPreloadSprite_direction().ordinal() + ");");
}
}
});
}
}
@Override
protected void generateObjectCreation() {
if (_state.isPreloader()) {
return;
}
super.generateObjectCreation();
}
@Override
protected void generatePublicFields() {
if (_state.isPreloader()) {
return;
}
super.generatePublicFields();
}
protected void generateInitMethodBody() {
trim(() -> {
line();
userCode(_settings.getUserCode().getState_init_before());
});
trim(() -> {
line();
StateSettings state = _model.getStateSettings();
if (!StateSettings.SCALE_MODE_NO_SCALE.equals(state.getScaleMode())) {
line("this.scale.scaleMode = Phaser.ScaleManager." + state.getScaleMode() + ";");
}
if (state.isPageAlignHorizontally()) {
line("this.scale.pageAlignHorizontally = true;");
}
if (state.isPageAlignVertically()) {
line("this.scale.pageAlignVertically = true;");
}
if (state.isRendererRoundPixels()) {
line("this.game.renderer.renderSession.roundPixels = true;");
}
if (state.getPhysicsSystem() != PhysicsType.NONE) {
line("this.physics.startSystem(Phaser.Physics." + state.getPhysicsSystem().name() + ");");
}
if (!state.getStageBackgroundColor().equals(new RGB(0, 0, 0))) {
line("this.stage.backgroundColor = '" + getHexString(state.getStageBackgroundColor()) + "';");
}
});
trim(() -> {
line();
userCode(_settings.getUserCode().getState_init_after());
});
}
}
|
package com.newsblur.fragment;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.newsblur.R;
import com.newsblur.activity.ItemsList;
import com.newsblur.database.DatabaseConstants;
import com.newsblur.database.StoryItemsAdapter;
import com.newsblur.domain.Story;
import com.newsblur.service.NBSyncService;
import com.newsblur.util.DefaultFeedView;
import com.newsblur.util.FeedSet;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.PrefsUtils;
import com.newsblur.util.StateFilter;
import com.newsblur.util.StoryOrder;
import com.newsblur.view.ProgressThrobber;
public abstract class ItemListFragment extends NbFragment implements OnScrollListener, OnCreateContextMenuListener, LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
public static int ITEMLIST_LOADER = 0x01;
protected ItemsList activity;
protected ListView itemList;
protected StoryItemsAdapter adapter;
protected DefaultFeedView defaultFeedView;
protected StateFilter currentState;
private boolean cursorSeenYet = false;
private boolean firstStorySeenYet = false;
// loading indicator for when stories are present but stale (at top of list)
protected ProgressThrobber headerProgressView;
// loading indicator for when stories are present and fresh (at bottom of list)
protected ProgressThrobber footerProgressView;
// loading indicator for when no stories are loaded yet (instead of list)
protected ProgressThrobber emptyProgressView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentState = (StateFilter) getArguments().getSerializable("currentState");
defaultFeedView = (DefaultFeedView)getArguments().getSerializable("defaultFeedView");
activity = (ItemsList) getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_itemlist, null);
itemList = (ListView) v.findViewById(R.id.itemlistfragment_list);
emptyProgressView = (ProgressThrobber) v.findViewById(R.id.empty_view_loading_throb);
emptyProgressView.setColors(getResources().getColor(R.color.refresh_1),
getResources().getColor(R.color.refresh_2),
getResources().getColor(R.color.refresh_3),
getResources().getColor(R.color.refresh_4));
View headerView = inflater.inflate(R.layout.row_loading_throbber, null);
headerProgressView = (ProgressThrobber) headerView.findViewById(R.id.itemlist_loading_throb);
headerProgressView.setColors(getResources().getColor(R.color.refresh_1),
getResources().getColor(R.color.refresh_2),
getResources().getColor(R.color.refresh_3),
getResources().getColor(R.color.refresh_4));
itemList.addHeaderView(headerView, null, false);
itemList.setHeaderDividersEnabled(false);
View footerView = inflater.inflate(R.layout.row_loading_throbber, null);
footerProgressView = (ProgressThrobber) footerView.findViewById(R.id.itemlist_loading_throb);
footerProgressView.setColors(getResources().getColor(R.color.refresh_1),
getResources().getColor(R.color.refresh_2),
getResources().getColor(R.color.refresh_3),
getResources().getColor(R.color.refresh_4));
itemList.addFooterView(footerView, null, false);
itemList.setFooterDividersEnabled(false);
itemList.setEmptyView(v.findViewById(R.id.empty_view));
setupBezelSwipeDetector(itemList);
itemList.setOnScrollListener(this);
itemList.setOnItemClickListener(this);
itemList.setOnCreateContextMenuListener(this);
if (adapter != null) {
// normally the adapter is set when it is created in onLoadFinished(), but sometimes
// onCreateView gets re-called thereafter.
itemList.setAdapter(adapter);
}
return v;
}
@Override
public synchronized void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getLoaderManager().getLoader(ITEMLIST_LOADER) == null) {
getLoaderManager().initLoader(ITEMLIST_LOADER, null, this);
}
}
private void triggerRefresh(int desiredStoryCount, int totalSeen) {
boolean gotSome = NBSyncService.requestMoreForFeed(getFeedSet(), desiredStoryCount, totalSeen);
if (gotSome) triggerSync();
}
/**
* Indicate that the DB was cleared.
*/
public void resetEmptyState() {
cursorSeenYet = false;
firstStorySeenYet = false;
}
/**
* Turns on/off the loading indicator. Note that the text component of the
* loading indicator requires a cursor and is handled below.
*/
public void setLoading(boolean isLoading) {
if (footerProgressView != null ) {
if (isLoading) {
if (NBSyncService.isFeedSetStoriesFresh(getFeedSet())) {
headerProgressView.setVisibility(View.INVISIBLE);
footerProgressView.setVisibility(View.VISIBLE);
} else {
headerProgressView.setVisibility(View.VISIBLE);
footerProgressView.setVisibility(View.GONE);
}
emptyProgressView.setVisibility(View.VISIBLE);
} else {
headerProgressView.setVisibility(View.INVISIBLE);
footerProgressView.setVisibility(View.GONE);
emptyProgressView.setVisibility(View.GONE);
}
}
}
private void updateLoadingMessage() {
View v = this.getView();
if (v == null) return; // we might have beat construction?
ListView itemList = (ListView) v.findViewById(R.id.itemlistfragment_list);
if (itemList == null) {
Log.w(this.getClass().getName(), "ItemListFragment does not have the expected ListView.");
return;
}
View emptyView = itemList.getEmptyView();
TextView textView = (TextView) emptyView.findViewById(R.id.empty_view_text);
boolean isLoading = NBSyncService.isFeedSetSyncing(getFeedSet(), activity);
if (isLoading || (!cursorSeenYet)) {
textView.setText(R.string.empty_list_view_loading);
} else {
textView.setText(R.string.empty_list_view_no_stories);
}
}
public void scrollToTop() {
View v = this.getView();
if (v == null) return; // we might have beat construction?
ListView itemList = (ListView) v.findViewById(R.id.itemlistfragment_list);
if (itemList == null) {
Log.w(this.getClass().getName(), "ItemListFragment does not have the expected ListView.");
return;
}
itemList.setSelection(0);
}
@Override
public synchronized void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) {
// load an extra page or two worth of stories past the viewport
int desiredStoryCount = firstVisible + (visibleCount*2) + 1;
triggerRefresh(desiredStoryCount, totalCount);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) { }
public void changeState(StateFilter state) {
currentState = state;
hasUpdated();
}
protected FeedSet getFeedSet() {
return activity.getFeedSet();
}
public void hasUpdated() {
if (isAdded()) {
getLoaderManager().restartLoader(ITEMLIST_LOADER , null, this);
}
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return FeedUtils.dbHelper.getStoriesLoader(getFeedSet(), currentState);
}
@Override
public synchronized void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor != null) {
cursorSeenYet = true;
if (cursor.getCount() < 1) {
triggerRefresh(1, 0);
} else {
if (!firstStorySeenYet) {
// once we have at least a single story, we can instruct the sync service as to how to safely
// activate new stories we recieve
firstStorySeenYet = true;
cursor.moveToFirst();
long cutoff = cursor.getLong(cursor.getColumnIndex(DatabaseConstants.STORY_TIMESTAMP));
cursor.moveToPosition(-1);
if (activity.getStoryOrder() == StoryOrder.NEWEST) {
NBSyncService.setActivationMode(NBSyncService.ActivationMode.OLDER, cutoff);
} else {
NBSyncService.setActivationMode(NBSyncService.ActivationMode.NEWER, cutoff);
}
}
}
adapter.swapCursor(cursor);
}
updateLoadingMessage();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
if (adapter != null) adapter.notifyDataSetInvalidated();
}
public void setDefaultFeedView(DefaultFeedView value) {
this.defaultFeedView = value;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
MenuInflater inflater = getActivity().getMenuInflater();
if (PrefsUtils.getStoryOrder(activity, getFeedSet()) == StoryOrder.NEWEST) {
inflater.inflate(R.menu.context_story_newest, menu);
} else {
inflater.inflate(R.menu.context_story_oldest, menu);
}
int truePosition = ((AdapterView.AdapterContextMenuInfo) menuInfo).position - 1;
Story story = adapter.getStory(truePosition);
if (story.read) {
menu.removeItem(R.id.menu_mark_story_as_read);
} else {
menu.removeItem(R.id.menu_mark_story_as_unread);
}
if (story.starred) {
menu.removeItem(R.id.menu_save_story);
} else {
menu.removeItem(R.id.menu_unsave_story);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int truePosition = menuInfo.position - 1;
Story story = adapter.getStory(truePosition);
Activity activity = getActivity();
switch (item.getItemId()) {
case R.id.menu_mark_story_as_read:
FeedUtils.markStoryAsRead(story, activity);
return true;
case R.id.menu_mark_story_as_unread:
FeedUtils.markStoryUnread(story, activity);
return true;
case R.id.menu_mark_older_stories_as_read:
FeedUtils.markFeedsRead(getFeedSet(), story.timestamp, null, activity);
return true;
case R.id.menu_mark_newer_stories_as_read:
FeedUtils.markFeedsRead(getFeedSet(), null, story.timestamp, activity);
return true;
case R.id.menu_shared:
FeedUtils.shareStory(story, activity);
return true;
case R.id.menu_save_story:
FeedUtils.setStorySaved(story, true, activity);
return true;
case R.id.menu_unsave_story:
FeedUtils.setStorySaved(story, false, activity);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int truePosition = position - 1;
onItemClick_(parent, view, truePosition, id);
}
public abstract void onItemClick_(AdapterView<?> parent, View view, int position, long id);
protected void setupBezelSwipeDetector(View v) {
final GestureDetector gestureDetector = new GestureDetector(getActivity(), new BezelSwipeDetector());
v.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
}
/**
* A gesture detector that captures bezel swipes and finishes the activity,
* to simulate a 'back' gesture.
*
* NB: pretty much all Views still try to process on-tap events despite
* returning true, so be sure to check isFinishing() on all other
* tap handlers.
*/
class BezelSwipeDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if((e1.getX() < 75f) && // the gesture should start from the left bezel and
((e2.getX()-e1.getX()) > 90f) && // move horizontally to the right and
(Math.abs(e1.getY()-e2.getY()) < 40f) // have minimal vertical travel, so we don't capture scrolling gestures
) {
ItemListFragment.this.getActivity().finish();
return true;
}
return false;
}
}
}
|
package org.jetel.component;
import java.util.LinkedList;
import java.util.List;
import org.jetel.data.DataRecord;
import org.jetel.data.lookup.LookupTable;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.SynchronizeUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.w3c.dom.Element;
public class LookupTableReaderWriter extends Node {
private static final String XML_LOOKUP_TABLE_ATTRIBUTE = "lookupTable";
private static final String XML_FREE_LOOKUP_TABLE_ATTRIBUTE = "freeLookupTable";
public final static String COMPONENT_TYPE = "LOOKUP_TABLE_READER_WRITER";
private String lookupTableName;
private final static int READ_FROM_PORT = 0;
private boolean readFromTable = false;
private boolean writeToTable = false;
private LookupTable lookupTable;
private boolean freeLookupTable;
public LookupTableReaderWriter(String id, String lookupTableName, boolean freeLookupTable) {
super(id);
this.lookupTableName = lookupTableName;
this.freeLookupTable = freeLookupTable;
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#getType()
*/
@Override
public String getType() {
return COMPONENT_TYPE;
}
@Override
public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
//set reading/writing mode
readFromTable = outPorts.size() > 0;
writeToTable = inPorts.size() > 0;
//init lookup table
lookupTable = getGraph().getLookupTable(lookupTableName);
if (lookupTable == null) {
throw new ComponentNotReadyException("Lookup table \"" + lookupTableName +
"\" not found.");
}
if (!lookupTable.isInitialized()) {
lookupTable.init();
}
}
@Override
public synchronized void reset() throws ComponentNotReadyException {
super.reset();
}
@Override
public Result execute() throws Exception {
if (writeToTable) {//putting records to lookup table
InputPort inPort = getInputPort(READ_FROM_PORT);
DataRecord inRecord = new DataRecord(inPort.getMetadata());
inRecord.init();
while ((inRecord = inPort.readRecord(inRecord)) != null && runIt) {
lookupTable.put(inRecord);
SynchronizeUtils.cloverYield();
}
}
if (readFromTable) {
//for each record from lookup table send to to the edge
for (DataRecord record : lookupTable) {
if (!runIt) break;
writeRecordBroadcast(record);
SynchronizeUtils.cloverYield();
}
}
broadcastEOF();
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
@Override
public void free() {
if(!isInitialized()) return;
super.free();
if (freeLookupTable && lookupTable != null){
lookupTable.free();
}
}
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
try{
return new LookupTableReaderWriter(xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getString(XML_LOOKUP_TABLE_ATTRIBUTE),
xattribs.getBoolean(XML_FREE_LOOKUP_TABLE_ATTRIBUTE, false));
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex);
}
}
public void toXML(org.w3c.dom.Element xmlElement) {
super.toXML(xmlElement);
xmlElement.setAttribute(XML_LOOKUP_TABLE_ATTRIBUTE,this.lookupTable.getId());
xmlElement.setAttribute(XML_FREE_LOOKUP_TABLE_ATTRIBUTE, String.valueOf(freeLookupTable));
}
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if(!checkInputPorts(status, 0, 1)
|| !checkOutputPorts(status, 0, Integer.MAX_VALUE)) {
return status;
}
lookupTable = getGraph().getLookupTable(lookupTableName);
if (lookupTable == null) {
ConfigurationProblem problem = new ConfigurationProblem("Lookup table \"" + lookupTableName +
"\" not found.", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
problem.setAttributeName(XML_LOOKUP_TABLE_ATTRIBUTE);
status.add(problem);
// check lookup metadata against in/out metadata
} else {
DataRecordMetadata lMetadata = lookupTable.getMetadata();
if (lMetadata != null) {
List<DataRecordMetadata> lookupMetadata = new LinkedList<DataRecordMetadata>();
lookupMetadata.add(lMetadata);
List<DataRecordMetadata> inOutMetadata = outPorts.size() > 0 ? getOutMetadata() : getInMetadata();
checkMetadata(status, lookupMetadata, inOutMetadata, false);
}
}
return status;
}
}
|
package com.wandrell.tabletop.punkapocalyptic.service.ruleset.command;
import static com.google.common.base.Preconditions.checkNotNull;
import com.wandrell.pattern.command.ResultCommand;
import com.wandrell.tabletop.punkapocalyptic.model.inventory.Equipment;
import com.wandrell.tabletop.punkapocalyptic.model.inventory.Weapon;
import com.wandrell.tabletop.punkapocalyptic.model.unit.GroupedUnit;
import com.wandrell.tabletop.punkapocalyptic.model.unit.Unit;
import com.wandrell.tabletop.punkapocalyptic.model.unit.mutation.MutantUnit;
import com.wandrell.tabletop.punkapocalyptic.model.unit.mutation.Mutation;
public final class GetUnitValorationCommand implements ResultCommand<Integer> {
private final Unit unit;
private Integer valoration;
public GetUnitValorationCommand(final Unit unit) {
super();
checkNotNull(unit, "Received a null pointer as unit");
this.unit = unit;
}
@Override
public final void execute() {
valoration = getUnit().getBaseCost();
for (final Weapon weapon : getUnit().getWeapons()) {
valoration += weapon.getCost();
}
for (final Equipment equipment : getUnit().getEquipment()) {
valoration += equipment.getCost();
}
if (getUnit().getArmor() != null) {
valoration += getUnit().getArmor().getCost();
}
if (getUnit() instanceof MutantUnit) {
for (final Mutation mutation : ((MutantUnit) getUnit())
.getMutations()) {
valoration += mutation.getCost();
}
}
if (getUnit() instanceof GroupedUnit) {
valoration = valoration
* ((GroupedUnit) getUnit()).getGroupSize().getValue();
}
}
@Override
public final Integer getResult() {
return valoration;
}
private final Unit getUnit() {
return unit;
}
}
|
package eu.dzhw.fdz.metadatamanagement.web.variablemanagement.search.dto;
import java.util.HashMap;
import java.util.Map;
import org.springframework.util.StringUtils;
import eu.dzhw.fdz.metadatamanagement.data.variablemanagement.documents.VariableDocument;
import net.karneim.pojobuilder.GeneratePojoBuilder;
/**
* The SearchForm Data transfer object (dto). This dto
*
* @author Daniel Katzberg
*
*/
@GeneratePojoBuilder(
intoPackage = "eu.dzhw.fdz.metadatamanagement.web.variablemanagement.search.dto.builders")
public class VariableSearchFormDto {
private String query;
private String scaleLevel;
private String surveyTitel;
/**
* @return A list with all filter values.
*/
public Map<String, String> getAllFilterValues() {
Map<String, String> filterValues = new HashMap<>();
// ScaleLevel
if (StringUtils.hasText(this.scaleLevel)) {
filterValues.put(VariableDocument.SCALE_LEVEL_FIELD, this.scaleLevel);
}
// Survey Title
if (StringUtils.hasText(this.surveyTitel)) {
filterValues.put(VariableDocument.NESTED_VARIABLE_SURVEY_TITLE_FIELD, this.surveyTitel);
}
return filterValues;
}
/**
* @return Return true if in any field is text.
*/
public boolean hasTextInAnyField() {
return StringUtils.hasText(this.query) || !this.getAllFilterValues().isEmpty();
}
/* GETTER / SETTER */
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getScaleLevel() {
return scaleLevel;
}
public void setScaleLevel(String scaleLevel) {
this.scaleLevel = scaleLevel;
}
public String getSurveyTitel() {
return surveyTitel;
}
public void setSurveyTitel(String surveyTitel) {
this.surveyTitel = surveyTitel;
}
}
|
package ca.corefacility.bioinformatics.irida.web.controller.test.integration.project;
import static ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils.asAdmin;
import static ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils.asSequencer;
import static ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils.asOtherUser;
import static ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils.asUser;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import ca.corefacility.bioinformatics.irida.config.data.IridaApiJdbcDataSourceConfig;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiPropertyPlaceholderConfig;
import ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestSystemProperties;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
import com.jayway.restassured.response.Response;
/**
* Integration tests for projects.
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiJdbcDataSourceConfig.class,
IridaApiPropertyPlaceholderConfig.class })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class })
@ActiveProfiles("it")
@DatabaseSetup("/ca/corefacility/bioinformatics/irida/web/controller/test/integration/project/ProjectIntegrationTest.xml")
@DatabaseTearDown("classpath:/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml")
public class ProjectIT {
private static final String PROJECTS = "/api/projects";
/**
* If I try to issue a create request for an object with an invalid field
* name, the server should respond with 400.
*/
@Test
public void testCreateProjectBadFieldName() {
Response r = asUser().body("{ \"projectName\": \"some stupid project\" }").expect().response()
.statusCode(HttpStatus.BAD_REQUEST.value()).when().post(PROJECTS);
assertTrue("body should contain 'You must provide a project name.'", r.getBody().asString().contains("You must provide a project name."));
}
/**
* Field names should be quoted. We should handle that failure gracefully.
*/
@Test
public void testCreateProjectNoQuotes() {
Response r = asUser().body("{ name: \"some stupid project\" }").expect().response()
.statusCode(HttpStatus.BAD_REQUEST.value()).when().post(PROJECTS);
assertTrue(r.getBody().asString().contains("double quotes"));
}
@Test
public void testCreateProject() {
Map<String, String> project = new HashMap<>();
project.put("name", "new project");
Response r = asUser().and().body(project).expect().response().statusCode(HttpStatus.CREATED.value()).when()
.post(PROJECTS);
String location = r.getHeader(HttpHeaders.LOCATION);
assertNotNull("Project location must not be null",location);
assertTrue(location.startsWith(ITestSystemProperties.BASE_URL + "/api/projects/"));
String responseBody = asUser().get(location).asString();
assertTrue("Result of POST must equal result of GET",r.asString().equals(responseBody));
String projectUsersLocation = from(responseBody).get("resource.links.find{it.rel=='project/users'}.href");
// confirm that the current user was added to the project.
asUser().expect().body("resource.resources.username", hasItem("fbristow")).when().get(projectUsersLocation);
}
@Test
public void testGetProject() {
asUser().expect().body("resource.name", equalTo("project22")).and()
.body("resource.links.rel", hasItems("self", "project/users", "project/samples")).when().get(PROJECTS + "/5");
}
@Test
public void testUpdateProjectName() {
Map<String, String> project = new HashMap<>();
String updatedName = "updated new project";
String location = PROJECTS + "/5";
project.put("name", updatedName);
asUser().body(project).expect().statusCode(HttpStatus.OK.value()).when().patch(location);
asUser().expect().body("resource.name", equalTo(updatedName)).when().get(location);
}
@Test
public void testUpdateProjectNameWithoutPrivileges() {
Map<String, String> project = new HashMap<>();
String updatedName = "updated new project";
String location = PROJECTS + "/5";
project.put("name", updatedName);
asOtherUser().body(project).expect().statusCode(HttpStatus.FORBIDDEN.value()).when().patch(location);
asUser().expect().body("resource.name", equalTo("project22")).when().get(location);
}
@Test
public void testGetProjects() {
// first page shouldn't have prev link, default view returns 20 projects
asAdmin().expect().body("resource.links.rel", hasItems("self")).when().get(PROJECTS);
}
@Test
public void testDeleteProject() {
String projectUri = ITestSystemProperties.BASE_URL + "/api/projects/5";
asUser().expect().body("resource.links.rel", hasItems("collection")).and()
.body("resource.links.href", hasItems(ITestSystemProperties.BASE_URL + "/api/projects")).when().delete(projectUri);
}
/**
* Make sure that if we issue a HEAD request on a resource, the request
* succeeds. We have two valid endpoints where a client can get data from
* (provided that they use the correct Accept headers). Make sure that both
* work.
*/
@Test
public void verifyExistenceOfProjectWithHEAD() {
String projectUri = ITestSystemProperties.BASE_URL + "/api/projects/5";
asUser().expect().statusCode(HttpStatus.OK.value()).when().head(projectUri);
asUser().given().header("Accept", MediaType.JSON_UTF_8.toString()).expect().statusCode(HttpStatus.OK.value())
.when().head(projectUri);
}
@Test
public void testListProjectsAsSequencer() {
asSequencer().expect().statusCode(HttpStatus.OK.value()).and().body("resource.links.rel", hasItems("self")).when().get(PROJECTS);
}
}
|
package org.sagebionetworks.web.unitclient.widget.entity.controller;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.sagebionetworks.repo.model.Entity;
import org.sagebionetworks.repo.model.Reference;
import org.sagebionetworks.repo.model.entitybundle.v2.EntityBundle;
import org.sagebionetworks.repo.model.provenance.Activity;
import org.sagebionetworks.repo.model.provenance.Used;
import org.sagebionetworks.repo.model.provenance.UsedEntity;
import org.sagebionetworks.repo.model.provenance.UsedURL;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.SynapseJavascriptClient;
import org.sagebionetworks.web.client.events.EntityUpdatedEvent;
import org.sagebionetworks.web.client.widget.entity.controller.EntityRefProvEntryView;
import org.sagebionetworks.web.client.widget.entity.controller.ProvenanceEditorWidget;
import org.sagebionetworks.web.client.widget.entity.controller.ProvenanceEditorWidgetView;
import org.sagebionetworks.web.client.widget.entity.controller.ProvenanceEntry;
import org.sagebionetworks.web.client.widget.entity.controller.ProvenanceListWidget;
import org.sagebionetworks.web.client.widget.entity.controller.ProvenanceURLDialogWidget;
import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert;
import org.sagebionetworks.web.client.widget.entity.controller.URLProvEntryView;
import org.sagebionetworks.web.shared.exceptions.NotFoundException;
import org.sagebionetworks.web.test.helper.AsyncMockStubber;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
@RunWith(MockitoJUnitRunner.class)
public class ProvenanceEditorWidgetTest {
@Mock
ProvenanceEditorWidgetView mockView;
@Mock
SynapseJavascriptClient mockJsClient;
@Mock
SynapseAlert mockSynAlert;
@Mock
PortalGinInjector mockInjector;
@Mock
ProvenanceListWidget mockProvenanceList;
@Mock
Activity mockActivity;
@Mock
ProvenanceURLDialogWidget mockUrlDialog;
ProvenanceEditorWidget presenter;
@Mock
EntityBundle mockEntityBundle;
@Mock
Entity mockEntity;
@Mock
Reference mockRef;
@Mock
EntityRefProvEntryView mockEntityProvEntry;
@Mock
URLProvEntryView mockUrlProvEntry;
@Mock
EventBus mockEventBus;
Set<Used> usedSet = new HashSet<Used>();
String name = "testName";
String url = "test.com";
String entityId = "syn123";
Long version = 1L;
Exception caught = new Exception("this is an exception");
@Before
public void before() {
when(mockInjector.getProvenanceListWidget()).thenReturn(mockProvenanceList);
presenter = new ProvenanceEditorWidget(mockView, mockJsClient, mockSynAlert, mockInjector, mockUrlDialog, mockEventBus);
when(mockInjector.getEntityRefEntry()).thenReturn(mockEntityProvEntry);
when(mockInjector.getURLEntry()).thenReturn(mockUrlProvEntry);
when(mockEntityBundle.getEntity()).thenReturn(mockEntity);
UsedURL usedUrl = new UsedURL();
usedUrl.setName(name);
usedUrl.setUrl(url);
usedUrl.setWasExecuted(true);
UsedEntity usedEntity = new UsedEntity();
when(mockRef.getTargetId()).thenReturn(entityId);
when(mockRef.getTargetVersionNumber()).thenReturn(version);
usedEntity.setReference(mockRef);
usedEntity.setWasExecuted(false);
usedSet.add(usedUrl);
usedSet.add(usedEntity);
when(mockActivity.getUsed()).thenReturn(usedSet);
List<ProvenanceEntry> provList = new LinkedList<ProvenanceEntry>();
provList.add(mockEntityProvEntry);
provList.add(mockUrlProvEntry);
when(mockProvenanceList.getEntries()).thenReturn(provList);
}
@Test
public void testConstruction() {
verify(mockInjector, times(2)).getProvenanceListWidget();
verify(mockProvenanceList, times(2)).setURLDialog(mockUrlDialog);
verify(mockView).setSynAlertWidget(mockSynAlert);
verify(mockView).setUsedProvenanceList(mockProvenanceList);
verify(mockView).setExecutedProvenanceList(mockProvenanceList);
verify(mockView).setURLDialog(mockUrlDialog);
verify(mockView).setPresenter(presenter);
}
@Test
public void testConfigureSuccessProvenanceCreated() {
when(mockActivity.getUsed()).thenReturn(null);
AsyncMockStubber.callSuccessWith(mockActivity).when(mockJsClient).getActivityForEntityVersion(anyString(), anyLong(), any(AsyncCallback.class));
when(mockProvenanceList.getEntries()).thenReturn(new LinkedList<ProvenanceEntry>());
presenter.configure(mockEntityBundle);
verify(mockView).setName(mockActivity.getName());
verify(mockView).setDescription(mockActivity.getDescription());
verify(mockActivity).getUsed();
verify(mockInjector, Mockito.never()).getEntityRefEntry();
verify(mockInjector.getEntityRefEntry(), Mockito.never()).configure(mockRef.getTargetId(), mockRef.getTargetVersionNumber().toString());
verify(mockInjector.getEntityRefEntry(), Mockito.never()).setAnchorTarget(anyString());
verify(mockInjector, Mockito.never()).getURLEntry();
verify(mockInjector.getURLEntry(), Mockito.never()).configure(name, url);
verify(mockInjector.getURLEntry(), Mockito.never()).setAnchorTarget(anyString());
verify(mockProvenanceList, Mockito.never()).configure(anyList(), any());
presenter.onSave();
verify(mockActivity).setName(mockView.getName());
verify(mockActivity).setDescription(mockView.getDescription());
ArgumentCaptor<Set> captor = ArgumentCaptor.forClass(Set.class);
verify(mockActivity).setUsed(captor.capture());
Set newProvSet = captor.getValue();
assertTrue(newProvSet.isEmpty());
verify(mockJsClient).updateActivity(eq(mockActivity), any(AsyncCallback.class));
}
@Test
public void testConfigureSuccess() {
AsyncMockStubber.callSuccessWith(mockActivity).when(mockJsClient).getActivityForEntityVersion(anyString(), anyLong(), any(AsyncCallback.class));
presenter.configure(mockEntityBundle);
verify(mockView).setName(mockActivity.getName());
verify(mockView).setDescription(mockActivity.getDescription());
verify(mockActivity).getUsed();
verify(mockInjector).getEntityRefEntry();
verify(mockInjector.getEntityRefEntry()).configure(mockRef.getTargetId(), mockRef.getTargetVersionNumber().toString());
verify(mockInjector.getEntityRefEntry()).setAnchorTarget(anyString());
verify(mockInjector).getURLEntry();
verify(mockInjector.getURLEntry()).configure(name, url);
verify(mockInjector.getURLEntry()).setAnchorTarget(anyString());
verify(mockProvenanceList, times(2)).configure(anyList(), any());
}
@Test
public void testConfigureFailure() {
AsyncMockStubber.callFailureWith(caught).when(mockJsClient).getActivityForEntityVersion(anyString(), anyLong(), any(AsyncCallback.class));
presenter.configure(mockEntityBundle);
verify(mockSynAlert).handleException(caught);
}
@Test
public void onSaveSuccess() {
// First configure
AsyncMockStubber.callSuccessWith(mockActivity).when(mockJsClient).getActivityForEntityVersion(anyString(), anyLong(), any(AsyncCallback.class));
presenter.configure(mockEntityBundle);
AsyncMockStubber.callSuccessWith(null).when(mockJsClient).updateActivity(eq(mockActivity), any(AsyncCallback.class));
// calls under test
presenter.setActivity(mockActivity);
presenter.onSave();
verify(mockUrlProvEntry, times(2)).getURL();
verify(mockUrlProvEntry, times(2)).getTitle();
verify(mockEntityProvEntry, times(2)).getEntryId();
verify(mockEntityProvEntry, times(2)).getEntryVersion();
ArgumentCaptor<Set> captor = ArgumentCaptor.forClass(Set.class);
verify(mockActivity).setUsed(captor.capture());
Set usedSet = captor.getValue();
assertTrue(usedSet.size() == 4);
verify(mockJsClient).updateActivity(eq(mockActivity), any(AsyncCallback.class));
verify(mockView).hide();
verify(mockEventBus).fireEvent(any(EntityUpdatedEvent.class));
}
@Test
public void onSaveNewActivitySuccess() {
AsyncMockStubber.callFailureWith(new NotFoundException()).when(mockJsClient).getActivityForEntityVersion(anyString(), anyLong(), any(AsyncCallback.class));
presenter.configure(mockEntityBundle);
AsyncMockStubber.callSuccessWith(null).when(mockJsClient).createActivityAndLinkToEntity(any(Activity.class), eq(mockEntity), any(AsyncCallback.class));
presenter.onSave();
verify(mockJsClient).createActivityAndLinkToEntity(any(Activity.class), eq(mockEntity), any(AsyncCallback.class));
verify(mockView).hide();
verify(mockEventBus).fireEvent(any(EntityUpdatedEvent.class));
}
@Test
public void onSaveFailure() {
AsyncMockStubber.callFailureWith(caught).when(mockJsClient).updateActivity(eq(mockActivity), any(AsyncCallback.class));
presenter.setActivity(mockActivity);
presenter.onSave();
verify(mockJsClient).updateActivity(eq(mockActivity), any(AsyncCallback.class));
verify(mockSynAlert).handleException(caught);
}
}
|
package org.carlspring.strongbox.booters;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ILock;
import org.carlspring.strongbox.configuration.Configuration;
import org.carlspring.strongbox.configuration.ConfigurationManager;
import org.carlspring.strongbox.providers.layout.LayoutProviderRegistry;
import org.carlspring.strongbox.providers.repository.group.GroupRepositorySetCollector;
import org.carlspring.strongbox.repository.RepositoryManagementStrategyException;
import org.carlspring.strongbox.services.RepositoryManagementService;
import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.repository.Repository;
import org.carlspring.strongbox.storage.repository.RepositoryStatusEnum;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.carlspring.strongbox.util.ThrowingConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author mtodorov
*/
public class StorageBooter
{
private static final Logger logger = LoggerFactory.getLogger(StorageBooter.class);
@Inject
private ConfigurationManager configurationManager;
@Inject
private LayoutProviderRegistry layoutProviderRegistry;
@Inject
private RepositoryManagementService repositoryManagementService;
@Inject
private GroupRepositorySetCollector groupRepositorySetCollector;
@Inject
private PropertiesBooter propertiesBooter;
private ILock lock;
// TODO: Inject hazelconfiguration as dependency
@Inject
private HazelcastInstance hazelcastInstance;
public StorageBooter()
{
}
@PostConstruct
public void initialize()
throws IOException, RepositoryManagementStrategyException
{
lock = hazelcastInstance.getLock("StorageBooterLock");
if (lock.tryLock())
{
try {
final Configuration configuration = configurationManager.getConfiguration();
initializeStorages(configuration.getStorages());
Collection<Repository> repositories = getRepositoriesHierarchy(configuration.getStorages());
if (!repositories.isEmpty())
{
logger.info(" -> Initializing repositories...");
}
repositories.forEach(ThrowingConsumer.unchecked(this::initializeRepository));
}
finally {
lock.unlock();
}
}
else
{
logger.debug("Failed to initialize the repositories. Another JVM may have already done this.");
}
}
private void initializeStorages(final Map<String, Storage> storages)
throws IOException
{
logger.info("Running Strongbox storage booter...");
logger.info(" -> Creating storage directory skeleton...");
for (Map.Entry<String, Storage> stringStorageEntry : storages.entrySet())
{
initializeStorage(stringStorageEntry.getValue());
}
}
private void initializeStorage(Storage storage)
throws IOException
{
logger.info(" * Initializing " + storage.getId() + "...");
}
private void initializeRepository(Repository repository)
throws IOException, RepositoryManagementStrategyException
{
logger.info(" * Initializing " + repository.getStorage().getId() + ":" + repository.getId() + "...");
if (layoutProviderRegistry.getProvider(repository.getLayout()) == null)
{
logger.error(String.format("Failed to resolve layout [%s] for repository [%s].",
repository.getLayout(),
repository.getId()));
return;
}
repositoryManagementService.createRepository(repository.getStorage().getId(), repository.getId());
if (RepositoryStatusEnum.IN_SERVICE.getStatus().equals(repository.getStatus()))
{
repositoryManagementService.putInService(repository.getStorage().getId(), repository.getId());
}
}
private Collection<Repository> getRepositoriesHierarchy(final Map<String, Storage> storages)
{
final Map<String, Repository> repositoriesHierarchy = new LinkedHashMap<>();
for (final Storage storage : storages.values())
{
for (final Repository repository : storage.getRepositories().values())
{
addRepositoriesByChildrenFirst(repositoriesHierarchy, repository);
}
}
return repositoriesHierarchy.values();
}
private void addRepositoriesByChildrenFirst(final Map<String, Repository> repositoriesHierarchy,
final Repository repository)
{
if (!repository.isGroupRepository())
{
repositoriesHierarchy.putIfAbsent(repository.getId(), repository);
return;
}
groupRepositorySetCollector.collect(repository, true)
.stream().forEach(r -> addRepositoriesByChildrenFirst(repositoriesHierarchy, r));
repositoriesHierarchy.putIfAbsent(repository.getId(), repository);
}
public RepositoryManagementService getRepositoryManagementService()
{
return repositoryManagementService;
}
public void setRepositoryManagementService(RepositoryManagementService repositoryManagementService)
{
this.repositoryManagementService = repositoryManagementService;
}
}
|
package org.elasticsearch.xpack.ml.dataframe.extractor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.util.CachedSupplier;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.StoredFieldsContext;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.xpack.core.ClientHelper;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.DataFrameAnalysis;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.dataframe.DestinationIndex;
import org.elasticsearch.xpack.ml.dataframe.traintestsplit.TrainTestSplitter;
import org.elasticsearch.xpack.ml.extractor.ExtractedField;
import org.elasticsearch.xpack.ml.extractor.ExtractedFields;
import org.elasticsearch.xpack.ml.extractor.ProcessedField;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* An implementation that extracts data from elasticsearch using ranged searches
* on the incremental id.
* We detect the end of the extraction by doing an additional search at the end
* which should return empty results.
* It supports safe and responsive cancellation by continuing from the latest
* incremental id that was seen.
* Note that this class is NOT thread-safe.
*/
public class DataFrameDataExtractor {
private static final Logger LOGGER = LogManager.getLogger(DataFrameDataExtractor.class);
public static final String NULL_VALUE = "\0";
private final Client client;
private final DataFrameDataExtractorContext context;
private long lastSortKey = -1;
private boolean isCancelled;
private boolean hasNext;
private boolean hasPreviousSearchFailed;
private final CachedSupplier<TrainTestSplitter> trainTestSplitter;
// These are fields that are sent directly to the analytics process
// They are not passed through a feature_processor
private final String[] organicFeatures;
// These are the output field names for the feature_processors
private final String[] processedFeatures;
private final Map<String, ExtractedField> extractedFieldsByName;
DataFrameDataExtractor(Client client, DataFrameDataExtractorContext context) {
this.client = Objects.requireNonNull(client);
this.context = Objects.requireNonNull(context);
this.organicFeatures = context.extractedFields.extractOrganicFeatureNames();
this.processedFeatures = context.extractedFields.extractProcessedFeatureNames();
this.extractedFieldsByName = new LinkedHashMap<>();
context.extractedFields.getAllFields().forEach(f -> this.extractedFieldsByName.put(f.getName(), f));
hasNext = true;
hasPreviousSearchFailed = false;
this.trainTestSplitter = new CachedSupplier<>(context.trainTestSplitterFactory::create);
}
public Map<String, String> getHeaders() {
return Collections.unmodifiableMap(context.headers);
}
public boolean hasNext() {
return hasNext;
}
public boolean isCancelled() {
return isCancelled;
}
public void cancel() {
LOGGER.debug("[{}] Data extractor was cancelled", context.jobId);
isCancelled = true;
}
public Optional<List<Row>> next() throws IOException {
if (!hasNext()) {
throw new NoSuchElementException();
}
Optional<List<Row>> hits = Optional.ofNullable(nextSearch());
if (hits.isPresent() && hits.get().isEmpty() == false) {
lastSortKey = hits.get().get(hits.get().size() - 1).getSortKey();
} else {
hasNext = false;
}
return hits;
}
protected List<Row> nextSearch() throws IOException {
return tryRequestWithSearchResponse(() -> executeSearchRequest(buildSearchRequest()));
}
private List<Row> tryRequestWithSearchResponse(Supplier<SearchResponse> request) throws IOException {
try {
// We've set allow_partial_search_results to false which means if something
// goes wrong the request will throw.
SearchResponse searchResponse = request.get();
LOGGER.debug("[{}] Search response was obtained", context.jobId);
List<Row> rows = processSearchResponse(searchResponse);
// Request was successfully executed and processed so we can restore the flag to retry if a future failure occurs
hasPreviousSearchFailed = false;
return rows;
} catch (Exception e) {
if (hasPreviousSearchFailed) {
throw e;
}
LOGGER.warn(new ParameterizedMessage("[{}] Search resulted to failure; retrying once", context.jobId), e);
markScrollAsErrored();
return nextSearch();
}
}
protected SearchResponse executeSearchRequest(SearchRequestBuilder searchRequestBuilder) {
return ClientHelper.executeWithHeaders(context.headers, ClientHelper.ML_ORIGIN, client, searchRequestBuilder::get);
}
private SearchRequestBuilder buildSearchRequest() {
long from = lastSortKey + 1;
long to = from + context.scrollSize;
LOGGER.debug(() -> new ParameterizedMessage(
"[{}] Searching docs with [{}] in [{}, {})", context.jobId, DestinationIndex.INCREMENTAL_ID, from, to));
SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client, SearchAction.INSTANCE)
// This ensures the search throws if there are failures and the scroll context gets cleared automatically
.setAllowPartialSearchResults(false)
.addSort(DestinationIndex.INCREMENTAL_ID, SortOrder.ASC)
.setIndices(context.indices)
.setSize(context.scrollSize);
searchRequestBuilder.setQuery(
QueryBuilders.boolQuery()
.filter(context.query)
.filter(QueryBuilders.rangeQuery(DestinationIndex.INCREMENTAL_ID).gte(from).lt(to))
);
setFetchSource(searchRequestBuilder);
for (ExtractedField docValueField : context.extractedFields.getDocValueFields()) {
searchRequestBuilder.addDocValueField(docValueField.getSearchField(), docValueField.getDocValueFormat());
}
return searchRequestBuilder;
}
private void setFetchSource(SearchRequestBuilder searchRequestBuilder) {
if (context.includeSource) {
searchRequestBuilder.setFetchSource(true);
} else {
String[] sourceFields = context.extractedFields.getSourceFields();
if (sourceFields.length == 0) {
searchRequestBuilder.setFetchSource(false);
searchRequestBuilder.storedFields(StoredFieldsContext._NONE_);
} else {
searchRequestBuilder.setFetchSource(sourceFields, null);
}
}
}
private List<Row> processSearchResponse(SearchResponse searchResponse) {
if (searchResponse.getHits().getHits().length == 0) {
hasNext = false;
return null;
}
SearchHit[] hits = searchResponse.getHits().getHits();
List<Row> rows = new ArrayList<>(hits.length);
for (SearchHit hit : hits) {
if (isCancelled) {
hasNext = false;
break;
}
rows.add(createRow(hit));
}
return rows;
}
private String extractNonProcessedValues(SearchHit hit, String organicFeature) {
ExtractedField field = extractedFieldsByName.get(organicFeature);
Object[] values = field.value(hit);
if (values.length == 1 && isValidValue(values[0])) {
return Objects.toString(values[0]);
}
if (values.length == 0 && context.supportsRowsWithMissingValues) {
// if values is empty then it means it's a missing value
return NULL_VALUE;
}
// we are here if we have a missing value but the analysis does not support those
// or the value type is not supported (e.g. arrays, etc.)
return null;
}
private String[] extractProcessedValue(ProcessedField processedField, SearchHit hit) {
Object[] values = processedField.value(hit, extractedFieldsByName::get);
if (values.length == 0 && context.supportsRowsWithMissingValues == false) {
return null;
}
final String[] extractedValue = new String[processedField.getOutputFieldNames().size()];
for (int i = 0; i < processedField.getOutputFieldNames().size(); i++) {
extractedValue[i] = NULL_VALUE;
}
// if values is empty then it means it's a missing value
if (values.length == 0) {
return extractedValue;
}
if (values.length != processedField.getOutputFieldNames().size()) {
throw ExceptionsHelper.badRequestException(
"field_processor [{}] output size expected to be [{}], instead it was [{}]",
processedField.getProcessorName(),
processedField.getOutputFieldNames().size(),
values.length);
}
for (int i = 0; i < processedField.getOutputFieldNames().size(); ++i) {
Object value = values[i];
if (value == null && context.supportsRowsWithMissingValues) {
continue;
}
if (isValidValue(value) == false) {
// we are here if we have a missing value but the analysis does not support those
// or the value type is not supported (e.g. arrays, etc.)
return null;
}
extractedValue[i] = Objects.toString(value);
}
return extractedValue;
}
private Row createRow(SearchHit hit) {
String[] extractedValues = new String[organicFeatures.length + processedFeatures.length];
int i = 0;
for (String organicFeature : organicFeatures) {
String extractedValue = extractNonProcessedValues(hit, organicFeature);
if (extractedValue == null) {
return new Row(null, hit, true);
}
extractedValues[i++] = extractedValue;
}
for (ProcessedField processedField : context.extractedFields.getProcessedFields()) {
String[] processedValues = extractProcessedValue(processedField, hit);
if (processedValues == null) {
return new Row(null, hit, true);
}
for (String processedValue : processedValues) {
extractedValues[i++] = processedValue;
}
}
boolean isTraining = trainTestSplitter.get().isTraining(extractedValues);
Row row = new Row(extractedValues, hit, isTraining);
LOGGER.debug(() -> new ParameterizedMessage("[{}] Extracted row: sort key = [{}], is_training = [{}], values = {}",
context.jobId, row.getSortKey(), isTraining, Arrays.toString(row.values)));
return row;
}
private void markScrollAsErrored() {
// This could be a transient error with the scroll Id.
// Reinitialise the scroll and try again but only once.
hasPreviousSearchFailed = true;
}
public List<String> getFieldNames() {
return Stream.concat(Arrays.stream(organicFeatures), Arrays.stream(processedFeatures)).collect(Collectors.toList());
}
public ExtractedFields getExtractedFields() {
return context.extractedFields;
}
public DataSummary collectDataSummary() {
SearchRequestBuilder searchRequestBuilder = buildDataSummarySearchRequestBuilder();
SearchResponse searchResponse = executeSearchRequest(searchRequestBuilder);
long rows = searchResponse.getHits().getTotalHits().value;
LOGGER.debug("[{}] Data summary rows [{}]", context.jobId, rows);
return new DataSummary(rows, organicFeatures.length + processedFeatures.length);
}
public void collectDataSummaryAsync(ActionListener<DataSummary> dataSummaryActionListener) {
SearchRequestBuilder searchRequestBuilder = buildDataSummarySearchRequestBuilder();
final int numberOfFields = organicFeatures.length + processedFeatures.length;
ClientHelper.executeWithHeadersAsync(context.headers,
ClientHelper.ML_ORIGIN,
client,
SearchAction.INSTANCE,
searchRequestBuilder.request(),
ActionListener.wrap(
searchResponse -> dataSummaryActionListener.onResponse(
new DataSummary(searchResponse.getHits().getTotalHits().value, numberOfFields)),
dataSummaryActionListener::onFailure
));
}
private SearchRequestBuilder buildDataSummarySearchRequestBuilder() {
QueryBuilder summaryQuery = context.query;
if (context.supportsRowsWithMissingValues == false) {
summaryQuery = QueryBuilders.boolQuery()
.filter(summaryQuery)
.filter(allExtractedFieldsExistQuery());
}
return new SearchRequestBuilder(client, SearchAction.INSTANCE)
.setAllowPartialSearchResults(false)
.setIndices(context.indices)
.setSize(0)
.setQuery(summaryQuery)
.setTrackTotalHits(true);
}
private QueryBuilder allExtractedFieldsExistQuery() {
BoolQueryBuilder query = QueryBuilders.boolQuery();
for (ExtractedField field : context.extractedFields.getAllFields()) {
query.filter(QueryBuilders.existsQuery(field.getName()));
}
return query;
}
public Set<String> getCategoricalFields(DataFrameAnalysis analysis) {
return ExtractedFieldsDetector.getCategoricalOutputFields(context.extractedFields, analysis);
}
public static boolean isValidValue(Object value) {
// We should allow a number, string or a boolean.
// It is possible for a field to be categorical and have a `keyword` mapping, but be any of these
// three types, in the same index.
return value instanceof Number || value instanceof String || value instanceof Boolean;
}
public static class DataSummary {
public final long rows;
public final int cols;
public DataSummary(long rows, int cols) {
this.rows = rows;
this.cols = cols;
}
}
public static class Row {
private final SearchHit hit;
@Nullable
private final String[] values;
private final boolean isTraining;
private Row(String[] values, SearchHit hit, boolean isTraining) {
this.values = values;
this.hit = hit;
this.isTraining = isTraining;
}
@Nullable
public String[] getValues() {
return values;
}
public SearchHit getHit() {
return hit;
}
public boolean shouldSkip() {
return values == null;
}
public boolean isTraining() {
return isTraining;
}
public int getChecksum() {
return (int) getSortKey();
}
public long getSortKey() {
return (long) hit.getSortValues()[0];
}
}
}
|
package com.akh.algorithms.dataStructure.tree.bst;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Stack;
import org.junit.Test;
public class LowestCommonAncestor_BST {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
@Override
public String toString() {
return ("Node val = "+val);
}
}
public TreeNode lowestCommonAncestor_No_Stack(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)
return null;
if(p.val < root.val && q.val < root.val)
return lowestCommonAncestor_No_Stack(root.left, p, q);
if(p.val > root.val && q.val > root.val)
return lowestCommonAncestor_No_Stack(root.right, p, q);
return root;
}
public TreeNode lowestCommonAncestor_2_Stack(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || p == null || q == null)
return null;
Stack<TreeNode> p_Parents = getParents(root, p);
Stack<TreeNode> q_Parents = getParents(root, q);
while(p_Parents.size() > q_Parents.size()) {
p_Parents.pop();
}
while(q_Parents.size() > p_Parents.size()) {
q_Parents.pop();
}
while(!p_Parents.isEmpty() && !q_Parents.isEmpty()) {
if(p_Parents.peek().val == q_Parents.peek().val)
return p_Parents.pop();
else {
p_Parents.pop();
q_Parents.pop();
}
}
return null;
}
public Stack<TreeNode> getParents(TreeNode root, TreeNode target){
Stack<TreeNode> parents = new Stack<>();
search(root, target, parents);
System.out.println(Arrays.deepToString(parents.toArray()));
return parents;
}
private void search(TreeNode root, TreeNode target, Stack<TreeNode> parents) {
if(root == null || target == null)
return;
if(root.val == target.val) { //descendant of itself
parents.push(root);
return;
}
parents.push(root);
if(target.val < root.val) {
search(root.left, target, parents);
}else {
search(root.right, target, parents);
}
}
private TreeNode constructTree(int[] data, int index) {
if(index > data.length-1)
return null;
if(data[index] == -1) {
return null;
}
TreeNode node = new TreeNode(data[index]);
node.left = constructTree(data, getLeftChildIndex(index));
node.right = constructTree(data, getRightChildIndex(index));
return node;
}
private int getParentIndex(int childIndex) {
return ((childIndex - 1) / 2);
}
private int getLeftChildIndex(int parentIndex) {
return ((parentIndex * 2) + 1);
}
private int getRightChildIndex(int parentIndex) {
return ((parentIndex * 2) + 2);
}
@Test
public void test_1(){
LowestCommonAncestor_BST lowestCommonAncestor = new LowestCommonAncestor_BST();
int[] arr = {6,2,8,0,4,7,9,-1,-1,3,5};
TreeNode root = lowestCommonAncestor.constructTree(arr, 0);
TreeNode p = new TreeNode(2);
TreeNode q = new TreeNode(8);
//TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_2_Stack(root, p, q);
TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_No_Stack(root, p, q);
System.out.println("LowestCommonAncestor of "+p.val+" & "+q.val+" ==> "+commonAncestor.val);
assertEquals(6, commonAncestor.val);
}
@Test
public void test_2(){
LowestCommonAncestor_BST lowestCommonAncestor = new LowestCommonAncestor_BST();
int[] arr = {6,2,8,0,4,7,9,-1,-1,3,5};
TreeNode root = lowestCommonAncestor.constructTree(arr, 0);
TreeNode p = new TreeNode(2);
TreeNode q = new TreeNode(4);
//TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_2_Stack(root, p, q);
TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_No_Stack(root, p, q);
System.out.println("LowestCommonAncestor of "+p.val+" & "+q.val+" ==> "+commonAncestor.val);
assertEquals(2, commonAncestor.val);
}
@Test
public void test_One_Not_Child(){
LowestCommonAncestor_BST lowestCommonAncestor = new LowestCommonAncestor_BST();
int[] arr = {6,2,8,0,4,7,9,-1,-1,3,5};
TreeNode root = lowestCommonAncestor.constructTree(arr, 0);
TreeNode p = new TreeNode(-2);
TreeNode q = new TreeNode(4);
//TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_2_Stack(root, p, q);
TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_No_Stack(root, p, q);
if(commonAncestor != null) {
System.out.println("LowestCommonAncestor of "+p.val+" & "+q.val+" ==> "+commonAncestor.val);
}
assertTrue(commonAncestor == null);
}
@Test
public void test_Both_Not_Child(){
LowestCommonAncestor_BST lowestCommonAncestor = new LowestCommonAncestor_BST();
int[] arr = {6,2,8,0,4,7,9,-1,-1,3,5};
TreeNode root = lowestCommonAncestor.constructTree(arr, 0);
TreeNode p = new TreeNode(-2);
TreeNode q = new TreeNode(40);
//TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_2_Stack(root, p, q);
TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_No_Stack(root, p, q);
if(commonAncestor != null) {
System.out.println("LowestCommonAncestor of "+p.val+" & "+q.val+" ==> "+commonAncestor.val);
}
assertTrue(commonAncestor == null);
}
@Test
public void test_Empty_Tree(){
LowestCommonAncestor_BST lowestCommonAncestor = new LowestCommonAncestor_BST();
int[] arr = {};
TreeNode root = lowestCommonAncestor.constructTree(arr, 0);
TreeNode p = new TreeNode(-2);
TreeNode q = new TreeNode(40);
//TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_2_Stack(root, p, q);
TreeNode commonAncestor = lowestCommonAncestor.lowestCommonAncestor_No_Stack(root, p, q);
if(commonAncestor != null) {
System.out.println("LowestCommonAncestor of "+p.val+" & "+q.val+" ==> "+commonAncestor.val);
}
assertTrue(commonAncestor == null);
}
}
|
package com.heavyplayer.audioplayerrecorder.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import com.heavyplayer.audioplayerrecorder.R;
import com.heavyplayer.audioplayerrecorder.widget.interface_.OnDetachListener;
public class AudioPlayerLayout extends ViewGroup {
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
public OnDetachListener mOnDetachListener;
private PlayPauseImageButton mButton;
private SeekBar mSeekBar;
private TextView mLengthTextView;
// Attributes.
private Integer mPlayResId;
private Integer mPauseResId;
private Integer mButtonWidth;
private Integer mButtonHeight;
private Integer mButtonBackgroundResId;
private Integer mSeekBarMarginLeft;
private Integer mSeekBarMarginRight;
private int mLengthCurrentPosition = -1;
private String mLengthCurrentPositionStr;
private int mLengthDuration = -1;
private String mLengthDurationStr;
public AudioPlayerLayout(Context context) {
super(context);
init(context, null);
}
public AudioPlayerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public AudioPlayerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS); // Enhance compatibility with ListView.
// Set time.
setLengthDuration(0, false);
setLengthCurrentPosition(0, false);
updateLength();
if(attrs != null) {
final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AudioPlayerLayout);
if(ta != null) {
try {
mPlayResId = getResourceId(ta, R.styleable.AudioPlayerLayout_playSrc);
mPauseResId = getResourceId(ta, R.styleable.AudioPlayerLayout_pauseSrc);
mButtonWidth = getDimensionPixelSize(ta, R.styleable.AudioPlayerLayout_buttonWidth);
mButtonHeight = getDimensionPixelSize(ta, R.styleable.AudioPlayerLayout_buttonHeight);
mButtonBackgroundResId = getResourceId(ta, R.styleable.AudioPlayerLayout_buttonBackground);
mSeekBarMarginLeft = getDimensionPixelSize(ta, R.styleable.AudioPlayerLayout_seekBarMarginLeft);
mSeekBarMarginRight = getDimensionPixelSize(ta, R.styleable.AudioPlayerLayout_seekBarMarginRight);
} finally {
ta.recycle();
}
}
}
}
private Integer getResourceId(TypedArray ta, int index) {
return ta.hasValue(index) ? ta.getResourceId(index, 0) : null;
}
private Integer getDimensionPixelSize(TypedArray ta, int index) {
return ta.hasValue(index) ? ta.getDimensionPixelSize(index, 0) : null;
}
@Override
public void addView(View child, int index, LayoutParams params) {
final int id = child.getId();
switch(id) {
case android.R.id.button1:
if(!(child instanceof PlayPauseImageButton))
throw new IllegalStateException("View with id android.R.id.button1 must extend PlayPauseImageButton.");
mButton = (PlayPauseImageButton)child;
if(mButtonWidth != null || mButtonHeight != null) {
if(params == null)
params = new LayoutParams(
mButtonWidth != null ? mButtonWidth : LayoutParams.WRAP_CONTENT,
mButtonHeight!= null ? mButtonHeight : LayoutParams.WRAP_CONTENT);
else {
if(mButtonWidth != null)
params.width = mButtonWidth;
if(mButtonHeight != null)
params.height = mButtonHeight;
}
}
// Configure button.
if(mPlayResId != null)
mButton.setPlayDrawableResource(mPlayResId);
if(mPauseResId != null)
mButton.setPauseDrawableResource(mPauseResId);
if(mButtonBackgroundResId != null) {
mButton.setPadding(0, 0, 0, 0); // Remove image button padding, before setting the background.
mButton.setBackgroundResource(mButtonBackgroundResId);
}
break;
case android.R.id.progress:
if(!(child instanceof SeekBar))
throw new IllegalStateException("View with id android.R.id.progress must extend SeekBar.");
mSeekBar = (SeekBar)child;
// Configure seek bar layout params.
if(!(params instanceof MarginLayoutParams)) {
params = params == null ?
new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) :
new MarginLayoutParams(params);
}
if(mSeekBarMarginLeft != null)
((MarginLayoutParams)params).leftMargin = mSeekBarMarginLeft;
if(mSeekBarMarginRight != null)
((MarginLayoutParams)params).rightMargin = mSeekBarMarginRight;
break;
case android.R.id.text1:
if(!(child instanceof TextView))
throw new IllegalStateException("View with android.R.id.text1 must extend TextView.");
mLengthTextView = (TextView)child;
mLengthTextView.setFreezesText(true);
break;
default:
break;
}
super.addView(child, index, params);
}
@Override
protected void onFinishInflate() {
final Context context = getContext();
if(context != null) {
if(findViewById(android.R.id.button1) == null) {
final PlayPauseImageButton button = new PlayPauseImageButton(context);
button.setId(android.R.id.button1);
addView(button);
}
if(findViewById(android.R.id.progress) == null) {
final SeekBar seekBar = new SeekBar(context);
seekBar.setId(android.R.id.progress);
final MarginLayoutParams seekBarParams =
new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
final Resources resources = getResources();
// Default margins.
if(resources != null) {
seekBarParams.leftMargin = resources.getDimensionPixelSize(R.dimen.apl_seek_bar_margin_left);
seekBarParams.rightMargin = resources.getDimensionPixelSize(R.dimen.apl_seek_bar_margin_right);
}
addView(seekBar, seekBarParams);
}
if(findViewById(android.R.id.text1) == null) {
final TextView textView = new TextView(context);
textView.setId(android.R.id.text1);
addView(textView);
}
}
// Make sure the length is initialized.
updateLength();
super.onFinishInflate();
}
public PlayPauseImageButton getButton() {
return mButton;
}
public SeekBar getSeekBar() {
return mSeekBar;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Measure button.
measureChild(mButton, widthMeasureSpec, heightMeasureSpec);
// Measure length text view.
measureChild(mLengthTextView, widthMeasureSpec, heightMeasureSpec);
// Measure seek bar.
final int remainingWidth =
MeasureSpec.getSize(widthMeasureSpec) -
mButton.getMeasuredWidth() -
mLengthTextView.getMeasuredWidth();
final int remainingWidthMeasureSpec = MeasureSpec.makeMeasureSpec(remainingWidth, MeasureSpec.EXACTLY);
measureChildWithMargins(mSeekBar, remainingWidthMeasureSpec, 0, heightMeasureSpec, 0);
// Calculate max width and height, taking padding into account.
final int measuredWidth =
mButton.getMeasuredWidth() +
mSeekBar.getMeasuredWidth() +
mLengthTextView.getMeasuredWidth() +
getPaddingLeft() + getPaddingRight();
final int measuredHeight =
Math.max(
Math.max(mButton.getMeasuredHeight(), mSeekBar.getMeasuredHeight()),
mLengthTextView.getMeasuredHeight()) +
getPaddingTop() + getPaddingBottom();
setMeasuredDimension(
resolveSize(measuredWidth, widthMeasureSpec),
resolveSize(measuredHeight, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Layout button.
int left = getPaddingLeft();
layoutChild(mButton, left, t, b);
// Layout seek bar.
final MarginLayoutParams seekBarParams = (MarginLayoutParams)mSeekBar.getLayoutParams();
final int seekBarMarginLeft = seekBarParams != null ? seekBarParams.leftMargin : 0;
final int seekBarMarginRight = seekBarParams != null ? seekBarParams.rightMargin : 0;
left += mButton.getMeasuredWidth() + seekBarMarginLeft;
layoutChild(mSeekBar, left, t, b);
// Layout length text view.
left += mSeekBar.getMeasuredWidth() + seekBarMarginRight;
layoutChild(mLengthTextView, left, t, b);
}
protected void layoutChild(View child, int l, int t, int b) {
final int height = b - t;
final int measuredHeight = child.getMeasuredHeight();
final int nt = (int)((height - measuredHeight) / 2 + .5f);
child.layout(l, nt, l + child.getMeasuredWidth(), nt + measuredHeight);
}
public void setLengthCurrentPosition(int currentPosition) {
if(mLengthCurrentPosition != currentPosition)
setLengthCurrentPosition(currentPosition, true);
}
protected void setLengthCurrentPosition(int currentPosition, boolean update) {
mLengthCurrentPosition = currentPosition;
mLengthCurrentPositionStr = millisToTimeString(mLengthCurrentPosition);
if(update)
updateLength();
}
public void setLengthDuration(int duration) {
if(mLengthDuration != duration)
setLengthDuration(duration, true);
}
protected void setLengthDuration(int duration, boolean update) {
// Update length current position if it needs to include or exclude hours
// depending on the duration.
final boolean updateCurrentPosition = includeHours(mLengthDuration) != includeHours(duration);
mLengthDuration = duration;
mLengthDurationStr = millisToTimeString(mLengthDuration);
if(updateCurrentPosition)
setLengthCurrentPosition(mLengthCurrentPosition, false);
if(update)
updateLength();
}
private void updateLength() {
if(mLengthTextView != null)
mLengthTextView.setText(String.format("%s / %s", mLengthCurrentPositionStr, mLengthDurationStr));
}
private String millisToTimeString(long millis) {
final long seconds = (millis / SECOND_MILLIS) % 60 ;
final long minutes = ((millis / MINUTE_MILLIS) % 60);
final long hours = ((millis / HOUR_MILLIS) % 24);
return includeHours(mLengthDuration) ?
String.format("%02d:%02d:%02d", hours, minutes, seconds) :
String.format("%02d:%02d", minutes, seconds);
}
private boolean includeHours(long millis) {
return millis >= HOUR_MILLIS;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if(mOnDetachListener != null)
mOnDetachListener.onDetachedFromWindow(this);
}
@Override
public void onStartTemporaryDetach() {
super.onStartTemporaryDetach();
if(mOnDetachListener != null)
mOnDetachListener.onStartTemporaryDetach(this);
}
public void setOnDetachListener(OnDetachListener listener) {
mOnDetachListener = listener;
}
@Override
protected void dispatchSaveInstanceState(SparseArray container) {
super.dispatchFreezeSelfOnly(container);
}
@Override
protected void dispatchRestoreInstanceState(SparseArray container) {
super.dispatchThawSelfOnly(container);
}
@Override
protected Parcelable onSaveInstanceState() {
final SavedState ss = new SavedState(super.onSaveInstanceState());
ss.buttonSavedState = mButton.onSaveInstanceState();
ss.seekBarSavedState = mSeekBar.onSaveInstanceState();
ss.lengthCurrentPosition = mLengthCurrentPosition;
ss.lengthDuration = mLengthDuration;
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if(!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
final SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
mButton.onRestoreInstanceState(ss.buttonSavedState);
mSeekBar.onRestoreInstanceState(ss.seekBarSavedState);
// Update length.
setLengthDuration(ss.lengthDuration, false);
setLengthCurrentPosition(ss.lengthCurrentPosition, false);
updateLength();
}
static class SavedState extends BaseSavedState {
Parcelable buttonSavedState;
Parcelable seekBarSavedState;
int lengthCurrentPosition;
int lengthDuration;
public SavedState(Parcel source) {
super(source);
buttonSavedState = source.readParcelable(SavedState.class.getClassLoader());
seekBarSavedState = source.readParcelable(SavedState.class.getClassLoader());
lengthCurrentPosition = source.readInt();
lengthDuration = source.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeParcelable(buttonSavedState, 0);
dest.writeParcelable(seekBarSavedState, 0);
dest.writeInt(lengthCurrentPosition);
dest.writeInt(lengthDuration);
}
public SavedState(Parcelable superState) {
super(superState);
}
public final static Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[0];
}
};
}
}
|
package org.osgi.impl.service.midletcontainer;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.*;
import javax.microedition.midlet.MIDlet;
import org.osgi.framework.*;
import org.osgi.service.application.*;
public final class MidletDescriptor extends ApplicationDescriptor {
private Properties props;
private Hashtable names;
private Hashtable icons;
private BundleContext bc;
private String startClass;
private String pid;
private Bundle bundle;
private String defaultLanguage;
private boolean locked;
private MidletContainer midletContainer;
private static int instanceCounter;
public MidletDescriptor(BundleContext bc, Properties props, Map names, Map icons,
String defaultLang, String startClass, Bundle bundle,
MidletContainer midletContainer) throws Exception {
super( (String)props.get(Constants.SERVICE_PID) );
this.bc = bc;
this.midletContainer = midletContainer;
this.props = new Properties();
this.props.putAll(props);
this.names = new Hashtable(names);
this.icons = new Hashtable(icons);
this.startClass = startClass;
this.bundle = bundle;
if (names.size() == 0 || icons.size() == 0
|| !props.containsKey("application.bundle.id")
|| !props.containsKey(Constants.SERVICE_PID)
|| !props.containsKey(ApplicationDescriptor.APPLICATION_VERSION))
throw new Exception("Invalid MEG container input!");
if (!names.containsKey(defaultLang)) {
throw new Exception("Invalid default language!");
}
else {
defaultLanguage = defaultLang;
pid = props.getProperty(Constants.SERVICE_PID);
return;
}
}
public long getBundleId() {
return Long.parseLong(props.getProperty("application.bundle.id"));
}
Bundle getBundle() {
return bundle;
}
public String getStartClass() {
return startClass;
}
public String getPID() {
return pid;
}
protected BundleContext getBundleContext() {
return bc;
}
public Map getPropertiesSpecific(String locale) {
Hashtable properties = new Hashtable();
if( locale == null )
locale = "";
String localizedName = (String) names.get(locale);
if (localizedName == null) {
if ((localizedName = (String) names.get(defaultLanguage)) == null) {
Enumeration enum = names.keys();
String firstKey = (String) enum.nextElement();
localizedName = (String) names.get(firstKey);
locale = firstKey;
}
else {
localizedName = (String) names.get(defaultLanguage);
}
locale = defaultLanguage;
}
properties.put(ApplicationDescriptor.APPLICATION_NAME, localizedName);
properties.put(ApplicationDescriptor.APPLICATION_ICON, icons.get(locale));
properties.put("application.bundle.id", props
.getProperty("application.bundle.id"));
properties.put(ApplicationDescriptor.APPLICATION_VERSION, props
.getProperty(ApplicationDescriptor.APPLICATION_VERSION));
properties.put(ApplicationDescriptor.APPLICATION_VENDOR, props
.getProperty(ApplicationDescriptor.APPLICATION_VENDOR));
String visible = props.getProperty(ApplicationDescriptor.APPLICATION_VISIBLE);
if (visible != null && visible.equalsIgnoreCase("false"))
properties.put(ApplicationDescriptor.APPLICATION_VISIBLE, "false");
else
properties.put(ApplicationDescriptor.APPLICATION_VISIBLE, "true");
boolean launchable = false;
try {
launchable = isLaunchable();
}
catch (Exception e) {
MidletContainer.log(bc,1,"Exception occurred at searching the Midlet container reference!",e);
}
properties.put(ApplicationDescriptor.APPLICATION_LOCKED, (new Boolean(locked)).toString());
properties.put(ApplicationDescriptor.APPLICATION_LAUNCHABLE, (new Boolean(launchable))
.toString());
properties.put(ApplicationDescriptor.APPLICATION_CONTAINER, "MIDlet");
properties.put(Constants.SERVICE_PID, new String(pid));
return properties;
}
public ApplicationHandle launchSpecific(Map args) throws Exception {
MIDlet midlet = createMidletInstance();
if (midlet == null)
throw new Exception("Cannot create meglet instance!");
else {
MidletHandle midHnd = new MidletHandle(bc, createNewInstanceID(pid), this,
midletContainer, midlet, startClass );
midHnd.startHandle(args);
return midHnd;
}
}
public void lockSpecific() {
locked = true;
}
public void unlockSpecific() {
locked = false;
}
static synchronized String createNewInstanceID(String pid) {
return new String(pid + ":" + instanceCounter++);
}
public boolean isLaunchable() {
try {
if ( locked )
return false;
if( !midletContainer.getOATInterface().isLaunchable( getBundle(), startClass ) )
return false;
return true;
}
catch (Exception e) {
MidletContainer.log(bc, 1, "Exception occurred at checking if the midlet is launchable!", e);
}
return false;
}
public MIDlet createMidletInstance() throws Exception {
return (MIDlet)AccessController.doPrivileged(new PrivilegedExceptionAction() {
public java.lang.Object run() throws Exception {
Bundle appBundle = bc.getBundle(getBundleId());
Class mainClass = appBundle.loadClass(getStartClass());
String mainClassFileName = getStartClass().replace( '.', '/' ) + ".class";
URL url = appBundle.getResource( mainClassFileName );
if( url == null )
throw new Exception( "Internal error!" );
String urlName = url.toString();
if( !urlName.endsWith( mainClassFileName ) )
throw new Exception( "Internal error!" );
String location = urlName.substring( 0, urlName.length() - mainClassFileName.length() );
ClassLoader loader = new MIDletClassLoader(mainClass.getClassLoader(),
appBundle, mainClass.getProtectionDomain(), location );
Class midletClass = loader.loadClass(getStartClass());
Constructor constructor = midletClass
.getDeclaredConstructor(new Class[0]);
constructor.setAccessible(true);
MIDlet app = (MIDlet) constructor.newInstance(new Object[0]);
return app;
}});
}
}
|
package org.intermine.bio.dataconversion;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.intermine.metadata.ConstraintOp;
import org.intermine.metadata.StringUtil;
import org.intermine.model.bio.Publication;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.util.SAXParser;
import org.intermine.xml.full.FullRenderer;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ItemFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
/**
* Class to fill in all publication information from pubmed
* @author Mark Woodbridge
*/
public class EntrezPublicationsRetriever
{
protected static final Logger LOG = Logger.getLogger(EntrezPublicationsRetriever.class);
protected static final String ENDL = System.getProperty("line.separator");
// full record (new)
// rettype=abstract or just leave it out
protected static final String EFETCH_URL =
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?tool=flymine&db=pubmed"
+ "&rettype=abstract&retmode=xml&id=";
// summary
protected static final String ESUMMARY_URL =
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?tool=flymine&db=pubmed&id=";
// number of records to retrieve per request
protected static final int BATCH_SIZE = 500;
// number of times to try the same batch from the server
private static final int MAX_TRIES = 5;
private String osAlias = null, outputFile = null;
private Set<Integer> seenPubMeds = new HashSet<Integer>();
private Map<String, Item> authorMap = new HashMap<String, Item>();
private String cacheDirName = "build/";
private ItemFactory itemFactory;
private boolean loadFullRecord = false;
private Map<String, Item> meshTerms = new HashMap<String, Item>();
/**
* Load summary version of Publication record by default. If this boolean (loadFullRecord)
* is true, load all data, eg. abstract, MeSH terms etc.
*
* @param loadFullRecord if TRUE load full record of publication.
*/
public void setLoadFullRecord(String loadFullRecord) {
if ("true".equalsIgnoreCase(loadFullRecord)) {
this.loadFullRecord = true;
}
}
/**
* Set the ObjectStore alias.
* @param osAlias The ObjectStore alias
*/
public void setOsAlias(String osAlias) {
this.osAlias = osAlias;
}
/**
* Set the output file name
* @param outputFile The output file name
*/
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
/**
* Set the cache file name
* @param cacheDirName The cache file
*/
public void setCacheDirName(String cacheDirName) {
if (!cacheDirName.startsWith("${")) {
this.cacheDirName = cacheDirName;
}
}
/**
* Synchronize publications with pubmed using pmid
* @throws Exception if an error occurs
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void execute() throws Exception {
// Needed so that STAX can find it's implementation classes
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
Database db = null;
Transaction txn = null;
try {
if (osAlias == null) {
throw new BuildException("osAlias attribute is not set");
}
if (outputFile == null) {
throw new BuildException("outputFile attribute is not set");
}
// environment is transactional
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
/**
* Add a Map of pubication information to the Database
*/
private static void addToDb(Transaction txn, Database db,
Map<String, Map<String, Object>> fromServerMap)
throws IOException, DatabaseException {
for (Map.Entry<String, Map<String, Object>> entry: fromServerMap.entrySet()) {
String pubMedId = entry.getKey();
DatabaseEntry key = new DatabaseEntry(pubMedId.getBytes());
Map dataMap = entry.getValue();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream serializer = new ObjectOutputStream(arrayOutputStream);
serializer.writeObject(dataMap);
DatabaseEntry data = new DatabaseEntry(arrayOutputStream.toByteArray());
db.put(txn, key, data);
}
}
/**
* Retrieve the publications to be updated
* @param os The ObjectStore to read from
* @return a List of publications
*/
protected List<Publication> getPublications(ObjectStore os) {
Query q = new Query();
QueryClass qc = new QueryClass(Publication.class);
q.addFrom(qc);
q.addToSelect(qc);
ConstraintSet cs = new ConstraintSet(ConstraintOp.OR);
SimpleConstraint scTitle =
new SimpleConstraint(new QueryField(qc, "title"), ConstraintOp.IS_NULL);
cs.addConstraint(scTitle);
SimpleConstraint scYear =
new SimpleConstraint(new QueryField(qc, "year"), ConstraintOp.IS_NULL);
cs.addConstraint(scYear);
SimpleConstraint scFirstAuthor =
new SimpleConstraint(new QueryField(qc, "firstAuthor"), ConstraintOp.IS_NULL);
cs.addConstraint(scFirstAuthor);
q.setConstraint(cs);
List<Publication> retval = ((List) os.executeSingleton(q));
return retval;
}
/**
* Obtain the pubmed esummary information for the publications
* @param ids the pubMedIds of the publications
* @return a Reader for the information
* @throws Exception if an error occurs
*/
protected Reader getReader(Set<Integer> ids) throws Exception {
String urlString = ESUMMARY_URL + StringUtil.join(ids, ",");
if (loadFullRecord) {
urlString = EFETCH_URL + StringUtil.join(ids, ",");
}
System.err .println("retrieving: " + urlString);
return new BufferedReader(new InputStreamReader(new URL(urlString).openStream()));
}
private Set<Item> mapToItems(ItemFactory factory, Map map) {
Set<Item> retSet = new HashSet<Item>();
Item publication = factory.makeItemForClass("Publication");
retSet.add(publication);
publication.setAttribute("pubMedId", (String) map.get("id"));
final String title = (String) map.get("title");
if (!StringUtils.isEmpty(title)) {
publication.setAttribute("title", title);
}
final String journal = (String) map.get("journal");
if (!StringUtils.isEmpty(journal)) {
publication.setAttribute("journal", journal);
}
final String volume = (String) map.get("volume");
if (!StringUtils.isEmpty(volume)) {
publication.setAttribute("volume", volume);
}
final String issue = (String) map.get("issue");
if (!StringUtils.isEmpty(issue)) {
publication.setAttribute("issue", issue);
}
final String pages = (String) map.get("pages");
if (!StringUtils.isEmpty(pages)) {
publication.setAttribute("pages", pages);
}
if (map.get("year") != null) {
publication.setAttribute("year", (String) map.get("year"));
}
final String abstractText = (String) map.get("abstractText");
if (!StringUtils.isEmpty(abstractText)) {
publication.setAttribute("abstractText", abstractText);
}
final String month = (String) map.get("month");
if (!StringUtils.isEmpty(month)) {
publication.setAttribute("month", month);
}
final String doi = (String) map.get("doi");
if (!StringUtils.isEmpty(doi)) {
publication.setAttribute("doi", doi);
}
final List<String> termsToStore = (List<String>) map.get("meshTerms");
if (termsToStore != null && !termsToStore.isEmpty()) {
processMeshTerms(publication, termsToStore);
}
List<String> authors = (List<String>) map.get("authors");
if (authors != null) {
for (String authorString : authors) {
Item author = authorMap.get(authorString);
if (author == null) {
author = factory.makeItemForClass("Author");
author.setAttribute("name", authorString);
authorMap.put(authorString, author);
}
publication.addToCollection("authors", author);
if (!publication.hasAttribute("firstAuthor")) {
publication.setAttribute("firstAuthor", authorString);
}
}
}
return retSet;
}
private void processMeshTerms(Item publication, List<String> newTerms) {
for (String name : newTerms) {
Item item = meshTerms.get(name);
if (item == null) {
item = itemFactory.makeItemForClass("MeshTerm");
item.setAttribute("name", name);
meshTerms.put(name, item);
}
publication.addToCollection("meshTerms", item);
}
}
/**
* Extension of DefaultHandler to handle for a publication
*/
class FullRecordHandler extends DefaultHandler
{
private Map<String, Object> pubMap;
private StringBuffer characters;
private boolean duplicateEntry = false;
private Map<String, Map<String, Object>> cache;
private Stack<String> stack = new Stack<String>();
private String name;
private AuthorHolder authorHolder = null; // holds first and last name
/**
* Constructor
* @param fromServerMap cache of publications
*/
public FullRecordHandler(Map<String, Map<String, Object>> fromServerMap) {
this.cache = fromServerMap;
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
name = null;
if ("ArticleId".equals(qName) && "doi".equals(attrs.getValue("IdType"))) {
name = "doi";
} else if ("DescriptorName".equals(qName)) {
name = "meshTerm";
}
stack.push(qName);
characters = new StringBuffer();
}
/**
* {@inheritDoc}
*/
@Override
public void characters(char[] ch, int start, int length) {
int st = start;
int l = length;
// DefaultHandler may call this method more than once for a single
// attribute content -> hold text & create attribute in endElement
while (l > 0) {
boolean whitespace = false;
switch(ch[st]) {
case ' ':
case '\r':
case '\n':
case '\t':
whitespace = true;
break;
default:
break;
}
if (!whitespace) {
break;
}
++st;
--l;
}
if (l > 0) {
StringBuffer s = new StringBuffer();
s.append(ch, st, l);
characters.append(s);
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public void endElement(String uri, String localName, String qName) {
stack.pop();
if (duplicateEntry) {
return;
}
if ("ERROR".equals(name)) {
LOG.error("Unable to retrieve pubmed record: " + characters);
} else if ("PMID".equals(qName) && "MedlineCitation".equals(stack.peek())) {
String pubMedId = characters.toString();
Integer pubMedIdInteger;
try {
pubMedIdInteger = Integer.valueOf(pubMedId);
if (seenPubMeds.contains(pubMedId)) {
duplicateEntry = true;
return;
}
pubMap = new HashMap<String, Object>();
pubMap.put("id", pubMedId);
seenPubMeds.add(pubMedIdInteger);
cache.put(pubMedId, pubMap);
} catch (NumberFormatException e) {
throw new RuntimeException("got non-integer pubmed id from NCBI: " + pubMedId);
}
} else if ("Year".equalsIgnoreCase(qName) && !stack.isEmpty()
&& "PubDate".equals(stack.peek())) {
String year = characters.toString();
try {
Integer.parseInt(year);
pubMap.put("year", year);
} catch (NumberFormatException e) {
LOG.warn("Cannot parse year from publication: " + characters.toString());
}
} else if ("Journal".equals(qName)) {
pubMap.put("journal", characters.toString());
} else if ("ArticleTitle".equals(qName)) {
pubMap.put("title", characters.toString());
} else if ("Volume".equals(qName)) {
pubMap.put("volume", characters.toString());
} else if ("Issue".equals(qName)) {
pubMap.put("issue", characters.toString());
} else if ("MedlinePgn".equals(qName)) {
pubMap.put("pages", characters.toString());
} else if ("AbstractText".equals(qName)) {
String abstractText = (String) pubMap.get("abstractText");
if (StringUtils.isEmpty(abstractText)) {
abstractText = characters.toString();
} else {
abstractText += " " + characters.toString();
}
pubMap.put("abstractText", abstractText);
} else if ("Month".equalsIgnoreCase(qName) && !stack.isEmpty()
&& "PubDate".equals(stack.peek())) {
pubMap.put("month", characters.toString());
} else if ("doi".equals(name) && "ArticleId".equals(qName)) {
pubMap.put("doi", characters.toString());
} else if ("meshTerm".equals(name) && "DescriptorName".equals(qName)) {
String termName = characters.toString();
List<String> termList = (List<String>) pubMap.get("meshTerms");
if (termList == null) {
termList = new ArrayList<String>();
pubMap.put("meshTerms", termList);
}
termList.add(termName);
} else if (!stack.isEmpty() && "Author".equals(stack.peek())) {
if (authorHolder == null) {
authorHolder = new AuthorHolder();
}
if ("ForeName".equals(qName)) {
authorHolder.firstName = characters.toString();
} else if ("LastName".equals(qName)) {
authorHolder.lastName = characters.toString();
} else if ("CollectiveName".equals(qName)) {
authorHolder.collectiveName = characters.toString();
}
} else if ("Author".equals(qName)) {
String authorString = authorHolder.getName();
List<String> authorList = (List<String>) pubMap.get("authors");
if (authorList == null) {
authorList = new ArrayList<String>();
pubMap.put("authors", authorList);
}
authorList.add(authorString);
authorHolder = null;
}
name = null;
}
private class AuthorHolder
{
protected String firstName;
protected String lastName;
protected String collectiveName;
protected String getName() {
if (StringUtils.isNotEmpty(collectiveName)) {
return collectiveName;
}
return lastName + " " + firstName;
}
}
}
/**
* Extension of DefaultHandler to handle an esummary for a publication
*/
class SummaryRecordHandler extends DefaultHandler
{
Map<String, Object> pubMap;
String name;
StringBuffer characters;
boolean duplicateEntry = false;
Map<String, Map<String, Object>> cache;
/**
* Constructor
* @param fromServerMap cache of publications
*/
public SummaryRecordHandler(Map<String, Map<String, Object>> fromServerMap) {
this.cache = fromServerMap;
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
if ("ERROR".equals(qName)) {
name = qName;
} else if ("Id".equals(qName)) {
name = "Id";
} else if ("DocSum".equals(qName)) {
duplicateEntry = false;
} else {
name = attrs.getValue("Name");
}
characters = new StringBuffer();
}
/**
* {@inheritDoc}
*/
@Override
public void characters(char[] ch, int start, int length) {
characters.append(new String(ch, start, length));
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(String uri, String localName, String qName) {
// do nothing if we have seen this pubmed id before
if (duplicateEntry) {
return;
}
if ("ERROR".equals(name)) {
LOG.error("Unable to retrieve pubmed record: " + characters);
} else if ("Id".equals(name)) {
String pubMedId = characters.toString();
Integer pubMedIdInteger;
try {
pubMedIdInteger = Integer.valueOf(pubMedId);
if (seenPubMeds.contains(pubMedId)) {
duplicateEntry = true;
return;
}
pubMap = new HashMap<String, Object>();
pubMap.put("id", pubMedId);
seenPubMeds.add(pubMedIdInteger);
cache.put(pubMedId, pubMap);
} catch (NumberFormatException e) {
throw new RuntimeException("got non-integer pubmed id from NCBI: " + pubMedId);
}
} else if ("PubDate".equals(name)) {
String year = characters.toString().split(" ")[0];
try {
Integer.parseInt(year);
pubMap.put("year", year);
} catch (NumberFormatException e) {
LOG.warn("Cannot parse year from publication: " + year);
}
} else if ("Source".equals(name)) {
pubMap.put("journal", characters.toString());
} else if ("Title".equals(name)) {
pubMap.put("title", characters.toString());
} else if ("Volume".equals(name)) {
pubMap.put("volume", characters.toString());
} else if ("Issue".equals(name)) {
pubMap.put("issue", characters.toString());
} else if ("Pages".equals(name)) {
pubMap.put("pages", characters.toString());
} else if ("Author".equals(name)) {
String authorString = characters.toString();
@SuppressWarnings("unchecked")
List<String> authorList = (List<String>) pubMap.get("authors");
if (authorList == null) {
authorList = new ArrayList<String>();
pubMap.put("authors", authorList);
}
authorList.add(authorString);
}
name = null;
}
}
}
|
package org.intermine.bio.dataconversion;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.util.SAXParser;
import org.intermine.util.StringUtil;
import org.intermine.xml.full.FullRenderer;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ItemFactory;
import org.intermine.model.bio.Publication;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.commons.lang.StringUtils;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
/**
* Class to fill in all publication information from pubmed
* @author Mark Woodbridge
*/
public class EntrezPublicationsRetriever
{
protected static final Logger LOG = Logger.getLogger(EntrezPublicationsRetriever.class);
protected static final String ENDL = System.getProperty("line.separator");
protected static final String ESUMMARY_URL =
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?tool=flymine&db=pubmed&id=";
// number of summaries to retrieve per request
protected static final int BATCH_SIZE = 500;
// number of times to try the same bacth from the server
private static final int MAX_TRIES = 5;
private String osAlias = null, outputFile = null;
private Set<Integer> seenPubMeds = new HashSet<Integer>();
private Map<String, Item> authorMap = new HashMap<String, Item>();
private String cacheDirName;
private ItemFactory itemFactory;
/**
* Set the ObjectStore alias.
* @param osAlias The ObjectStore alias
*/
public void setOsAlias(String osAlias) {
this.osAlias = osAlias;
}
/**
* Set the output file name
* @param outputFile The output file name
*/
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
/**
* Set the cache file name
* @param cacheDirName The cache file
*/
public void setCacheDirName(String cacheDirName) {
this.cacheDirName = cacheDirName;
}
/**
* Synchronize publications with pubmed using pmid
* @throws Exception if an error occurs
*/
public void execute() throws Exception {
// Needed so that STAX can find it's implementation classes
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
Database db = null;
Transaction txn = null;
try {
if (osAlias == null) {
throw new BuildException("osAlias attribute is not set");
}
if (outputFile == null) {
throw new BuildException("outputFile attribute is not set");
}
// environment is transactional
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
Environment env = new Environment(new File(cacheDirName), envConfig);
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setTransactional(true);
dbConfig.setAllowCreate(true);
dbConfig.setSortedDuplicates(true);
db = env.openDatabase(null , "publications_db", dbConfig);
txn = env.beginTransaction(null, null);
LOG.info("Starting EntrezPublicationsRetriever");
Writer writer = new FileWriter(outputFile);
ObjectStore os = ObjectStoreFactory.getObjectStore(osAlias);
Set<Integer> idsToFetch = new HashSet<Integer>();
itemFactory = new ItemFactory(os.getModel(), "-1_");
writer.write(FullRenderer.getHeader() + ENDL);
for (Iterator<Publication> iter = getPublications(os).iterator(); iter.hasNext();) {
String pubMedId = iter.next().getPubMedId();
Integer pubMedIdInteger;
try {
pubMedIdInteger = Integer.valueOf(pubMedId);
} catch (NumberFormatException e) {
// not a pubmed id
continue;
}
if (seenPubMeds.contains(pubMedIdInteger)) {
continue;
}
DatabaseEntry key = new DatabaseEntry(pubMedId.getBytes());
DatabaseEntry data = new DatabaseEntry();
if (db.get(txn, key, data, null).equals(OperationStatus.SUCCESS)) {
try {
ByteArrayInputStream mapInputStream =
new ByteArrayInputStream(data.getData());
ObjectInputStream deserializer = new ObjectInputStream(mapInputStream);
Map<String, Object> pubMap = (Map) deserializer.readObject();
writeItems(writer, mapToItems(itemFactory, pubMap));
// System.err. println("found in cache: " + pubMedId);
seenPubMeds.add(pubMedIdInteger);
} catch (EOFException e) {
// ignore and fetch it again
System.err .println("found in cache, but igored due to cache problem: "
+ pubMedIdInteger);
}
} else {
idsToFetch.add(pubMedIdInteger);
}
}
Iterator<Integer> idIter = idsToFetch.iterator();
Set<Integer> thisBatch = new HashSet<Integer>();
while (idIter.hasNext()) {
Integer pubMedIdInteger = idIter.next();
thisBatch.add(pubMedIdInteger);
if (thisBatch.size() == BATCH_SIZE || !idIter.hasNext() && thisBatch.size() > 0) {
try {
// the server may return less publications than we ask for, so keep a Map
Map<String, Map<String, Object>> fromServerMap = null;
for (int i = 0; i < MAX_TRIES; i++) {
BufferedReader br = new BufferedReader(getReader(thisBatch));
StringBuffer buf = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
buf.append(line + "\n");
}
fromServerMap = new HashMap<String, Map<String, Object>>();
Throwable throwable = null;
try {
SAXParser.parse(new InputSource(new StringReader(buf.toString())),
new Handler(fromServerMap), false);
} catch (Throwable e) {
// try again or re-throw the Throwable
throwable = e;
}
if (i == MAX_TRIES) {
throw new RuntimeException("failed to parse: " + buf.toString()
+ " - tried " + MAX_TRIES + " times",
throwable);
} else {
if (throwable != null) {
// try again
continue;
}
}
for (String id: fromServerMap.keySet()) {
writeItems(writer, mapToItems(itemFactory, fromServerMap.get(id)));
}
addToDb(txn, db, fromServerMap);
break;
}
thisBatch.clear();
} finally {
txn.commit();
// start a new transaction incase there is an exception while parsing
txn = env.beginTransaction(null, null);
}
}
}
writeItems(writer, authorMap.values());
writer.write(FullRenderer.getFooter() + ENDL);
writer.flush();
writer.close();
} catch (Throwable e) {
throw new RuntimeException("failed to get all publications", e);
} finally {
txn.commit();
db.close();
Thread.currentThread().setContextClassLoader(cl);
}
}
private void writeItems(Writer writer, Collection<Item> items) throws IOException {
for (Item item: items) {
writer.write(FullRenderer.render(item));
}
}
/**
* Add a Map of pubication information to the Database
*/
private void addToDb(Transaction txn, Database db,
Map<String, Map<String, Object>> fromServerMap)
throws IOException, DatabaseException {
for (Map.Entry<String, Map<String, Object>> entry: fromServerMap.entrySet()) {
String pubMedId = entry.getKey();
// System.err .println("adding to cache: " + pubMedId);
DatabaseEntry key = new DatabaseEntry(pubMedId.getBytes());
Map dataMap = entry.getValue();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream serializer = new ObjectOutputStream(arrayOutputStream);
serializer.writeObject(dataMap);
DatabaseEntry data = new DatabaseEntry(arrayOutputStream.toByteArray());
db.put(txn, key, data);
}
}
/**
* Retrieve the publications to be updated
* @param os The ObjectStore to read from
* @return a List of publications
*/
protected List<Publication> getPublications(ObjectStore os) {
Query q = new Query();
QueryClass qc = new QueryClass(Publication.class);
q.addFrom(qc);
q.addToSelect(qc);
ConstraintSet cs = new ConstraintSet(ConstraintOp.OR);
SimpleConstraint scTitle =
new SimpleConstraint(new QueryField(qc, "title"), ConstraintOp.IS_NULL);
cs.addConstraint(scTitle);
SimpleConstraint scYear =
new SimpleConstraint(new QueryField(qc, "year"), ConstraintOp.IS_NULL);
cs.addConstraint(scYear);
SimpleConstraint scFirstAuthor =
new SimpleConstraint(new QueryField(qc, "firstAuthor"), ConstraintOp.IS_NULL);
cs.addConstraint(scFirstAuthor);
q.setConstraint(cs);
@SuppressWarnings("unchecked") List<Publication> retval = (List<Publication>) ((List) os
.executeSingleton(q));
return retval;
}
/**
* Obtain the pubmed esummary information for the publications
* @param ids the pubMedIds of the publications
* @return a Reader for the information
* @throws Exception if an error occurs
*/
protected Reader getReader(Set<Integer> ids) throws Exception {
String urlString = ESUMMARY_URL + StringUtil.join(ids, ",");
System.err .println("retrieving: " + urlString);
return new BufferedReader(new InputStreamReader(new URL(urlString).openStream()));
}
private Set<Item> mapToItems(ItemFactory itemFactory, Map map) {
Set<Item> retSet = new HashSet<Item>();
Item publication = itemFactory.makeItemForClass("Publication");
retSet.add(publication);
publication.setAttribute("pubMedId", (String) map.get("id"));
final String title = (String) map.get("title");
if (!StringUtils.isEmpty(title)) {
publication.setAttribute("title", title);
}
final String journal = (String) map.get("journal");
if (!StringUtils.isEmpty(journal)) {
publication.setAttribute("journal", journal);
}
final String volume = (String) map.get("volume");
if (!StringUtils.isEmpty(volume)) {
publication.setAttribute("volume", volume);
}
final String issue = (String) map.get("issue");
if (!StringUtils.isEmpty(issue)) {
publication.setAttribute("issue", issue);
}
final String pages = (String) map.get("pages");
if (!StringUtils.isEmpty(pages)) {
publication.setAttribute("pages", pages);
}
if (map.get("year") != null) {
publication.setAttribute("year", (String) map.get("year"));
}
List<String> authors = (List<String>) map.get("authors");
if (authors != null) {
for (String authorString : authors) {
Item author = authorMap.get(authorString);
if (author == null) {
author = itemFactory.makeItemForClass("Author");
author.setAttribute("name", authorString);
authorMap.put(authorString, author);
}
author.addToCollection("publications", publication);
publication.addToCollection("authors", author);
if (!publication.hasAttribute("firstAuthor")) {
publication.setAttribute("firstAuthor", authorString);
}
}
}
return retSet;
}
/**
* Extension of DefaultHandler to handle an esummary for a publication
*/
class Handler extends DefaultHandler
{
Map<String, Object> pubMap;
String name;
StringBuffer characters;
boolean duplicateEntry = false;
Map<String, Map<String, Object>> cache;
/**
* Constructor
* @param fromServerMap cache of publications
*/
public Handler(Map<String, Map<String, Object>> fromServerMap) {
this.cache = fromServerMap;
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
if ("ERROR".equals(qName)) {
name = qName;
} else if ("Id".equals(qName)) {
name = "Id";
} else if ("DocSum".equals(qName)) {
duplicateEntry = false;
} else {
name = attrs.getValue("Name");
}
characters = new StringBuffer();
}
/**
* {@inheritDoc}
*/
@Override
public void characters(char[] ch, int start, int length) {
characters.append(new String(ch, start, length));
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(String uri, String localName, String qName) {
// do nothing if we have seen this pubmed id before
if (duplicateEntry) {
return;
}
if ("ERROR".equals(name)) {
LOG.error("Unable to retrieve pubmed record: " + characters);
} else if ("Id".equals(name)) {
String pubMedId = characters.toString();
Integer pubMedIdInteger;
try {
pubMedIdInteger = Integer.valueOf(pubMedId);
if (seenPubMeds.contains(pubMedId)) {
duplicateEntry = true;
return;
}
pubMap = new HashMap<String, Object>();
pubMap.put("id", pubMedId);
seenPubMeds.add(pubMedIdInteger);
cache.put(pubMedId, pubMap);
} catch (NumberFormatException e) {
throw new RuntimeException("got non-integer pubmed id from NCBI: " + pubMedId);
}
} else if ("PubDate".equals(name)) {
String year = characters.toString().split(" ")[0];
try {
Integer.parseInt(year);
pubMap.put("year", year);
} catch (NumberFormatException e) {
LOG.warn("Cannot parse year from publication: " + year);
}
} else if ("Source".equals(name)) {
pubMap.put("journal", characters.toString());
} else if ("Title".equals(name)) {
pubMap.put("title", characters.toString());
} else if ("Volume".equals(name)) {
pubMap.put("volume", characters.toString());
} else if ("Issue".equals(name)) {
pubMap.put("issue", characters.toString());
} else if ("Pages".equals(name)) {
pubMap.put("pages", characters.toString());
} else if ("Author".equals(name)) {
String authorString = characters.toString();
List<String> authorList = (List<String>) pubMap.get("authors");
if (authorList == null) {
authorList = new ArrayList<String>();
pubMap.put("authors", authorList);
}
authorList.add(authorString);
}
name = null;
}
}
}
|
package io.cattle.platform.engine.process.impl;
import static io.cattle.platform.engine.process.ExitReason.*;
import static io.cattle.platform.util.time.TimeUtils.*;
import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.async.utils.TimeoutException;
import io.cattle.platform.deferred.util.DeferredUtils;
import io.cattle.platform.engine.context.EngineContext;
import io.cattle.platform.engine.eventing.EngineEvents;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessHandler;
import io.cattle.platform.engine.handler.ProcessLogic;
import io.cattle.platform.engine.handler.ProcessPostListener;
import io.cattle.platform.engine.handler.ProcessPreListener;
import io.cattle.platform.engine.idempotent.Idempotent;
import io.cattle.platform.engine.idempotent.IdempotentExecution;
import io.cattle.platform.engine.idempotent.IdempotentRetryException;
import io.cattle.platform.engine.manager.ProcessManager;
import io.cattle.platform.engine.manager.impl.ProcessRecord;
import io.cattle.platform.engine.process.ExecutionExceptionHandler;
import io.cattle.platform.engine.process.ExitReason;
import io.cattle.platform.engine.process.LaunchConfiguration;
import io.cattle.platform.engine.process.Predicate;
import io.cattle.platform.engine.process.ProcessDefinition;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessInstanceException;
import io.cattle.platform.engine.process.ProcessPhase;
import io.cattle.platform.engine.process.ProcessResult;
import io.cattle.platform.engine.process.ProcessServiceContext;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.engine.process.ProcessStateTransition;
import io.cattle.platform.engine.process.StateChangeMonitor;
import io.cattle.platform.engine.process.log.ExceptionLog;
import io.cattle.platform.engine.process.log.ParentLog;
import io.cattle.platform.engine.process.log.ProcessExecutionLog;
import io.cattle.platform.engine.process.log.ProcessLog;
import io.cattle.platform.engine.process.log.ProcessLogicExecutionLog;
import io.cattle.platform.eventing.model.Event;
import io.cattle.platform.eventing.model.EventVO;
import io.cattle.platform.lock.LockCallback;
import io.cattle.platform.lock.LockCallbackNoReturn;
import io.cattle.platform.lock.definition.DefaultMultiLockDefinition;
import io.cattle.platform.lock.definition.LockDefinition;
import io.cattle.platform.lock.definition.Namespace;
import io.cattle.platform.lock.exception.FailedToAcquireLockException;
import io.cattle.platform.util.exception.ExceptionUtils;
import io.cattle.platform.util.exception.ExecutionException;
import io.cattle.platform.util.exception.LoggableException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.config.DynamicLongProperty;
public class DefaultProcessInstanceImpl implements ProcessInstance {
private static final DynamicLongProperty RETRY_MAX_WAIT = ArchaiusUtil.getLong("process.retry_max_wait.millis");
private static final DynamicLongProperty RETRY_RUNNING_DELAY = ArchaiusUtil.getLong("process.running_delay.millis");
private static final Logger log = LoggerFactory.getLogger(DefaultProcessInstanceImpl.class);
ProcessServiceContext context;
ProcessInstanceContext instanceContext;
Stack<ProcessInstanceContext> instanceContextHistory = new Stack<ProcessInstanceContext>();
ProcessRecord record;
ProcessLog processLog;
ProcessExecutionLog execution;
ExitReason finalReason;
String chainProcess;
Date exceptionRunAfter;
volatile boolean inLogic = false;
boolean executed = false;
boolean schedule = false;
public DefaultProcessInstanceImpl(ProcessServiceContext context, ProcessRecord record, ProcessDefinition processDefinition, ProcessState state,
boolean schedule, boolean replay) {
super();
this.schedule = schedule;
this.context = context;
this.instanceContext = new ProcessInstanceContext();
this.instanceContext.setProcessDefinition(processDefinition);
this.instanceContext.setState(state);
this.instanceContext.setPhase(record.getPhase());
this.instanceContext.setReplay(replay);
this.record = record;
this.processLog = record.getProcessLog();
}
@Override
public ExitReason execute() {
synchronized (this) {
if (executed) {
throw new IllegalStateException("A process can only be executed once");
}
executed = true;
}
if (record.getEndTime() != null) {
return exit(ALREADY_DONE);
}
LockDefinition lockDef = new ProcessLock(this);
try {
log.debug("Attempting to run process [{}:{}] on resource [{}]", getName(), getId(), instanceContext.state.getResourceId());
return context.getLockManager().lock(lockDef, new LockCallback<ExitReason>() {
@Override
public ExitReason doWithLock() {
return executeWithProcessInstanceLock();
}
});
} catch (FailedToAcquireLockException e) {
if (e.isLock(lockDef)) {
exit(PROCESS_ALREADY_IN_PROGRESS);
throw new ProcessInstanceException(this, new ProcessExecutionExitException(PROCESS_ALREADY_IN_PROGRESS));
} else {
throw e;
}
} finally {
log.debug("Exiting [{}] process [{}:{}] on resource [{}]", finalReason, getName(), getId(), instanceContext.state.getResourceId());
}
}
protected void openLog(EngineContext engineContext) {
if (processLog == null) {
ParentLog parentLog = engineContext.peekLog();
if (parentLog == null) {
processLog = new ProcessLog();
} else {
processLog = parentLog.newChildLog();
}
}
execution = processLog.newExecution();
execution.setProcessId(record.getId());
execution.setResourceType(instanceContext.getProcessDefinition().getResourceType());
execution.setResourceId(instanceContext.getState().getResourceId());
execution.setProcessName(instanceContext.getProcessDefinition().getName());
engineContext.pushLog(execution);
}
protected void closeLog(EngineContext engineContext) {
engineContext.popLog();
}
protected ExitReason executeWithProcessInstanceLock() {
EngineContext engineContext = EngineContext.getEngineContext();
try {
runDelegateLoop(engineContext);
return exit(ExitReason.DONE);
} catch (ProcessExecutionExitException e) {
exit(e.getExitReason());
if (e.getExitReason() != null && e.getExitReason().getResult() == ProcessResult.SUCCESS) {
return e.getExitReason();
}
if (e.getExitReason().isRethrow()) {
Throwable t = e.getCause();
ExceptionUtils.rethrowRuntime(t == null ? e : t);
}
throw new ProcessInstanceException(this, e);
} finally {
context.getProcessManager().persistState(this, schedule);
}
}
protected void runDelegateLoop(EngineContext engineContext) {
while (true) {
try {
openLog(engineContext);
preRunStateCheck();
acquireLockAndRun();
break;
} catch (ProcessCancelException e) {
if (shouldAbort(e)) {
if (!instanceContext.getState().shouldCancel(record) && instanceContext.getState().isTransitioning())
throw new IllegalStateException("Attempt to cancel when process is still transitioning", e);
throw e;
} else {
execution.exit(DELEGATE);
}
} catch (ProcessExecutionExitException e) {
e.log(log);
throw e;
} catch (IdempotentRetryException e) {
execution.setException(new ExceptionLog(e));
throw new ProcessExecutionExitException(RETRY_EXCEPTION, e);
} catch (TimeoutException t) {
throw new ProcessExecutionExitException(TIMEOUT, t);
} catch (Throwable t) {
execution.setException(new ExceptionLog(t));
if (t instanceof LoggableException) {
((LoggableException) t).log(log);
} else {
log.error("Unknown exception", t);
}
throw new ProcessExecutionExitException(UNKNOWN_EXCEPTION, t);
} finally {
closeLog(engineContext);
}
}
}
protected boolean shouldAbort(ProcessCancelException e) {
ProcessDefinition def = context.getProcessManager().getProcessDelegate(instanceContext.getProcessDefinition());
if (def == null) {
return true;
}
ProcessState state = def.constructProcessState(record);
if (state.shouldCancel(record)) {
return true;
}
ProcessInstanceContext newContext = new ProcessInstanceContext();
newContext.setProcessDefinition(def);
newContext.setState(state);
newContext.setPhase(ProcessPhase.STARTED);
instanceContextHistory.push(instanceContext);
instanceContext = newContext;
return false;
}
protected void acquireLockAndRun() {
startLock();
try {
context.getLockManager().lock(instanceContext.getProcessLock(), new LockCallbackNoReturn() {
@Override
public void doWithLockNoResult() {
runWithProcessLock();
}
});
} catch (FailedToAcquireLockException e) {
throw new ProcessExecutionExitException(RESOURCE_BUSY, e);
}
}
protected void preRunStateCheck() {
if (instanceContext.getState().isDone(schedule)) {
String configuredChainProcess = getConfiguredChainProcess();
if (configuredChainProcess != null) {
try {
scheduleChain(configuredChainProcess);
throw new ProcessExecutionExitException(ExitReason.CHAIN);
} catch (ProcessCancelException e) {
}
}
throw new ProcessExecutionExitException(ALREADY_DONE);
}
}
protected boolean shouldCancel() {
return instanceContext.getState().shouldCancel(record) ||
(instanceContext.isReplay() && !instanceContext.getState().isTransitioning() && instanceContext.getState().isStart(record));
}
protected void incrementExecutionCountAndRunAfter() {
long count = record.getExecutionCount();
count += 1;
record.setExecutionCount(count);
record.setRunAfter(new Date(System.currentTimeMillis() + RETRY_RUNNING_DELAY.get()));
record.setRunningProcessServerId(EngineContext.getProcessServerId());
}
protected void setNextRunAfter() {
Long count = record.getExecutionCount();
if (count == 0) {
count = 1L;
}
long wait = RETRY_MAX_WAIT.get();
double maxCount = Math.ceil(Math.log(RETRY_MAX_WAIT.get())/Math.log(2));
if (count <= maxCount) {
wait = Math.min(RETRY_MAX_WAIT.get(), Math.abs(2000L + (long)Math.pow(2, count-1) * 100));
}
record.setRunAfter(new Date(System.currentTimeMillis() + wait));
if (exceptionRunAfter != null && exceptionRunAfter.after(record.getRunAfter())) {
record.setRunAfter(exceptionRunAfter);
}
record.setRunningProcessServerId(null);
}
protected void runWithProcessLock() {
String previousState = null;
boolean success = false;
try {
ProcessState state = instanceContext.getState();
state.rebuild();
if (state.getResource() == null) {
throw new ProcessCancelException("Resource is null [" + getName() + ":" + getId() + "] on resource [" +
getResourceId() + "]");
}
preRunStateCheck();
if (shouldCancel()) {
throw new ProcessCancelException("State [" + instanceContext.getState().getState() + "] is not valid for process [" +
getName() + ":" + getId() + "] on resource [" + getResourceId() + "]");
}
if (schedule) {
Predicate predicate = record.getPredicate();
if (predicate != null) {
if (!predicate.evaluate(this.instanceContext.getState(), this, this.instanceContext.getProcessDefinition())) {
throw new ProcessCancelException("Predicate is not valid");
}
}
}
if (instanceContext.getState().isStart(record)) {
previousState = setTransitioning();
}
if (schedule) {
runScheduled();
}
if (instanceContext.getPhase() == ProcessPhase.REQUESTED) {
instanceContext.setPhase(ProcessPhase.STARTED);
}
incrementExecutionCountAndRunAfter();
getProcessManager().persistState(this, schedule);
previousState = state.getState();
runLogic();
boolean chain = setDone(previousState);
success = true;
if (chain) {
throw new ProcessExecutionExitException(ExitReason.CHAIN);
}
} catch (ProcessDelayException e) {
exceptionRunAfter = e.getRunAfter();
throw e;
} finally {
if (!schedule) {
setNextRunAfter();
}
if (!success && !EngineContext.isNestedExecution()) {
/*
* This is not so obvious why we do this. If a process fails it
* may have scheduled a compensating process. That means the
* state changed under the hood and we should look for that as
* it possibly cancels this process. If the process is nested,
* we don't want to cancel because it will mask the exception
* being thrown and additionally there is no process to cancel
* because the process is really owned by the parent. If we were
* to cancel a nested process, it will just look like a
* RuntimeException to the parent
*/
if (previousState != null)
assertState(previousState);
}
}
}
protected void runScheduled() {
DeferredUtils.defer(new Runnable() {
@Override
public void run() {
Long id = record.getId();
if (id != null) {
Event event = EventVO.newEvent(EngineEvents.PROCESS_EXECUTE).withResourceId(id.toString());
context.getEventService().publish(event);
}
}
});
throw new ProcessExecutionExitException(SCHEDULED);
}
protected String getConfiguredChainProcess() {
ProcessState state = instanceContext.getState();
ProcessDefinition processDefinition = instanceContext.getProcessDefinition();
if (state.getData().containsKey(processDefinition.getName() + ProcessLogic.CHAIN_PROCESS)) {
return state.getData().get(processDefinition.getName() + ProcessLogic.CHAIN_PROCESS).toString();
}
return null;
}
protected boolean runHandlers(ProcessPhase phase, List<? extends ProcessLogic> handlers) {
boolean shouldDelegate = false;
final ProcessDefinition processDefinition = instanceContext.getProcessDefinition();
final ProcessState state = instanceContext.getState();
ProcessPhase currentPhase = instanceContext.getPhase();
if (instanceContext.getPhase().ordinal() < phase.ordinal()) {
final EngineContext context = EngineContext.getEngineContext();
for (final ProcessLogic handler : handlers) {
HandlerResult result = Idempotent.execute(new IdempotentExecution<HandlerResult>() {
@Override
public HandlerResult execute() {
if (Idempotent.enabled()) {
state.reload();
}
return runHandler(processDefinition, state, context, handler);
}
});
if (result != null) {
String chainResult = result.getChainProcessName();
if (chainResult != null) {
if (chainProcess != null && !chainResult.equals(chainProcess)) {
log.error("Not chaining process to [{}] because [{}] already set", chainResult, chainProcess);
}
chainProcess = chainResult;
}
shouldDelegate |= result.shouldDelegate();
if (!result.shouldContinue(instanceContext.getPhase())) {
break;
}
}
}
String configuredChainProcess = getConfiguredChainProcess();
if (currentPhase == ProcessPhase.POST_LISTENERS && chainProcess == null && configuredChainProcess != null ) {
chainProcess = configuredChainProcess;
}
instanceContext.setPhase(phase);
}
return shouldDelegate;
}
protected String logicTypeString(ProcessLogic logic) {
if (logic instanceof ProcessPreListener) {
return "pre listener ";
} else if (logic instanceof ProcessHandler) {
return "handler ";
} else if (logic instanceof ProcessPostListener) {
return "post listener ";
}
return "";
}
protected HandlerResult runHandler(ProcessDefinition processDefinition, ProcessState state, EngineContext context, ProcessLogic handler) {
final ProcessLogicExecutionLog processExecution = execution.newProcessLogicExecution(handler);
context.pushLog(processExecution);
try {
log.debug("Running {}[{}]", logicTypeString(handler), handler.getName());
HandlerResult handlerResult = handler.handle(state, DefaultProcessInstanceImpl.this);
log.debug("Finished {}[{}]", logicTypeString(handler), handler.getName());
if (handlerResult == null) {
return handlerResult;
}
boolean shouldContinue = handlerResult.shouldContinue(state.getPhase());
Map<String, Object> resultData = state.convertData(handlerResult.getData());
processExecution.setShouldDelegate(handlerResult.shouldDelegate());
processExecution.setShouldContinue(shouldContinue);
processExecution.setChainProcessName(handlerResult.getChainProcessName());
if (resultData.size() > 0) {
state.applyData(resultData);
}
return handlerResult;
} catch (ExecutionException e) {
Idempotent.tempDisable();
ExecutionExceptionHandler exceptionHandler = this.context.getExceptionHandler();
if (exceptionHandler != null) {
exceptionHandler.handleException(e, state, this.context);
}
processExecution.setException(new ExceptionLog(e));
throw e;
} catch (ProcessCancelException e) {
throw e;
} catch (RuntimeException e) {
processExecution.setException(new ExceptionLog(e));
throw e;
} finally {
processExecution.setStopTime(now());
context.popLog();
}
}
protected void runLogic() {
inLogic = true;
boolean shouldDelegate = false;
try {
instanceContext.setPhase(ProcessPhase.PRE_LISTENERS);
shouldDelegate |= runHandlers(ProcessPhase.PRE_LISTENERS_DONE, instanceContext.getProcessDefinition().getPreProcessListeners());
instanceContext.setPhase(ProcessPhase.HANDLERS);
shouldDelegate |= runHandlers(ProcessPhase.HANDLER_DONE, instanceContext.getProcessDefinition().getProcessHandlers());
instanceContext.setPhase(ProcessPhase.POST_LISTENERS);
shouldDelegate |= runHandlers(ProcessPhase.POST_LISTENERS_DONE, instanceContext.getProcessDefinition().getPostProcessListeners());
if (shouldDelegate) {
throw new ProcessCancelException("Process result triggered a delegation");
}
} finally {
inLogic = false;
}
instanceContext.setPhase(ProcessPhase.DONE);
}
protected void assertState(String previousState) {
ProcessState state = instanceContext.getState();
state.reload();
String newState = state.getState();
if (!previousState.equals(newState)) {
preRunStateCheck();
throw new ProcessExecutionExitException("Previous state [" + previousState + "] does not equal current state [" + newState + "]", STATE_CHANGED);
}
}
public ProcessRecord getProcessRecord() {
record.setPhase(instanceContext.getPhase());
record.setProcessLog(processLog);
record.setExitReason(finalReason);
if (finalReason == null) {
record.setRunningProcessServerId(EngineContext.getProcessServerId());
} else {
if (finalReason == ExitReason.RETRY_EXCEPTION) {
record.setRunAfter(null);
}
record.setRunningProcessServerId(null);
if (finalReason.isTerminating() && execution != null && execution.getStopTime() != null) {
record.setEndTime(new Date(execution.getStopTime()));
}
record.setResult(finalReason.getResult());
}
return record;
}
protected String setTransitioning() {
ProcessState state = instanceContext.getState();
String previousState = state.getState();
String newState = state.setTransitioning();
log.debug("Changing state [{}->{}] on [{}:{}]", previousState, newState, record.getResourceType(), record.getResourceId());
execution.getTransitions().add(new ProcessStateTransition(previousState, newState, "transitioning", now()));
publishChanged(previousState, newState, schedule);
return newState;
}
protected void scheduleChain(final String chainProcess) {
final ProcessState state = instanceContext.getState();
final LaunchConfiguration config = new LaunchConfiguration(chainProcess, record.getResourceType(), record.getResourceId(), record.getAccountId(),
record.getPriority(), state.getData());
config.setParentProcessState(state);
ExecutionExceptionHandler handler = this.context.getExceptionHandler();
Runnable run = new Runnable() {
@Override
public void run() {
DefaultProcessInstanceImpl.this.context.getProcessManager().scheduleProcessInstance(config);
log.debug("Chained [{}] to [{}]", record.getProcessName(), chainProcess);
state.reload();
}
};
if (handler == null) {
run.run();
} else {
handler.wrapChainSchedule(state, context, run);
}
}
protected boolean setDone(String previousState) {
boolean chained = false;
final ProcessState state = instanceContext.getState();
assertState(previousState);
if (chainProcess != null) {
scheduleChain(chainProcess);
chained = true;
}
String newState = chained ? state.getState() : state.setDone();
log.debug("Changing state [{}->{}] on [{}:{}]", previousState, newState, record.getResourceType(), record.getResourceId());
execution.getTransitions().add(new ProcessStateTransition(previousState, newState, chained ? "chain" : "done", now()));
publishChanged(previousState, newState, schedule);
return chained;
}
protected void publishChanged(String previousState, String newState, boolean defer) {
for (StateChangeMonitor monitor : context.getChangeMonitors()) {
monitor.onChange(defer, previousState, newState, record, instanceContext.getState(), context);
}
}
protected void startLock() {
ProcessState state = instanceContext.getState();
LockDefinition lockDef = state.getProcessLock();
if (schedule) {
LockDefinition scheduleLock = new Namespace("schedule").getLockDefinition(lockDef);
if (record.getPredicate() == null) {
lockDef = scheduleLock;
} else {
lockDef = new DefaultMultiLockDefinition(lockDef, scheduleLock);
}
}
instanceContext.setProcessLock(lockDef);
}
protected ExitReason exit(ExitReason reason) {
if (execution != null) {
execution.exit(reason);
}
return finalReason = reason;
}
@Override
public Long getId() {
return record.getId();
}
@Override
public String getName() {
return instanceContext.getProcessDefinition().getName();
}
@Override
public boolean isRunningLogic() {
return inLogic;
}
@Override
public ExitReason getExitReason() {
return finalReason;
}
@Override
public ProcessManager getProcessManager() {
return context.getProcessManager();
}
@Override
public String toString() {
try {
return "Process [" + instanceContext.getProcessDefinition().getName() + "] resource [" + instanceContext.getState().getResourceId() + "]";
} catch (NullPointerException e) {
return super.toString();
}
}
@Override
public String getResourceId() {
return instanceContext.getState().getResourceId();
}
}
|
package edu.duke.cabig.c3pr.domain.repository.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.transaction.annotation.Transactional;
import edu.duke.cabig.c3pr.dao.EpochDao;
import edu.duke.cabig.c3pr.dao.ParticipantDao;
import edu.duke.cabig.c3pr.dao.StratumGroupDao;
import edu.duke.cabig.c3pr.dao.StudySubjectDao;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.NonTreatmentEpoch;
import edu.duke.cabig.c3pr.domain.RegistrationDataEntryStatus;
import edu.duke.cabig.c3pr.domain.RegistrationWorkFlowStatus;
import edu.duke.cabig.c3pr.domain.ScheduledArm;
import edu.duke.cabig.c3pr.domain.ScheduledEpoch;
import edu.duke.cabig.c3pr.domain.ScheduledEpochDataEntryStatus;
import edu.duke.cabig.c3pr.domain.ScheduledEpochWorkFlowStatus;
import edu.duke.cabig.c3pr.domain.ScheduledNonTreatmentEpoch;
import edu.duke.cabig.c3pr.domain.ScheduledTreatmentEpoch;
import edu.duke.cabig.c3pr.domain.StudySubject;
import edu.duke.cabig.c3pr.domain.factory.StudySubjectFactory;
import edu.duke.cabig.c3pr.domain.repository.StudySubjectRepository;
import edu.duke.cabig.c3pr.exception.C3PRBaseException;
import edu.duke.cabig.c3pr.exception.C3PRCodedException;
import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper;
import edu.duke.cabig.c3pr.service.impl.StudySubjectXMLImporterServiceImpl;
@Transactional
public class StudySubjectRepositoryImpl implements StudySubjectRepository {
private StudySubjectDao studySubjectDao;
private ParticipantDao participantDao;
private EpochDao epochDao;
private StratumGroupDao stratumGroupDao;
private C3PRExceptionHelper exceptionHelper;
private MessageSource c3prErrorMessages;
private StudySubjectFactory studySubjectFactory;
private Logger log = Logger.getLogger(StudySubjectXMLImporterServiceImpl.class.getName());
public void assignC3DIdentifier(StudySubject studySubject, String c3dIdentifierValue) {
StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId());
loadedSubject.setC3DIdentifier(c3dIdentifierValue);
studySubjectDao.save(loadedSubject);
}
public void assignCoOrdinatingCenterIdentifier(StudySubject studySubject, String identifierValue) {
StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId());
loadedSubject.setCoOrdinatingCenterIdentifier(identifierValue);
studySubjectDao.save(loadedSubject);
}
public boolean isEpochAccrualCeilingReached(int epochId) {
Epoch epoch = epochDao.getById(epochId);
if (epoch.isReserving()) {
ScheduledEpoch scheduledEpoch = new ScheduledNonTreatmentEpoch(true);
scheduledEpoch.setEpoch(epoch);
List<StudySubject> list = studySubjectDao.searchByScheduledEpoch(scheduledEpoch);
NonTreatmentEpoch nEpoch = (NonTreatmentEpoch) epoch;
if (nEpoch.getAccrualCeiling() != null
&& list.size() >= nEpoch.getAccrualCeiling().intValue()) {
return true;
}
}
return false;
}
private StudySubject doRandomization(StudySubject studySubject) throws C3PRBaseException {
// randomize subject
switch (studySubject.getStudySite().getStudy().getRandomizationType()) {
case PHONE_CALL:
break;
case BOOK:
doBookRandomization(studySubject);
break;
case CALL_OUT:
break;
default:
break;
}
return studySubject;
}
private void doBookRandomization(StudySubject studySubject) throws C3PRBaseException {
ScheduledArm sa = new ScheduledArm();
ScheduledTreatmentEpoch ste = (ScheduledTreatmentEpoch) studySubject.getScheduledEpoch();
sa.setArm(studySubject.getStratumGroup().getNextArm());
if (sa.getArm() != null) {
ste.addScheduledArm(sa);
stratumGroupDao.merge(studySubject.getStratumGroup());
}
}
public StudySubject doLocalRegistration(StudySubject studySubject) throws C3PRCodedException {
studySubject.updateDataEntryStatus();
if (!studySubject.isDataEntryComplete()) return studySubject;
ScheduledEpoch scheduledEpoch = studySubject.getScheduledEpoch();
if (studySubject.getScheduledEpoch().getRequiresRandomization()) {
try {
this.doRandomization(studySubject);
}
catch (Exception e) {
scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.UNAPPROVED);
throw exceptionHelper.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.RANDOMIZATION.CODE"), e);
}
if (((ScheduledTreatmentEpoch) studySubject.getScheduledEpoch()).getScheduledArm() == null) {
scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.UNAPPROVED);
throw exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.CANNOT_ASSIGN_ARM.CODE"));
}
else {
// logic for accrual ceiling check
scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.APPROVED);
}
}
else {
// logic for accrual ceiling check
scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.APPROVED);
}
return this.save(studySubject);
}
/**
* Saves the Imported StudySubject to the database. Moved it from the service as a part of the
* refactoring effort.
*
* @param deserialedStudySubject
* @return
* @throws C3PRCodedException
*/
@Transactional(readOnly = false)
public StudySubject importStudySubject(StudySubject deserialedStudySubject)
throws C3PRCodedException {
StudySubject studySubject = studySubjectFactory.buildStudySubject(deserialedStudySubject);
if (studySubject.getParticipant().getId() != null) {
StudySubject exampleSS = new StudySubject(true);
exampleSS.setParticipant(studySubject.getParticipant());
exampleSS.setStudySite(studySubject.getStudySite());
List<StudySubject> registrations = studySubjectDao.searchBySubjectAndStudySite(exampleSS);
if (registrations.size() > 0) {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE"));
}
} else {
if (studySubject.getParticipant().validateParticipant())
participantDao.save(studySubject.getParticipant());
else {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE"));
}
}
if (studySubject.getScheduledEpoch().getEpoch().getRequiresArm()) {
ScheduledTreatmentEpoch scheduledTreatmentEpoch = (ScheduledTreatmentEpoch) studySubject
.getScheduledEpoch();
if (scheduledTreatmentEpoch.getScheduledArm() == null
|| scheduledTreatmentEpoch.getScheduledArm().getArm() == null
|| scheduledTreatmentEpoch.getScheduledArm().getArm().getId() == null)
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.IMPORT.REQUIRED.ARM.NOTFOUND.CODE"));
}
studySubject.setRegDataEntryStatus(studySubject.evaluateRegistrationDataEntryStatus());
studySubject.getScheduledEpoch().setScEpochDataEntryStatus(studySubject.evaluateScheduledEpochDataEntryStatus());
if (studySubject.getRegDataEntryStatus() == RegistrationDataEntryStatus.INCOMPLETE) {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.DATA_ENTRY_INCOMPLETE.CODE"));
}
if (studySubject.getScheduledEpoch().getScEpochDataEntryStatus() == ScheduledEpochDataEntryStatus.INCOMPLETE) {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.SCHEDULEDEPOCH.DATA_ENTRY_INCOMPLETE.CODE"));
}
if (studySubject.getScheduledEpoch().isReserving()) {
studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.RESERVED);
} else if (studySubject.getScheduledEpoch().getEpoch().isEnrolling()) {
studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.REGISTERED);
} else {
studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.UNREGISTERED);
}
studySubjectDao.save(studySubject);
log.debug("Registration saved with grid ID" + studySubject.getGridId());
return studySubject;
}
public void setStudySubjectDao(StudySubjectDao studySubjectDao) {
this.studySubjectDao = studySubjectDao;
}
public void setEpochDao(EpochDao epochDao) {
this.epochDao = epochDao;
}
public void setStratumGroupDao(StratumGroupDao stratumGroupDao) {
this.stratumGroupDao = stratumGroupDao;
}
public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) {
this.exceptionHelper = exceptionHelper;
}
public void setC3prErrorMessages(MessageSource errorMessages) {
c3prErrorMessages = errorMessages;
}
private int getCode(String errortypeString) {
return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null));
}
public StudySubject save(StudySubject studySubject) {
studySubject.updateDataEntryStatus();
if (studySubject.getId() != null) return studySubjectDao.merge(studySubject);
studySubjectDao.save(studySubject);
return studySubject;
}
public void setStudySubjectFactory(StudySubjectFactory studySubjectFactory) {
this.studySubjectFactory = studySubjectFactory;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
}
|
package org.kuali.coeus.s2sgen.impl.generate.support;
import gov.grants.apply.system.metaGrantApplication.GrantApplicationDocument;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.junit.Assert;
import org.kuali.coeus.common.budget.framework.core.category.BudgetCategory;
import org.kuali.coeus.common.budget.framework.core.category.BudgetCategoryType;
import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetLineItem;
import org.kuali.coeus.common.budget.framework.period.BudgetPeriod;
import org.kuali.coeus.common.framework.org.Organization;
import org.kuali.coeus.propdev.impl.attachment.Narrative;
import org.kuali.coeus.propdev.impl.attachment.NarrativeAttachment;
import org.kuali.coeus.propdev.impl.attachment.NarrativeType;
import org.kuali.coeus.propdev.impl.budget.ProposalDevelopmentBudgetExt;
import org.kuali.coeus.propdev.impl.budget.subaward.BudgetSubAwards;
import org.kuali.coeus.propdev.impl.core.DevelopmentProposal;
import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentDocument;
import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentService;
import org.kuali.coeus.propdev.impl.location.ProposalSite;
import org.kuali.coeus.propdev.impl.person.ProposalPerson;
import org.kuali.coeus.s2sgen.impl.generate.S2SBaseFormGenerator;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.rice.core.api.util.ClassLoaderUtils;
import org.kuali.rice.krad.data.DataObjectService;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import static org.kuali.coeus.sys.framework.service.KcServiceLocator.getService;
public abstract class RRSubAwardBudgetBaseGeneratorTest extends S2SModularBudgetTestBase {
protected abstract String getBudgetFormGeneratorName();
protected abstract String getBudgetJustificationNarrativeType();
@Override
protected void prepareData(ProposalDevelopmentDocument document)
throws Exception {
ProposalDevelopmentBudgetExt proposalDevelopmentBudgetExt = new ProposalDevelopmentBudgetExt();
proposalDevelopmentBudgetExt.setBudgetVersionNumber(1);
proposalDevelopmentBudgetExt.setDevelopmentProposal(document
.getDevelopmentProposal());
proposalDevelopmentBudgetExt.setBudgetStatus("1");
proposalDevelopmentBudgetExt.setBudgetId(1L);
proposalDevelopmentBudgetExt
.setName("test Document Description1");
proposalDevelopmentBudgetExt.setOnOffCampusFlag("Y");
proposalDevelopmentBudgetExt.setStartDate(new Date(new Long(
"1183316613046")));
proposalDevelopmentBudgetExt.setEndDate(new Date(new Long(
"1214852613046")));
proposalDevelopmentBudgetExt.setOhRateTypeCode("1");
BudgetSubAwards budgetSubAwards = new BudgetSubAwards();
budgetSubAwards.setSubAwardNumber(1);
budgetSubAwards.setBudgetId(1L);
budgetSubAwards.setBudget(proposalDevelopmentBudgetExt);
Organization testOrg = new Organization();
testOrg.setOrganizationName("University of Maine");
testOrg.setOrganizationId("000040");
budgetSubAwards.setOrganization(testOrg);
budgetSubAwards.setSubAwardStatusCode(1);
budgetSubAwards.setHiddenInHierarchy(false);
S2SBaseFormGenerator generatorObject1;
generatorObject1 = KcServiceLocator
.getService(getBudgetFormGeneratorName());
budgetSubAwards
.setNamespace(generatorObject1.getNamespace());
generatorObject1.setAttachments(new ArrayList<>());
ProposalDevelopmentDocument doc = initializeDocument();
initializeDevelopmentProposal(doc);
prepareDatas(doc);
XmlObject object = generatorObject1.getFormObject(doc);
GrantApplicationDocument.GrantApplication.Forms forms = GrantApplicationDocument.GrantApplication.Forms.Factory.newInstance();
setFormObject(forms, object);
GrantApplicationDocument.GrantApplication grantApplication = GrantApplicationDocument.GrantApplication.Factory
.newInstance();
grantApplication.setForms(forms);
budgetSubAwards.setSubAwardXmlFileData(grantApplication.xmlText());
List<BudgetSubAwards> budgetSubAwardsList = new ArrayList<>();
budgetSubAwardsList.add(budgetSubAwards);
proposalDevelopmentBudgetExt.setBudgetSubAwards(budgetSubAwardsList);
proposalDevelopmentBudgetExt.setOhRateClassCode("1");
proposalDevelopmentBudgetExt.setModularBudgetFlag(false);
proposalDevelopmentBudgetExt.setUrRateClassCode("1");
proposalDevelopmentBudgetExt = getService(DataObjectService.class)
.save(proposalDevelopmentBudgetExt);
List<ProposalDevelopmentBudgetExt> proposalDevelopmentBudgetExtList = new ArrayList<>();
proposalDevelopmentBudgetExtList.add(proposalDevelopmentBudgetExt);
document.getDevelopmentProposal().setBudgets(
proposalDevelopmentBudgetExtList);
document.getDevelopmentProposal().setFinalBudget(proposalDevelopmentBudgetExt);
}
@Override
public ProposalDevelopmentDocument initializeDocument() throws Exception {
ProposalDevelopmentDocument pd = (ProposalDevelopmentDocument) KRADServiceLocatorWeb
.getDocumentService().getNewDocument(
"ProposalDevelopmentDocument");
Assert.assertNotNull(pd.getDocumentHeader().getWorkflowDocument());
ProposalDevelopmentService pdService = getService(ProposalDevelopmentService.class);
pdService.initializeUnitOrganizationLocation(pd);
pdService.initializeProposalSiteNumbers(pd);
return pd;
}
@Override
public DevelopmentProposal initializeDevelopmentProposal(
ProposalDevelopmentDocument pd) {
DevelopmentProposal developmentProposal = pd.getDevelopmentProposal();
developmentProposal.setPrimeSponsorCode("000120");
developmentProposal.setActivityTypeCode("1");
developmentProposal.refreshReferenceObject("activityType");
developmentProposal.setSponsorCode("000162");
developmentProposal.setOwnedByUnitNumber("000001");
developmentProposal.refreshReferenceObject("ownedByUnit");
developmentProposal.setProposalTypeCode("1");
developmentProposal.setCreationStatusCode("1");
developmentProposal.setApplicantOrganizationId("000001");
developmentProposal.setPerformingOrganizationId("000001");
developmentProposal.setNoticeOfOpportunityCode("1");
developmentProposal.setRequestedStartDateInitial(new Date(
Calendar.getInstance().getTimeInMillis()));
developmentProposal.setRequestedEndDateInitial(new Date(
Calendar.getInstance().getTimeInMillis()));
developmentProposal.setTitle("Test s2s service title");
developmentProposal.setDeadlineType("P");
developmentProposal.setDeadlineDate(new Date(Calendar
.getInstance().getTimeInMillis()));
developmentProposal.setNsfCode("J.05");
return developmentProposal;
}
public void prepareDatas(ProposalDevelopmentDocument document)
throws Exception {
Organization organization = new Organization();
organization.setOrganizationName("University");
organization.setOrganizationId("000001");
organization.setContactAddressId(1);
ProposalSite applicantOrganization = new ProposalSite();
applicantOrganization.setLocationTypeCode(2);
applicantOrganization.setOrganization(organization);
applicantOrganization.setSiteNumber(1);
applicantOrganization.setLocationName(organization
.getOrganizationName());
document.getDevelopmentProposal().setApplicantOrganization(
applicantOrganization);
document.getDevelopmentProposal().getApplicantOrganization()
.getOrganization().setDunsNumber("00-176-5866");
NarrativeAttachment narrativeAttachment = new NarrativeAttachment();
DefaultResourceLoader resourceLoader = new DefaultResourceLoader(
ClassLoaderUtils.getDefaultClassLoader());
Resource resource = resourceLoader
.getResource(S2STestConstants.ATT_PACKAGE + "/exercise2.pdf");
InputStream inputStream = resource.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
byte[] narrativePdf = new byte[bis.available()];
narrativeAttachment.setData(narrativePdf);
narrativeAttachment.setName("exercise1");
Narrative narrative = new Narrative();
List<Narrative> narrativeList = new ArrayList<>();
narrative.setDevelopmentProposal(document.getDevelopmentProposal());
NarrativeType narrativeType = new NarrativeType();
narrativeType.setCode(getBudgetJustificationNarrativeType());
narrativeType.setAllowMultiple(true);
narrativeType.setSystemGenerated(false);
narrativeType.setDescription("Testing for Attachments Attachment");
getService(DataObjectService.class).save(narrativeType);
narrative.setNarrativeType(narrativeType);
narrative.setNarrativeTypeCode(getBudgetJustificationNarrativeType());
narrative.setNarrativeAttachment(narrativeAttachment);
narrative.setModuleTitle("Allows Multiple Description");
narrativeList.add(narrative);
document.getDevelopmentProposal().setNarratives(narrativeList);
List<ProposalPerson> proposalPersons = new ArrayList<>();
ProposalPerson principalInvestigator = new ProposalPerson();
principalInvestigator.setFirstName("ALAN");
principalInvestigator.setLastName("MCAFEE");
principalInvestigator.setProposalPersonRoleId("PI");
principalInvestigator.setPersonId("0001");
principalInvestigator.setRolodexId(8);
proposalPersons.add(principalInvestigator);
document.getDevelopmentProposal().setProposalPersons(proposalPersons);
ProposalDevelopmentBudgetExt proposalDevelopmentBudgetExt = new ProposalDevelopmentBudgetExt();
proposalDevelopmentBudgetExt.setBudgetVersionNumber(1);
proposalDevelopmentBudgetExt.setBudgetStatus("1");
proposalDevelopmentBudgetExt.setBudgetId(1L);
proposalDevelopmentBudgetExt
.setName("test Document Description2");
proposalDevelopmentBudgetExt.setOnOffCampusFlag("Y");
proposalDevelopmentBudgetExt.setStartDate(new Date(new Long(
"1183316613046")));
proposalDevelopmentBudgetExt.setEndDate(new Date(new Long(
"1214852613046")));
proposalDevelopmentBudgetExt.setOhRateTypeCode("1");
proposalDevelopmentBudgetExt.setOhRateClassCode("1");
proposalDevelopmentBudgetExt.setModularBudgetFlag(false);
proposalDevelopmentBudgetExt.setUrRateClassCode("1");
List<BudgetPeriod> budgetPeriods = new ArrayList<>();
BudgetPeriod budgetPeriod = new BudgetPeriod();
budgetPeriod.setBudgetPeriodId(1L);
budgetPeriod.setStartDate(new Date(new Long("1183316613046")));
budgetPeriod.setEndDate(new Date(new Long("1214852613046")));
budgetPeriod.setBudgetPeriod(1);
budgetPeriod.setBudget(proposalDevelopmentBudgetExt);
BudgetLineItem equipment = new BudgetLineItem();
equipment.setBudget(proposalDevelopmentBudgetExt);
equipment.setBudgetLineItemId(1L);
equipment.setBudgetPeriodBO(budgetPeriod);
equipment.setBudgetPeriod(1);
equipment.setBudgetCategoryCode("20");
equipment.setLineItemDescription("A bulldozer");
BudgetCategoryType categoryType = new BudgetCategoryType();
categoryType.setCode("E");
categoryType.setDescription("Equipment");
BudgetCategory category = new BudgetCategory();
category.setBudgetCategoryType(categoryType);
category.setBudgetCategoryTypeCode("E");
category.setCode("20");
category.setDescription("Purchased Equipment");
equipment.setBudgetCategory(category);
List<BudgetLineItem> items = new ArrayList<>();
items.add(equipment);
budgetPeriod.setBudgetLineItems(items);
budgetPeriods.add(budgetPeriod);
proposalDevelopmentBudgetExt.setBudgetPeriods(budgetPeriods);
List<ProposalDevelopmentBudgetExt> proposalDevelopmentBudgetExtList = new ArrayList<>();
proposalDevelopmentBudgetExtList.add(proposalDevelopmentBudgetExt);
document.getDevelopmentProposal().setBudgets(
proposalDevelopmentBudgetExtList);
document.getDevelopmentProposal().setFinalBudget(proposalDevelopmentBudgetExt);
}
protected void setFormObject(GrantApplicationDocument.GrantApplication.Forms forms, XmlObject formObject) {
XmlCursor formCursor = formObject.newCursor();
formCursor.toStartDoc();
formCursor.toNextToken();
XmlCursor metaGrantCursor = forms.newCursor();
metaGrantCursor.toNextToken();
formCursor.moveXml(metaGrantCursor);
}
}
|
package promotionSystem;
public class Personaje {
protected int salud;
protected int energia;
protected int ataque;
protected int defensa;
public Personaje(){
energia=100;
salud=100;
ataque=10;
defensa=2;
}
public final void atacar(Personaje atacado) {
if(puedeAtacar()){
int puntosARestar=calcularPuntosDeAtaque()-atacado.calcularPuntosDeDefensa();
atacado.serAtacado(puntosARestar<0?0:puntosARestar);
energia-=calcularPuntosDeAtaque();
despuesDeAtacar();
}
}
public void despuesDeAtacar(){
}
private void serAtacado(int ataque) {
salud-=ataque;
if(salud<0){
salud=0;
}
}
private boolean puedeAtacar() {
return energia>=ataque;
}
public int getSalud() {
return salud;
}
public int getEnergia() {
return energia;
}
public boolean estaVivo() {
return salud>0;
}
public void serCurado() {
salud=100;
}
public void serEnergizado() {
energia=100;
}
public void setSalud(int salud) {
this.salud=salud;
}
public void setEnergia(int energia) {
this.energia=energia;
}
protected int calcularPuntosDeAtaque(){
return ataque;
}
protected int calcularPuntosDeDefensa(){
return defensa;
}
public void setDefensa(int defensa) {
this.defensa=defensa;
}
public int obtenerPuntosDeAtaque(){
return calcularPuntosDeAtaque();
}
public int obtenerPuntosDeDefensa(){
return calcularPuntosDeDefensa();
}
}
|
package com.pg85.otg.gen;
import static com.pg85.otg.util.ChunkCoordinate.CHUNK_SIZE;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Random;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import com.pg85.otg.gen.biome.BiomeInterpolator;
import com.pg85.otg.gen.biome.layers.LayerSource;
import com.pg85.otg.gen.carver.Carver;
import com.pg85.otg.gen.carver.CaveCarver;
import com.pg85.otg.gen.carver.RavineCarver;
import com.pg85.otg.gen.noise.OctavePerlinNoiseSampler;
import com.pg85.otg.gen.noise.PerlinNoiseSampler;
import com.pg85.otg.gen.noise.legacy.NoiseGeneratorPerlinMesaBlocks;
import com.pg85.otg.util.ChunkCoordinate;
import com.pg85.otg.util.gen.ChunkBuffer;
import com.pg85.otg.util.gen.GeneratingChunk;
import com.pg85.otg.util.helpers.MathHelper;
import com.pg85.otg.util.interfaces.IBiomeConfig;
import it.unimi.dsi.fastutil.HashCommon;
/**
* 1.16 version of {@link ChunkProviderOTG}. Will be renamed at some point.
*/
public class OTGChunkGenerator
{
// "It's a number that made the worldgen look good!" - Dinnerbone 2020
private static final double WORLD_GEN_CONSTANT = 684.412;
private static final float[] BIOME_WEIGHT_TABLE = make(new float[65 * 65], (array) ->
{
for (int x = -32; x <= 32; ++x)
{
for (int z = -32; z <= 32; ++z)
{
float f = 10.0F / MathHelper.sqrt((float) (x * x + z * z) + 0.2F);
array[x + 32 + (z + 32) * 65] = f;
}
}
});
private final OctavePerlinNoiseSampler interpolationNoise; // Volatility noise
private final OctavePerlinNoiseSampler lowerInterpolatedNoise; // Volatility1 noise
private final OctavePerlinNoiseSampler upperInterpolatedNoise; // Volatility2 noise
private final OctavePerlinNoiseSampler depthNoise;
private final long seed;
private final LayerSource biomeGenerator;
private final int noiseSizeX = 4;
private final int noiseSizeY = 32;
private final int noiseSizeZ = 4;
private final ThreadLocal<NoiseCache> noiseCache;
// Biome blocks noise
// TODO: Use new noise?
private double[] biomeBlocksNoise = new double[CHUNK_SIZE * CHUNK_SIZE];
private final NoiseGeneratorPerlinMesaBlocks biomeBlocksNoiseGen;
// Carvers
private final Carver caves = new CaveCarver(256);
private final Carver ravines = new RavineCarver(256);
public OTGChunkGenerator(long seed, LayerSource biomeGenerator)
{
this.seed = seed;
this.biomeGenerator = biomeGenerator;
// Setup noises
Random random = new Random(seed);
this.interpolationNoise = new OctavePerlinNoiseSampler(random, IntStream.rangeClosed(-7, 0));
this.lowerInterpolatedNoise = new OctavePerlinNoiseSampler(random, IntStream.rangeClosed(-15, 0));
this.upperInterpolatedNoise = new OctavePerlinNoiseSampler(random, IntStream.rangeClosed(-15, 0));
this.depthNoise = new OctavePerlinNoiseSampler(random, IntStream.rangeClosed(-15, 0));
this.noiseCache = ThreadLocal.withInitial(() -> new NoiseCache(128, this.noiseSizeY + 1));
this.biomeBlocksNoiseGen = new NoiseGeneratorPerlinMesaBlocks(random, 4);
}
private static <T> T make(T object, Consumer<T> consumer)
{
consumer.accept(object);
return object;
}
private double sampleNoise(int x, int y, int z, double horizontalScale, double verticalScale, double horizontalStretch, double verticalStretch, double volatility1, double volatility2, double volatilityWeight1, double volatilityWeight2)
{
// The algorithm for noise generation varies slightly here as it calculates the interpolation first and then the interpolated noise to avoid sampling noise that will never be used.
// The end result is ~2x faster terrain generation.
double delta = getInterpolationNoise(x, y, z, horizontalStretch, verticalStretch);
if (delta < volatilityWeight1)
{
return getInterpolatedNoise(this.lowerInterpolatedNoise, x, y, z, horizontalScale, verticalScale) / 512.0D * volatility1;
} else if (delta > volatilityWeight2)
{
return getInterpolatedNoise(this.upperInterpolatedNoise, x, y, z, horizontalScale, verticalScale) / 512.0D * volatility2;
} else
{
// TODO: should probably use clamping here to prevent weird artifacts
return MathHelper.lerp(
delta,
getInterpolatedNoise(this.lowerInterpolatedNoise, x, y, z, horizontalScale, verticalScale) / 512.0D * volatility1,
getInterpolatedNoise(this.upperInterpolatedNoise, x, y, z, horizontalScale, verticalScale) / 512.0D * volatility2);
}
}
private double getInterpolationNoise(int x, int y, int z, double horizontalStretch, double verticalStretch) {
double interpolation = 0.0D;
double amplitude = 1.0D;
for (int i = 0; i < 8; i++)
{
PerlinNoiseSampler interpolationSampler = this.interpolationNoise.getOctave(i);
if (interpolationSampler != null)
{
interpolation += interpolationSampler.sample(OctavePerlinNoiseSampler.maintainPrecision((double) x * horizontalStretch * amplitude), OctavePerlinNoiseSampler.maintainPrecision((double) y * verticalStretch * amplitude), OctavePerlinNoiseSampler.maintainPrecision((double) z * horizontalStretch * amplitude), verticalStretch * amplitude, (double) y * verticalStretch * amplitude) / amplitude;
}
amplitude /= 2.0D;
}
return (interpolation / 10.0D + 1.0D) / 2.0D;
}
private double getInterpolatedNoise(OctavePerlinNoiseSampler sampler, int x, int y, int z, double horizontalScale, double verticalScale) {
double noise = 0.0D;
double amplitude = 1.0D;
for (int i = 0; i < 16; ++i)
{
double scaledX = OctavePerlinNoiseSampler.maintainPrecision((double) x * horizontalScale * amplitude);
double scaledY = OctavePerlinNoiseSampler.maintainPrecision((double) y * verticalScale * amplitude);
double scaledZ = OctavePerlinNoiseSampler.maintainPrecision((double) z * horizontalScale * amplitude);
double scaledVerticalScale = verticalScale * amplitude;
PerlinNoiseSampler perlinNoiseSampler = sampler.getOctave(i);
if (perlinNoiseSampler != null)
{
noise += perlinNoiseSampler.sample(scaledX, scaledY, scaledZ, scaledVerticalScale, (double) y * scaledVerticalScale) / amplitude;
}
amplitude /= 2.0D;
}
return noise;
}
private double getExtraHeightAt(int x, int z, double maxAverageDepth, double maxAverageHeight)
{
double noiseHeight = this.depthNoise.sample(x * 200, 10.0D, z * 200, 1.0D, 0.0D, true) * 65535.0 / 8000.0;
if (noiseHeight < 0.0D)
{
noiseHeight = -noiseHeight * 0.3D;
}
noiseHeight = noiseHeight * 3.0D - 2.0D;
if (noiseHeight < 0.0D)
{
noiseHeight /= 2.0D;
if (noiseHeight < -1.0D)
{
noiseHeight = -1.0D;
}
noiseHeight -= maxAverageDepth;
noiseHeight /= 1.4D;
noiseHeight /= 2.0D;
} else
{
if (noiseHeight > 1.0D)
{
noiseHeight = 1.0D;
}
noiseHeight += maxAverageHeight;
noiseHeight /= 8.0D;
}
return noiseHeight;
}
private void getNoiseColumn(double[] buffer, int x, int z)
{
// TODO: check only for edges
this.noiseCache.get().get(buffer, x, z);
}
private void generateNoiseColumn(double[] noiseColumn, int noiseX, int noiseZ)
{
IBiomeConfig center = getBiomeAt(noiseX, noiseZ);
float height = 0; // depth
float volatility = 0; // scale
double volatility1 = 0;
double volatility2 = 0;
double horizontalFracture = 0;
double verticalFracture = 0;
double volatilityWeight1 = 0;
double volatilityWeight2 = 0;
double maxAverageDepth = 0;
double maxAverageHeight = 0;
double[] chc = new double[this.noiseSizeY + 1];
float weight = 0;
for (int x1 = -center.getSmoothRadius(); x1 <= center.getSmoothRadius(); ++x1)
{
for (int z1 = -center.getSmoothRadius(); z1 <= center.getSmoothRadius(); ++z1)
{
// TODO: thread local lossy cache for biome sampling
IBiomeConfig data = getBiomeAt(noiseX + x1, noiseZ + z1);
float heightAt = data.getBiomeHeight();
// TODO: vanilla reduces the weight by half when the depth here is greater than the center depth, but OTG doesn't do that?
float weightAt = BIOME_WEIGHT_TABLE[x1 + 32 + (z1 + 32) * 65] / (heightAt + 2.0F);
weight += weightAt;
height += heightAt * weightAt;
volatility += data.getBiomeVolatility() * weightAt;
volatility1 += data.getVolatility1() * weightAt;
volatility2 += data.getVolatility2() * weightAt;
horizontalFracture += data.getFractureHorizontal() * weightAt;
verticalFracture += data.getFractureVertical() * weightAt;
volatilityWeight1 += data.getVolatilityWeight1() * weightAt;
volatilityWeight2 += data.getVolatilityWeight2() * weightAt;
maxAverageDepth += data.getMaxAverageDepth() * weightAt;
maxAverageHeight += data.getMaxAverageHeight() * weightAt;
for (int y = 0; y < this.noiseSizeY + 1; y++)
{
chc[y] += data.getCHCData(y) * weightAt;
}
}
}
// Normalize biome data
height /= weight;
volatility /= weight;
volatility1 /= weight;
volatility2 /= weight;
horizontalFracture /= weight;
verticalFracture /= weight;
volatilityWeight1 /= weight;
volatilityWeight2 /= weight;
maxAverageDepth /= weight;
maxAverageHeight /= weight;
// Normalize CHC
for (int y = 0; y < this.noiseSizeY + 1; y++)
{
chc[y] /= weight;
}
// Do some math on volatility and height
volatility = volatility * 0.9f + 0.1f;
height = (height * 4.0F - 1.0F) / 8.0F;
// Vary the height with more noise
height += getExtraHeightAt(noiseX, noiseZ, maxAverageDepth, maxAverageHeight) * 0.2;
for (int y = 0; y <= this.noiseSizeY; ++y)
{
// Calculate falloff
double falloff = ((8.5D + height * 8.5D / 8.0D * 4.0D) - y) * 12.0D * 128.0D / 256.0 / volatility;
if (falloff > 0.0)
{
falloff *= 4.0;
}
double horizontalScale = WORLD_GEN_CONSTANT * horizontalFracture;
double verticalScale = WORLD_GEN_CONSTANT * verticalFracture;
double noise = sampleNoise(noiseX, y, noiseZ, horizontalScale, verticalScale, horizontalScale / 80, verticalScale / 160, volatility1, volatility2, volatilityWeight1, volatilityWeight2);
// TODO: add if statement for biome height control here
noise += falloff;
// Reduce the last 3 layers
if (y > 28)
{
noise = MathHelper.clampedLerp(noise, -10, ((double) y - 28) / 3.0);
}
// Add chc data
noise += chc[y];
// Store value
noiseColumn[y] = noise;
}
}
private IBiomeConfig getBiomeAt(int x, int z)
{
return biomeGenerator.getConfig(x, z);
}
public void populateNoise(int worldHeightCap, Random random, ChunkBuffer buffer, ChunkCoordinate pos)
{
// Fill waterLevel array, used when placing stone/ground/surface blocks.
// TODO: water levels
byte[] waterLevel = new byte[CHUNK_SIZE * CHUNK_SIZE];
Arrays.fill(waterLevel, (byte)63);
// TODO: this double[][][] is probably really bad for performance
double[][][] noiseData = new double[2][this.noiseSizeZ + 1][this.noiseSizeY + 1];
// Initialize noise data on the x0 column.
for (int noiseZ = 0; noiseZ < this.noiseSizeZ + 1; ++noiseZ)
{
noiseData[0][noiseZ] = new double[this.noiseSizeY + 1];
this.getNoiseColumn(noiseData[0][noiseZ], pos.getChunkX() * this.noiseSizeX, pos.getChunkZ() * this.noiseSizeZ + noiseZ);
noiseData[1][noiseZ] = new double[this.noiseSizeY + 1];
}
// [0, 4] -> x noise chunks
for (int noiseX = 0; noiseX < this.noiseSizeX; ++noiseX)
{
// Initialize noise data on the x1 column
int noiseZ;
for (noiseZ = 0; noiseZ < this.noiseSizeZ + 1; ++noiseZ)
{
this.getNoiseColumn(noiseData[1][noiseZ], pos.getChunkX() * this.noiseSizeX + noiseX + 1, pos.getChunkZ() * this.noiseSizeZ + noiseZ);
}
// [0, 4] -> z noise chunks
for (noiseZ = 0; noiseZ < this.noiseSizeZ; ++noiseZ)
{
// [0, 32] -> y noise chunks
for (int noiseY = this.noiseSizeY - 1; noiseY >= 0; --noiseY)
{
// Lower samples
double x0z0y0 = noiseData[0][noiseZ][noiseY];
double x0z1y0 = noiseData[0][noiseZ + 1][noiseY];
double x1z0y0 = noiseData[1][noiseZ][noiseY];
double x1z1y0 = noiseData[1][noiseZ + 1][noiseY];
// Upper samples
double x0z0y1 = noiseData[0][noiseZ][noiseY + 1];
double x0z1y1 = noiseData[0][noiseZ + 1][noiseY + 1];
double x1z0y1 = noiseData[1][noiseZ][noiseY + 1];
double x1z1y1 = noiseData[1][noiseZ + 1][noiseY + 1];
// [0, 8] -> y noise pieces
for (int pieceY = 8 - 1; pieceY >= 0; --pieceY)
{
int realY = noiseY * 8 + pieceY;
// progress within loop
double yLerp = (double) pieceY / 8.0;
// Interpolate noise data based on y progress
double x0z0 = MathHelper.lerp(yLerp, x0z0y0, x0z0y1);
double x1z0 = MathHelper.lerp(yLerp, x1z0y0, x1z0y1);
double x0z1 = MathHelper.lerp(yLerp, x0z1y0, x0z1y1);
double x1z1 = MathHelper.lerp(yLerp, x1z1y0, x1z1y1);
// [0, 4] -> x noise pieces
for (int pieceX = 0; pieceX < 4; ++pieceX)
{
int realX = pos.getBlockX() + noiseX * 4 + pieceX;
int localX = realX & 15;
double xLerp = (double) pieceX / 4.0;
// Interpolate noise based on x progress
double z0 = MathHelper.lerp(xLerp, x0z0, x1z0);
double z1 = MathHelper.lerp(xLerp, x0z1, x1z1);
// [0, 4) -> z noise pieces
for (int pieceZ = 0; pieceZ < 4; ++pieceZ)
{
int realZ = pos.getBlockZ() + noiseZ * 4 + pieceZ;
int localZ = realZ & 15;
double zLerp = (double) pieceZ / 4.0;
// Get the real noise here by interpolating the last 2 noises together
double rawNoise = MathHelper.lerp(zLerp, z0, z1);
// Normalize the noise from (-256, 256) to [-1, 1]
double density = MathHelper.clamp(rawNoise / 200.0D, -1.0D, 1.0D);
if (density > 0.0)
{
IBiomeConfig biomeConfig = this.getBiomeAt(realX, realZ);
buffer.setBlock(localX, realY, localZ, biomeConfig.getStoneBlockReplaced((short)realY));
buffer.setHighestBlockForColumn(pieceX + noiseX * 4, noiseZ * 4 + pieceZ, realY);
}
else if (realY < 63)
{
// TODO: water levels
IBiomeConfig biomeConfig = this.getBiomeAt(realX, realZ);
buffer.setBlock(localX, realY, localZ, biomeConfig.getWaterBlockReplaced(realY));
buffer.setHighestBlockForColumn(pieceX + noiseX * 4, noiseZ * 4 + pieceZ, realY);
}
}
}
}
}
}
// Reuse noise data from the previous column for speed
double[][] xColumn = noiseData[0];
noiseData[0] = noiseData[1];
noiseData[1] = xColumn;
}
doSurfaceAndGroundControl(random, worldHeightCap, this.seed, buffer, waterLevel);
}
public void carve(ChunkBuffer chunk, long seed, int chunkX, int chunkZ, BitSet carvingMask) {
Random random = new Random();
for(int localChunkX = chunkX - 8; localChunkX <= chunkX + 8; ++localChunkX) {
for(int localChunkZ = chunkZ - 8; localChunkZ <= chunkZ + 8; ++localChunkZ) {
setCarverSeed(random, seed, localChunkX, localChunkZ);
if (this.caves.shouldCarve(random, localChunkX, localChunkZ)) {
this.caves.carve(chunk, random, 63, localChunkX, localChunkZ, chunkX, chunkZ, carvingMask);
}
if (this.ravines.shouldCarve(random, localChunkX, localChunkZ)) {
this.ravines.carve(chunk, random, 63, localChunkX, localChunkZ, chunkX, chunkZ, carvingMask);
}
}
}
}
private long setCarverSeed(Random random, long seed, int x, int z) {
random.setSeed(seed);
long i = random.nextLong();
long j = random.nextLong();
long k = (long)x * i ^ (long)z * j ^ seed;
random.setSeed(k);
return k;
}
private class NoiseCache
{
private final long[] keys;
private final double[] values;
private final int mask;
private NoiseCache(int size, int noiseSize)
{
size = MathHelper.smallestEncompassingPowerOfTwo(size);
this.mask = size - 1;
this.keys = new long[size];
Arrays.fill(this.keys, Long.MIN_VALUE);
this.values = new double[size * noiseSize];
}
public double[] get(double[] buffer, int x, int z)
{
long key = key(x, z);
int idx = hash(key) & this.mask;
// if the entry here has a key that matches ours, we have a cache hit
if (this.keys[idx] == key)
{
// Copy values into buffer
System.arraycopy(this.values, idx * buffer.length, buffer, 0, buffer.length);
} else {
// cache miss: sample and put the result into our cache entry
// Sample the noise column to store the new values
generateNoiseColumn(buffer, x, z);
// Create copy of the array
System.arraycopy(buffer, 0, this.values, idx * buffer.length, buffer.length);
this.keys[idx] = key;
}
return buffer;
}
private int hash(long key)
{
return (int) HashCommon.mix(key);
}
private long key(int x, int z)
{
return MathHelper.toLong(x, z);
}
}
// Surface / ground / stone blocks / SAGC
// Previously ChunkProviderOTG.addBiomeBlocksAndCheckWater
private void doSurfaceAndGroundControl(Random random, int heightCap, long worldSeed, ChunkBuffer chunkBuffer, byte[] waterLevel)
{
// Process surface and ground blocks for each column in the chunk
ChunkCoordinate chunkCoord = chunkBuffer.getChunkCoordinate();
double d1 = 0.03125D;
this.biomeBlocksNoise = this.biomeBlocksNoiseGen.getRegion(this.biomeBlocksNoise, chunkCoord.getBlockX(), chunkCoord.getBlockZ(), CHUNK_SIZE, CHUNK_SIZE, d1 * 2.0D, d1 * 2.0D, 1.0D);
GeneratingChunk generatingChunk = new GeneratingChunk(random, waterLevel, this.biomeBlocksNoise, heightCap);
for (int x = 0; x < CHUNK_SIZE; x++)
{
for (int z = 0; z < CHUNK_SIZE; z++)
{
// Get the current biome config and some properties
// TODO: Technically, we should be providing the hashed seed here. Perhaps this may work for the time being?
IBiomeConfig biomeConfig = BiomeInterpolator.getConfig(this.seed, chunkCoord.getBlockX() + x, 0, chunkCoord.getBlockZ() + z, this.biomeGenerator);
biomeConfig.doSurfaceAndGroundControl(worldSeed, generatingChunk, chunkBuffer, biomeConfig, chunkCoord.getBlockX() + x, chunkCoord.getBlockZ() + z);
}
}
}
private int lastX = Integer.MAX_VALUE;
private int lastZ = Integer.MAX_VALUE;
private double lastNoise = 0;
// Used by sagc for generating surface/ground block patterns
public double getBiomeBlocksNoiseValue(int blockX, int blockZ)
{
double noise = this.lastNoise;
if(this.lastX != blockX || this.lastZ != blockZ)
{
double d1 = 0.03125D;
noise = this.biomeBlocksNoiseGen.getRegion(new double[1], blockX, blockZ, 1, 1, d1 * 2.0D, d1 * 2.0D, 1.0D)[0];
this.lastX = blockX;
this.lastZ = blockZ;
this.lastNoise = noise;
}
return noise;
}
}
|
package com.yahoo.vespa.config.server.application;
import com.yahoo.compress.ArchiveStreamReader;
import com.yahoo.compress.ArchiveStreamReader.Options;
import com.yahoo.vespa.config.server.http.BadRequestException;
import com.yahoo.vespa.config.server.http.InternalServerException;
import com.yahoo.vespa.config.server.http.v2.ApplicationApiHandler;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.yahoo.yolean.Exceptions.uncheck;
/**
* A compressed application points to an application package that can be decompressed.
*
* @author Ulf Lilleengen
*/
public class CompressedApplicationInputStream implements AutoCloseable {
private static final Logger log = Logger.getLogger(CompressedApplicationInputStream.class.getPackage().getName());
private final ArchiveStreamReader reader;
private CompressedApplicationInputStream(ArchiveStreamReader reader) {
this.reader = reader;
}
/**
* Create an instance of a compressed application from an input stream.
*
* @param is the input stream containing the compressed files.
* @param contentType the content type for determining what kind of compressed stream should be used.
* @param maxSizeInBytes the maximum allowed size of the decompressed content
* @return An instance of an unpacked application.
*/
public static CompressedApplicationInputStream createFromCompressedStream(InputStream is, String contentType, long maxSizeInBytes) {
try {
Options options = Options.standard().maxSize(maxSizeInBytes).allowDotSegment(true);
switch (contentType) {
case ApplicationApiHandler.APPLICATION_X_GZIP:
return new CompressedApplicationInputStream(ArchiveStreamReader.ofTarGzip(is, options));
case ApplicationApiHandler.APPLICATION_ZIP:
return new CompressedApplicationInputStream(ArchiveStreamReader.ofZip(is, options));
default:
throw new BadRequestException("Unable to decompress");
}
} catch (UncheckedIOException e) {
throw new InternalServerException("Unable to create compressed application stream", e);
}
}
/**
* Close this stream.
* @throws IOException if the stream could not be closed
*/
public void close() throws IOException {
reader.close();
}
File decompress() throws IOException {
return decompress(uncheck(() -> java.nio.file.Files.createTempDirectory("decompress")).toFile());
}
public File decompress(File dir) throws IOException {
decompressInto(dir.toPath());
return dir;
}
private void decompressInto(Path dir) throws IOException {
if (!Files.isDirectory(dir)) throw new IllegalArgumentException("Not a directory: " + dir.toAbsolutePath());
log.log(Level.FINE, () -> "Application is in " + dir.toAbsolutePath());
int entries = 0;
Path tmpFile = null;
OutputStream tmpStream = null;
try {
tmpFile = createTempFile(dir);
tmpStream = Files.newOutputStream(tmpFile);
ArchiveStreamReader.ArchiveFile file;
while ((file = reader.readNextTo(tmpStream)) != null) {
tmpStream.close();
log.log(Level.FINE, "Creating output file: " + file.path());
Path dstFile = dir.resolve(file.path().toString()).normalize();
Files.createDirectories(dstFile.getParent());
Files.move(tmpFile, dstFile);
tmpFile = createTempFile(dir);
tmpStream = Files.newOutputStream(tmpFile);
entries++;
}
} finally {
if (tmpStream != null) tmpStream.close();
if (tmpFile != null) Files.deleteIfExists(tmpFile);
}
if (entries == 0) {
log.log(Level.WARNING, "Not able to decompress any entries to " + dir);
}
}
private static Path createTempFile(Path applicationDir) throws IOException {
return Files.createTempFile(applicationDir, "application", null);
}
}
|
package org.phenotips.tools;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.xpn.xwiki.api.Document;
/**
* @version $Id$
* @since 1.0M2
*/
public class FormData
{
private DisplayMode mode;
private Document doc;
private String positiveFieldName;
private String negativeFieldName;
private String positivePropertyName;
private String negativePropertyName;
private Collection<String> selectedValues;
private Collection<String> selectedNegativeValues;
private Map<String, List<String>> customCategories;
private Map<String, List<String>> customNegativeCategories;
/**
* @return the mode
*/
public DisplayMode getMode()
{
return this.mode;
}
/**
* @param mode the mode to set
*/
public void setMode(DisplayMode mode)
{
this.mode = mode;
}
/**
* @return the doc
*/
public Document getDocument()
{
return this.doc;
}
/**
* @param doc the doc to set
*/
public void setDocument(Document doc)
{
this.doc = doc;
}
/**
* @return the positiveFieldName
*/
public String getPositiveFieldName()
{
return this.positiveFieldName;
}
/**
* @param positiveFieldName the positiveFieldName to set
*/
public void setPositiveFieldName(String positiveFieldName)
{
this.positiveFieldName = positiveFieldName;
}
/**
* @return the negativeFieldName
*/
public String getNegativeFieldName()
{
return this.negativeFieldName;
}
/**
* @param negativeFieldName the negativeFieldName to set
*/
public void setNegativeFieldName(String negativeFieldName)
{
this.negativeFieldName = negativeFieldName;
}
/**
* @return the positivePropertyName
*/
public String getPositivePropertyName()
{
return this.positivePropertyName;
}
/**
* @param positivePropertyName the positivePropertyName to set
*/
public void setPositivePropertyName(String positivePropertyName)
{
this.positivePropertyName = positivePropertyName;
}
/**
* @return the negativePropertyName
*/
public String getNegativePropertyName()
{
return this.negativePropertyName;
}
/**
* @param negativePropertyName the negativePropertyName to set
*/
public void setNegativePropertyName(String negativePropertyName)
{
this.negativePropertyName = negativePropertyName;
}
/**
* @return the selectedValues
*/
public Collection<String> getSelectedValues()
{
return this.selectedValues;
}
/**
* @param selectedValues the selectedValues to set
*/
public void setSelectedValues(Collection<String> selectedValues)
{
this.selectedValues = selectedValues;
}
/**
* @return the selectedNegativeValues
*/
public Collection<String> getSelectedNegativeValues()
{
return this.selectedNegativeValues;
}
/**
* @param selectedNegativeValues the selectedNegativeValues to set
*/
public void setSelectedNegativeValues(Collection<String> selectedNegativeValues)
{
this.selectedNegativeValues = selectedNegativeValues;
}
/**
* @return the customCategories
*/
public Map<String, List<String>> getCustomCategories()
{
return this.customCategories;
}
/**
* Set the categories in which non-standard positive features have been recorded in.
*
* @param customCategories a map between custom terms and their categories, may be empty but not {@code null}
*/
public void setCustomCategories(Map<String, List<String>> customCategories)
{
this.customCategories = customCategories;
}
/**
* @return the customNegativeCategories
*/
public Map<String, List<String>> getCustomNegativeCategories()
{
return this.customNegativeCategories;
}
/**
* Set the categories in which non-standard negative features have been recorded in.
*
* @param customNegativeCategories a map between custom terms and their categories, may be empty but not {@code null}
*/
public void setCustomNegativeCategories(Map<String, List<String>> customNegativeCategories)
{
this.customNegativeCategories = customNegativeCategories;
}
}
|
package org.hisp.dhis.android.core.trackedentity;
import org.hisp.dhis.android.core.arch.api.executors.internal.RxAPICallExecutor;
import org.hisp.dhis.android.core.arch.api.paging.internal.ApiPagingEngine;
import org.hisp.dhis.android.core.arch.api.paging.internal.Paging;
import org.hisp.dhis.android.core.arch.call.D2Progress;
import org.hisp.dhis.android.core.arch.call.internal.D2ProgressManager;
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder;
import org.hisp.dhis.android.core.arch.db.stores.internal.LinkModelStore;
import org.hisp.dhis.android.core.arch.handlers.internal.Handler;
import org.hisp.dhis.android.core.arch.helpers.internal.TrackedEntityInstanceHelper;
import org.hisp.dhis.android.core.arch.repositories.collection.ReadOnlyWithDownloadObjectRepository;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitMode;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitProgramLink;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitProgramLinkTableInfo;
import org.hisp.dhis.android.core.program.internal.ProgramOrganisationUnitLastUpdated;
import org.hisp.dhis.android.core.resource.internal.Resource;
import org.hisp.dhis.android.core.resource.internal.ResourceHandler;
import org.hisp.dhis.android.core.systeminfo.DHISVersionManager;
import org.hisp.dhis.android.core.systeminfo.SystemInfo;
import org.hisp.dhis.android.core.user.internal.UserOrganisationUnitLinkStore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import dagger.Reusable;
import io.reactivex.Observable;
import io.reactivex.Single;
@Reusable
@SuppressWarnings({"PMD.ExcessiveImports"})
public final class TrackedEntityInstanceWithLimitCallFactory {
private final Resource.Type resourceType = Resource.Type.TRACKED_ENTITY_INSTANCE;
private final RxAPICallExecutor rxCallExecutor;
private final ResourceHandler resourceHandler;
private final Handler<ProgramOrganisationUnitLastUpdated> programOrganisationUnitLastUpdatedHandler;
private final UserOrganisationUnitLinkStore userOrganisationUnitLinkStore;
private final LinkModelStore<OrganisationUnitProgramLink> organisationUnitProgramLinkStore;
private final ReadOnlyWithDownloadObjectRepository<SystemInfo> systemInfoRepository;
private final DHISVersionManager versionManager;
private final TrackedEntityInstanceRelationshipDownloadAndPersistCallFactory relationshipDownloadCallFactory;
private final TrackedEntityInstancePersistenceCallFactory persistenceCallFactory;
private final TrackedEntityInstancesEndpointCallFactory endpointCallFactory;
// TODO use scheduler for parallel download
// private final Scheduler teiDownloadScheduler = Schedulers.from(Executors.newFixedThreadPool(6));
@Inject
TrackedEntityInstanceWithLimitCallFactory(
RxAPICallExecutor rxCallExecutor,
ResourceHandler resourceHandler,
Handler<ProgramOrganisationUnitLastUpdated> programOrganisationUnitLastUpdatedHandler,
UserOrganisationUnitLinkStore userOrganisationUnitLinkStore,
LinkModelStore<OrganisationUnitProgramLink> organisationUnitProgramLinkStore,
ReadOnlyWithDownloadObjectRepository<SystemInfo> systemInfoRepository,
TrackedEntityInstanceRelationshipDownloadAndPersistCallFactory relationshipDownloadCallFactory,
TrackedEntityInstancePersistenceCallFactory persistenceCallFactory,
DHISVersionManager versionManager,
TrackedEntityInstancesEndpointCallFactory endpointCallFactory) {
this.rxCallExecutor = rxCallExecutor;
this.resourceHandler = resourceHandler;
this.programOrganisationUnitLastUpdatedHandler = programOrganisationUnitLastUpdatedHandler;
this.userOrganisationUnitLinkStore = userOrganisationUnitLinkStore;
this.organisationUnitProgramLinkStore = organisationUnitProgramLinkStore;
this.systemInfoRepository = systemInfoRepository;
this.versionManager = versionManager;
this.relationshipDownloadCallFactory = relationshipDownloadCallFactory;
this.persistenceCallFactory = persistenceCallFactory;
this.endpointCallFactory = endpointCallFactory;
}
public Observable<D2Progress> download(final int teiLimit, final boolean limitByOrgUnit, boolean limitByProgram) {
Observable<D2Progress> observable = Observable.defer(() -> {
D2ProgressManager progressManager = new D2ProgressManager(null);
Set<ProgramOrganisationUnitLastUpdated> programOrganisationUnitSet = new HashSet<>();
if (userOrganisationUnitLinkStore.count() == 0) {
return Observable.just(
progressManager.increaseProgress(TrackedEntityInstance.class, true));
} else {
BooleanWrapper allOkay = new BooleanWrapper(true);
return Observable.concat(
downloadSystemInfo(progressManager),
downloadTeis(progressManager, teiLimit, limitByOrgUnit, limitByProgram, allOkay,
programOrganisationUnitSet),
downloadRelationshipTeis(progressManager),
updateResource(progressManager, allOkay, programOrganisationUnitSet)
);
}
});
return rxCallExecutor.wrapObservableTransactionally(observable, true);
}
private Observable<D2Progress> downloadSystemInfo(D2ProgressManager progressManager) {
return systemInfoRepository.download()
.toSingle(() -> progressManager.increaseProgress(SystemInfo.class, false))
.toObservable();
}
private Observable<D2Progress> downloadTeis(D2ProgressManager progressManager,
int teiLimit,
boolean limitByOrgUnit,
boolean limitByProgram,
BooleanWrapper allOkay,
Set<ProgramOrganisationUnitLastUpdated> programOrganisationUnitSet) {
int pageSize = TeiQuery.builder().build().pageSize();
List<Paging> pagingList = ApiPagingEngine.getPaginationList(pageSize, teiLimit);
Observable<List<TrackedEntityInstance>> teiDownloadObservable =
Observable.fromIterable(getTeiQueryBuilders(limitByOrgUnit, limitByProgram))
.flatMap(teiQueryBuilder -> {
return getTrackedEntityInstancesWithPaging(teiQueryBuilder, pagingList, allOkay);
// TODO .subscribeOn(teiDownloadScheduler);
});
Date serverDate = systemInfoRepository.get().serverDate();
return teiDownloadObservable.map(
teiList -> {
persistenceCallFactory.getCall(teiList).call();
programOrganisationUnitSet.addAll(
TrackedEntityInstanceHelper.getProgramOrganisationUnitTuple(teiList, serverDate));
return progressManager.increaseProgress(TrackedEntityInstance.class, false);
});
}
private Observable<D2Progress> downloadRelationshipTeis(D2ProgressManager progressManager) {
Observable<List<TrackedEntityInstance>> observable = versionManager.is2_29()
? Observable.just(Collections.emptyList())
: relationshipDownloadCallFactory.downloadAndPersist().toObservable();
return observable.map(
trackedEntityInstances -> progressManager.increaseProgress(TrackedEntityInstance.class, true));
}
private List<TeiQuery.Builder> getTeiQueryBuilders(boolean limitByOrgUnit, boolean limitByProgram) {
String lastUpdated = resourceHandler.getLastUpdated(resourceType);
List<TeiQuery.Builder> builders = new ArrayList<>();
if (limitByOrgUnit) {
List<String> captureOrgUnitUids = getCaptureOrgUnitUids();
if (limitByProgram) {
for (OrganisationUnitProgramLink link :
getOrganisationUnitProgramLinksByOrgunitUids(captureOrgUnitUids)) {
builders.add(getTeiBuilderForOrgUnit(lastUpdated, link.organisationUnit()).program(link.program()));
}
} else {
for (String orgUnitUid : captureOrgUnitUids) {
builders.add(getTeiBuilderForOrgUnit(lastUpdated, orgUnitUid));
}
}
} else {
List<String> rootCaptureOrgUnitUids = getRootCaptureOrgUnitUids();
if (limitByProgram) {
Set<String> programs = new HashSet<>();
for (OrganisationUnitProgramLink link : organisationUnitProgramLinkStore.selectAll()) {
programs.add(link.program());
}
for (String program : programs) {
builders.add(getTeiBuilderForRootOrgunits(lastUpdated, rootCaptureOrgUnitUids).program(program));
}
} else {
builders.add(getTeiBuilderForRootOrgunits(lastUpdated, rootCaptureOrgUnitUids));
}
}
return builders;
}
private TeiQuery.Builder getTeiBuilderForRootOrgunits(String lastUpdated, List<String> rootOrgunitUids) {
return TeiQuery.builder()
.lastUpdatedStartDate(lastUpdated)
.orgUnits(rootOrgunitUids)
.ouMode(OrganisationUnitMode.DESCENDANTS);
}
private TeiQuery.Builder getTeiBuilderForOrgUnit(String lastUpdated, String orgUnitUid) {
return TeiQuery.builder()
.lastUpdatedStartDate(lastUpdated)
.orgUnits(Collections.singleton(orgUnitUid));
}
private Observable<List<TrackedEntityInstance>> getTrackedEntityInstancesWithPaging(
TeiQuery.Builder teiQueryBuilder, List<Paging> pagingList, BooleanWrapper allOkay) {
Observable<Paging> pagingObservable = Observable.fromIterable(pagingList);
return pagingObservable
.flatMapSingle(paging -> {
teiQueryBuilder.page(paging.page()).pageSize(paging.pageSize());
return endpointCallFactory.getCall(teiQueryBuilder.build()).map(payload ->
new TeiListWithPaging(true, limitTeisForPage(payload.items(), paging), paging))
.onErrorResumeNext((err) -> {
allOkay.set(false);
return Single.just(new TeiListWithPaging(false, Collections.emptyList(), paging));
});
})
.takeUntil(res -> res.isSuccess && (res.paging.isLastPage() ||
!res.paging.isLastPage() && res.teiList.size() < res.paging.pageSize()))
.map(tuple -> tuple.teiList);
}
private List<TrackedEntityInstance> limitTeisForPage(List<TrackedEntityInstance> pageTrackedEntityInstances,
Paging paging) {
if (paging.isLastPage()
&& pageTrackedEntityInstances.size() > paging.previousItemsToSkipCount()) {
int toIndex = pageTrackedEntityInstances.size() <
paging.pageSize() - paging.posteriorItemsToSkipCount() ?
pageTrackedEntityInstances.size() :
paging.pageSize() - paging.posteriorItemsToSkipCount();
return pageTrackedEntityInstances.subList(paging.previousItemsToSkipCount(), toIndex);
} else {
return pageTrackedEntityInstances;
}
}
private List<String> getRootCaptureOrgUnitUids() {
return userOrganisationUnitLinkStore.queryRootCaptureOrganisationUnitUids();
}
private List<String> getCaptureOrgUnitUids() {
return userOrganisationUnitLinkStore
.queryOrganisationUnitUidsByScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE);
}
private List<OrganisationUnitProgramLink> getOrganisationUnitProgramLinksByOrgunitUids(List<String> uids) {
return organisationUnitProgramLinkStore.selectWhere(
new WhereClauseBuilder().appendInKeyStringValues(
OrganisationUnitProgramLinkTableInfo.Columns.ORGANISATION_UNIT,
uids
).build());
}
private Observable<D2Progress> updateResource(D2ProgressManager progressManager, BooleanWrapper allOkay,
Set<ProgramOrganisationUnitLastUpdated> programOrganisationUnitSet) {
return Single.fromCallable(() -> {
if (allOkay.get()) {
resourceHandler.handleResource(resourceType);
}
programOrganisationUnitLastUpdatedHandler.handleMany(programOrganisationUnitSet);
return progressManager.increaseProgress(TrackedEntityInstance.class, true);
}).toObservable();
}
private static class TeiListWithPaging {
final boolean isSuccess;
final List<TrackedEntityInstance> teiList;
final Paging paging;
TeiListWithPaging(boolean isSuccess, List<TrackedEntityInstance> teiList, Paging paging) {
this.isSuccess = isSuccess;
this.teiList = teiList;
this.paging = paging;
}
}
private static class BooleanWrapper {
private boolean value;
BooleanWrapper(boolean value) {
this.value = value;
}
boolean get() {
return value;
}
void set(boolean value) {
this.value = value;
}
}
}
|
package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.activity.INavigationSource;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.activity.TabbedViewPagerActivity;
import cgeo.geocaching.activity.TabbedViewPagerFragment;
import cgeo.geocaching.apps.cachelist.MapsMeCacheListApp;
import cgeo.geocaching.apps.navi.NavigationAppFactory;
import cgeo.geocaching.calendar.CalendarAdder;
import cgeo.geocaching.command.AbstractCommand;
import cgeo.geocaching.command.MoveToListAndRemoveFromOthersCommand;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.al.ALConnector;
import cgeo.geocaching.connector.capability.IFavoriteCapability;
import cgeo.geocaching.connector.capability.IIgnoreCapability;
import cgeo.geocaching.connector.capability.IVotingCapability;
import cgeo.geocaching.connector.capability.PersonalNoteCapability;
import cgeo.geocaching.connector.capability.PgcChallengeCheckerCapability;
import cgeo.geocaching.connector.capability.WatchListCapability;
import cgeo.geocaching.connector.internal.InternalConnector;
import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.connector.trackable.TrackableConnector;
import cgeo.geocaching.databinding.CachedetailDescriptionPageBinding;
import cgeo.geocaching.databinding.CachedetailDetailsPageBinding;
import cgeo.geocaching.databinding.CachedetailImagegalleryPageBinding;
import cgeo.geocaching.databinding.CachedetailImagesPageBinding;
import cgeo.geocaching.databinding.CachedetailInventoryPageBinding;
import cgeo.geocaching.databinding.CachedetailWaypointsHeaderBinding;
import cgeo.geocaching.databinding.CachedetailWaypointsPageBinding;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.enumerations.CacheAttributeCategory;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.export.FieldNoteExport;
import cgeo.geocaching.export.GpxExport;
import cgeo.geocaching.export.PersonalNoteExport;
import cgeo.geocaching.gcvote.VoteDialog;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.GeopointFormatter;
import cgeo.geocaching.location.Units;
import cgeo.geocaching.log.CacheLogsViewCreator;
import cgeo.geocaching.log.LogCacheActivity;
import cgeo.geocaching.log.LoggingUI;
import cgeo.geocaching.models.CalculatedCoordinate;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.models.WaypointParser;
import cgeo.geocaching.network.AndroidBeam;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.SmileyImage;
import cgeo.geocaching.permission.PermissionHandler;
import cgeo.geocaching.permission.PermissionRequestContext;
import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.service.GeocacheChangedBroadcastReceiver;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.speech.SpeechService;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.CoordinatesFormatSwitcher;
import cgeo.geocaching.ui.DecryptTextClickListener;
import cgeo.geocaching.ui.FastScrollListener;
import cgeo.geocaching.ui.ImageGalleryView;
import cgeo.geocaching.ui.ImagesList;
import cgeo.geocaching.ui.IndexOutOfBoundsAvoidingTextView;
import cgeo.geocaching.ui.TextParam;
import cgeo.geocaching.ui.TrackableListAdapter;
import cgeo.geocaching.ui.UserClickListener;
import cgeo.geocaching.ui.WeakReferenceHandler;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.ui.dialog.EditNoteDialog;
import cgeo.geocaching.ui.dialog.EditNoteDialog.EditNoteDialogListener;
import cgeo.geocaching.ui.dialog.SimpleDialog;
import cgeo.geocaching.ui.recyclerview.RecyclerViewProvider;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.CalendarUtils;
import cgeo.geocaching.utils.CheckerUtils;
import cgeo.geocaching.utils.ClipboardUtils;
import cgeo.geocaching.utils.ColorUtils;
import cgeo.geocaching.utils.CryptUtils;
import cgeo.geocaching.utils.DisposableHandler;
import cgeo.geocaching.utils.EmojiUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.LocalizationUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MapMarkerUtils;
import cgeo.geocaching.utils.ProcessUtils;
import cgeo.geocaching.utils.ShareUtils;
import cgeo.geocaching.utils.SimpleDisposableHandler;
import cgeo.geocaching.utils.SimpleHandler;
import cgeo.geocaching.utils.TextUtils;
import cgeo.geocaching.utils.UnknownTagsHandler;
import cgeo.geocaching.utils.functions.Action1;
import static cgeo.geocaching.apps.cache.WhereYouGoApp.getWhereIGoUrl;
import static cgeo.geocaching.apps.cache.WhereYouGoApp.isWhereYouGoInstalled;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.TooltipCompat;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.FragmentManager;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
/**
* Activity to handle all single-cache-stuff.
*
* e.g. details, description, logs, waypoints, inventory, variables...
*/
public class CacheDetailActivity extends TabbedViewPagerActivity
implements CacheMenuHandler.ActivityInterface, INavigationSource, AndroidBeam.ActivitySharingInterface, EditNoteDialogListener {
private static final int MESSAGE_FAILED = -1;
private static final int MESSAGE_SUCCEEDED = 1;
private static final String EXTRA_FORCE_WAYPOINTSPAGE = "cgeo.geocaching.extra.cachedetail.forceWaypointsPage";
private static final float CONTRAST_THRESHOLD = 4.5f;
public static final String STATE_PAGE_INDEX = "cgeo.geocaching.pageIndex";
// Store Geocode here, as 'cache' is loaded Async.
private String geocode;
private Geocache cache;
@NonNull
private final List<Trackable> genericTrackables = new ArrayList<>();
private final Progress progress = new Progress();
private SearchResult search;
private GeoDirHandler locationUpdater;
private CharSequence clickedItemText = null;
private MenuItem menuItemToggleWaypointsFromNote = null;
/**
* If another activity is called and can modify the data of this activity, we refresh it on resume.
*/
private boolean refreshOnResume = false;
// some views that must be available from everywhere // TODO: Reference can block GC?
private TextView cacheDistanceView;
protected ImagesList imagesList;
private ImageGalleryView imageGallery;
private final CompositeDisposable createDisposables = new CompositeDisposable();
/**
* waypoint selected in context menu. This variable will be gone when the waypoint context menu is a fragment.
*/
private Waypoint selectedWaypoint;
private boolean requireGeodata;
private final CompositeDisposable geoDataDisposable = new CompositeDisposable();
private final EnumSet<TrackableBrand> processedBrands = EnumSet.noneOf(TrackableBrand.class);
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setThemeAndContentView(R.layout.tabbed_viewpager_activity_refreshable);
// get parameters
final Bundle extras = getIntent().getExtras();
final Uri uri = AndroidBeam.getUri(getIntent());
// try to get data from extras
String name = null;
String guid = null;
boolean forceWaypointsPage = false;
if (extras != null) {
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
forceWaypointsPage = extras.getBoolean(EXTRA_FORCE_WAYPOINTSPAGE);
}
// When clicking a cache in MapsWithMe, we get back a PendingIntent
if (StringUtils.isEmpty(geocode)) {
geocode = MapsMeCacheListApp.getCacheFromMapsWithMe(this, getIntent());
}
if (geocode == null && uri != null) {
geocode = ConnectorFactory.getGeocodeFromURL(uri.toString());
}
// try to get data from URI
if (geocode == null && guid == null && uri != null) {
final String uriHost = uri.getHost().toLowerCase(Locale.US);
final String uriPath = uri.getPath().toLowerCase(Locale.US);
final String uriQuery = uri.getQuery();
if (uriQuery != null) {
Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
} else {
Log.i("Opening URI: " + uriHost + uriPath);
}
if (uriHost.contains("geocaching.com")) {
if (StringUtils.startsWith(uriPath, "/geocache/gc")) {
geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US);
} else {
geocode = uri.getQueryParameter("wp");
guid = uri.getQueryParameter("guid");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
}
}
}
// no given data
if (geocode == null && guid == null) {
showToast(res.getString(R.string.err_detail_cache));
finish();
return;
}
// If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details
setCacheTitleBar(geocode, name, null);
final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress);
try {
String title = res.getString(R.string.cache);
if (StringUtils.isNotBlank(name)) {
title = name;
} else if (StringUtils.isNotBlank(geocode)) {
title = geocode;
}
progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.disposeMessage());
} catch (final RuntimeException ignored) {
// nothing, we lost the window
}
locationUpdater = new CacheDetailsGeoDirHandler(this);
final long pageToOpen = forceWaypointsPage ? Page.WAYPOINTS.id :
savedInstanceState != null ?
savedInstanceState.getLong(STATE_PAGE_INDEX, Page.DETAILS.id) :
Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : Page.DETAILS.id;
createViewPager(pageToOpen, getOrderedPages(), currentPageId -> {
if (Settings.isOpenLastDetailsPage()) {
Settings.setLastDetailsPage((int) (long) currentPageId);
}
requireGeodata = currentPageId == Page.DETAILS.id;
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this, new RestartLocationPermissionGrantedCallback(PermissionRequestContext.CacheDetailActivity) {
@Override
public void executeAfter() {
startOrStopGeoDataListener(false);
}
});
// dispose contextual actions on page change
if (currentActionMode != null) {
currentActionMode.finish();
}
}, true);
requireGeodata = pageToOpen == Page.DETAILS.id;
final String realGeocode = geocode;
final String realGuid = guid;
AndroidRxUtils.networkScheduler.scheduleDirect(() -> {
search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null, false, loadCacheHandler);
loadCacheHandler.sendMessage(Message.obtain());
});
// Load Generic Trackables
if (StringUtils.isNotBlank(geocode)) {
AndroidRxUtils.bindActivity(this,
// Obtain the active connectors and load trackables in parallel.
Observable.fromIterable(ConnectorFactory.getGenericTrackablesConnectors()).flatMap((Function<TrackableConnector, Observable<Trackable>>) trackableConnector -> {
processedBrands.add(trackableConnector.getBrand());
return Observable.defer(() -> Observable.fromIterable(trackableConnector.searchTrackables(geocode))).subscribeOn(AndroidRxUtils.networkScheduler);
}).toList()).subscribe(trackables -> {
// Todo: this is not really a good method, it may lead to duplicates ; ie: in OC connectors.
// Store trackables.
genericTrackables.addAll(trackables);
if (!trackables.isEmpty()) {
// Update the UI if any trackables were found.
notifyDataSetChanged();
}
});
}
// If we have a newer Android device setup Android Beam for easy cache sharing
AndroidBeam.enable(this, this);
// get notified on async cache changes (e.g.: waypoint creation from map or background refresh)
getLifecycle().addObserver(new GeocacheChangedBroadcastReceiver(this, true) {
@Override
protected void onReceive(final Context context, final String geocode) {
if (cache != null && cache.getGeocode().equals(geocode)) {
notifyDataSetChanged();
}
}
});
}
@Override
@Nullable
public String getAndroidBeamUri() {
return cache != null ? cache.getUrl() : null;
}
@Override
public void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(STATE_PAGE_INDEX, getCurrentPageId());
}
private void startOrStopGeoDataListener(final boolean initial) {
final boolean start;
if (Settings.useLowPowerMode()) {
geoDataDisposable.clear();
start = requireGeodata;
} else {
start = initial;
}
if (start) {
geoDataDisposable.add(locationUpdater.start(GeoDirHandler.UPDATE_GEODATA));
}
}
@Override
public void onResume() {
super.onResume();
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this, new RestartLocationPermissionGrantedCallback(PermissionRequestContext.CacheDetailActivity) {
@Override
public void executeAfter() {
startOrStopGeoDataListener(true);
}
});
if (refreshOnResume) {
notifyDataSetChanged();
refreshOnResume = false;
}
}
@Override
public void onPause() {
geoDataDisposable.clear();
super.onPause();
}
@Override
public void onDestroy() {
createDisposables.clear();
if (cache != null) {
cache.setChangeNotificationHandler(null);
}
super.onDestroy();
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View view, final ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
final int viewId = view.getId();
if (viewId == R.id.waypoint) {
menu.setHeaderTitle(selectedWaypoint.getName() + " (" + res.getString(R.string.waypoint) + ")");
getMenuInflater().inflate(R.menu.waypoint_options, menu);
final boolean isOriginalWaypoint = selectedWaypoint.getWaypointType() == WaypointType.ORIGINAL;
menu.findItem(R.id.menu_waypoint_reset_cache_coords).setVisible(isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_edit).setVisible(!isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_duplicate).setVisible(!isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_delete).setVisible(!isOriginalWaypoint || selectedWaypoint.belongsToUserDefinedCache());
final boolean hasCoords = selectedWaypoint.getCoords() != null;
final MenuItem defaultNavigationMenu = menu.findItem(R.id.menu_waypoint_navigate_default);
defaultNavigationMenu.setVisible(hasCoords);
defaultNavigationMenu.setTitle(NavigationAppFactory.getDefaultNavigationApplication().getName());
menu.findItem(R.id.menu_waypoint_navigate).setVisible(hasCoords);
menu.findItem(R.id.menu_waypoint_caches_around).setVisible(hasCoords);
menu.findItem(R.id.menu_waypoint_copy_coordinates).setVisible(hasCoords);
final boolean canClearCoords = hasCoords && (selectedWaypoint.isUserDefined() || selectedWaypoint.isOriginalCoordsEmpty());
menu.findItem(R.id.menu_waypoint_clear_coordinates).setVisible(canClearCoords);
menu.findItem(R.id.menu_waypoint_toclipboard).setVisible(true);
menu.findItem(R.id.menu_waypoint_open_geochecker).setVisible(CheckerUtils.getCheckerUrl(cache) != null);
} else {
if (imagesList != null) {
imagesList.onCreateContextMenu(menu, view);
}
}
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.menu_waypoint_edit) {
// waypoints
if (selectedWaypoint != null) {
ensureSaved();
EditWaypointActivity.startActivityEditWaypoint(this, cache, selectedWaypoint.getId());
refreshOnResume = true;
}
} else if (itemId == R.id.menu_waypoint_visited) {
if (selectedWaypoint != null) {
ensureSaved();
AndroidRxUtils.andThenOnUi(AndroidRxUtils.computationScheduler, () -> {
selectedWaypoint.setVisited(true);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
}, this::notifyDataSetChanged);
}
} else if (itemId == R.id.menu_waypoint_copy_coordinates) {
if (selectedWaypoint != null) {
final Geopoint coordinates = selectedWaypoint.getCoords();
if (coordinates != null) {
ClipboardUtils.copyToClipboard(
GeopointFormatter.reformatForClipboard(coordinates.toString()));
showToast(getString(R.string.clipboard_copy_ok));
}
}
} else if (itemId == R.id.menu_waypoint_clear_coordinates) {
if (selectedWaypoint != null) {
ensureSaved();
new ClearCoordinatesCommand(this, cache, selectedWaypoint).execute();
}
} else if (itemId == R.id.menu_waypoint_duplicate) {
ensureSaved();
AndroidRxUtils.andThenOnUi(AndroidRxUtils.computationScheduler, () -> {
if (cache.duplicateWaypoint(selectedWaypoint, true) != null) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
return false;
}, result -> {
if (result) {
notifyDataSetChanged();
}
});
} else if (itemId == R.id.menu_waypoint_toclipboard) {
if (selectedWaypoint != null) {
ensureSaved();
ClipboardUtils.copyToClipboard(selectedWaypoint.reformatForClipboard());
showToast(getString(R.string.clipboard_copy_ok));
}
} else if (itemId == R.id.menu_waypoint_open_geochecker) {
if (selectedWaypoint != null) {
ensureSaved();
final Pair<String, CheckerUtils.GeoChecker> geocheckerData = CheckerUtils.getCheckerData(cache, selectedWaypoint.getCoords());
if (geocheckerData != null) {
if (!geocheckerData.second.allowsCoordinate()) {
final Geopoint coordinates = selectedWaypoint.getCoords();
if (coordinates != null) {
ClipboardUtils.copyToClipboard(GeopointFormatter.reformatForClipboard(coordinates.toString()));
}
}
ShareUtils.openUrl(this, geocheckerData.first, true);
}
}
} else if (itemId == R.id.menu_waypoint_delete) {
ensureSaved();
AndroidRxUtils.andThenOnUi(AndroidRxUtils.computationScheduler, () -> {
if (cache.deleteWaypoint(selectedWaypoint)) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
return false;
}, result -> {
if (result) {
notifyDataSetChanged();
GeocacheChangedBroadcastReceiver.sendBroadcast(CacheDetailActivity.this, cache.getGeocode());
}
});
} else if (itemId == R.id.menu_waypoint_navigate_default) {
if (selectedWaypoint != null) {
NavigationAppFactory.startDefaultNavigationApplication(1, this, selectedWaypoint);
}
} else if (itemId == R.id.menu_waypoint_navigate) {
if (selectedWaypoint != null) {
NavigationAppFactory.showNavigationMenu(this, null, selectedWaypoint, null);
}
} else if (itemId == R.id.menu_waypoint_caches_around) {
if (selectedWaypoint != null) {
final Geopoint coordinates = selectedWaypoint.getCoords();
if (coordinates != null) {
CacheListActivity.startActivityCoordinates(this, coordinates, selectedWaypoint.getName());
}
}
} else if (itemId == R.id.menu_waypoint_reset_cache_coords) {
ensureSaved();
if (ConnectorFactory.getConnector(cache).supportsOwnCoordinates()) {
createResetCacheCoordinatesDialog(selectedWaypoint).show();
} else {
final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(this, progressDialog, false);
resetCoords(cache, handler, selectedWaypoint, true, false, progressDialog);
}
} else if (itemId == R.id.menu_calendar) {
CalendarAdder.addToCalendar(this, cache);
} else if (imagesList == null || !imagesList.onContextItemSelected(item)) {
return onOptionsItemSelected(item);
}
return true;
}
private abstract static class AbstractWaypointModificationCommand extends AbstractCommand {
protected final Waypoint waypoint;
protected final Geocache cache;
protected AbstractWaypointModificationCommand(final CacheDetailActivity context, final Geocache cache, final Waypoint waypoint) {
super(context);
this.cache = cache;
this.waypoint = waypoint;
}
@Override
protected void onFinished() {
((CacheDetailActivity) getContext()).notifyDataSetChanged();
}
@Override
protected void onFinishedUndo() {
((CacheDetailActivity) getContext()).notifyDataSetChanged();
}
}
private static final class ClearCoordinatesCommand extends AbstractWaypointModificationCommand {
private Geopoint coords;
ClearCoordinatesCommand(final CacheDetailActivity context, final Geocache cache, final Waypoint waypoint) {
super(context, cache, waypoint);
}
@Override
protected void doCommand() {
coords = waypoint.getCoords();
waypoint.setCoords(null);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
}
@Override
protected void undoCommand() {
waypoint.setCoords(coords);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
}
@Override
protected String getResultMessage() {
return getContext().getString(R.string.info_waypoint_coordinates_cleared);
}
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
CacheMenuHandler.addMenuItems(this, menu, cache);
CacheMenuHandler.initDefaultNavigationMenuItem(menu, this);
return true;
}
private void setMenuPreventWaypointsFromNote(final boolean preventWaypointsFromNote) {
if (null != menuItemToggleWaypointsFromNote) {
menuItemToggleWaypointsFromNote.setTitle(preventWaypointsFromNote ? R.string.cache_menu_allowWaypointExtraction : R.string.cache_menu_preventWaypointsFromNote);
}
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final IConnector connector = null != cache ? ConnectorFactory.getConnector(cache) : null;
final boolean isUDC = null != connector && connector.equals(InternalConnector.getInstance());
CacheMenuHandler.onPrepareOptionsMenu(menu, cache, false);
LoggingUI.onPrepareOptionsMenu(menu, cache);
if (cache != null) {
// top level menu items
menu.findItem(R.id.menu_tts_toggle).setVisible(!cache.isGotoHistoryUDC());
if (connector instanceof PgcChallengeCheckerCapability) {
menu.findItem(R.id.menu_challenge_checker).setVisible(((PgcChallengeCheckerCapability) connector).isChallengeCache(cache));
}
menu.findItem(R.id.menu_edit_fieldnote).setVisible(true);
// submenu waypoints
menu.findItem(R.id.menu_delete_userdefined_waypoints).setVisible(cache.isOffline() && cache.hasUserdefinedWaypoints());
menu.findItem(R.id.menu_delete_generated_waypoints).setVisible(cache.isOffline() && cache.hasGeneratedWaypoints());
menu.findItem(R.id.menu_extract_waypoints).setVisible(!isUDC);
menu.findItem(R.id.menu_scan_calculated_waypoints).setVisible(!isUDC);
menu.findItem(R.id.menu_clear_goto_history).setVisible(cache.isGotoHistoryUDC());
menuItemToggleWaypointsFromNote = menu.findItem(R.id.menu_toggleWaypointsFromNote);
setMenuPreventWaypointsFromNote(cache.isPreventWaypointsFromNote());
menuItemToggleWaypointsFromNote.setVisible(!cache.isGotoHistoryUDC());
menu.findItem(R.id.menu_waypoints).setVisible(true);
// submenu share / export
menu.findItem(R.id.menu_export).setVisible(true);
// submenu advanced
if (connector instanceof IVotingCapability) {
final MenuItem menuItemGCVote = menu.findItem(R.id.menu_gcvote);
menuItemGCVote.setVisible(((IVotingCapability) connector).supportsVoting(cache));
menuItemGCVote.setEnabled(Settings.isRatingWanted() && Settings.isGCVoteLoginValid());
}
if (connector instanceof IIgnoreCapability) {
menu.findItem(R.id.menu_ignore).setVisible(((IIgnoreCapability) connector).canIgnoreCache(cache));
}
menu.findItem(R.id.menu_set_cache_icon).setVisible(cache.isOffline());
menu.findItem(R.id.menu_advanced).setVisible(cache.getCoords() != null);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (CacheMenuHandler.onMenuItemSelected(item, this, cache, this::notifyDataSetChanged, false)) {
return true;
}
final int menuItem = item.getItemId();
if (menuItem == R.id.menu_delete_userdefined_waypoints) {
dropUserdefinedWaypoints();
} else if (menuItem == R.id.menu_delete_generated_waypoints) {
dropGeneratedWaypoints();
} else if (menuItem == R.id.menu_refresh) {
refreshCache();
} else if (menuItem == R.id.menu_gcvote) {
showVoteDialog();
} else if (menuItem == R.id.menu_challenge_checker) {
ShareUtils.openUrl(this, "https://project-gc.com/Challenges/" + cache.getGeocode());
} else if (menuItem == R.id.menu_ignore) {
ignoreCache();
} else if (menuItem == R.id.menu_extract_waypoints) {
final String searchText = cache.getShortDescription() + ' ' + cache.getDescription();
extractWaypoints(searchText, cache);
} else if (menuItem == R.id.menu_scan_calculated_waypoints) {
scanForCalculatedWaypints(cache);
} else if (menuItem == R.id.menu_toggleWaypointsFromNote) {
cache.setPreventWaypointsFromNote(!cache.isPreventWaypointsFromNote());
setMenuPreventWaypointsFromNote(cache.isPreventWaypointsFromNote());
AndroidRxUtils.andThenOnUi(AndroidRxUtils.computationScheduler, () -> DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)), this::notifyDataSetChanged);
} else if (menuItem == R.id.menu_clear_goto_history) {
SimpleDialog.of(this).setTitle(R.string.clear_goto_history_title).setMessage(R.string.clear_goto_history).confirm((dialog, which) -> AndroidRxUtils.andThenOnUi(Schedulers.io(), DataStore::clearGotoHistory, () -> {
cache = DataStore.loadCache(InternalConnector.GEOCODE_HISTORY_CACHE, LoadFlags.LOAD_ALL_DB_ONLY);
notifyDataSetChanged();
}));
} else if (menuItem == R.id.menu_export_gpx) {
new GpxExport().export(Collections.singletonList(cache), this);
} else if (menuItem == R.id.menu_export_fieldnotes) {
new FieldNoteExport().export(Collections.singletonList(cache), this);
} else if (menuItem == R.id.menu_export_persnotes) {
new PersonalNoteExport().export(Collections.singletonList(cache), this);
} else if (menuItem == R.id.menu_edit_fieldnote) {
ensureSaved();
editPersonalNote(cache, this);
} else if (menuItem == R.id.menu_navigate) {
NavigationAppFactory.onMenuItemSelected(item, this, cache);
} else if (menuItem == R.id.menu_tts_toggle) {
SpeechService.toggleService(this, cache.getCoords());
} else if (menuItem == R.id.menu_set_cache_icon) {
EmojiUtils.selectEmojiPopup(this, cache.getAssignedEmoji(), cache, this::setCacheIcon);
} else if (LoggingUI.onMenuItemSelected(item, this, cache, null)) {
refreshOnResume = true;
} else {
return super.onOptionsItemSelected(item);
}
return true;
}
private static void openGeochecker(final Activity activity, final Geocache cache) {
ShareUtils.openUrl(activity, CheckerUtils.getCheckerUrl(cache), true);
}
private void setCacheIcon(final int newCacheIcon) {
cache.setAssignedEmoji(newCacheIcon);
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
Toast.makeText(this, R.string.cache_icon_updated, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
private void ignoreCache() {
SimpleDialog.of(this).setTitle(R.string.ignore_confirm_title).setMessage(R.string.ignore_confirm_message).confirm((dialog, which) -> {
AndroidRxUtils.networkScheduler.scheduleDirect(() -> ((IIgnoreCapability) ConnectorFactory.getConnector(cache)).addToIgnorelist(cache));
// For consistency, remove also the local cache immediately from memory cache and database
if (cache.isOffline()) {
dropCache();
DataStore.removeCache(cache.getGeocode(), EnumSet.of(RemoveFlag.DB));
}
});
}
private void showVoteDialog() {
VoteDialog.show(this, cache, this::notifyDataSetChanged);
}
private static final class CacheDetailsGeoDirHandler extends GeoDirHandler {
private final WeakReference<CacheDetailActivity> activityRef;
CacheDetailsGeoDirHandler(final CacheDetailActivity activity) {
this.activityRef = new WeakReference<>(activity);
}
@Override
public void updateGeoData(final GeoData geo) {
final CacheDetailActivity activity = activityRef.get();
if (activity == null) {
return;
}
if (activity.cacheDistanceView == null) {
return;
}
if (activity.cache != null && activity.cache.getCoords() != null) {
activity.cacheDistanceView.setText(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(activity.cache.getCoords())));
activity.cacheDistanceView.bringToFront();
}
}
}
private static final class LoadCacheHandler extends SimpleDisposableHandler {
LoadCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_LOAD_PROGRESS_DETAIL && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
final CacheDetailActivity activity = (CacheDetailActivity) activityRef.get();
if (activity == null) {
return;
}
if (activity.search == null) {
showToast(R.string.err_dwld_details_failed);
dismissProgress();
finishActivity();
return;
}
if (activity.search.getError() != StatusCode.NO_ERROR) {
// Cache not found is not a download error
final StatusCode error = activity.search.getError();
final Resources res = activity.getResources();
final String toastPrefix = error != StatusCode.CACHE_NOT_FOUND ? res.getString(R.string.err_dwld_details_failed) + " " : "";
if (error == StatusCode.PREMIUM_ONLY) {
SimpleDialog.of(activity).setTitle(R.string.cache_status_premium).setMessage(R.string.err_detail_premium_log_found).setPositiveButton(TextParam.id(R.string.cache_menu_visit)).confirm((dialog, which) -> {
activity.startActivity(LogCacheActivity.getLogCacheIntent(activity, null, activity.geocode));
finishActivity();
}, (d, i) -> finishActivity());
dismissProgress();
} else {
activity.showToast(toastPrefix + error.getErrorString(res));
dismissProgress();
finishActivity();
}
return;
}
updateStatusMsg(activity.getString(R.string.cache_dialog_loading_details_status_render));
// Data loaded, we're ready to show it!
activity.notifyDataSetChanged();
}
}
private void updateStatusMsg(final String msg) {
final CacheDetailActivity activity = (CacheDetailActivity) activityRef.get();
if (activity == null) {
return;
}
setProgressMessage(activity.getString(R.string.cache_dialog_loading_details)
+ "\n\n"
+ msg);
}
@Override
public void handleDispose() {
finishActivity();
}
}
private void notifyDataSetChanged() {
// This might get called asynchronous when the activity is shut down
if (isFinishing()) {
return;
}
if (search == null) {
return;
}
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY);
if (cache == null) {
progress.dismiss();
showToast(res.getString(R.string.err_detail_cache_find_some));
finish();
return;
}
// allow cache to notify CacheDetailActivity when it changes so it can be reloaded
cache.setChangeNotificationHandler(new ChangeNotificationHandler(this, progress));
setCacheTitleBar(cache);
setIsContentRefreshable(cache.supportsRefresh());
// reset imagesList so Images view page will be redrawn
imagesList = null;
imageGallery = null;
setOrderedPages(getOrderedPages());
reinitializeViewPager();
// rendering done! remove progress popup if any there
invalidateOptionsMenuCompatible();
progress.dismiss();
Settings.addCacheToHistory(cache.getGeocode());
}
/**
* Tries to navigate to the {@link Geocache} of this activity using the default navigation tool.
*/
@Override
public void startDefaultNavigation() {
NavigationAppFactory.startDefaultNavigationApplication(1, this, cache);
}
/**
* Tries to navigate to the {@link Geocache} of this activity using the second default navigation tool.
*/
@Override
public void startDefaultNavigation2() {
NavigationAppFactory.startDefaultNavigationApplication(2, this, cache);
}
/**
* Wrapper for the referenced method in the xml-layout.
*/
public void goDefaultNavigation(@SuppressWarnings("unused") final View view) {
startDefaultNavigation();
}
/**
* referenced from XML view
*/
public void showNavigationMenu(@SuppressWarnings("unused") final View view) {
NavigationAppFactory.showNavigationMenu(this, cache, null, null, true, true);
}
public static void startActivity(final Context context, final String geocode, final boolean forceWaypointsPage) {
final Intent detailIntent = new Intent(context, CacheDetailActivity.class);
detailIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
detailIntent.putExtra(EXTRA_FORCE_WAYPOINTSPAGE, forceWaypointsPage);
context.startActivity(detailIntent);
}
public static void startActivity(final Context context, final String geocode) {
startActivity(context, geocode, false);
}
/**
* Enum of all possible pages with methods to get the view and a title.
*/
public enum Page {
DETAILS(R.string.detail),
DESCRIPTION(R.string.cache_description),
LOGS(R.string.cache_logs),
LOGSFRIENDS(R.string.cache_logs_friends_and_own),
WAYPOINTS(R.string.cache_waypoints),
INVENTORY(R.string.cache_inventory),
IMAGES(R.string.cache_images),
IMAGEGALLERY(R.string.cache_images),
VARIABLES(R.string.cache_variables),
;
private final int titleStringId;
public final long id;
Page(final int titleStringId) {
this.titleStringId = titleStringId;
this.id = ordinal();
}
static Page find(final long pageId) {
for (Page page : Page.values()) {
if (page.id == pageId) {
return page;
}
}
return null;
}
}
@Override
public void pullToRefreshActionTrigger() {
refreshCache();
}
private void refreshCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (!Network.isConnected()) {
showToast(getString(R.string.err_server));
return;
}
final RefreshCacheHandler refreshCacheHandler = new RefreshCacheHandler(this, progress);
progress.show(this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.disposeMessage());
cache.refresh(refreshCacheHandler, AndroidRxUtils.refreshScheduler);
}
private void dropCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
progress.show(this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null);
cache.drop(new ChangeNotificationHandler(this, progress));
}
private void dropUserdefinedWaypoints() {
if (null != cache && cache.hasUserdefinedWaypoints()) {
String info = getString(R.string.cache_delete_userdefined_waypoints_confirm);
if (!cache.isPreventWaypointsFromNote()) {
info += "\n\n" + getString(R.string.cache_delete_userdefined_waypoints_note);
}
SimpleDialog.of(this).setTitle(R.string.cache_delete_userdefined_waypoints).setMessage(TextParam.text(info)).confirm((dialog, which) -> {
for (Waypoint waypoint : new LinkedList<>(cache.getWaypoints())) {
if (waypoint.isUserDefined()) {
cache.deleteWaypoint(waypoint);
}
}
if (cache.addWaypointsFromNote()) {
Schedulers.io().scheduleDirect(() -> DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)));
}
ActivityMixin.showShortToast(this, R.string.cache_delete_userdefined_waypoints_success);
invalidateOptionsMenu();
reinitializePage(Page.WAYPOINTS.id);
});
}
}
private void dropGeneratedWaypoints() {
if (null != cache && cache.hasGeneratedWaypoints()) {
final String info = getString(R.string.cache_delete_generated_waypoints_confirm);
SimpleDialog.of(this).setTitle(R.string.cache_delete_generated_waypoints).setMessage(TextParam.text(info)).confirm((dialog, which) -> {
for (Waypoint waypoint : new LinkedList<>(cache.getWaypoints())) {
if (waypoint.getWaypointType() == WaypointType.GENERATED) {
cache.deleteWaypoint(waypoint);
}
}
ActivityMixin.showShortToast(this, R.string.cache_delete_generated_waypoints_success);
invalidateOptionsMenu();
reinitializePage(Page.WAYPOINTS.id);
});
}
}
private void storeCache(final boolean fastStoreOnLastSelection) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (Settings.getChooseList() || cache.isOffline()) {
// let user select list to store cache in
new StoredList.UserInterface(this).promptForMultiListSelection(R.string.lists_title,
this::storeCacheInLists, true, cache.getLists(), fastStoreOnLastSelection);
} else {
storeCacheInLists(Collections.singleton(StoredList.STANDARD_LIST_ID));
}
}
private void moveCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
new MoveToListAndRemoveFromOthersCommand(CacheDetailActivity.this, cache) {
@Override
protected void onFinished() {
updateCacheLists(CacheDetailActivity.this.findViewById(R.id.offline_lists), cache, res);
}
}.execute();
}
private void storeCacheInLists(final Set<Integer> selectedListIds) {
if (cache.isOffline()) {
// cache already offline, just add to another list
DataStore.saveLists(Collections.singletonList(cache), selectedListIds);
new StoreCacheHandler(CacheDetailActivity.this, progress).sendEmptyMessage(DisposableHandler.DONE);
} else {
storeCache(selectedListIds);
}
}
private static final class CheckboxHandler extends SimpleDisposableHandler {
private final WeakReference<DetailsViewCreator> creatorRef;
private final WeakReference<CacheDetailActivity> activityWeakReference;
CheckboxHandler(final DetailsViewCreator creator, final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
creatorRef = new WeakReference<>(creator);
activityWeakReference = new WeakReference<>(activity);
}
@Override
public void handleRegularMessage(final Message message) {
final DetailsViewCreator creator = creatorRef.get();
if (creator != null) {
super.handleRegularMessage(message);
creator.updateWatchlistBox(activityWeakReference.get());
creator.updateFavPointBox();
}
}
}
/**
* Creator for details-view.
*
* TODO: Extract inner class to own file for a better overview. Same might apply to all other view creators.
*/
public static class DetailsViewCreator extends TabbedViewPagerFragment<CachedetailDetailsPageBinding> {
private CacheDetailsCreator.NameValueLine favoriteLine;
private Geocache cache;
@Override
public CachedetailDetailsPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailDetailsPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.DETAILS.id;
}
@Override
// splitting up that method would not help improve readability
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"})
public void setContent() {
// retrieve activity and cache - if either of them is null, something's really wrong!
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
// Reference to the details list and favorite line, so that the helper-method can access them without an additional argument
final CacheDetailsCreator details = new CacheDetailsCreator(activity, binding.detailsList);
// cache name (full name), may be editable
final SpannableString span = TextUtils.coloredCacheText(cache, cache.getName());
final TextView cachename = details.add(R.string.cache_name, span).valueView;
activity.addContextMenu(cachename);
if (cache.supportsNamechange()) {
cachename.setOnClickListener(v -> Dialogs.input(activity, activity.getString(R.string.cache_name_set), cache.getName(), activity.getString(R.string.caches_sort_name), name -> {
cachename.setText(name);
cache.setName(name);
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
Toast.makeText(activity, R.string.cache_name_updated, Toast.LENGTH_SHORT).show();
}));
}
details.add(R.string.cache_type, cache.getType().getL10n());
if (cache.getType() == CacheType.ADVLAB) {
details.addAlcMode(cache);
}
details.addSize(cache);
activity.addContextMenu(details.add(R.string.cache_geocode, cache.getShortGeocode()).valueView);
details.addCacheState(cache);
activity.cacheDistanceView = details.addDistance(cache, activity.cacheDistanceView);
details.addDifficulty(cache);
details.addTerrain(cache);
details.addRating(cache);
// favorite count
favoriteLine = details.add(R.string.cache_favorite, "");
// own rating
if (cache.getMyVote() > 0) {
details.addStars(R.string.cache_own_rating, cache.getMyVote());
}
// cache author
if (StringUtils.isNotBlank(cache.getOwnerDisplayName()) || StringUtils.isNotBlank(cache.getOwnerUserId())) {
final TextView ownerView = details.add(R.string.cache_owner, "").valueView;
if (StringUtils.isNotBlank(cache.getOwnerDisplayName())) {
ownerView.setText(cache.getOwnerDisplayName(), TextView.BufferType.SPANNABLE);
} else { // OwnerReal guaranteed to be not blank based on above
ownerView.setText(cache.getOwnerUserId(), TextView.BufferType.SPANNABLE);
}
ownerView.setOnClickListener(UserClickListener.forOwnerOf(cache));
}
// hidden or event date
final TextView hiddenView = details.addHiddenDate(cache);
if (hiddenView != null) {
activity.addContextMenu(hiddenView);
if (cache.isEventCache()) {
hiddenView.setOnClickListener(v -> CalendarUtils.openCalendar(activity, cache.getHiddenDate()));
}
}
// cache location
if (StringUtils.isNotBlank(cache.getLocation())) {
details.add(R.string.cache_location, cache.getLocation());
}
// cache coordinates
if (cache.getCoords() != null) {
final TextView valueView = details.add(R.string.cache_coordinates, cache.getCoords().toString()).valueView;
new CoordinatesFormatSwitcher().setView(valueView).setCoordinate(cache.getCoords());
activity.addContextMenu(valueView);
}
// Latest logs
details.addLatestLogs(cache);
// cache attributes
updateAttributes(activity);
binding.attributesBox.setVisibility(cache.getAttributes().isEmpty() ? View.GONE : View.VISIBLE);
updateOfflineBox(binding.getRoot(), cache, activity.res, new RefreshCacheClickListener(), new DropCacheClickListener(),
new StoreCacheClickListener(), null, new MoveCacheClickListener(), new StoreCacheClickListener());
// list
updateCacheLists(binding.getRoot(), cache, activity.res);
// watchlist
binding.addToWatchlist.setOnClickListener(new AddToWatchlistClickListener());
binding.removeFromWatchlist.setOnClickListener(new RemoveFromWatchlistClickListener());
updateWatchlistBox(activity);
// WhereYouGo, ChirpWolf and Adventure Lab
updateWhereYouGoBox(activity);
updateChirpWolfBox(activity);
updateALCBox(activity);
// favorite points
binding.addToFavpoint.setOnClickListener(new FavoriteAddClickListener());
binding.removeFromFavpoint.setOnClickListener(new FavoriteRemoveClickListener());
updateFavPointBox();
final IConnector connector = ConnectorFactory.getConnector(cache);
final String license = connector.getLicenseText(cache);
if (StringUtils.isNotBlank(license)) {
binding.licenseBox.setVisibility(View.VISIBLE);
binding.license.setText(HtmlCompat.fromHtml(license, HtmlCompat.FROM_HTML_MODE_LEGACY), BufferType.SPANNABLE);
binding.license.setClickable(true);
binding.license.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
} else {
binding.licenseBox.findViewById(R.id.license_box).setVisibility(View.GONE);
}
}
private void updateAttributes(final Activity activity) {
final List<String> attributes = cache.getAttributes();
if (!CacheAttribute.hasRecognizedAttributeIcon(attributes)) {
binding.attributesGrid.setVisibility(View.GONE);
return;
}
final HashSet<String> attributesSet = new HashSet<>(attributes);
// traverse by category and attribute order
final ArrayList<String> orderedAttributeNames = new ArrayList<>();
final StringBuilder attributesText = new StringBuilder();
CacheAttributeCategory lastCategory = null;
for (CacheAttributeCategory category : CacheAttributeCategory.getOrderedCategoryList()) {
for (CacheAttribute attr : CacheAttribute.getByCategory(category)) {
for (Boolean enabled : Arrays.asList(false, true, null)) {
final String key = attr.getValue(enabled);
if (attributes.contains(key)) {
if (lastCategory != category) {
if (lastCategory != null) {
attributesText.append("<br /><br />");
}
attributesText.append("<b><u>").append(category.getName(activity)).append("</u></b><br />");
lastCategory = category;
} else {
attributesText.append("<br />");
}
orderedAttributeNames.add(key);
attributesText.append(attr.getL10n(enabled == null ? true : enabled));
}
}
}
}
binding.attributesGrid.setAdapter(new AttributesGridAdapter(activity, orderedAttributeNames, this::toggleAttributesView));
binding.attributesGrid.setVisibility(View.VISIBLE);
binding.attributesText.setText(HtmlCompat.fromHtml(attributesText.toString(), 0));
binding.attributesText.setVisibility(View.GONE);
binding.attributesText.setOnClickListener(v -> toggleAttributesView());
}
protected void toggleAttributesView() {
binding.attributesText.setVisibility(binding.attributesText.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
binding.attributesGrid.setVisibility(binding.attributesGrid.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
}
private class StoreCacheClickListener implements View.OnClickListener, View.OnLongClickListener {
@Override
public void onClick(final View arg0) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.storeCache(false);
}
}
@Override
public boolean onLongClick(final View v) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.storeCache(true);
}
return true;
}
}
private class MoveCacheClickListener implements OnLongClickListener {
@Override
public boolean onLongClick(final View v) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.moveCache();
}
return true;
}
}
private class DropCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.dropCache();
}
}
}
private class RefreshCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.refreshCache();
}
}
}
/**
* Abstract Listener for add / remove buttons for watchlist
*/
private abstract class AbstractPropertyListener implements View.OnClickListener {
private final SimpleDisposableHandler handler;
AbstractPropertyListener() {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
handler = new CheckboxHandler(DetailsViewCreator.this, activity, activity.progress);
}
public void doExecute(final int titleId, final int messageId, final Action1<SimpleDisposableHandler> action) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
if (activity.progress.isShowing()) {
activity.showToast(activity.res.getString(R.string.err_watchlist_still_managing));
return;
}
activity.progress.show(activity, activity.res.getString(titleId), activity.res.getString(messageId), true, null);
}
AndroidRxUtils.networkScheduler.scheduleDirect(() -> action.call(handler));
}
}
/**
* Listener for "add to watchlist" button
*/
private class AddToWatchlistClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_watchlist_add_title,
R.string.cache_dialog_watchlist_add_message,
DetailsViewCreator.this::watchListAdd);
}
}
/**
* Listener for "remove from watchlist" button
*/
private class RemoveFromWatchlistClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_watchlist_remove_title,
R.string.cache_dialog_watchlist_remove_message,
DetailsViewCreator.this::watchListRemove);
}
}
/**
* Add this cache to the watchlist of the user
*/
private void watchListAdd(final SimpleDisposableHandler handler) {
final WatchListCapability connector = (WatchListCapability) ConnectorFactory.getConnector(cache);
if (connector.addToWatchlist(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_watchlist_failed);
}
}
/**
* Remove this cache from the watchlist of the user
*/
private void watchListRemove(final SimpleDisposableHandler handler) {
final WatchListCapability connector = (WatchListCapability) ConnectorFactory.getConnector(cache);
if (connector.removeFromWatchlist(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_watchlist_failed);
}
}
/**
* Add this cache to the favorite list of the user
*/
private void favoriteAdd(final SimpleDisposableHandler handler) {
final IFavoriteCapability connector = (IFavoriteCapability) ConnectorFactory.getConnector(cache);
if (connector.addToFavorites(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_favorite_failed);
}
}
/**
* Remove this cache to the favorite list of the user
*/
private void favoriteRemove(final SimpleDisposableHandler handler) {
final IFavoriteCapability connector = (IFavoriteCapability) ConnectorFactory.getConnector(cache);
if (connector.removeFromFavorites(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_favorite_failed);
}
}
/**
* Listener for "add to favorites" button
*/
private class FavoriteAddClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_favorite_add_title,
R.string.cache_dialog_favorite_add_message,
DetailsViewCreator.this::favoriteAdd);
}
}
/**
* Listener for "remove from favorites" button
*/
private class FavoriteRemoveClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_favorite_remove_title,
R.string.cache_dialog_favorite_remove_message,
DetailsViewCreator.this::favoriteRemove);
}
}
/**
* Show/hide buttons, set text in watchlist box
*/
private void updateWatchlistBox(final CacheDetailActivity activity) {
final boolean supportsWatchList = cache.supportsWatchList();
binding.watchlistBox.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE);
if (!supportsWatchList) {
return;
}
final int watchListCount = cache.getWatchlistCount();
if (cache.isOnWatchlist() || cache.isOwner()) {
binding.addToWatchlist.setVisibility(View.GONE);
binding.removeFromWatchlist.setVisibility(View.VISIBLE);
if (watchListCount != -1) {
binding.watchlistText.setText(activity.res.getString(R.string.cache_watchlist_on_extra, watchListCount));
} else {
binding.watchlistText.setText(R.string.cache_watchlist_on);
}
} else {
binding.addToWatchlist.setVisibility(View.VISIBLE);
binding.removeFromWatchlist.setVisibility(View.GONE);
if (watchListCount != -1) {
binding.watchlistText.setText(activity.res.getString(R.string.cache_watchlist_not_on_extra, watchListCount));
} else {
binding.watchlistText.setText(R.string.cache_watchlist_not_on);
}
}
// the owner of a cache has it always on his watchlist. Adding causes an error
if (cache.isOwner()) {
binding.addToWatchlist.setEnabled(false);
binding.addToWatchlist.setVisibility(View.GONE);
binding.removeFromWatchlist.setEnabled(false);
binding.removeFromWatchlist.setVisibility(View.GONE);
}
}
/**
* Show/hide buttons, set text in favorite line and box
*/
private void updateFavPointBox() {
// Favorite counts
final int favCount = cache.getFavoritePoints();
if (favCount >= 0 && !cache.isEventCache()) {
favoriteLine.layout.setVisibility(View.VISIBLE);
final int findsCount = cache.getFindsCount();
if (findsCount > 0) {
favoriteLine.valueView.setText(getString(R.string.favorite_count_percent, favCount, (float) (favCount * 100) / findsCount));
} else {
favoriteLine.valueView.setText(getString(R.string.favorite_count, favCount));
}
} else {
favoriteLine.layout.setVisibility(View.GONE);
}
final boolean supportsFavoritePoints = cache.supportsFavoritePoints();
binding.favpointBox.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE);
if (!supportsFavoritePoints) {
return;
}
if (cache.isFavorite()) {
binding.addToFavpoint.setVisibility(View.GONE);
binding.removeFromFavpoint.setVisibility(View.VISIBLE);
binding.favpointText.setText(R.string.cache_favpoint_on);
} else {
binding.addToFavpoint.setVisibility(View.VISIBLE);
binding.removeFromFavpoint.setVisibility(View.GONE);
binding.favpointText.setText(R.string.cache_favpoint_not_on);
}
// Add/remove to Favorites is only possible if the cache has been found
if (!cache.isFound()) {
binding.addToFavpoint.setVisibility(View.GONE);
binding.removeFromFavpoint.setVisibility(View.GONE);
}
}
private void updateWhereYouGoBox(final CacheDetailActivity activity) {
final boolean isEnabled = cache.getType() == CacheType.WHERIGO && StringUtils.isNotEmpty(getWhereIGoUrl(cache));
binding.whereyougoBox.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
binding.whereyougoText.setText(isWhereYouGoInstalled() ? R.string.cache_whereyougo_start : R.string.cache_whereyougo_install);
if (isEnabled) {
binding.sendToWhereyougo.setOnClickListener(v -> {
// re-check installation state, might have changed since creating the view
if (isWhereYouGoInstalled()) {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getWhereIGoUrl(cache)));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
} else {
ProcessUtils.openMarket(activity, getString(R.string.package_whereyougo));
}
});
}
}
private void updateChirpWolfBox(final CacheDetailActivity activity) {
final Intent chirpWolf = ProcessUtils.getLaunchIntent(getString(R.string.package_chirpwolf));
final String compare = CacheAttribute.WIRELESSBEACON.getValue(true);
boolean isEnabled = false;
for (String current : cache.getAttributes()) {
if (StringUtils.equals(current, compare)) {
isEnabled = true;
break;
}
}
binding.chirpBox.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
binding.chirpText.setText(chirpWolf != null ? R.string.cache_chirpwolf_start : R.string.cache_chirpwolf_install);
if (isEnabled) {
binding.sendToChirp.setOnClickListener(v -> {
// re-check installation state, might have changed since creating the view
final Intent chirpWolf2 = ProcessUtils.getLaunchIntent(getString(R.string.package_chirpwolf));
if (chirpWolf2 != null) {
chirpWolf2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(chirpWolf2);
} else {
ProcessUtils.openMarket(activity, getString(R.string.package_chirpwolf));
}
});
}
}
private void updateALCBox(final CacheDetailActivity activity) {
final boolean isEnabled = cache.getType() == CacheType.ADVLAB && StringUtils.isNotEmpty(cache.getUrl());
final Intent alc = ProcessUtils.getLaunchIntent(getString(R.string.package_alc));
binding.alcBox.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
binding.alcText.setText(alc != null ? R.string.cache_alc_start : R.string.cache_alc_install);
if (isEnabled) {
binding.sendToAlc.setOnClickListener(v -> {
// re-check installation state, might have changed since creating the view
if (alc != null) {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(cache.getUrl()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
} else {
ProcessUtils.openMarket(activity, getString(R.string.package_alc));
}
});
}
}
}
/**
* Reflect the (contextual) action mode of the action bar.
*/
protected ActionMode currentActionMode;
public static class DescriptionViewCreator extends TabbedViewPagerFragment<CachedetailDescriptionPageBinding> {
private Geocache cache;
@Override
public CachedetailDescriptionPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailDescriptionPageBinding.inflate(getLayoutInflater(), container, false);
}
@Override
public long getPageId() {
return Page.DESCRIPTION.id;
}
@Override
// splitting up that method would not help improve readability
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"})
public void setContent() {
// retrieve activity and cache - if either of them is null, something's really wrong!
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
// reset description
binding.description.setText("");
// cache short description
if (StringUtils.isNotBlank(cache.getShortDescription())) {
loadDescription(activity, cache.getShortDescription(), false, binding.description, null);
}
// long description
if (StringUtils.isNotBlank(cache.getDescription()) || cache.supportsDescriptionchange()) {
loadLongDescription(activity, container);
}
fixOldGeocheckerLink(activity);
final String checkerUrl = CheckerUtils.getCheckerUrl(cache);
binding.descriptionChecker.setVisibility(checkerUrl == null ? View.GONE : View.VISIBLE);
if (checkerUrl != null) {
binding.descriptionChecker.setOnClickListener(v -> openGeochecker(activity, cache));
binding.descriptionCheckerButton.setOnClickListener(v -> openGeochecker(activity, cache));
}
// extra description
final String geocode = cache.getGeocode();
boolean hasExtraDescription = ALConnector.getInstance().canHandle(geocode); // could be generalized, but currently it's only AL
if (hasExtraDescription) {
final IConnector conn = ConnectorFactory.getConnector(geocode);
if (conn != null) {
binding.extraDescriptionTitle.setText(conn.getName());
binding.extraDescription.setText(conn.getExtraDescription());
} else {
hasExtraDescription = false;
}
}
binding.extraDescriptionBox.setVisibility(hasExtraDescription ? View.VISIBLE : View.GONE);
// cache personal note
setPersonalNote(binding.personalnote, binding.personalnoteButtonSeparator, cache.getPersonalNote());
binding.personalnote.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
activity.addContextMenu(binding.personalnote);
TooltipCompat.setTooltipText(binding.editPersonalnote, getString(R.string.cache_personal_note_edit));
binding.editPersonalnote.setOnClickListener(v -> {
activity.ensureSaved();
editPersonalNote(cache, activity);
});
binding.personalnote.setOnClickListener(v -> {
activity.ensureSaved();
editPersonalNote(cache, activity);
});
TooltipCompat.setTooltipText(binding.storewaypointsPersonalnote, getString(R.string.cache_personal_note_storewaypoints));
binding.storewaypointsPersonalnote.setOnClickListener(v -> {
activity.ensureSaved();
activity.storeWaypointsInPersonalNote(cache);
});
TooltipCompat.setTooltipText(binding.deleteewaypointsPersonalnote, getString(R.string.cache_personal_note_removewaypoints));
binding.deleteewaypointsPersonalnote.setOnClickListener(v -> {
activity.ensureSaved();
activity.removeWaypointsFromPersonalNote(cache);
});
final PersonalNoteCapability connector = ConnectorFactory.getConnectorAs(cache, PersonalNoteCapability.class);
if (connector != null && connector.canAddPersonalNote(cache)) {
final int maxPersonalNotesChars = connector.getPersonalNoteMaxChars();
binding.uploadPersonalnote.setVisibility(View.VISIBLE);
TooltipCompat.setTooltipText(binding.uploadPersonalnote, getString(R.string.cache_personal_note_upload));
binding.uploadPersonalnote.setOnClickListener(v -> {
final int personalNoteLength = StringUtils.length(cache.getPersonalNote());
if (personalNoteLength > maxPersonalNotesChars) {
warnPersonalNoteExceedsLimit(activity, personalNoteLength, maxPersonalNotesChars, connector.getName());
} else {
uploadPersonalNote(activity);
}
});
} else {
binding.uploadPersonalnote.setVisibility(View.GONE);
}
final List<Image> spoilerImages = cache.getFilteredSpoilers();
final boolean hasSpoilerImages = CollectionUtils.isNotEmpty(spoilerImages);
// cache hint and spoiler images
if (StringUtils.isNotBlank(cache.getHint()) || hasSpoilerImages) {
binding.hintBox.setVisibility(View.VISIBLE);
} else {
binding.hintBox.setVisibility(View.GONE);
}
if (StringUtils.isNotBlank(cache.getHint())) {
if (TextUtils.containsHtml(cache.getHint())) {
binding.hint.setText(HtmlCompat.fromHtml(cache.getHint(), HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(cache.getGeocode(), false, false, false), null), TextView.BufferType.SPANNABLE);
} else {
binding.hint.setText(cache.getHint());
}
binding.hint.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
binding.hint.setVisibility(View.VISIBLE);
if (Settings.getHintAsRot13()) {
binding.hint.setText(CryptUtils.rot13((Spannable) binding.hint.getText()));
binding.hint.setClickable(true);
binding.hint.setOnClickListener(new DecryptTextClickListener(binding.hint));
binding.hintBox.setOnClickListener(new DecryptTextClickListener(binding.hint));
binding.hintBox.setClickable(true);
}
activity.addContextMenu(binding.hint);
} else {
binding.hint.setVisibility(View.GONE);
binding.hint.setClickable(false);
binding.hint.setOnClickListener(null);
binding.hintBox.setClickable(false);
binding.hintBox.setOnClickListener(null);
}
if (hasSpoilerImages) {
binding.hintSpoilerlink.setVisibility(View.VISIBLE);
binding.hintSpoilerlink.setClickable(true);
binding.hintSpoilerlink.setOnClickListener(arg0 -> {
final List<Image> sis = cache.getFilteredSpoilers();
if (cache == null || sis.isEmpty()) {
activity.showToast(getString(R.string.err_detail_no_spoiler));
return;
}
ImageGalleryActivity.startActivity(activity, cache.getGeocode(), sis);
});
// if there is only a listing background image without other additional pictures, change the text to better explain the content.
if (spoilerImages.size() == 1 && getString(R.string.cache_image_background).equals(spoilerImages.get(0).title)) {
binding.hintSpoilerlink.setText(R.string.cache_image_background);
} else {
binding.hintSpoilerlink.setText(R.string.cache_menu_spoilers);
}
} else {
binding.hintSpoilerlink.setVisibility(View.GONE);
binding.hintSpoilerlink.setClickable(true);
binding.hintSpoilerlink.setOnClickListener(null);
}
}
private void uploadPersonalNote(final CacheDetailActivity activity) {
final SimpleDisposableHandler myHandler = new SimpleDisposableHandler(activity, activity.progress);
final Message cancelMessage = myHandler.cancelMessage(getString(R.string.cache_personal_note_upload_cancelled));
activity.progress.show(activity, getString(R.string.cache_personal_note_uploading), getString(R.string.cache_personal_note_uploading), true, cancelMessage);
myHandler.add(AndroidRxUtils.networkScheduler.scheduleDirect(() -> {
final PersonalNoteCapability connector = (PersonalNoteCapability) ConnectorFactory.getConnector(cache);
final boolean success = connector.uploadPersonalNote(cache);
final Message msg = Message.obtain();
final Bundle bundle = new Bundle();
bundle.putString(SimpleDisposableHandler.MESSAGE_TEXT,
CgeoApplication.getInstance().getString(success ? R.string.cache_personal_note_upload_done : R.string.cache_personal_note_upload_error));
msg.setData(bundle);
myHandler.sendMessage(msg);
}));
}
private void loadLongDescription(final CacheDetailActivity activity, final ViewGroup parentView) {
binding.loading.setVisibility(View.VISIBLE);
final String longDescription = cache.getDescription();
loadDescription(activity, longDescription, true, binding.description, binding.loading);
if (cache.supportsDescriptionchange()) {
binding.description.setOnClickListener(v -> Dialogs.input(activity, activity.getString(R.string.cache_description_set), cache.getDescription(), "Description", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL | InputType.TYPE_TEXT_FLAG_MULTI_LINE, 5, 10, description -> {
binding.description.setText(description);
cache.setDescription(description);
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
Toast.makeText(activity, R.string.cache_description_updated, Toast.LENGTH_SHORT).show();
}));
}
}
private void warnPersonalNoteExceedsLimit(final CacheDetailActivity activity, final int personalNoteLength, final int maxPersonalNotesChars, final String connectorName) {
final int reduceLength = personalNoteLength - maxPersonalNotesChars;
SimpleDialog.of(activity).setTitle(R.string.cache_personal_note_limit).setMessage(R.string.cache_personal_note_truncated_by, reduceLength, maxPersonalNotesChars, connectorName).confirm(
(dialog, which) -> {
dialog.dismiss();
uploadPersonalNote(activity);
});
}
/**
* Load the description in the background.
*
* @param descriptionString the HTML description as retrieved from the connector
* @param descriptionView the view to fill
* @param loadingIndicatorView the loading indicator view, will be hidden when completed
*/
private void loadDescription(final CacheDetailActivity activity, final String descriptionString, final boolean isLongDescription, final IndexOutOfBoundsAvoidingTextView descriptionView, final View loadingIndicatorView) {
try {
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
final Editable description = new SpannableStringBuilder(HtmlCompat.fromHtml(descriptionString, HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(cache.getGeocode(), true, false, descriptionView, false), unknownTagsHandler));
activity.addWarning(unknownTagsHandler, description);
if (StringUtils.isNotBlank(description)) {
fixRelativeLinks(description);
fixTextColor(description, R.color.colorBackground);
// check if short description is contained in long description
boolean longDescriptionContainsShortDescription = false;
final String shortDescription = cache.getShortDescription();
if (StringUtils.isNotBlank(shortDescription)) {
final int index = StringUtils.indexOf(cache.getDescription(), shortDescription);
// allow up to 200 characters of HTML formatting
if (index >= 0 && index < 200) {
longDescriptionContainsShortDescription = true;
}
}
try {
if (descriptionView.getText().length() == 0 || (longDescriptionContainsShortDescription && isLongDescription)) {
descriptionView.setText(description, TextView.BufferType.SPANNABLE);
} else if (!longDescriptionContainsShortDescription) {
descriptionView.append("\n");
descriptionView.append(description);
}
} catch (final Exception e) {
Log.e("Android bug setting text: ", e);
// remove the formatting by converting to a simple string
descriptionView.append(description.toString());
}
descriptionView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
descriptionView.setVisibility(View.VISIBLE);
activity.addContextMenu(descriptionView);
}
if (loadingIndicatorView != null) {
loadingIndicatorView.setVisibility(View.GONE);
}
} catch (final RuntimeException ignored) {
activity.showToast(getString(R.string.err_load_descr_failed));
}
}
private void fixRelativeLinks(final Spannable spannable) {
final String baseUrl = ConnectorFactory.getConnector(cache).getHostUrl() + "/";
final URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
for (final URLSpan span : spans) {
final Uri uri = Uri.parse(span.getURL());
if (uri.getScheme() == null && uri.getHost() == null) {
final int start = spannable.getSpanStart(span);
final int end = spannable.getSpanEnd(span);
final int flags = spannable.getSpanFlags(span);
final Uri absoluteUri = Uri.parse(baseUrl + uri.toString());
spannable.removeSpan(span);
spannable.setSpan(new URLSpan(absoluteUri.toString()), start, end, flags);
}
}
}
/**
* Old GCParser logic inserted an HTML link to their geochecker (when applicable)
* directly into the description text.
* When running on Android 12 this direct URL might be redirected to c:geo under
* specific system settings, leading to a loop (see #12889), so let's reassign
* this link to the proper openGeochecker method.
*
* @param activity calling activity
*/
private void fixOldGeocheckerLink(final Activity activity) {
final String gcLinkInfo = activity.getString(R.string.link_gc_checker);
final Spannable spannable = (Spannable) binding.description.getText();
final URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
for (final URLSpan span : spans) {
final int start = spannable.getSpanStart(span);
final int end = spannable.getSpanEnd(span);
if (StringUtils.equals(spannable.subSequence(start, end), gcLinkInfo)) {
final int flags = spannable.getSpanFlags(span);
spannable.removeSpan(span);
spannable.setSpan(new ClickableSpan() {
@Override
public void onClick(final @NonNull View widget) {
openGeochecker(activity, cache);
}
}, start, end, flags);
}
}
}
}
// If description has an HTML construct which may be problematic to render, add a note at the end of the long description.
// Technically, it may not be a table, but a pre, which has the same problems as a table, so the message is ok even though
// sometimes technically incorrect.
private void addWarning(final UnknownTagsHandler unknownTagsHandler, final Editable description) {
if (unknownTagsHandler.isProblematicDetected()) {
final int startPos = description.length();
final IConnector connector = ConnectorFactory.getConnector(cache);
if (StringUtils.isNotEmpty(cache.getUrl())) {
final Spanned tableNote = HtmlCompat.fromHtml(res.getString(R.string.cache_description_table_note, "<a href=\"" + cache.getUrl() + "\">" + connector.getName() + "</a>"), HtmlCompat.FROM_HTML_MODE_LEGACY);
description.append("\n\n").append(tableNote);
description.setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
private static void fixTextColor(final Spannable spannable, final int backgroundColor) {
final ForegroundColorSpan[] spans = spannable.getSpans(0, spannable.length(), ForegroundColorSpan.class);
for (final ForegroundColorSpan span : spans) {
if (ColorUtils.getContrastRatio(span.getForegroundColor(), backgroundColor) < CONTRAST_THRESHOLD) {
final int start = spannable.getSpanStart(span);
final int end = spannable.getSpanEnd(span);
// Assuming that backgroundColor can be either white or black,
// this will set opposite background color (white for black and black for white)
spannable.setSpan(new BackgroundColorSpan(backgroundColor ^ 0x00ffffff), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
protected void ensureSaved() {
if (!cache.isOffline()) {
showToast(getString(R.string.info_cache_saved));
cache.getLists().add(StoredList.STANDARD_LIST_ID);
AndroidRxUtils.computationScheduler.scheduleDirect(() -> DataStore.saveCache(cache, LoadFlags.SAVE_ALL));
notifyDataSetChanged();
}
}
public static class WaypointsViewCreator extends TabbedViewPagerFragment<CachedetailWaypointsPageBinding> {
private Geocache cache;
private void setClipboardButtonVisibility(final Button createFromClipboard) {
createFromClipboard.setVisibility(Waypoint.hasClipboardWaypoint() >= 0 ? View.VISIBLE : View.GONE);
}
private void addWaypointAndSort(final List<Waypoint> sortedWaypoints, final Waypoint newWaypoint) {
sortedWaypoints.add(newWaypoint);
Collections.sort(sortedWaypoints, cache.getWaypointComparator());
}
private List<Waypoint> createSortedWaypointList() {
final List<Waypoint> sortedWaypoints2 = new ArrayList<>(cache.getWaypoints());
final Iterator<Waypoint> waypointIterator = sortedWaypoints2.iterator();
while (waypointIterator.hasNext()) {
final Waypoint waypointInIterator = waypointIterator.next();
if (waypointInIterator.isVisited() && Settings.getHideVisitedWaypoints()) {
waypointIterator.remove();
}
}
return sortedWaypoints2;
}
@Override
public CachedetailWaypointsPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailWaypointsPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.WAYPOINTS.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
cache = activity.getCache();
if (cache == null) {
return;
}
final ListView v = binding.getRoot();
v.setVisibility(View.VISIBLE);
v.setClickable(true);
// sort waypoints: PP, Sx, FI, OWN
final List<Waypoint> sortedWaypoints = createSortedWaypointList();
Collections.sort(sortedWaypoints, cache.getWaypointComparator());
final ArrayAdapter<Waypoint> adapter = new ArrayAdapter<Waypoint>(activity, R.layout.waypoint_item, sortedWaypoints) {
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
rowView = getLayoutInflater().inflate(R.layout.waypoint_item, parent, false);
rowView.setClickable(true);
rowView.setLongClickable(true);
registerForContextMenu(rowView);
}
WaypointViewHolder holder = (WaypointViewHolder) rowView.getTag();
if (holder == null) {
holder = new WaypointViewHolder(rowView);
}
final Waypoint waypoint = getItem(position);
fillViewHolder(activity, rowView, holder, waypoint);
return rowView;
}
};
v.setAdapter(adapter);
v.setOnScrollListener(new FastScrollListener(v));
//register for changes of variableslist -> calculated waypoints may have changed
cache.getVariables().addChangeListener(this, s -> activity.runOnUiThread(() -> adapter.notifyDataSetChanged()));
if (v.getHeaderViewsCount() < 1) {
final CachedetailWaypointsHeaderBinding headerBinding = CachedetailWaypointsHeaderBinding.inflate(getLayoutInflater(), v, false);
v.addHeaderView(headerBinding.getRoot());
headerBinding.addWaypoint.setOnClickListener(v2 -> {
activity.ensureSaved();
EditWaypointActivity.startActivityAddWaypoint(activity, cache);
activity.refreshOnResume = true;
});
headerBinding.addWaypointCurrentlocation.setOnClickListener(v2 -> {
activity.ensureSaved();
final Waypoint newWaypoint = new Waypoint(Waypoint.getDefaultWaypointName(cache, WaypointType.WAYPOINT), WaypointType.WAYPOINT, true);
newWaypoint.setCoords(Sensors.getInstance().currentGeo().getCoords());
newWaypoint.setGeocode(cache.getGeocode());
if (cache.addOrChangeWaypoint(newWaypoint, true)) {
addWaypointAndSort(sortedWaypoints, newWaypoint);
adapter.notifyDataSetChanged();
activity.reinitializePage(Page.WAYPOINTS.id);
ActivityMixin.showShortToast(activity, getString(R.string.waypoint_added));
}
});
headerBinding.hideVisitedWaypoints.setChecked(Settings.getHideVisitedWaypoints());
headerBinding.hideVisitedWaypoints.setOnCheckedChangeListener((buttonView, isChecked) -> {
Settings.setHideVisitedWaypoints(isChecked);
final List<Waypoint> sortedWaypoints2 = createSortedWaypointList();
Collections.sort(sortedWaypoints2, cache.getWaypointComparator());
adapter.clear();
adapter.addAll(sortedWaypoints2);
adapter.notifyDataSetChanged();
activity.reinitializePage(Page.WAYPOINTS.id);
});
// read waypoint from clipboard
setClipboardButtonVisibility(headerBinding.addWaypointFromclipboard);
headerBinding.addWaypointFromclipboard.setOnClickListener(v2 -> {
final Waypoint oldWaypoint = DataStore.loadWaypoint(Waypoint.hasClipboardWaypoint());
if (null != oldWaypoint) {
activity.ensureSaved();
final Waypoint newWaypoint = cache.duplicateWaypoint(oldWaypoint, cache.getGeocode().equals(oldWaypoint.getGeocode()));
if (null != newWaypoint) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
addWaypointAndSort(sortedWaypoints, newWaypoint);
adapter.notifyDataSetChanged();
activity.reinitializePage(Page.WAYPOINTS.id);
if (oldWaypoint.isUserDefined()) {
SimpleDialog.of((Activity) v.getContext()).setTitle(R.string.cache_waypoints_add_fromclipboard).setMessage(R.string.cache_waypoints_remove_original_waypoint).confirm((dialog, which) -> {
DataStore.deleteWaypoint(oldWaypoint.getId());
ClipboardUtils.clearClipboard();
});
}
}
}
});
final ClipboardManager cliboardManager = (ClipboardManager) activity.getSystemService(CLIPBOARD_SERVICE);
cliboardManager.addPrimaryClipChangedListener(() -> setClipboardButtonVisibility(headerBinding.addWaypointFromclipboard));
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (cache != null && cache.getVariables() != null) {
cache.getVariables().removeChangeListener(this);
}
}
protected void fillViewHolder(final CacheDetailActivity activity, final View rowView, final WaypointViewHolder holder, final Waypoint wpt) {
// coordinates
final TextView coordinatesView = holder.binding.coordinates;
final TextView calculatedCoordinatesView = holder.binding.calculatedCoordinates;
final Geopoint coordinates = wpt.getCoords();
final String calcStateJson = wpt.getCalcStateConfig();
// coordinates
holder.setCoordinate(coordinates);
activity.addContextMenu(coordinatesView);
coordinatesView.setVisibility(null != coordinates ? View.VISIBLE : View.GONE);
calculatedCoordinatesView.setVisibility(null != calcStateJson ? View.VISIBLE : View.GONE);
final CalculatedCoordinate cc = CalculatedCoordinate.createFromConfig(calcStateJson);
calculatedCoordinatesView.setText(cc.isFilled() ? "(x):" + cc.getLatitudePattern() + " | " + cc.getLongitudePattern() : LocalizationUtils.getString(R.string.waypoint_calculated_coordinates));
holder.binding.calculatedCoordinatesIcon.setVisibility(wpt.isCalculated() ? View.VISIBLE : View.GONE);
// info
final String waypointInfo = Formatter.formatWaypointInfo(wpt);
final TextView infoView = holder.binding.info;
if (StringUtils.isNotBlank(waypointInfo)) {
infoView.setText(waypointInfo);
infoView.setVisibility(View.VISIBLE);
} else {
infoView.setVisibility(View.GONE);
}
// title
holder.binding.name.setText(StringUtils.isNotBlank(wpt.getName()) ? StringEscapeUtils.unescapeHtml4(wpt.getName()) : coordinates != null ? coordinates.toString() : getString(R.string.waypoint));
holder.binding.textIcon.setImageDrawable(MapMarkerUtils.getWaypointMarker(activity.res, wpt, false).getDrawable());
// visited
/* @todo
if (wpt.isVisited()) {
final TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.text_color_grey, typedValue, true);
if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT) {
// really should be just a color!
nameView.setTextColor(typedValue.data);
}
}
*/
// note
final TextView noteView = holder.binding.note;
if (StringUtils.isNotBlank(wpt.getNote())) {
noteView.setOnClickListener(new DecryptTextClickListener(noteView));
noteView.setVisibility(View.VISIBLE);
if (TextUtils.containsHtml(wpt.getNote())) {
noteView.setText(HtmlCompat.fromHtml(wpt.getNote(), HtmlCompat.FROM_HTML_MODE_LEGACY, new SmileyImage(cache.getGeocode(), noteView), new UnknownTagsHandler()), TextView.BufferType.SPANNABLE);
} else {
noteView.setText(wpt.getNote());
}
} else {
noteView.setVisibility(View.GONE);
}
// user note
final TextView userNoteView = holder.binding.userNote;
if (StringUtils.isNotBlank(wpt.getUserNote()) && !StringUtils.equals(wpt.getNote(), wpt.getUserNote())) {
userNoteView.setOnClickListener(new DecryptTextClickListener(userNoteView));
userNoteView.setVisibility(View.VISIBLE);
userNoteView.setText(wpt.getUserNote());
} else {
userNoteView.setVisibility(View.GONE);
}
final View wpNavView = holder.binding.wpDefaultNavigation;
wpNavView.setOnClickListener(v -> NavigationAppFactory.startDefaultNavigationApplication(1, activity, wpt));
wpNavView.setOnLongClickListener(v -> {
NavigationAppFactory.startDefaultNavigationApplication(2, activity, wpt);
return true;
});
activity.addContextMenu(rowView);
rowView.setOnClickListener(v -> {
activity.selectedWaypoint = wpt;
activity.ensureSaved();
EditWaypointActivity.startActivityEditWaypoint(activity, cache, wpt.getId());
activity.refreshOnResume = true;
});
rowView.setOnLongClickListener(v -> {
activity.selectedWaypoint = wpt;
activity.openContextMenu(v);
return true;
});
}
}
public static class InventoryViewCreator extends TabbedViewPagerFragment<CachedetailInventoryPageBinding> {
@Override
public CachedetailInventoryPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailInventoryPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.INVENTORY.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
final Geocache cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
// TODO: fix layout, then switch back to Android-resource and delete copied one
// this copy is modified to respect the text color
RecyclerViewProvider.provideRecyclerView(activity, binding.getRoot(), true, true);
cache.mergeInventory(activity.genericTrackables, activity.processedBrands);
final TrackableListAdapter adapterTrackables = new TrackableListAdapter(cache.getInventory(), trackable -> TrackableActivity.startActivity(activity, trackable.getGuid(), trackable.getGeocode(), trackable.getName(), cache.getGeocode(), trackable.getBrand().getId()));
binding.getRoot().setAdapter(adapterTrackables);
cache.mergeInventory(activity.genericTrackables, activity.processedBrands);
}
}
public static class ImagesViewCreator extends TabbedViewPagerFragment<CachedetailImagesPageBinding> {
@Override
public CachedetailImagesPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailImagesPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.IMAGES.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
final Geocache cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
if (activity.imagesList == null) {
activity.imagesList = new ImagesList(activity, cache.getGeocode(), cache);
activity.createDisposables.add(activity.imagesList.loadImages(binding.getRoot(), cache.getNonStaticImages()));
}
}
}
public static class ImageGalleryCreator extends TabbedViewPagerFragment<CachedetailImagegalleryPageBinding> {
@Override
public CachedetailImagegalleryPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailImagegalleryPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.IMAGEGALLERY.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
final Geocache cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
if (activity.imageGallery == null) {
final ImageGalleryView imageGallery = binding.getRoot().findViewById(R.id.image_gallery);
ImageUtils.initializeImageGallery(imageGallery, cache.getGeocode(), cache.getNonStaticImages());
activity.imageGallery = imageGallery;
reinitializeTitle();
activity.imageGallery.setImageCountChangeCallback((ig, c) -> reinitializeTitle());
}
}
}
public static void startActivity(final Context context, final String geocode, final String cacheName) {
final Intent cachesIntent = new Intent(context, CacheDetailActivity.class);
cachesIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
cachesIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cachesIntent);
}
private ActionMode mActionMode = null;
private boolean mSelectionModeActive = false;
private IndexOutOfBoundsAvoidingTextView selectedTextView;
private class TextMenuItemClickListener implements MenuItem.OnMenuItemClickListener {
@Override
public boolean onMenuItemClick(final MenuItem menuItem) {
final int startSelection = selectedTextView.getSelectionStart();
final int endSelection = selectedTextView.getSelectionEnd();
clickedItemText = selectedTextView.getText().subSequence(startSelection, endSelection);
return onClipboardItemSelected(mActionMode, menuItem, clickedItemText, cache);
}
}
@Override
public void onSupportActionModeStarted(@NonNull final ActionMode mode) {
if (mSelectionModeActive && selectedTextView != null) {
mSelectionModeActive = false;
mActionMode = mode;
final Menu menu = mode.getMenu();
mode.getMenuInflater().inflate(R.menu.details_context, menu);
menu.findItem(R.id.menu_copy).setVisible(false);
menu.findItem(R.id.menu_cache_share_field).setOnMenuItemClickListener(new TextMenuItemClickListener());
menu.findItem(R.id.menu_translate_to_sys_lang).setOnMenuItemClickListener(new TextMenuItemClickListener());
menu.findItem(R.id.menu_translate_to_english).setOnMenuItemClickListener(new TextMenuItemClickListener());
final MenuItem extWpts = menu.findItem(R.id.menu_extract_waypoints);
extWpts.setVisible(true);
extWpts.setOnMenuItemClickListener(new TextMenuItemClickListener());
buildDetailsContextMenu(mode, menu, res.getString(R.string.cache_description), false);
selectedTextView.setWindowFocusWait(true);
}
super.onSupportActionModeStarted(mode);
}
@Override
public void onSupportActionModeFinished(@NonNull final ActionMode mode) {
mActionMode = null;
if (selectedTextView != null) {
selectedTextView.setWindowFocusWait(false);
}
if (!mSelectionModeActive) {
selectedTextView = null;
}
super.onSupportActionModeFinished(mode);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, @Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (imageGallery != null) {
imageGallery.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void addContextMenu(final View view) {
view.setOnLongClickListener(v -> {
if (view.getId() == R.id.description || view.getId() == R.id.hint) {
selectedTextView = (IndexOutOfBoundsAvoidingTextView) view;
mSelectionModeActive = true;
return false;
}
currentActionMode = startSupportActionMode(new ActionMode.Callback() {
@Override
public boolean onPrepareActionMode(final ActionMode actionMode, final Menu menu) {
return prepareClipboardActionMode(view, actionMode, menu);
}
private boolean prepareClipboardActionMode(final View view1, final ActionMode actionMode, final Menu menu) {
final int viewId = view1.getId();
if (viewId == R.id.value) { // coordinates, gc-code, name
clickedItemText = ((TextView) view1).getText();
final CharSequence itemTitle = ((TextView) ((View) view1.getParent().getParent()).findViewById(R.id.name)).getText();
if (itemTitle.equals(res.getText(R.string.cache_coordinates))) {
clickedItemText = GeopointFormatter.reformatForClipboard(clickedItemText);
}
buildDetailsContextMenu(actionMode, menu, itemTitle, true);
} else if (viewId == R.id.description) {
// combine short and long description
final String shortDesc = cache.getShortDescription();
if (StringUtils.isBlank(shortDesc)) {
clickedItemText = cache.getDescription();
} else {
clickedItemText = shortDesc + "\n\n" + cache.getDescription();
}
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_description), false);
} else if (viewId == R.id.personalnote) {
clickedItemText = cache.getPersonalNote();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_personal_note), true);
} else if (viewId == R.id.hint) {
clickedItemText = cache.getHint();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_hint), false);
} else if (viewId == R.id.log) {
clickedItemText = ((TextView) view1).getText();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_logs), false);
} else if (viewId == R.id.date) { // event date
clickedItemText = Formatter.formatHiddenDate(cache);
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_event), true);
menu.findItem(R.id.menu_calendar).setVisible(cache.canBeAddedToCalendar());
} else if (viewId == R.id.coordinates) {
clickedItemText = ((TextView) view1).getText();
clickedItemText = GeopointFormatter.reformatForClipboard(clickedItemText);
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_coordinates), true);
} else {
return false;
}
return true;
}
@Override
public void onDestroyActionMode(final ActionMode actionMode) {
currentActionMode = null;
}
@Override
public boolean onCreateActionMode(final ActionMode actionMode, final Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.details_context, menu);
prepareClipboardActionMode(view, actionMode, menu);
// Return true so that the action mode is shown
return true;
}
@Override
public boolean onActionItemClicked(final ActionMode actionMode, final MenuItem menuItem) {
// detail fields
if (menuItem.getItemId() == R.id.menu_calendar) {
CalendarAdder.addToCalendar(CacheDetailActivity.this, cache);
actionMode.finish();
return true;
// handle clipboard actions in base
}
return onClipboardItemSelected(actionMode, menuItem, clickedItemText, cache);
}
});
return true;
});
}
public static void startActivityGuid(final Context context, final String guid, final String cacheName) {
final Intent cacheIntent = new Intent(context, CacheDetailActivity.class);
cacheIntent.putExtra(Intents.EXTRA_GUID, guid);
cacheIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cacheIntent);
}
/**
* A dialog to allow the user to select reseting coordinates local/remote/both.
*/
private AlertDialog createResetCacheCoordinatesDialog(final Waypoint wpt) {
final AlertDialog.Builder builder = Dialogs.newBuilder(this);
builder.setTitle(R.string.waypoint_reset_cache_coords);
final String[] items = {res.getString(R.string.waypoint_localy_reset_cache_coords), res.getString(R.string.waypoint_reset_local_and_remote_cache_coords)};
builder.setSingleChoiceItems(items, 0, (dialog, which) -> {
dialog.dismiss();
final ProgressDialog progressDialog = ProgressDialog.show(CacheDetailActivity.this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(CacheDetailActivity.this, progressDialog, which == 1);
resetCoords(cache, handler, wpt, which == 0 || which == 1, which == 1, progressDialog);
});
return builder.create();
}
private static class HandlerResetCoordinates extends WeakReferenceHandler<CacheDetailActivity> {
public static final int LOCAL = 0;
public static final int ON_WEBSITE = 1;
private boolean remoteFinished = false;
private boolean localFinished = false;
private final ProgressDialog progressDialog;
private final boolean resetRemote;
protected HandlerResetCoordinates(final CacheDetailActivity activity, final ProgressDialog progressDialog, final boolean resetRemote) {
super(activity);
this.progressDialog = progressDialog;
this.resetRemote = resetRemote;
}
@Override
public void handleMessage(final Message msg) {
if (msg.what == LOCAL) {
localFinished = true;
} else {
remoteFinished = true;
}
if (localFinished && (remoteFinished || !resetRemote)) {
progressDialog.dismiss();
final CacheDetailActivity activity = getReference();
if (activity != null) {
activity.notifyDataSetChanged();
}
}
}
}
private void resetCoords(final Geocache cache, final Handler handler, final Waypoint wpt, final boolean local, final boolean remote, final ProgressDialog progress) {
AndroidRxUtils.networkScheduler.scheduleDirect(() -> {
if (local) {
runOnUiThread(() -> progress.setMessage(res.getString(R.string.waypoint_reset_cache_coords)));
cache.setCoords(wpt.getCoords());
cache.setUserModifiedCoords(false);
cache.deleteWaypointForce(wpt);
DataStore.saveUserModifiedCoords(cache);
handler.sendEmptyMessage(HandlerResetCoordinates.LOCAL);
}
final IConnector con = ConnectorFactory.getConnector(cache);
if (remote && con.supportsOwnCoordinates()) {
runOnUiThread(() -> progress.setMessage(res.getString(R.string.waypoint_coordinates_being_reset_on_website)));
final boolean result = con.deleteModifiedCoordinates(cache);
runOnUiThread(() -> {
if (result) {
showToast(getString(R.string.waypoint_coordinates_has_been_reset_on_website));
} else {
showToast(getString(R.string.waypoint_coordinates_upload_error));
}
handler.sendEmptyMessage(HandlerResetCoordinates.ON_WEBSITE);
notifyDataSetChanged();
});
}
});
}
@Override
protected String getTitle(final long pageId) {
// show number of waypoints directly in waypoint title
if (pageId == Page.WAYPOINTS.id) {
final int waypointCount = cache == null ? 0 : cache.getWaypoints().size();
return String.format(getString(R.string.waypoints_tabtitle), waypointCount);
} else if (pageId == Page.VARIABLES.id) {
final int varCount = cache == null ? 0 : cache.getVariables().size();
return this.getString(Page.VARIABLES.titleStringId) + " (" + varCount + ")";
} else if (pageId == Page.IMAGEGALLERY.id) {
String title = "*" + this.getString(Page.IMAGEGALLERY.titleStringId);
if (this.imageGallery != null) {
title += " (" + this.imageGallery.getCount() + ")";
}
return title;
} else if (pageId == Page.LOGSFRIENDS.id) {
final int logCount = cache == null ? 0 : cache.getFriendsLogs().size();
return this.getString(Page.LOGSFRIENDS.titleStringId) + " (" + logCount + ")";
}
return this.getString(Page.find(pageId).titleStringId);
}
protected long[] getOrderedPages() {
final ArrayList<Long> pages = new ArrayList<>();
pages.add(Page.VARIABLES.id);
pages.add(Page.WAYPOINTS.id);
pages.add(Page.DETAILS.id);
pages.add(Page.DESCRIPTION.id);
// enforce showing the empty log book if new entries can be added
if (cache != null) {
if (cache.supportsLogging() || !cache.getLogs().isEmpty()) {
pages.add(Page.LOGS.id);
}
if (CollectionUtils.isNotEmpty(cache.getFriendsLogs()) && Settings.isFriendLogsWanted()) {
pages.add(Page.LOGSFRIENDS.id);
}
if (CollectionUtils.isNotEmpty(cache.getInventory()) || CollectionUtils.isNotEmpty(genericTrackables)) {
pages.add(Page.INVENTORY.id);
}
if (Settings.enableFeatureNewImageGallery()) {
pages.add(Page.IMAGEGALLERY.id);
}
if (!Settings.enableFeatureNewImageGallery() && CollectionUtils.isNotEmpty(cache.getNonStaticImages())) {
pages.add(Page.IMAGES.id);
}
}
final long[] result = new long[pages.size()];
for (int i = 0; i < pages.size(); i++) {
result[i] = pages.get(i);
}
return result;
}
@Override
@SuppressWarnings("rawtypes")
protected TabbedViewPagerFragment createNewFragment(final long pageId) {
if (pageId == Page.DETAILS.id) {
return new DetailsViewCreator();
} else if (pageId == Page.DESCRIPTION.id) {
return new DescriptionViewCreator();
} else if (pageId == Page.LOGS.id) {
return CacheLogsViewCreator.newInstance(true);
} else if (pageId == Page.LOGSFRIENDS.id) {
return CacheLogsViewCreator.newInstance(false);
} else if (pageId == Page.WAYPOINTS.id) {
return new WaypointsViewCreator();
} else if (pageId == Page.INVENTORY.id) {
return new InventoryViewCreator();
} else if (pageId == Page.IMAGES.id) {
return new ImagesViewCreator();
} else if (pageId == Page.IMAGEGALLERY.id) {
return new ImageGalleryCreator();
} else if (pageId == Page.VARIABLES.id) {
return new VariablesViewPageFragment();
}
throw new IllegalStateException(); // cannot happen as long as switch case is enum complete
}
@SuppressLint("SetTextI18n")
static boolean setOfflineHintText(final OnClickListener showHintClickListener, final TextView offlineHintTextView, final String hint, final String personalNote) {
if (null != showHintClickListener) {
final boolean hintGiven = StringUtils.isNotEmpty(hint);
final boolean personalNoteGiven = StringUtils.isNotEmpty(personalNote);
if (hintGiven || personalNoteGiven) {
offlineHintTextView.setText((hintGiven ? hint + (personalNoteGiven ? "\r\n" : "") : "") + (personalNoteGiven ? personalNote : ""));
return true;
}
}
return false;
}
static void updateOfflineBox(final View view, final Geocache cache, final Resources res,
final OnClickListener refreshCacheClickListener,
final OnClickListener dropCacheClickListener,
final OnClickListener storeCacheClickListener,
final OnClickListener showHintClickListener,
final OnLongClickListener moveCacheListener,
final OnLongClickListener storeCachePreselectedListener) {
// offline use
final TextView offlineText = view.findViewById(R.id.offline_text);
final View offlineRefresh = view.findViewById(R.id.offline_refresh);
final View offlineStore = view.findViewById(R.id.offline_store);
final View offlineDrop = view.findViewById(R.id.offline_drop);
final View offlineEdit = view.findViewById(R.id.offline_edit);
// check if hint is available and set onClickListener and hint button visibility accordingly
final boolean hintButtonEnabled = setOfflineHintText(showHintClickListener, view.findViewById(R.id.offline_hint_text), cache.getHint(), cache.getPersonalNote());
final View offlineHint = view.findViewById(R.id.offline_hint);
if (null != offlineHint) {
if (hintButtonEnabled) {
offlineHint.setVisibility(View.VISIBLE);
offlineHint.setClickable(true);
offlineHint.setOnClickListener(showHintClickListener);
} else {
offlineHint.setVisibility(View.GONE);
offlineHint.setClickable(false);
offlineHint.setOnClickListener(null);
}
}
offlineStore.setClickable(true);
offlineStore.setOnClickListener(storeCacheClickListener);
offlineStore.setOnLongClickListener(storeCachePreselectedListener);
offlineDrop.setClickable(true);
offlineDrop.setOnClickListener(dropCacheClickListener);
offlineDrop.setOnLongClickListener(null);
offlineEdit.setOnClickListener(storeCacheClickListener);
if (moveCacheListener != null) {
offlineEdit.setOnLongClickListener(moveCacheListener);
}
offlineRefresh.setVisibility(cache.supportsRefresh() ? View.VISIBLE : View.GONE);
offlineRefresh.setClickable(true);
offlineRefresh.setOnClickListener(refreshCacheClickListener);
if (cache.isOffline()) {
offlineText.setText(Formatter.formatStoredAgo(cache.getDetailedUpdate()));
offlineStore.setVisibility(View.GONE);
offlineDrop.setVisibility(View.VISIBLE);
offlineEdit.setVisibility(View.VISIBLE);
} else {
offlineText.setText(res.getString(R.string.cache_offline_not_ready));
offlineStore.setVisibility(View.VISIBLE);
offlineDrop.setVisibility(View.GONE);
offlineEdit.setVisibility(View.GONE);
}
}
static void updateCacheLists(final View view, final Geocache cache, final Resources res) {
final SpannableStringBuilder builder = new SpannableStringBuilder();
for (final Integer listId : cache.getLists()) {
if (builder.length() > 0) {
builder.append(", ");
}
appendClickableList(builder, view, listId);
}
builder.insert(0, res.getString(R.string.list_list_headline) + " ");
final TextView offlineLists = view.findViewById(R.id.offline_lists);
offlineLists.setText(builder);
offlineLists.setMovementMethod(LinkMovementMethod.getInstance());
}
static void appendClickableList(final SpannableStringBuilder builder, final View view, final Integer listId) {
final int start = builder.length();
builder.append(DataStore.getList(listId).getTitle());
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull final View widget) {
Settings.setLastDisplayedList(listId);
CacheListActivity.startActivityOffline(view.getContext());
}
}, start, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
public Geocache getCache() {
return cache;
}
private static class StoreCacheHandler extends SimpleDisposableHandler {
StoreCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_LOAD_PROGRESS_DETAIL && msg.obj instanceof String) {
updateStatusMsg(R.string.cache_dialog_offline_save_message, (String) msg.obj);
} else {
notifyDataSetChanged(activityRef);
}
}
}
private static final class RefreshCacheHandler extends SimpleDisposableHandler {
RefreshCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_LOAD_PROGRESS_DETAIL && msg.obj instanceof String) {
updateStatusMsg(R.string.cache_dialog_refresh_message, (String) msg.obj);
} else if (msg.what == UPDATE_SHOW_STATUS_TOAST && msg.obj instanceof String) {
showToast((String) msg.obj);
} else {
notifyDataSetChanged(activityRef);
}
}
}
private static final class ChangeNotificationHandler extends SimpleHandler {
ChangeNotificationHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleMessage(final Message msg) {
notifyDataSetChanged(activityRef);
}
}
private static void notifyDataSetChanged(final WeakReference<AbstractActivity> activityRef) {
final CacheDetailActivity activity = (CacheDetailActivity) activityRef.get();
if (activity != null) {
activity.notifyDataSetChanged();
}
}
protected void storeCache(final Set<Integer> listIds) {
final StoreCacheHandler storeCacheHandler = new StoreCacheHandler(CacheDetailActivity.this, progress);
progress.show(this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.disposeMessage());
AndroidRxUtils.networkScheduler.scheduleDirect(() -> cache.store(listIds, storeCacheHandler));
}
public static void editPersonalNote(final Geocache cache, final CacheDetailActivity activity) {
final FragmentManager fm = activity.getSupportFragmentManager();
final EditNoteDialog dialog = EditNoteDialog.newInstance(cache.getPersonalNote(), cache.isPreventWaypointsFromNote());
dialog.show(fm, "fragment_edit_note");
}
@Override
public void onFinishEditNoteDialog(final String note, final boolean preventWaypointsFromNote) {
setNewPersonalNote(note, preventWaypointsFromNote);
}
public void removeWaypointsFromPersonalNote(final Geocache cache) {
final String note = cache.getPersonalNote() == null ? "" : cache.getPersonalNote();
final String newNote = WaypointParser.removeParseableWaypointsFromText(note);
if (newNote != null) {
setNewPersonalNote(newNote);
}
showShortToast(note.equals(newNote) ? R.string.cache_personal_note_removewaypoints_nowaypoints : R.string.cache_personal_note_removedwaypoints);
}
public void storeWaypointsInPersonalNote(final Geocache cache) {
final String note = cache.getPersonalNote() == null ? "" : cache.getPersonalNote();
//only user modified waypoints
final List<Waypoint> userModifiedWaypoints = new ArrayList<>();
for (Waypoint w : cache.getWaypoints()) {
if (w.isUserModified()) {
userModifiedWaypoints.add(w);
}
}
if (userModifiedWaypoints.isEmpty() && cache.getVariables().isEmpty()) {
showShortToast(getString(R.string.cache_personal_note_storewaypoints_nowaypoints));
return;
}
final String newNote = WaypointParser.putParseableWaypointsInText(note, userModifiedWaypoints, cache.getVariables());
setNewPersonalNote(newNote);
showShortToast(R.string.cache_personal_note_storewaypoints_success);
}
private void setNewPersonalNote(final String newNote) {
setNewPersonalNote(newNote, cache.isPreventWaypointsFromNote());
}
/**
* Internal method to set new personal note and update all corresponding entities (DB, dialogs etc)
*
* @param newNote new note to set
* @param newPreventWaypointsFromNote new preventWaypointsFromNote flag to set
*/
private void setNewPersonalNote(final String newNote, final boolean newPreventWaypointsFromNote) {
// trim note to avoid unnecessary uploads for whitespace only changes
final String trimmedNote = StringUtils.trim(newNote);
cache.setPersonalNote(trimmedNote);
cache.setPreventWaypointsFromNote(newPreventWaypointsFromNote);
if (cache.addWaypointsFromNote()) {
reinitializePage(Page.WAYPOINTS.id);
/* @todo mb Does above line work?
final PageViewCreator wpViewCreator = getViewCreator(Page.WAYPOINTS);
if (wpViewCreator != null) {
wpViewCreator.notifyDataSetChanged();
}
*/
}
setMenuPreventWaypointsFromNote(cache.isPreventWaypointsFromNote());
final TextView personalNoteView = findViewById(R.id.personalnote);
final View separator = findViewById(R.id.personalnote_button_separator);
if (personalNoteView != null) {
setPersonalNote(personalNoteView, separator, trimmedNote);
} else {
reinitializePage(Page.DESCRIPTION.id);
}
Schedulers.io().scheduleDirect(() -> DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)));
}
private static void setPersonalNote(final TextView personalNoteView, final View separator, final String personalNote) {
personalNoteView.setText(personalNote, TextView.BufferType.SPANNABLE);
if (StringUtils.isNotBlank(personalNote)) {
personalNoteView.setVisibility(View.VISIBLE);
separator.setVisibility(View.VISIBLE);
Linkify.addLinks(personalNoteView, Linkify.MAP_ADDRESSES | Linkify.WEB_URLS);
} else {
personalNoteView.setVisibility(View.GONE);
separator.setVisibility(View.GONE);
}
}
@Override
public void navigateTo() {
startDefaultNavigation();
}
@Override
public void showNavigationMenu() {
NavigationAppFactory.showNavigationMenu(this, cache, null, null);
}
@Override
public void cachesAround() {
CacheListActivity.startActivityCoordinates(this, cache.getCoords(), cache.getName());
}
public void setNeedsRefresh() {
refreshOnResume = true;
}
}
|
package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.activity.INavigationSource;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.activity.TabbedViewPagerActivity;
import cgeo.geocaching.activity.TabbedViewPagerFragment;
import cgeo.geocaching.apps.cachelist.MapsMeCacheListApp;
import cgeo.geocaching.apps.navi.NavigationAppFactory;
import cgeo.geocaching.calendar.CalendarAdder;
import cgeo.geocaching.command.AbstractCommand;
import cgeo.geocaching.command.MoveToListAndRemoveFromOthersCommand;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.al.ALConnector;
import cgeo.geocaching.connector.capability.IFavoriteCapability;
import cgeo.geocaching.connector.capability.IIgnoreCapability;
import cgeo.geocaching.connector.capability.IVotingCapability;
import cgeo.geocaching.connector.capability.PersonalNoteCapability;
import cgeo.geocaching.connector.capability.PgcChallengeCheckerCapability;
import cgeo.geocaching.connector.capability.WatchListCapability;
import cgeo.geocaching.connector.internal.InternalConnector;
import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.connector.trackable.TrackableConnector;
import cgeo.geocaching.databinding.CachedetailDescriptionPageBinding;
import cgeo.geocaching.databinding.CachedetailDetailsPageBinding;
import cgeo.geocaching.databinding.CachedetailImagegalleryPageBinding;
import cgeo.geocaching.databinding.CachedetailImagesPageBinding;
import cgeo.geocaching.databinding.CachedetailInventoryPageBinding;
import cgeo.geocaching.databinding.CachedetailWaypointsHeaderBinding;
import cgeo.geocaching.databinding.CachedetailWaypointsPageBinding;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.enumerations.CacheAttributeCategory;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.export.FieldNoteExport;
import cgeo.geocaching.export.GpxExport;
import cgeo.geocaching.export.PersonalNoteExport;
import cgeo.geocaching.gcvote.VoteDialog;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.GeopointFormatter;
import cgeo.geocaching.location.Units;
import cgeo.geocaching.log.CacheLogsViewCreator;
import cgeo.geocaching.log.LogCacheActivity;
import cgeo.geocaching.log.LoggingUI;
import cgeo.geocaching.models.CalculatedCoordinate;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.models.WaypointParser;
import cgeo.geocaching.network.AndroidBeam;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.SmileyImage;
import cgeo.geocaching.permission.PermissionHandler;
import cgeo.geocaching.permission.PermissionRequestContext;
import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.speech.SpeechService;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.CoordinatesFormatSwitcher;
import cgeo.geocaching.ui.DecryptTextClickListener;
import cgeo.geocaching.ui.FastScrollListener;
import cgeo.geocaching.ui.ImageGalleryView;
import cgeo.geocaching.ui.ImagesList;
import cgeo.geocaching.ui.IndexOutOfBoundsAvoidingTextView;
import cgeo.geocaching.ui.TextParam;
import cgeo.geocaching.ui.TrackableListAdapter;
import cgeo.geocaching.ui.UserClickListener;
import cgeo.geocaching.ui.WeakReferenceHandler;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.ui.dialog.EditNoteDialog;
import cgeo.geocaching.ui.dialog.EditNoteDialog.EditNoteDialogListener;
import cgeo.geocaching.ui.dialog.SimpleDialog;
import cgeo.geocaching.ui.recyclerview.RecyclerViewProvider;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.BranchDetectionHelper;
import cgeo.geocaching.utils.CalendarUtils;
import cgeo.geocaching.utils.CheckerUtils;
import cgeo.geocaching.utils.ClipboardUtils;
import cgeo.geocaching.utils.ColorUtils;
import cgeo.geocaching.utils.CryptUtils;
import cgeo.geocaching.utils.DisposableHandler;
import cgeo.geocaching.utils.EmojiUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.LocalizationUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MapMarkerUtils;
import cgeo.geocaching.utils.ProcessUtils;
import cgeo.geocaching.utils.ShareUtils;
import cgeo.geocaching.utils.SimpleDisposableHandler;
import cgeo.geocaching.utils.SimpleHandler;
import cgeo.geocaching.utils.TextUtils;
import cgeo.geocaching.utils.UnknownTagsHandler;
import cgeo.geocaching.utils.functions.Action1;
import static cgeo.geocaching.apps.cache.WhereYouGoApp.getWhereIGoUrl;
import static cgeo.geocaching.apps.cache.WhereYouGoApp.isWhereYouGoInstalled;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.TooltipCompat;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.FragmentManager;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.text.StringEscapeUtils;
/**
* Activity to handle all single-cache-stuff.
*
* e.g. details, description, logs, waypoints, inventory, variables...
*/
public class CacheDetailActivity extends TabbedViewPagerActivity
implements CacheMenuHandler.ActivityInterface, INavigationSource, AndroidBeam.ActivitySharingInterface, EditNoteDialogListener {
private static final int MESSAGE_FAILED = -1;
private static final int MESSAGE_SUCCEEDED = 1;
private static final String EXTRA_FORCE_WAYPOINTSPAGE = "cgeo.geocaching.extra.cachedetail.forceWaypointsPage";
private static final float CONTRAST_THRESHOLD = 4.5f;
public static final String STATE_PAGE_INDEX = "cgeo.geocaching.pageIndex";
// Store Geocode here, as 'cache' is loaded Async.
private String geocode;
private Geocache cache;
@NonNull
private final List<Trackable> genericTrackables = new ArrayList<>();
private final Progress progress = new Progress();
private SearchResult search;
private GeoDirHandler locationUpdater;
private CharSequence clickedItemText = null;
private MenuItem menuItemToggleWaypointsFromNote = null;
/**
* If another activity is called and can modify the data of this activity, we refresh it on resume.
*/
private boolean refreshOnResume = false;
// some views that must be available from everywhere // TODO: Reference can block GC?
private TextView cacheDistanceView;
protected ImagesList imagesList;
private ImageGalleryView imageGallery;
private final CompositeDisposable createDisposables = new CompositeDisposable();
/**
* waypoint selected in context menu. This variable will be gone when the waypoint context menu is a fragment.
*/
private Waypoint selectedWaypoint;
private boolean requireGeodata;
private final CompositeDisposable geoDataDisposable = new CompositeDisposable();
private final EnumSet<TrackableBrand> processedBrands = EnumSet.noneOf(TrackableBrand.class);
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setThemeAndContentView(R.layout.tabbed_viewpager_activity_refreshable);
// get parameters
final Bundle extras = getIntent().getExtras();
final Uri uri = AndroidBeam.getUri(getIntent());
// try to get data from extras
String name = null;
String guid = null;
boolean forceWaypointsPage = false;
if (extras != null) {
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
forceWaypointsPage = extras.getBoolean(EXTRA_FORCE_WAYPOINTSPAGE);
}
// When clicking a cache in MapsWithMe, we get back a PendingIntent
if (StringUtils.isEmpty(geocode)) {
geocode = MapsMeCacheListApp.getCacheFromMapsWithMe(this, getIntent());
}
if (geocode == null && uri != null) {
geocode = ConnectorFactory.getGeocodeFromURL(uri.toString());
}
// try to get data from URI
if (geocode == null && guid == null && uri != null) {
final String uriHost = uri.getHost().toLowerCase(Locale.US);
final String uriPath = uri.getPath().toLowerCase(Locale.US);
final String uriQuery = uri.getQuery();
if (uriQuery != null) {
Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
} else {
Log.i("Opening URI: " + uriHost + uriPath);
}
if (uriHost.contains("geocaching.com")) {
if (StringUtils.startsWith(uriPath, "/geocache/gc")) {
geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US);
} else {
geocode = uri.getQueryParameter("wp");
guid = uri.getQueryParameter("guid");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
}
}
}
// no given data
if (geocode == null && guid == null) {
showToast(res.getString(R.string.err_detail_cache));
finish();
return;
}
// If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details
setCacheTitleBar(geocode, name, null);
final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress);
try {
String title = res.getString(R.string.cache);
if (StringUtils.isNotBlank(name)) {
title = name;
} else if (StringUtils.isNotBlank(geocode)) {
title = geocode;
}
progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.disposeMessage());
} catch (final RuntimeException ignored) {
// nothing, we lost the window
}
locationUpdater = new CacheDetailsGeoDirHandler(this);
final long pageToOpen = forceWaypointsPage ? Page.WAYPOINTS.id :
savedInstanceState != null ?
savedInstanceState.getLong(STATE_PAGE_INDEX, Page.DETAILS.id) :
Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : Page.DETAILS.id;
createViewPager(pageToOpen, getOrderedPages(), currentPageId -> {
if (Settings.isOpenLastDetailsPage()) {
Settings.setLastDetailsPage((int) (long) currentPageId);
}
requireGeodata = currentPageId == Page.DETAILS.id;
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this, new RestartLocationPermissionGrantedCallback(PermissionRequestContext.CacheDetailActivity) {
@Override
public void executeAfter() {
startOrStopGeoDataListener(false);
}
});
// dispose contextual actions on page change
if (currentActionMode != null) {
currentActionMode.finish();
}
}, true);
requireGeodata = pageToOpen == Page.DETAILS.id;
final String realGeocode = geocode;
final String realGuid = guid;
AndroidRxUtils.networkScheduler.scheduleDirect(() -> {
search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null, false, loadCacheHandler);
loadCacheHandler.sendMessage(Message.obtain());
});
// Load Generic Trackables
if (StringUtils.isNotBlank(geocode)) {
AndroidRxUtils.bindActivity(this,
// Obtain the active connectors and load trackables in parallel.
Observable.fromIterable(ConnectorFactory.getGenericTrackablesConnectors()).flatMap((Function<TrackableConnector, Observable<Trackable>>) trackableConnector -> {
processedBrands.add(trackableConnector.getBrand());
return Observable.defer(() -> Observable.fromIterable(trackableConnector.searchTrackables(geocode))).subscribeOn(AndroidRxUtils.networkScheduler);
}).toList()).subscribe(trackables -> {
// Todo: this is not really a good method, it may lead to duplicates ; ie: in OC connectors.
// Store trackables.
genericTrackables.addAll(trackables);
if (!trackables.isEmpty()) {
// Update the UI if any trackables were found.
notifyDataSetChanged();
}
});
}
// If we have a newer Android device setup Android Beam for easy cache sharing
AndroidBeam.enable(this, this);
// get notified on cache changes (e.g.: waypoint creation from map)
LocalBroadcastManager.getInstance(this).registerReceiver(updateReceiver, new IntentFilter(Intents.INTENT_CACHE_CHANGED));
}
@Override
@Nullable
public String getAndroidBeamUri() {
return cache != null ? cache.getUrl() : null;
}
@Override
public void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(STATE_PAGE_INDEX, getCurrentPageId());
}
private void startOrStopGeoDataListener(final boolean initial) {
final boolean start;
if (Settings.useLowPowerMode()) {
geoDataDisposable.clear();
start = requireGeodata;
} else {
start = initial;
}
if (start) {
geoDataDisposable.add(locationUpdater.start(GeoDirHandler.UPDATE_GEODATA));
}
}
@Override
public void onResume() {
super.onResume();
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this, new RestartLocationPermissionGrantedCallback(PermissionRequestContext.CacheDetailActivity) {
@Override
public void executeAfter() {
startOrStopGeoDataListener(true);
}
});
if (refreshOnResume) {
notifyDataSetChanged();
refreshOnResume = false;
}
}
@Override
public void onPause() {
geoDataDisposable.clear();
super.onPause();
}
@Override
public void onDestroy() {
createDisposables.clear();
SpeechService.stopService(this);
if (cache != null) {
cache.setChangeNotificationHandler(null);
}
LocalBroadcastManager.getInstance(this).unregisterReceiver(updateReceiver);
super.onDestroy();
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View view, final ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
final int viewId = view.getId();
if (viewId == R.id.waypoint) {
menu.setHeaderTitle(selectedWaypoint.getName() + " (" + res.getString(R.string.waypoint) + ")");
getMenuInflater().inflate(R.menu.waypoint_options, menu);
final boolean isOriginalWaypoint = selectedWaypoint.getWaypointType() == WaypointType.ORIGINAL;
menu.findItem(R.id.menu_waypoint_reset_cache_coords).setVisible(isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_edit).setVisible(!isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_duplicate).setVisible(!isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_delete).setVisible(!isOriginalWaypoint || selectedWaypoint.belongsToUserDefinedCache());
final boolean hasCoords = selectedWaypoint.getCoords() != null;
final MenuItem defaultNavigationMenu = menu.findItem(R.id.menu_waypoint_navigate_default);
defaultNavigationMenu.setVisible(hasCoords);
defaultNavigationMenu.setTitle(NavigationAppFactory.getDefaultNavigationApplication().getName());
menu.findItem(R.id.menu_waypoint_navigate).setVisible(hasCoords);
menu.findItem(R.id.menu_waypoint_caches_around).setVisible(hasCoords);
menu.findItem(R.id.menu_waypoint_copy_coordinates).setVisible(hasCoords);
final boolean canClearCoords = hasCoords && (selectedWaypoint.isUserDefined() || selectedWaypoint.isOriginalCoordsEmpty());
menu.findItem(R.id.menu_waypoint_clear_coordinates).setVisible(canClearCoords);
menu.findItem(R.id.menu_waypoint_toclipboard).setVisible(true);
} else {
if (imagesList != null) {
imagesList.onCreateContextMenu(menu, view);
}
}
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.menu_waypoint_edit) {
// waypoints
if (selectedWaypoint != null) {
ensureSaved();
EditWaypointActivity.startActivityEditWaypoint(this, cache, selectedWaypoint.getId());
refreshOnResume = true;
}
} else if (itemId == R.id.menu_waypoint_visited) {
if (selectedWaypoint != null) {
ensureSaved();
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(final Void... params) {
selectedWaypoint.setVisited(true);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
@Override
protected void onPostExecute(final Boolean result) {
if (result) {
notifyDataSetChanged();
}
}
}.execute();
}
} else if (itemId == R.id.menu_waypoint_copy_coordinates) {
if (selectedWaypoint != null) {
final Geopoint coordinates = selectedWaypoint.getCoords();
if (coordinates != null) {
ClipboardUtils.copyToClipboard(
GeopointFormatter.reformatForClipboard(coordinates.toString()));
showToast(getString(R.string.clipboard_copy_ok));
}
}
} else if (itemId == R.id.menu_waypoint_clear_coordinates) {
if (selectedWaypoint != null) {
ensureSaved();
new ClearCoordinatesCommand(this, cache, selectedWaypoint).execute();
}
} else if (itemId == R.id.menu_waypoint_duplicate) {
ensureSaved();
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(final Void... params) {
if (cache.duplicateWaypoint(selectedWaypoint, true) != null) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
return false;
}
@Override
protected void onPostExecute(final Boolean result) {
if (result) {
notifyDataSetChanged();
}
}
}.execute();
} else if (itemId == R.id.menu_waypoint_toclipboard) {
if (selectedWaypoint != null) {
ensureSaved();
ClipboardUtils.copyToClipboard(selectedWaypoint.reformatForClipboard());
showToast(getString(R.string.clipboard_copy_ok));
}
} else if (itemId == R.id.menu_waypoint_delete) {
ensureSaved();
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(final Void... params) {
if (cache.deleteWaypoint(selectedWaypoint)) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
return false;
}
@Override
protected void onPostExecute(final Boolean result) {
if (result) {
notifyDataSetChanged();
LocalBroadcastManager.getInstance(CacheDetailActivity.this).sendBroadcast(new Intent(Intents.INTENT_CACHE_CHANGED));
}
}
}.execute();
} else if (itemId == R.id.menu_waypoint_navigate_default) {
if (selectedWaypoint != null) {
NavigationAppFactory.startDefaultNavigationApplication(1, this, selectedWaypoint);
}
} else if (itemId == R.id.menu_waypoint_navigate) {
if (selectedWaypoint != null) {
NavigationAppFactory.showNavigationMenu(this, null, selectedWaypoint, null);
}
} else if (itemId == R.id.menu_waypoint_caches_around) {
if (selectedWaypoint != null) {
final Geopoint coordinates = selectedWaypoint.getCoords();
if (coordinates != null) {
CacheListActivity.startActivityCoordinates(this, coordinates, selectedWaypoint.getName());
}
}
} else if (itemId == R.id.menu_waypoint_reset_cache_coords) {
ensureSaved();
if (ConnectorFactory.getConnector(cache).supportsOwnCoordinates()) {
createResetCacheCoordinatesDialog(selectedWaypoint).show();
} else {
final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(this, progressDialog, false);
resetCoords(cache, handler, selectedWaypoint, true, false, progressDialog);
}
} else if (itemId == R.id.menu_calendar) {
CalendarAdder.addToCalendar(this, cache);
} else if (imagesList == null || !imagesList.onContextItemSelected(item)) {
return onOptionsItemSelected(item);
}
return true;
}
private abstract static class AbstractWaypointModificationCommand extends AbstractCommand {
protected final Waypoint waypoint;
protected final Geocache cache;
protected AbstractWaypointModificationCommand(final CacheDetailActivity context, final Geocache cache, final Waypoint waypoint) {
super(context);
this.cache = cache;
this.waypoint = waypoint;
}
@Override
protected void onFinished() {
((CacheDetailActivity) getContext()).notifyDataSetChanged();
}
@Override
protected void onFinishedUndo() {
((CacheDetailActivity) getContext()).notifyDataSetChanged();
}
}
private static final class ClearCoordinatesCommand extends AbstractWaypointModificationCommand {
private Geopoint coords;
ClearCoordinatesCommand(final CacheDetailActivity context, final Geocache cache, final Waypoint waypoint) {
super(context, cache, waypoint);
}
@Override
protected void doCommand() {
coords = waypoint.getCoords();
waypoint.setCoords(null);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
}
@Override
protected void undoCommand() {
waypoint.setCoords(coords);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
}
@Override
protected String getResultMessage() {
return getContext().getString(R.string.info_waypoint_coordinates_cleared);
}
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
CacheMenuHandler.addMenuItems(this, menu, cache);
CacheMenuHandler.initDefaultNavigationMenuItem(menu, this);
return true;
}
private void setMenuPreventWaypointsFromNote(final boolean preventWaypointsFromNote) {
if (null != menuItemToggleWaypointsFromNote) {
menuItemToggleWaypointsFromNote.setTitle(preventWaypointsFromNote ? R.string.cache_menu_allowWaypointExtraction : R.string.cache_menu_preventWaypointsFromNote);
}
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final IConnector connector = null != cache ? ConnectorFactory.getConnector(cache) : null;
final boolean isUDC = null != connector && connector.equals(InternalConnector.getInstance());
CacheMenuHandler.onPrepareOptionsMenu(menu, cache, false);
LoggingUI.onPrepareOptionsMenu(menu, cache);
if (cache != null) {
// top level menu items
menu.findItem(R.id.menu_tts_toggle).setVisible(!cache.isGotoHistoryUDC());
menu.findItem(R.id.menu_checker).setVisible(StringUtils.isNotEmpty(CheckerUtils.getCheckerUrl(cache)));
if (connector instanceof PgcChallengeCheckerCapability) {
menu.findItem(R.id.menu_challenge_checker).setVisible(((PgcChallengeCheckerCapability) connector).isChallengeCache(cache));
}
menu.findItem(R.id.menu_edit_fieldnote).setVisible(true);
// submenu waypoints
menu.findItem(R.id.menu_delete_userdefined_waypoints).setVisible(cache.isOffline() && cache.hasUserdefinedWaypoints());
menu.findItem(R.id.menu_delete_generated_waypoints).setVisible(cache.isOffline() && cache.hasGeneratedWaypoints());
menu.findItem(R.id.menu_extract_waypoints).setVisible(!isUDC);
menu.findItem(R.id.menu_scan_calculated_waypoints).setVisible(!isUDC);
menu.findItem(R.id.menu_clear_goto_history).setVisible(cache.isGotoHistoryUDC());
menuItemToggleWaypointsFromNote = menu.findItem(R.id.menu_toggleWaypointsFromNote);
setMenuPreventWaypointsFromNote(cache.isPreventWaypointsFromNote());
menuItemToggleWaypointsFromNote.setVisible(!cache.isGotoHistoryUDC());
menu.findItem(R.id.menu_waypoints).setVisible(true);
// submenu share / export
menu.findItem(R.id.menu_export).setVisible(true);
// submenu advanced
if (connector instanceof IVotingCapability) {
final MenuItem menuItemGCVote = menu.findItem(R.id.menu_gcvote);
menuItemGCVote.setVisible(((IVotingCapability) connector).supportsVoting(cache));
menuItemGCVote.setEnabled(Settings.isRatingWanted() && Settings.isGCVoteLoginValid());
}
if (connector instanceof IIgnoreCapability) {
menu.findItem(R.id.menu_ignore).setVisible(((IIgnoreCapability) connector).canIgnoreCache(cache));
}
menu.findItem(R.id.menu_set_cache_icon).setVisible(cache.isOffline());
menu.findItem(R.id.menu_advanced).setVisible(cache.getCoords() != null);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (CacheMenuHandler.onMenuItemSelected(item, this, cache, this::notifyDataSetChanged, false)) {
return true;
}
final int menuItem = item.getItemId();
if (menuItem == R.id.menu_delete_userdefined_waypoints) {
dropUserdefinedWaypoints();
} else if (menuItem == R.id.menu_delete_generated_waypoints) {
dropGeneratedWaypoints();
} else if (menuItem == R.id.menu_refresh) {
refreshCache();
} else if (menuItem == R.id.menu_gcvote) {
showVoteDialog();
} else if (menuItem == R.id.menu_checker) {
ShareUtils.openUrl(this, CheckerUtils.getCheckerUrl(cache), true);
} else if (menuItem == R.id.menu_challenge_checker) {
ShareUtils.openUrl(this, "https://project-gc.com/Challenges/" + cache.getGeocode());
} else if (menuItem == R.id.menu_ignore) {
ignoreCache();
} else if (menuItem == R.id.menu_extract_waypoints) {
final String searchText = cache.getShortDescription() + ' ' + cache.getDescription();
extractWaypoints(searchText, cache);
} else if (menuItem == R.id.menu_scan_calculated_waypoints) {
scanForCalculatedWaypints(cache);
} else if (menuItem == R.id.menu_toggleWaypointsFromNote) {
cache.setPreventWaypointsFromNote(!cache.isPreventWaypointsFromNote());
setMenuPreventWaypointsFromNote(cache.isPreventWaypointsFromNote());
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(final Void... params) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
@Override
protected void onPostExecute(final Boolean result) {
if (result) {
notifyDataSetChanged();
}
}
}.execute();
} else if (menuItem == R.id.menu_clear_goto_history) {
SimpleDialog.of(this).setTitle(R.string.clear_goto_history_title).setMessage(R.string.clear_goto_history).confirm((dialog, which) -> AndroidRxUtils.andThenOnUi(Schedulers.io(), DataStore::clearGotoHistory, () -> {
cache = DataStore.loadCache(InternalConnector.GEOCODE_HISTORY_CACHE, LoadFlags.LOAD_ALL_DB_ONLY);
notifyDataSetChanged();
}));
} else if (menuItem == R.id.menu_export_gpx) {
new GpxExport().export(Collections.singletonList(cache), this);
} else if (menuItem == R.id.menu_export_fieldnotes) {
new FieldNoteExport().export(Collections.singletonList(cache), this);
} else if (menuItem == R.id.menu_export_persnotes) {
new PersonalNoteExport().export(Collections.singletonList(cache), this);
} else if (menuItem == R.id.menu_edit_fieldnote) {
ensureSaved();
editPersonalNote(cache, this);
} else if (menuItem == R.id.menu_navigate) {
NavigationAppFactory.onMenuItemSelected(item, this, cache);
} else if (menuItem == R.id.menu_tts_toggle) {
SpeechService.toggleService(this, cache.getCoords());
} else if (menuItem == R.id.menu_set_cache_icon) {
EmojiUtils.selectEmojiPopup(this, cache.getAssignedEmoji(), cache, this::setCacheIcon);
} else if (LoggingUI.onMenuItemSelected(item, this, cache, null)) {
refreshOnResume = true;
} else {
return super.onOptionsItemSelected(item);
}
return true;
}
private void setCacheIcon(final int newCacheIcon) {
cache.setAssignedEmoji(newCacheIcon);
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
Toast.makeText(this, R.string.cache_icon_updated, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
private void ignoreCache() {
SimpleDialog.of(this).setTitle(R.string.ignore_confirm_title).setMessage(R.string.ignore_confirm_message).confirm((dialog, which) -> {
AndroidRxUtils.networkScheduler.scheduleDirect(() -> ((IIgnoreCapability) ConnectorFactory.getConnector(cache)).addToIgnorelist(cache));
// For consistency, remove also the local cache immediately from memory cache and database
if (cache.isOffline()) {
dropCache();
DataStore.removeCache(cache.getGeocode(), EnumSet.of(RemoveFlag.DB));
}
});
}
private void showVoteDialog() {
VoteDialog.show(this, cache, this::notifyDataSetChanged);
}
private static final class CacheDetailsGeoDirHandler extends GeoDirHandler {
private final WeakReference<CacheDetailActivity> activityRef;
CacheDetailsGeoDirHandler(final CacheDetailActivity activity) {
this.activityRef = new WeakReference<>(activity);
}
@Override
public void updateGeoData(final GeoData geo) {
final CacheDetailActivity activity = activityRef.get();
if (activity == null) {
return;
}
if (activity.cacheDistanceView == null) {
return;
}
if (activity.cache != null && activity.cache.getCoords() != null) {
activity.cacheDistanceView.setText(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(activity.cache.getCoords())));
activity.cacheDistanceView.bringToFront();
}
}
}
private static final class LoadCacheHandler extends SimpleDisposableHandler {
LoadCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_LOAD_PROGRESS_DETAIL && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
final CacheDetailActivity activity = (CacheDetailActivity) activityRef.get();
if (activity == null) {
return;
}
if (activity.search == null) {
showToast(R.string.err_dwld_details_failed);
dismissProgress();
finishActivity();
return;
}
if (activity.search.getError() != StatusCode.NO_ERROR) {
// Cache not found is not a download error
final StatusCode error = activity.search.getError();
final Resources res = activity.getResources();
final String toastPrefix = error != StatusCode.CACHE_NOT_FOUND ? res.getString(R.string.err_dwld_details_failed) + " " : "";
if (error == StatusCode.PREMIUM_ONLY) {
SimpleDialog.of(activity).setTitle(R.string.cache_status_premium).setMessage(R.string.err_detail_premium_log_found).setPositiveButton(TextParam.id(R.string.cache_menu_visit)).confirm((dialog, which) -> {
activity.startActivity(LogCacheActivity.getLogCacheIntent(activity, null, activity.geocode));
finishActivity();
}, (d, i) -> finishActivity());
dismissProgress();
} else {
activity.showToast(toastPrefix + error.getErrorString(res));
dismissProgress();
finishActivity();
}
return;
}
updateStatusMsg(activity.getString(R.string.cache_dialog_loading_details_status_render));
// Data loaded, we're ready to show it!
activity.notifyDataSetChanged();
}
}
private void updateStatusMsg(final String msg) {
final CacheDetailActivity activity = (CacheDetailActivity) activityRef.get();
if (activity == null) {
return;
}
setProgressMessage(activity.getString(R.string.cache_dialog_loading_details)
+ "\n\n"
+ msg);
}
@Override
public void handleDispose() {
finishActivity();
}
}
private void notifyDataSetChanged() {
// This might get called asynchronous when the activity is shut down
if (isFinishing()) {
return;
}
if (search == null) {
return;
}
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY);
if (cache == null) {
progress.dismiss();
showToast(res.getString(R.string.err_detail_cache_find_some));
finish();
return;
}
// allow cache to notify CacheDetailActivity when it changes so it can be reloaded
cache.setChangeNotificationHandler(new ChangeNotificationHandler(this, progress));
setCacheTitleBar(cache);
setIsContentRefreshable(cache.supportsRefresh());
// reset imagesList so Images view page will be redrawn
imagesList = null;
imageGallery = null;
setOrderedPages(getOrderedPages());
reinitializeViewPager();
// rendering done! remove progress popup if any there
invalidateOptionsMenuCompatible();
progress.dismiss();
Settings.addCacheToHistory(cache.getGeocode());
}
/**
* Receives update notifications from asynchronous processes
*/
private final BroadcastReceiver updateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
notifyDataSetChanged();
}
};
/**
* Tries to navigate to the {@link Geocache} of this activity using the default navigation tool.
*/
@Override
public void startDefaultNavigation() {
NavigationAppFactory.startDefaultNavigationApplication(1, this, cache);
}
/**
* Tries to navigate to the {@link Geocache} of this activity using the second default navigation tool.
*/
@Override
public void startDefaultNavigation2() {
NavigationAppFactory.startDefaultNavigationApplication(2, this, cache);
}
/**
* Wrapper for the referenced method in the xml-layout.
*/
public void goDefaultNavigation(@SuppressWarnings("unused") final View view) {
startDefaultNavigation();
}
/**
* referenced from XML view
*/
public void showNavigationMenu(@SuppressWarnings("unused") final View view) {
NavigationAppFactory.showNavigationMenu(this, cache, null, null, true, true);
}
public static void startActivity(final Context context, final String geocode, final boolean forceWaypointsPage) {
final Intent detailIntent = new Intent(context, CacheDetailActivity.class);
detailIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
detailIntent.putExtra(EXTRA_FORCE_WAYPOINTSPAGE, forceWaypointsPage);
context.startActivity(detailIntent);
}
public static void startActivity(final Context context, final String geocode) {
startActivity(context, geocode, false);
}
/**
* Enum of all possible pages with methods to get the view and a title.
*/
public enum Page {
DETAILS(R.string.detail),
DESCRIPTION(R.string.cache_description),
LOGS(R.string.cache_logs),
LOGSFRIENDS(R.string.cache_logs_friends_and_own),
WAYPOINTS(R.string.cache_waypoints),
INVENTORY(R.string.cache_inventory),
IMAGES(R.string.cache_images),
IMAGEGALLERY(R.string.cache_images),
VARIABLES(R.string.cache_variables),
;
private final int titleStringId;
public final long id;
Page(final int titleStringId) {
this.titleStringId = titleStringId;
this.id = ordinal();
}
static Page find(final long pageId) {
for (Page page : Page.values()) {
if (page.id == pageId) {
return page;
}
}
return null;
}
}
@Override
public void pullToRefreshActionTrigger() {
refreshCache();
}
private void refreshCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (!Network.isConnected()) {
showToast(getString(R.string.err_server));
return;
}
final RefreshCacheHandler refreshCacheHandler = new RefreshCacheHandler(this, progress);
progress.show(this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.disposeMessage());
cache.refresh(refreshCacheHandler, AndroidRxUtils.refreshScheduler);
}
private void dropCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
progress.show(this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null);
cache.drop(new ChangeNotificationHandler(this, progress));
}
private void dropUserdefinedWaypoints() {
if (null != cache && cache.hasUserdefinedWaypoints()) {
String info = getString(R.string.cache_delete_userdefined_waypoints_confirm);
if (!cache.isPreventWaypointsFromNote()) {
info += "\n\n" + getString(R.string.cache_delete_userdefined_waypoints_note);
}
SimpleDialog.of(this).setTitle(R.string.cache_delete_userdefined_waypoints).setMessage(TextParam.text(info)).confirm((dialog, which) -> {
for (Waypoint waypoint : new LinkedList<>(cache.getWaypoints())) {
if (waypoint.isUserDefined()) {
cache.deleteWaypoint(waypoint);
}
}
if (cache.addWaypointsFromNote()) {
Schedulers.io().scheduleDirect(() -> DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)));
}
ActivityMixin.showShortToast(this, R.string.cache_delete_userdefined_waypoints_success);
invalidateOptionsMenu();
reinitializePage(Page.WAYPOINTS.id);
});
}
}
private void dropGeneratedWaypoints() {
if (null != cache && cache.hasGeneratedWaypoints()) {
final String info = getString(R.string.cache_delete_generated_waypoints_confirm);
SimpleDialog.of(this).setTitle(R.string.cache_delete_generated_waypoints).setMessage(TextParam.text(info)).confirm((dialog, which) -> {
for (Waypoint waypoint : new LinkedList<>(cache.getWaypoints())) {
if (waypoint.getWaypointType() == WaypointType.GENERATED) {
cache.deleteWaypoint(waypoint);
}
}
ActivityMixin.showShortToast(this, R.string.cache_delete_generated_waypoints_success);
invalidateOptionsMenu();
reinitializePage(Page.WAYPOINTS.id);
});
}
}
private void storeCache(final boolean fastStoreOnLastSelection) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (Settings.getChooseList() || cache.isOffline()) {
// let user select list to store cache in
new StoredList.UserInterface(this).promptForMultiListSelection(R.string.lists_title,
this::storeCacheInLists, true, cache.getLists(), fastStoreOnLastSelection);
} else {
storeCacheInLists(Collections.singleton(StoredList.STANDARD_LIST_ID));
}
}
private void moveCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
new MoveToListAndRemoveFromOthersCommand(CacheDetailActivity.this, cache) {
@Override
protected void onFinished() {
updateCacheLists(CacheDetailActivity.this.findViewById(R.id.offline_lists), cache, res);
}
}.execute();
}
private void storeCacheInLists(final Set<Integer> selectedListIds) {
if (cache.isOffline()) {
// cache already offline, just add to another list
DataStore.saveLists(Collections.singletonList(cache), selectedListIds);
new StoreCacheHandler(CacheDetailActivity.this, progress).sendEmptyMessage(DisposableHandler.DONE);
} else {
storeCache(selectedListIds);
}
}
private static final class CheckboxHandler extends SimpleDisposableHandler {
private final WeakReference<DetailsViewCreator> creatorRef;
private final WeakReference<CacheDetailActivity> activityWeakReference;
CheckboxHandler(final DetailsViewCreator creator, final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
creatorRef = new WeakReference<>(creator);
activityWeakReference = new WeakReference<>(activity);
}
@Override
public void handleRegularMessage(final Message message) {
final DetailsViewCreator creator = creatorRef.get();
if (creator != null) {
super.handleRegularMessage(message);
creator.updateWatchlistBox(activityWeakReference.get());
creator.updateFavPointBox();
}
}
}
/**
* Creator for details-view.
*
* TODO: Extract inner class to own file for a better overview. Same might apply to all other view creators.
*/
public static class DetailsViewCreator extends TabbedViewPagerFragment<CachedetailDetailsPageBinding> {
private ImmutablePair<RelativeLayout, TextView> favoriteLine;
private Geocache cache;
@Override
public CachedetailDetailsPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailDetailsPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.DETAILS.id;
}
@Override
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"}) // splitting up that method would not help improve readability
public void setContent() {
// retrieve activity and cache - if either of them is null, something's really wrong!
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
// Reference to the details list and favorite line, so that the helper-method can access them without an additional argument
final CacheDetailsCreator details = new CacheDetailsCreator(activity, binding.detailsList);
// cache name (full name), may be editable
final SpannableString span = TextUtils.coloredCacheText(cache, cache.getName());
final TextView cachename = details.add(R.string.cache_name, span).right;
activity.addContextMenu(cachename);
if (cache.supportsNamechange()) {
cachename.setOnClickListener(v -> Dialogs.input(activity, activity.getString(R.string.cache_name_set), cache.getName(), activity.getString(R.string.caches_sort_name), name -> {
cachename.setText(name);
cache.setName(name);
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
Toast.makeText(activity, R.string.cache_name_updated, Toast.LENGTH_SHORT).show();
}));
}
details.add(R.string.cache_type, cache.getType().getL10n());
details.addSize(cache);
activity.addContextMenu(details.add(R.string.cache_geocode, cache.getShortGeocode()).right);
details.addCacheState(cache);
activity.cacheDistanceView = details.addDistance(cache, activity.cacheDistanceView);
details.addDifficulty(cache);
details.addTerrain(cache);
details.addRating(cache);
// favorite count
favoriteLine = details.add(R.string.cache_favorite, "");
// own rating
if (cache.getMyVote() > 0) {
details.addStars(R.string.cache_own_rating, cache.getMyVote());
}
// cache author
if (StringUtils.isNotBlank(cache.getOwnerDisplayName()) || StringUtils.isNotBlank(cache.getOwnerUserId())) {
final TextView ownerView = details.add(R.string.cache_owner, "").right;
if (StringUtils.isNotBlank(cache.getOwnerDisplayName())) {
ownerView.setText(cache.getOwnerDisplayName(), TextView.BufferType.SPANNABLE);
} else { // OwnerReal guaranteed to be not blank based on above
ownerView.setText(cache.getOwnerUserId(), TextView.BufferType.SPANNABLE);
}
ownerView.setOnClickListener(UserClickListener.forOwnerOf(cache));
}
// hidden or event date
final TextView hiddenView = details.addHiddenDate(cache);
if (hiddenView != null) {
activity.addContextMenu(hiddenView);
if (cache.isEventCache()) {
hiddenView.setOnClickListener(v -> CalendarUtils.openCalendar(activity, cache.getHiddenDate()));
}
}
// cache location
if (StringUtils.isNotBlank(cache.getLocation())) {
details.add(R.string.cache_location, cache.getLocation());
}
// cache coordinates
if (cache.getCoords() != null) {
final TextView valueView = details.add(R.string.cache_coordinates, cache.getCoords().toString()).right;
new CoordinatesFormatSwitcher().setView(valueView).setCoordinate(cache.getCoords());
activity.addContextMenu(valueView);
}
// Latest logs
details.addLatestLogs(cache);
// cache attributes
updateAttributes(activity);
binding.attributesBox.setVisibility(cache.getAttributes().isEmpty() ? View.GONE : View.VISIBLE);
updateOfflineBox(binding.getRoot(), cache, activity.res, new RefreshCacheClickListener(), new DropCacheClickListener(),
new StoreCacheClickListener(), null, new MoveCacheClickListener(), new StoreCacheClickListener());
// list
updateCacheLists(binding.getRoot(), cache, activity.res);
// watchlist
binding.addToWatchlist.setOnClickListener(new AddToWatchlistClickListener());
binding.removeFromWatchlist.setOnClickListener(new RemoveFromWatchlistClickListener());
updateWatchlistBox(activity);
// WhereYouGo, ChirpWolf and Adventure Lab
updateWhereYouGoBox(activity);
updateChirpWolfBox(activity);
updateALCBox(activity);
// favorite points
binding.addToFavpoint.setOnClickListener(new FavoriteAddClickListener());
binding.removeFromFavpoint.setOnClickListener(new FavoriteRemoveClickListener());
updateFavPointBox();
final IConnector connector = ConnectorFactory.getConnector(cache);
final String license = connector.getLicenseText(cache);
if (StringUtils.isNotBlank(license)) {
binding.licenseBox.setVisibility(View.VISIBLE);
binding.license.setText(HtmlCompat.fromHtml(license, HtmlCompat.FROM_HTML_MODE_LEGACY), BufferType.SPANNABLE);
binding.license.setClickable(true);
binding.license.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
} else {
binding.licenseBox.findViewById(R.id.license_box).setVisibility(View.GONE);
}
}
private void updateAttributes(final Activity activity) {
final List<String> attributes = cache.getAttributes();
if (!CacheAttribute.hasRecognizedAttributeIcon(attributes)) {
binding.attributesGrid.setVisibility(View.GONE);
return;
}
final HashSet<String> attributesSet = new HashSet<>(attributes);
// traverse by category and attribute order
final ArrayList<String> orderedAttributeNames = new ArrayList<>();
final StringBuilder attributesText = new StringBuilder();
CacheAttributeCategory lastCategory = null;
for (CacheAttributeCategory category : CacheAttributeCategory.getOrderedCategoryList()) {
for (CacheAttribute attr : CacheAttribute.getByCategory(category)) {
for (Boolean enabled : Arrays.asList(false, true, null)) {
final String key = attr.getValue(enabled);
if (attributes.contains(key)) {
if (lastCategory != category) {
if (lastCategory != null) {
attributesText.append("<br /><br />");
}
attributesText.append("<b><u>").append(category.getName(activity)).append("</u></b><br />");
lastCategory = category;
} else {
attributesText.append("<br />");
}
orderedAttributeNames.add(key);
attributesText.append(attr.getL10n(enabled == null ? true : enabled));
}
}
}
}
binding.attributesGrid.setAdapter(new AttributesGridAdapter(activity, orderedAttributeNames, this::toggleAttributesView));
binding.attributesGrid.setVisibility(View.VISIBLE);
binding.attributesText.setText(HtmlCompat.fromHtml(attributesText.toString(), 0));
binding.attributesText.setVisibility(View.GONE);
binding.attributesText.setOnClickListener(v -> toggleAttributesView());
}
protected void toggleAttributesView() {
binding.attributesText.setVisibility(binding.attributesText.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
binding.attributesGrid.setVisibility(binding.attributesGrid.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
}
private class StoreCacheClickListener implements View.OnClickListener, View.OnLongClickListener {
@Override
public void onClick(final View arg0) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.storeCache(false);
}
}
@Override
public boolean onLongClick(final View v) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.storeCache(true);
}
return true;
}
}
private class MoveCacheClickListener implements OnLongClickListener {
@Override
public boolean onLongClick(final View v) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.moveCache();
}
return true;
}
}
private class DropCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.dropCache();
}
}
}
private class RefreshCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
activity.refreshCache();
}
}
}
/**
* Abstract Listener for add / remove buttons for watchlist
*/
private abstract class AbstractPropertyListener implements View.OnClickListener {
private final SimpleDisposableHandler handler;
AbstractPropertyListener() {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
handler = new CheckboxHandler(DetailsViewCreator.this, activity, activity.progress);
}
public void doExecute(final int titleId, final int messageId, final Action1<SimpleDisposableHandler> action) {
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity != null) {
if (activity.progress.isShowing()) {
activity.showToast(activity.res.getString(R.string.err_watchlist_still_managing));
return;
}
activity.progress.show(activity, activity.res.getString(titleId), activity.res.getString(messageId), true, null);
}
AndroidRxUtils.networkScheduler.scheduleDirect(() -> action.call(handler));
}
}
/**
* Listener for "add to watchlist" button
*/
private class AddToWatchlistClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_watchlist_add_title,
R.string.cache_dialog_watchlist_add_message,
DetailsViewCreator.this::watchListAdd);
}
}
/**
* Listener for "remove from watchlist" button
*/
private class RemoveFromWatchlistClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_watchlist_remove_title,
R.string.cache_dialog_watchlist_remove_message,
DetailsViewCreator.this::watchListRemove);
}
}
/** Add this cache to the watchlist of the user */
private void watchListAdd(final SimpleDisposableHandler handler) {
final WatchListCapability connector = (WatchListCapability) ConnectorFactory.getConnector(cache);
if (connector.addToWatchlist(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_watchlist_failed);
}
}
/** Remove this cache from the watchlist of the user */
private void watchListRemove(final SimpleDisposableHandler handler) {
final WatchListCapability connector = (WatchListCapability) ConnectorFactory.getConnector(cache);
if (connector.removeFromWatchlist(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_watchlist_failed);
}
}
/** Add this cache to the favorite list of the user */
private void favoriteAdd(final SimpleDisposableHandler handler) {
final IFavoriteCapability connector = (IFavoriteCapability) ConnectorFactory.getConnector(cache);
if (connector.addToFavorites(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_favorite_failed);
}
}
/** Remove this cache to the favorite list of the user */
private void favoriteRemove(final SimpleDisposableHandler handler) {
final IFavoriteCapability connector = (IFavoriteCapability) ConnectorFactory.getConnector(cache);
if (connector.removeFromFavorites(cache)) {
handler.obtainMessage(MESSAGE_SUCCEEDED).sendToTarget();
} else {
handler.sendTextMessage(MESSAGE_FAILED, R.string.err_favorite_failed);
}
}
/**
* Listener for "add to favorites" button
*/
private class FavoriteAddClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_favorite_add_title,
R.string.cache_dialog_favorite_add_message,
DetailsViewCreator.this::favoriteAdd);
}
}
/**
* Listener for "remove from favorites" button
*/
private class FavoriteRemoveClickListener extends AbstractPropertyListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_favorite_remove_title,
R.string.cache_dialog_favorite_remove_message,
DetailsViewCreator.this::favoriteRemove);
}
}
/**
* Show/hide buttons, set text in watchlist box
*/
private void updateWatchlistBox(final CacheDetailActivity activity) {
final boolean supportsWatchList = cache.supportsWatchList();
binding.watchlistBox.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE);
if (!supportsWatchList) {
return;
}
final int watchListCount = cache.getWatchlistCount();
if (cache.isOnWatchlist() || cache.isOwner()) {
binding.addToWatchlist.setVisibility(View.GONE);
binding.removeFromWatchlist.setVisibility(View.VISIBLE);
if (watchListCount != -1) {
binding.watchlistText.setText(activity.res.getString(R.string.cache_watchlist_on_extra, watchListCount));
} else {
binding.watchlistText.setText(R.string.cache_watchlist_on);
}
} else {
binding.addToWatchlist.setVisibility(View.VISIBLE);
binding.removeFromWatchlist.setVisibility(View.GONE);
if (watchListCount != -1) {
binding.watchlistText.setText(activity.res.getString(R.string.cache_watchlist_not_on_extra, watchListCount));
} else {
binding.watchlistText.setText(R.string.cache_watchlist_not_on);
}
}
// the owner of a cache has it always on his watchlist. Adding causes an error
if (cache.isOwner()) {
binding.addToWatchlist.setEnabled(false);
binding.addToWatchlist.setVisibility(View.GONE);
binding.removeFromWatchlist.setEnabled(false);
binding.removeFromWatchlist.setVisibility(View.GONE);
}
}
/**
* Show/hide buttons, set text in favorite line and box
*/
private void updateFavPointBox() {
// Favorite counts
final int favCount = cache.getFavoritePoints();
if (favCount >= 0 && !cache.isEventCache()) {
favoriteLine.left.setVisibility(View.VISIBLE);
final int findsCount = cache.getFindsCount();
if (findsCount > 0) {
favoriteLine.right.setText(getString(R.string.favorite_count_percent, favCount, (float) (favCount * 100) / findsCount));
} else {
favoriteLine.right.setText(getString(R.string.favorite_count, favCount));
}
} else {
favoriteLine.left.setVisibility(View.GONE);
}
final boolean supportsFavoritePoints = cache.supportsFavoritePoints();
binding.favpointBox.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE);
if (!supportsFavoritePoints) {
return;
}
if (cache.isFavorite()) {
binding.addToFavpoint.setVisibility(View.GONE);
binding.removeFromFavpoint.setVisibility(View.VISIBLE);
binding.favpointText.setText(R.string.cache_favpoint_on);
} else {
binding.addToFavpoint.setVisibility(View.VISIBLE);
binding.removeFromFavpoint.setVisibility(View.GONE);
binding.favpointText.setText(R.string.cache_favpoint_not_on);
}
// Add/remove to Favorites is only possible if the cache has been found
if (!cache.isFound()) {
binding.addToFavpoint.setVisibility(View.GONE);
binding.removeFromFavpoint.setVisibility(View.GONE);
}
}
private void updateWhereYouGoBox(final CacheDetailActivity activity) {
final boolean isEnabled = cache.getType() == CacheType.WHERIGO && StringUtils.isNotEmpty(getWhereIGoUrl(cache));
binding.whereyougoBox.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
binding.whereyougoText.setText(isWhereYouGoInstalled() ? R.string.cache_whereyougo_start : R.string.cache_whereyougo_install);
if (isEnabled) {
binding.sendToWhereyougo.setOnClickListener(v -> {
// re-check installation state, might have changed since creating the view
if (isWhereYouGoInstalled()) {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getWhereIGoUrl(cache)));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
} else {
ProcessUtils.openMarket(activity, getString(R.string.package_whereyougo));
}
});
}
}
private void updateChirpWolfBox(final CacheDetailActivity activity) {
final Intent chirpWolf = ProcessUtils.getLaunchIntent(getString(R.string.package_chirpwolf));
final String compare = CacheAttribute.WIRELESSBEACON.getValue(true);
boolean isEnabled = false;
for (String current : cache.getAttributes()) {
if (StringUtils.equals(current, compare)) {
isEnabled = true;
break;
}
}
binding.chirpBox.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
binding.chirpText.setText(chirpWolf != null ? R.string.cache_chirpwolf_start : R.string.cache_chirpwolf_install);
if (isEnabled) {
binding.sendToChirp.setOnClickListener(v -> {
// re-check installation state, might have changed since creating the view
final Intent chirpWolf2 = ProcessUtils.getLaunchIntent(getString(R.string.package_chirpwolf));
if (chirpWolf2 != null) {
chirpWolf2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(chirpWolf2);
} else {
ProcessUtils.openMarket(activity, getString(R.string.package_chirpwolf));
}
});
}
}
private void updateALCBox(final CacheDetailActivity activity) {
final boolean isEnabled = cache.getType() == CacheType.ADVLAB && StringUtils.isNotEmpty(cache.getUrl());
final Intent alc = ProcessUtils.getLaunchIntent(getString(R.string.package_alc));
binding.alcBox.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
binding.alcText.setText(alc != null ? R.string.cache_alc_start : R.string.cache_alc_install);
if (isEnabled) {
binding.sendToAlc.setOnClickListener(v -> {
// re-check installation state, might have changed since creating the view
if (alc != null) {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(cache.getUrl()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
} else {
ProcessUtils.openMarket(activity, getString(R.string.package_alc));
}
});
}
}
}
/**
* Reflect the (contextual) action mode of the action bar.
*/
protected ActionMode currentActionMode;
public static class DescriptionViewCreator extends TabbedViewPagerFragment<CachedetailDescriptionPageBinding> {
private int maxPersonalNotesChars = 0;
private Geocache cache;
@Override
public CachedetailDescriptionPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailDescriptionPageBinding.inflate(getLayoutInflater(), container, false);
}
@Override
public long getPageId() {
return Page.DESCRIPTION.id;
}
@Override
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"}) // splitting up that method would not help improve readability
public void setContent() {
// retrieve activity and cache - if either of them is null, something's really wrong!
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
// reset description
binding.description.setText("");
// cache short description
if (StringUtils.isNotBlank(cache.getShortDescription())) {
loadDescription(activity, cache.getShortDescription(), false, binding.description, null);
}
// long description
if (StringUtils.isNotBlank(cache.getDescription()) || cache.supportsDescriptionchange()) {
loadLongDescription(activity, container);
}
// extra description
final String geocode = cache.getGeocode();
boolean hasExtraDescription = ALConnector.getInstance().canHandle(geocode); // could be generalized, but currently it's only AL
if (hasExtraDescription) {
final IConnector conn = ConnectorFactory.getConnector(geocode);
if (conn != null) {
binding.extraDescriptionTitle.setText(conn.getName());
binding.extraDescription.setText(conn.getExtraDescription());
} else {
hasExtraDescription = false;
}
}
binding.extraDescriptionBox.setVisibility(hasExtraDescription ? View.VISIBLE : View.GONE);
// cache personal note
setPersonalNote(binding.personalnote, binding.personalnoteButtonSeparator, cache.getPersonalNote());
binding.personalnote.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
activity.addContextMenu(binding.personalnote);
TooltipCompat.setTooltipText(binding.editPersonalnote, getString(R.string.cache_personal_note_edit));
binding.editPersonalnote.setOnClickListener(v -> {
activity.ensureSaved();
editPersonalNote(cache, activity);
});
binding.personalnote.setOnClickListener(v -> {
activity.ensureSaved();
editPersonalNote(cache, activity);
});
TooltipCompat.setTooltipText(binding.storewaypointsPersonalnote, getString(R.string.cache_personal_note_storewaypoints));
binding.storewaypointsPersonalnote.setOnClickListener(v -> {
activity.ensureSaved();
activity.storeWaypointsInPersonalNote(cache, maxPersonalNotesChars);
});
TooltipCompat.setTooltipText(binding.deleteewaypointsPersonalnote, getString(R.string.cache_personal_note_removewaypoints));
binding.deleteewaypointsPersonalnote.setOnClickListener(v -> {
activity.ensureSaved();
activity.removeWaypointsFromPersonalNote(cache);
});
final PersonalNoteCapability connector = ConnectorFactory.getConnectorAs(cache, PersonalNoteCapability.class);
if (connector != null && connector.canAddPersonalNote(cache)) {
maxPersonalNotesChars = connector.getPersonalNoteMaxChars();
binding.uploadPersonalnote.setVisibility(View.VISIBLE);
TooltipCompat.setTooltipText(binding.uploadPersonalnote, getString(R.string.cache_personal_note_upload));
binding.uploadPersonalnote.setOnClickListener(v -> {
if (StringUtils.length(cache.getPersonalNote()) > maxPersonalNotesChars) {
warnPersonalNoteExceedsLimit(activity);
} else {
uploadPersonalNote(activity);
}
});
} else {
binding.uploadPersonalnote.setVisibility(View.GONE);
}
// cache hint and spoiler images
if (StringUtils.isNotBlank(cache.getHint()) || CollectionUtils.isNotEmpty(cache.getSpoilers())) {
binding.hintBox.setVisibility(View.VISIBLE);
} else {
binding.hintBox.setVisibility(View.GONE);
}
if (StringUtils.isNotBlank(cache.getHint())) {
if (TextUtils.containsHtml(cache.getHint())) {
binding.hint.setText(HtmlCompat.fromHtml(cache.getHint(), HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(cache.getGeocode(), false, false, false), null), TextView.BufferType.SPANNABLE);
binding.hint.setText(CryptUtils.rot13((Spannable) binding.hint.getText()));
} else {
binding.hint.setText(CryptUtils.rot13(cache.getHint()));
}
binding.hint.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
binding.hint.setVisibility(View.VISIBLE);
binding.hint.setClickable(true);
binding.hint.setOnClickListener(new DecryptTextClickListener(binding.hint));
binding.hintBox.setOnClickListener(new DecryptTextClickListener(binding.hint));
binding.hintBox.setClickable(true);
activity.addContextMenu(binding.hint);
} else {
binding.hint.setVisibility(View.GONE);
binding.hint.setClickable(false);
binding.hint.setOnClickListener(null);
binding.hintBox.setClickable(false);
binding.hintBox.setOnClickListener(null);
}
if (CollectionUtils.isNotEmpty(cache.getSpoilers())) {
binding.hintSpoilerlink.setVisibility(View.VISIBLE);
binding.hintSpoilerlink.setClickable(true);
binding.hintSpoilerlink.setOnClickListener(arg0 -> {
if (cache == null || CollectionUtils.isEmpty(cache.getSpoilers())) {
activity.showToast(getString(R.string.err_detail_no_spoiler));
return;
}
ImagesActivity.startActivity(activity, cache.getGeocode(), cache.getSpoilers());
});
// if there is only a listing background image without other additional pictures, change the text to better explain the content.
if (cache.getSpoilers().size() == 1 && getString(R.string.cache_image_background).equals(cache.getSpoilers().get(0).title)) {
binding.hintSpoilerlink.setText(R.string.cache_image_background);
} else {
binding.hintSpoilerlink.setText(R.string.cache_menu_spoilers);
}
} else {
binding.hintSpoilerlink.setVisibility(View.GONE);
binding.hintSpoilerlink.setClickable(true);
binding.hintSpoilerlink.setOnClickListener(null);
}
}
private void uploadPersonalNote(final CacheDetailActivity activity) {
final SimpleDisposableHandler myHandler = new SimpleDisposableHandler(activity, activity.progress);
final Message cancelMessage = myHandler.cancelMessage(getString(R.string.cache_personal_note_upload_cancelled));
activity.progress.show(activity, getString(R.string.cache_personal_note_uploading), getString(R.string.cache_personal_note_uploading), true, cancelMessage);
myHandler.add(AndroidRxUtils.networkScheduler.scheduleDirect(() -> {
final PersonalNoteCapability connector = (PersonalNoteCapability) ConnectorFactory.getConnector(cache);
final boolean success = connector.uploadPersonalNote(cache);
final Message msg = Message.obtain();
final Bundle bundle = new Bundle();
bundle.putString(SimpleDisposableHandler.MESSAGE_TEXT,
CgeoApplication.getInstance().getString(success ? R.string.cache_personal_note_upload_done : R.string.cache_personal_note_upload_error));
msg.setData(bundle);
myHandler.sendMessage(msg);
}));
}
private void loadLongDescription(final CacheDetailActivity activity, final ViewGroup parentView) {
binding.loading.setVisibility(View.VISIBLE);
final String longDescription = cache.getDescription();
loadDescription(activity, longDescription, true, binding.description, binding.loading);
if (cache.supportsDescriptionchange()) {
binding.description.setOnClickListener(v -> Dialogs.input(activity, activity.getString(R.string.cache_description_set), cache.getDescription(), "Description", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL | InputType.TYPE_TEXT_FLAG_MULTI_LINE, 5, 10, description -> {
binding.description.setText(description);
cache.setDescription(description);
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
Toast.makeText(activity, R.string.cache_description_updated, Toast.LENGTH_SHORT).show();
}));
}
}
private void warnPersonalNoteExceedsLimit(final CacheDetailActivity activity) {
SimpleDialog.of(activity).setTitle(R.string.cache_personal_note_limit).setMessage(R.string.cache_personal_note_truncation, maxPersonalNotesChars).confirm(
(dialog, which) -> {
dialog.dismiss();
uploadPersonalNote(activity);
});
}
/**
* Load the description in the background.
*
* @param descriptionString
* the HTML description as retrieved from the connector
* @param descriptionView
* the view to fill
* @param loadingIndicatorView
* the loading indicator view, will be hidden when completed
*/
private void loadDescription(final CacheDetailActivity activity, final String descriptionString, final boolean isLongDescription, final IndexOutOfBoundsAvoidingTextView descriptionView, final View loadingIndicatorView) {
try {
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
final Editable description = new SpannableStringBuilder(HtmlCompat.fromHtml(descriptionString, HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(cache.getGeocode(), true, false, descriptionView, false), unknownTagsHandler));
activity.addWarning(unknownTagsHandler, description);
if (StringUtils.isNotBlank(description)) {
fixRelativeLinks(description);
fixTextColor(description, R.color.colorBackground);
// check if short description is contained in long description
boolean longDescriptionContainsShortDescription = false;
final String shortDescription = cache.getShortDescription();
if (StringUtils.isNotBlank(shortDescription)) {
final int index = StringUtils.indexOf(cache.getDescription(), shortDescription);
// allow up to 200 characters of HTML formatting
if (index >= 0 && index < 200) {
longDescriptionContainsShortDescription = true;
}
}
try {
if (descriptionView.getText().length() == 0 || (longDescriptionContainsShortDescription && isLongDescription)) {
descriptionView.setText(description, TextView.BufferType.SPANNABLE);
} else if (!longDescriptionContainsShortDescription) {
descriptionView.append("\n");
descriptionView.append(description);
}
} catch (final Exception e) {
Log.e("Android bug setting text: ", e);
// remove the formatting by converting to a simple string
descriptionView.append(description.toString());
}
descriptionView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
descriptionView.setVisibility(View.VISIBLE);
activity.addContextMenu(descriptionView);
}
if (loadingIndicatorView != null) {
loadingIndicatorView.setVisibility(View.GONE);
}
} catch (final RuntimeException ignored) {
activity.showToast(getString(R.string.err_load_descr_failed));
}
}
private void fixRelativeLinks(final Spannable spannable) {
final String baseUrl = ConnectorFactory.getConnector(cache).getHostUrl() + "/";
final URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
for (final URLSpan span : spans) {
final Uri uri = Uri.parse(span.getURL());
if (uri.getScheme() == null && uri.getHost() == null) {
final int start = spannable.getSpanStart(span);
final int end = spannable.getSpanEnd(span);
final int flags = spannable.getSpanFlags(span);
final Uri absoluteUri = Uri.parse(baseUrl + uri.toString());
spannable.removeSpan(span);
spannable.setSpan(new URLSpan(absoluteUri.toString()), start, end, flags);
}
}
}
}
// If description has an HTML construct which may be problematic to render, add a note at the end of the long description.
// Technically, it may not be a table, but a pre, which has the same problems as a table, so the message is ok even though
// sometimes technically incorrect.
private void addWarning(final UnknownTagsHandler unknownTagsHandler, final Editable description) {
if (unknownTagsHandler.isProblematicDetected()) {
final int startPos = description.length();
final IConnector connector = ConnectorFactory.getConnector(cache);
if (StringUtils.isNotEmpty(cache.getUrl())) {
final Spanned tableNote = HtmlCompat.fromHtml(res.getString(R.string.cache_description_table_note, "<a href=\"" + cache.getUrl() + "\">" + connector.getName() + "</a>"), HtmlCompat.FROM_HTML_MODE_LEGACY);
description.append("\n\n").append(tableNote);
description.setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
private static void fixTextColor(final Spannable spannable, final int backgroundColor) {
final ForegroundColorSpan[] spans = spannable.getSpans(0, spannable.length(), ForegroundColorSpan.class);
for (final ForegroundColorSpan span : spans) {
if (ColorUtils.getContrastRatio(span.getForegroundColor(), backgroundColor) < CONTRAST_THRESHOLD) {
final int start = spannable.getSpanStart(span);
final int end = spannable.getSpanEnd(span);
// Assuming that backgroundColor can be either white or black,
// this will set opposite background color (white for black and black for white)
spannable.setSpan(new BackgroundColorSpan(backgroundColor ^ 0x00ffffff), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
protected void ensureSaved() {
if (!cache.isOffline()) {
showToast(getString(R.string.info_cache_saved));
cache.getLists().add(StoredList.STANDARD_LIST_ID);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... params) {
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
return null;
}
}.execute();
notifyDataSetChanged();
}
}
public static class WaypointsViewCreator extends TabbedViewPagerFragment<CachedetailWaypointsPageBinding> {
private Geocache cache;
private void setClipboardButtonVisibility(final Button createFromClipboard) {
createFromClipboard.setVisibility(Waypoint.hasClipboardWaypoint() >= 0 ? View.VISIBLE : View.GONE);
}
private void addWaypointAndSort(final List<Waypoint> sortedWaypoints, final Waypoint newWaypoint) {
sortedWaypoints.add(newWaypoint);
Collections.sort(sortedWaypoints, cache.getWaypointComparator());
}
private List<Waypoint> createSortedWaypointList() {
final List<Waypoint> sortedWaypoints2 = new ArrayList<>(cache.getWaypoints());
final Iterator<Waypoint> waypointIterator = sortedWaypoints2.iterator();
while (waypointIterator.hasNext()) {
final Waypoint waypointInIterator = waypointIterator.next();
if (waypointInIterator.isVisited() && Settings.getHideVisitedWaypoints()) {
waypointIterator.remove();
}
}
return sortedWaypoints2;
}
@Override
public CachedetailWaypointsPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailWaypointsPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.WAYPOINTS.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
cache = activity.getCache();
if (cache == null) {
return;
}
final ListView v = binding.getRoot();
v.setVisibility(View.VISIBLE);
v.setClickable(true);
// sort waypoints: PP, Sx, FI, OWN
final List<Waypoint> sortedWaypoints = createSortedWaypointList();
Collections.sort(sortedWaypoints, cache.getWaypointComparator());
final ArrayAdapter<Waypoint> adapter = new ArrayAdapter<Waypoint>(activity, R.layout.waypoint_item, sortedWaypoints) {
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
rowView = getLayoutInflater().inflate(R.layout.waypoint_item, parent, false);
rowView.setClickable(true);
rowView.setLongClickable(true);
registerForContextMenu(rowView);
}
WaypointViewHolder holder = (WaypointViewHolder) rowView.getTag();
if (holder == null) {
holder = new WaypointViewHolder(rowView);
}
final Waypoint waypoint = getItem(position);
fillViewHolder(activity, rowView, holder, waypoint);
return rowView;
}
};
v.setAdapter(adapter);
v.setOnScrollListener(new FastScrollListener(v));
//register for changes of variableslist -> calculated waypoints may have changed
cache.getVariables().addChangeListener(this, s -> adapter.notifyDataSetChanged());
if (v.getHeaderViewsCount() < 1) {
final CachedetailWaypointsHeaderBinding headerBinding = CachedetailWaypointsHeaderBinding.inflate(getLayoutInflater(), v, false);
v.addHeaderView(headerBinding.getRoot());
headerBinding.addWaypoint.setOnClickListener(v2 -> {
activity.ensureSaved();
EditWaypointActivity.startActivityAddWaypoint(activity, cache);
activity.refreshOnResume = true;
});
headerBinding.addWaypointCurrentlocation.setOnClickListener(v2 -> {
activity.ensureSaved();
final Waypoint newWaypoint = new Waypoint(Waypoint.getDefaultWaypointName(cache, WaypointType.WAYPOINT), WaypointType.WAYPOINT, true);
newWaypoint.setCoords(Sensors.getInstance().currentGeo().getCoords());
newWaypoint.setGeocode(cache.getGeocode());
if (cache.addOrChangeWaypoint(newWaypoint, true)) {
addWaypointAndSort(sortedWaypoints, newWaypoint);
adapter.notifyDataSetChanged();
activity.reinitializePage(Page.WAYPOINTS.id);
ActivityMixin.showShortToast(activity, getString(R.string.waypoint_added));
}
});
headerBinding.hideVisitedWaypoints.setChecked(Settings.getHideVisitedWaypoints());
headerBinding.hideVisitedWaypoints.setOnCheckedChangeListener((buttonView, isChecked) -> {
Settings.setHideVisitedWaypoints(isChecked);
final List<Waypoint> sortedWaypoints2 = createSortedWaypointList();
Collections.sort(sortedWaypoints2, cache.getWaypointComparator());
adapter.clear();
adapter.addAll(sortedWaypoints2);
adapter.notifyDataSetChanged();
activity.reinitializePage(Page.WAYPOINTS.id);
});
// read waypoint from clipboard
setClipboardButtonVisibility(headerBinding.addWaypointFromclipboard);
headerBinding.addWaypointFromclipboard.setOnClickListener(v2 -> {
final Waypoint oldWaypoint = DataStore.loadWaypoint(Waypoint.hasClipboardWaypoint());
if (null != oldWaypoint) {
activity.ensureSaved();
final Waypoint newWaypoint = cache.duplicateWaypoint(oldWaypoint, cache.getGeocode().equals(oldWaypoint.getGeocode()));
if (null != newWaypoint) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
addWaypointAndSort(sortedWaypoints, newWaypoint);
adapter.notifyDataSetChanged();
activity.reinitializePage(Page.WAYPOINTS.id);
if (oldWaypoint.isUserDefined()) {
SimpleDialog.of((Activity) v.getContext()).setTitle(R.string.cache_waypoints_add_fromclipboard).setMessage(R.string.cache_waypoints_remove_original_waypoint).confirm((dialog, which) -> {
DataStore.deleteWaypoint(oldWaypoint.getId());
ClipboardUtils.clearClipboard();
});
}
}
}
});
final ClipboardManager cliboardManager = (ClipboardManager) activity.getSystemService(CLIPBOARD_SERVICE);
cliboardManager.addPrimaryClipChangedListener(() -> setClipboardButtonVisibility(headerBinding.addWaypointFromclipboard));
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (cache != null && cache.getVariables() != null) {
cache.getVariables().removeChangeListener(this);
}
}
protected void fillViewHolder(final CacheDetailActivity activity, final View rowView, final WaypointViewHolder holder, final Waypoint wpt) {
// coordinates
final TextView coordinatesView = holder.binding.coordinates;
final TextView calculatedCoordinatesView = holder.binding.calculatedCoordinates;
final Geopoint coordinates = wpt.getCoords();
final String calcStateJson = wpt.getCalcStateConfig();
// coordinates
holder.setCoordinate(coordinates);
activity.addContextMenu(coordinatesView);
coordinatesView.setVisibility(null != coordinates ? View.VISIBLE : View.GONE);
calculatedCoordinatesView.setVisibility(null != calcStateJson ? View.VISIBLE : View.GONE);
final CalculatedCoordinate cc = CalculatedCoordinate.createFromConfig(calcStateJson);
calculatedCoordinatesView.setText(cc.isFilled() ? "(x):" + cc.getLatitudePattern() + " | " + cc.getLongitudePattern() : LocalizationUtils.getString(R.string.waypoint_calculated_coordinates));
holder.binding.calculatedCoordinatesIcon.setVisibility(wpt.isCalculated() ? View.VISIBLE : View.GONE);
// info
final String waypointInfo = Formatter.formatWaypointInfo(wpt);
final TextView infoView = holder.binding.info;
if (StringUtils.isNotBlank(waypointInfo)) {
infoView.setText(waypointInfo);
infoView.setVisibility(View.VISIBLE);
} else {
infoView.setVisibility(View.GONE);
}
// title
holder.binding.name.setText(StringUtils.isNotBlank(wpt.getName()) ? StringEscapeUtils.unescapeHtml4(wpt.getName()) : coordinates != null ? coordinates.toString() : getString(R.string.waypoint));
holder.binding.textIcon.setImageDrawable(MapMarkerUtils.getWaypointMarker(activity.res, wpt, false).getDrawable());
// visited
/* @todo
if (wpt.isVisited()) {
final TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.text_color_grey, typedValue, true);
if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT) {
// really should be just a color!
nameView.setTextColor(typedValue.data);
}
}
*/
// note
final TextView noteView = holder.binding.note;
if (StringUtils.isNotBlank(wpt.getNote())) {
noteView.setOnClickListener(new DecryptTextClickListener(noteView));
noteView.setVisibility(View.VISIBLE);
if (TextUtils.containsHtml(wpt.getNote())) {
noteView.setText(HtmlCompat.fromHtml(wpt.getNote(), HtmlCompat.FROM_HTML_MODE_LEGACY, new SmileyImage(cache.getGeocode(), noteView), new UnknownTagsHandler()), TextView.BufferType.SPANNABLE);
} else {
noteView.setText(wpt.getNote());
}
} else {
noteView.setVisibility(View.GONE);
}
// user note
final TextView userNoteView = holder.binding.userNote;
if (StringUtils.isNotBlank(wpt.getUserNote()) && !StringUtils.equals(wpt.getNote(), wpt.getUserNote())) {
userNoteView.setOnClickListener(new DecryptTextClickListener(userNoteView));
userNoteView.setVisibility(View.VISIBLE);
userNoteView.setText(wpt.getUserNote());
} else {
userNoteView.setVisibility(View.GONE);
}
final View wpNavView = holder.binding.wpDefaultNavigation;
wpNavView.setOnClickListener(v -> NavigationAppFactory.startDefaultNavigationApplication(1, activity, wpt));
wpNavView.setOnLongClickListener(v -> {
NavigationAppFactory.startDefaultNavigationApplication(2, activity, wpt);
return true;
});
activity.addContextMenu(rowView);
rowView.setOnClickListener(v -> {
activity.selectedWaypoint = wpt;
activity.ensureSaved();
EditWaypointActivity.startActivityEditWaypoint(activity, cache, wpt.getId());
activity.refreshOnResume = true;
});
rowView.setOnLongClickListener(v -> {
activity.selectedWaypoint = wpt;
activity.openContextMenu(v);
return true;
});
}
}
public static class InventoryViewCreator extends TabbedViewPagerFragment<CachedetailInventoryPageBinding> {
@Override
public CachedetailInventoryPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailInventoryPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.INVENTORY.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
final Geocache cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
// TODO: fix layout, then switch back to Android-resource and delete copied one
// this copy is modified to respect the text color
RecyclerViewProvider.provideRecyclerView(activity, binding.getRoot(), true, true);
cache.mergeInventory(activity.genericTrackables, activity.processedBrands);
final TrackableListAdapter adapterTrackables = new TrackableListAdapter(cache.getInventory(), trackable -> TrackableActivity.startActivity(activity, trackable.getGuid(), trackable.getGeocode(), trackable.getName(), cache.getGeocode(), trackable.getBrand().getId()));
binding.getRoot().setAdapter(adapterTrackables);
cache.mergeInventory(activity.genericTrackables, activity.processedBrands);
}
}
public static class ImagesViewCreator extends TabbedViewPagerFragment<CachedetailImagesPageBinding> {
@Override
public CachedetailImagesPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailImagesPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.IMAGES.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
final Geocache cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
if (activity.imagesList == null) {
activity.imagesList = new ImagesList(activity, cache.getGeocode(), cache);
activity.createDisposables.add(activity.imagesList.loadImages(binding.getRoot(), cache.getNonStaticImages()));
}
}
}
public static class ImageGalleryCreator extends TabbedViewPagerFragment<CachedetailImagegalleryPageBinding> {
@Override
public CachedetailImagegalleryPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailImagegalleryPageBinding.inflate(inflater, container, false);
}
@Override
public long getPageId() {
return Page.IMAGEGALLERY.id;
}
@Override
public void setContent() {
// retrieve activity and cache - if either if this is null, something is really wrong...
final CacheDetailActivity activity = (CacheDetailActivity) getActivity();
if (activity == null) {
return;
}
final Geocache cache = activity.getCache();
if (cache == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
if (activity.imageGallery == null) {
final ImageGalleryView imageGallery = binding.getRoot().findViewById(R.id.image_gallery);
imageGallery.clear();
imageGallery.setup(cache.getGeocode());
imageGallery.setEditableCategory(Image.ImageCategory.OWN.getI18n(),
new ImageGalleryView.FolderCategoryHandler(cache.getGeocode()));
imageGallery.addImages(cache.getNonStaticImages());
activity.imageGallery = imageGallery;
}
}
}
public static void startActivity(final Context context, final String geocode, final String cacheName) {
final Intent cachesIntent = new Intent(context, CacheDetailActivity.class);
cachesIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
cachesIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cachesIntent);
}
private ActionMode mActionMode = null;
private boolean mSelectionModeActive = false;
private IndexOutOfBoundsAvoidingTextView selectedTextView;
private class TextMenuItemClickListener implements MenuItem.OnMenuItemClickListener {
@Override
public boolean onMenuItemClick(final MenuItem menuItem) {
final int startSelection = selectedTextView.getSelectionStart();
final int endSelection = selectedTextView.getSelectionEnd();
clickedItemText = selectedTextView.getText().subSequence(startSelection, endSelection);
return onClipboardItemSelected(mActionMode, menuItem, clickedItemText, cache);
}
}
@Override
public void onSupportActionModeStarted(@NonNull final ActionMode mode) {
if (mSelectionModeActive && selectedTextView != null) {
mSelectionModeActive = false;
mActionMode = mode;
final Menu menu = mode.getMenu();
mode.getMenuInflater().inflate(R.menu.details_context, menu);
menu.findItem(R.id.menu_copy).setVisible(false);
menu.findItem(R.id.menu_cache_share_field).setOnMenuItemClickListener(new TextMenuItemClickListener());
menu.findItem(R.id.menu_translate_to_sys_lang).setOnMenuItemClickListener(new TextMenuItemClickListener());
menu.findItem(R.id.menu_translate_to_english).setOnMenuItemClickListener(new TextMenuItemClickListener());
final MenuItem extWpts = menu.findItem(R.id.menu_extract_waypoints);
extWpts.setVisible(true);
extWpts.setOnMenuItemClickListener(new TextMenuItemClickListener());
buildDetailsContextMenu(mode, menu, res.getString(R.string.cache_description), false);
selectedTextView.setWindowFocusWait(true);
}
super.onSupportActionModeStarted(mode);
}
@Override
public void onSupportActionModeFinished(@NonNull final ActionMode mode) {
mActionMode = null;
if (selectedTextView != null) {
selectedTextView.setWindowFocusWait(false);
}
if (!mSelectionModeActive) {
selectedTextView = null;
}
super.onSupportActionModeFinished(mode);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, @Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (imageGallery != null) {
imageGallery.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void addContextMenu(final View view) {
view.setOnLongClickListener(v -> {
if (view.getId() == R.id.description || view.getId() == R.id.hint) {
selectedTextView = (IndexOutOfBoundsAvoidingTextView) view;
mSelectionModeActive = true;
return false;
}
currentActionMode = startSupportActionMode(new ActionMode.Callback() {
@Override
public boolean onPrepareActionMode(final ActionMode actionMode, final Menu menu) {
return prepareClipboardActionMode(view, actionMode, menu);
}
private boolean prepareClipboardActionMode(final View view1, final ActionMode actionMode, final Menu menu) {
final int viewId = view1.getId();
if (viewId == R.id.value) { // coordinates, gc-code, name
clickedItemText = ((TextView) view1).getText();
final CharSequence itemTitle = ((TextView) ((View) view1.getParent().getParent()).findViewById(R.id.name)).getText();
if (itemTitle.equals(res.getText(R.string.cache_coordinates))) {
clickedItemText = GeopointFormatter.reformatForClipboard(clickedItemText);
}
buildDetailsContextMenu(actionMode, menu, itemTitle, true);
} else if (viewId == R.id.description) {
// combine short and long description
final String shortDesc = cache.getShortDescription();
if (StringUtils.isBlank(shortDesc)) {
clickedItemText = cache.getDescription();
} else {
clickedItemText = shortDesc + "\n\n" + cache.getDescription();
}
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_description), false);
} else if (viewId == R.id.personalnote) {
clickedItemText = cache.getPersonalNote();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_personal_note), true);
} else if (viewId == R.id.hint) {
clickedItemText = cache.getHint();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_hint), false);
} else if (viewId == R.id.log) {
clickedItemText = ((TextView) view1).getText();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_logs), false);
} else if (viewId == R.id.date) { // event date
clickedItemText = Formatter.formatHiddenDate(cache);
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_event), true);
menu.findItem(R.id.menu_calendar).setVisible(cache.canBeAddedToCalendar());
} else if (viewId == R.id.coordinates) {
clickedItemText = ((TextView) view1).getText();
clickedItemText = GeopointFormatter.reformatForClipboard(clickedItemText);
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_coordinates), true);
} else {
return false;
}
return true;
}
@Override
public void onDestroyActionMode(final ActionMode actionMode) {
currentActionMode = null;
}
@Override
public boolean onCreateActionMode(final ActionMode actionMode, final Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.details_context, menu);
prepareClipboardActionMode(view, actionMode, menu);
// Return true so that the action mode is shown
return true;
}
@Override
public boolean onActionItemClicked(final ActionMode actionMode, final MenuItem menuItem) {
// detail fields
if (menuItem.getItemId() == R.id.menu_calendar) {
CalendarAdder.addToCalendar(CacheDetailActivity.this, cache);
actionMode.finish();
return true;
// handle clipboard actions in base
}
return onClipboardItemSelected(actionMode, menuItem, clickedItemText, cache);
}
});
return true;
});
}
public static void startActivityGuid(final Context context, final String guid, final String cacheName) {
final Intent cacheIntent = new Intent(context, CacheDetailActivity.class);
cacheIntent.putExtra(Intents.EXTRA_GUID, guid);
cacheIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cacheIntent);
}
/**
* A dialog to allow the user to select reseting coordinates local/remote/both.
*/
private AlertDialog createResetCacheCoordinatesDialog(final Waypoint wpt) {
final AlertDialog.Builder builder = Dialogs.newBuilder(this);
builder.setTitle(R.string.waypoint_reset_cache_coords);
final String[] items = { res.getString(R.string.waypoint_localy_reset_cache_coords), res.getString(R.string.waypoint_reset_local_and_remote_cache_coords) };
builder.setSingleChoiceItems(items, 0, (dialog, which) -> {
dialog.dismiss();
final ProgressDialog progressDialog = ProgressDialog.show(CacheDetailActivity.this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(CacheDetailActivity.this, progressDialog, which == 1);
resetCoords(cache, handler, wpt, which == 0 || which == 1, which == 1, progressDialog);
});
return builder.create();
}
private static class HandlerResetCoordinates extends WeakReferenceHandler<CacheDetailActivity> {
public static final int LOCAL = 0;
public static final int ON_WEBSITE = 1;
private boolean remoteFinished = false;
private boolean localFinished = false;
private final ProgressDialog progressDialog;
private final boolean resetRemote;
protected HandlerResetCoordinates(final CacheDetailActivity activity, final ProgressDialog progressDialog, final boolean resetRemote) {
super(activity);
this.progressDialog = progressDialog;
this.resetRemote = resetRemote;
}
@Override
public void handleMessage(final Message msg) {
if (msg.what == LOCAL) {
localFinished = true;
} else {
remoteFinished = true;
}
if (localFinished && (remoteFinished || !resetRemote)) {
progressDialog.dismiss();
final CacheDetailActivity activity = getReference();
if (activity != null) {
activity.notifyDataSetChanged();
}
}
}
}
private void resetCoords(final Geocache cache, final Handler handler, final Waypoint wpt, final boolean local, final boolean remote, final ProgressDialog progress) {
AndroidRxUtils.networkScheduler.scheduleDirect(() -> {
if (local) {
runOnUiThread(() -> progress.setMessage(res.getString(R.string.waypoint_reset_cache_coords)));
cache.setCoords(wpt.getCoords());
cache.setUserModifiedCoords(false);
cache.deleteWaypointForce(wpt);
DataStore.saveUserModifiedCoords(cache);
handler.sendEmptyMessage(HandlerResetCoordinates.LOCAL);
}
final IConnector con = ConnectorFactory.getConnector(cache);
if (remote && con.supportsOwnCoordinates()) {
runOnUiThread(() -> progress.setMessage(res.getString(R.string.waypoint_coordinates_being_reset_on_website)));
final boolean result = con.deleteModifiedCoordinates(cache);
runOnUiThread(() -> {
if (result) {
showToast(getString(R.string.waypoint_coordinates_has_been_reset_on_website));
} else {
showToast(getString(R.string.waypoint_coordinates_upload_error));
}
handler.sendEmptyMessage(HandlerResetCoordinates.ON_WEBSITE);
notifyDataSetChanged();
});
}
});
}
@Override
protected String getTitle(final long pageId) {
// show number of waypoints directly in waypoint title
if (pageId == Page.WAYPOINTS.id) {
final int waypointCount = cache == null ? 0 : cache.getWaypoints().size();
return String.format(getString(R.string.waypoints_tabtitle), waypointCount);
} else if (pageId == Page.VARIABLES.id) {
final int varCount = cache == null ? 0 : cache.getVariables().size();
return this.getString(Page.VARIABLES.titleStringId) + " (" + varCount + ")";
} else if (pageId == Page.IMAGEGALLERY.id) {
return this.getString(Page.IMAGEGALLERY.titleStringId) + "*";
}
return this.getString(Page.find(pageId).titleStringId);
}
protected long[] getOrderedPages() {
final ArrayList<Long> pages = new ArrayList<>();
pages.add(Page.VARIABLES.id);
pages.add(Page.WAYPOINTS.id);
pages.add(Page.DETAILS.id);
pages.add(Page.DESCRIPTION.id);
// enforce showing the empty log book if new entries can be added
if (cache != null) {
if (cache.supportsLogging() || !cache.getLogs().isEmpty()) {
pages.add(Page.LOGS.id);
}
if (CollectionUtils.isNotEmpty(cache.getFriendsLogs()) && Settings.isFriendLogsWanted()) {
pages.add(Page.LOGSFRIENDS.id);
}
if (CollectionUtils.isNotEmpty(cache.getInventory()) || CollectionUtils.isNotEmpty(genericTrackables)) {
pages.add(Page.INVENTORY.id);
}
if (CollectionUtils.isNotEmpty(cache.getNonStaticImages())) {
pages.add(Page.IMAGES.id);
}
}
if (!BranchDetectionHelper.isProductionBuild()) {
pages.add(Page.IMAGEGALLERY.id);
}
final long[] result = new long[pages.size()];
for (int i = 0; i < pages.size(); i++) {
result[i] = pages.get(i);
}
return result;
}
@Override
@SuppressWarnings("rawtypes")
protected TabbedViewPagerFragment createNewFragment(final long pageId) {
if (pageId == Page.DETAILS.id) {
return new DetailsViewCreator();
} else if (pageId == Page.DESCRIPTION.id) {
return new DescriptionViewCreator();
} else if (pageId == Page.LOGS.id) {
return CacheLogsViewCreator.newInstance(true);
} else if (pageId == Page.LOGSFRIENDS.id) {
return CacheLogsViewCreator.newInstance(false);
} else if (pageId == Page.WAYPOINTS.id) {
return new WaypointsViewCreator();
} else if (pageId == Page.INVENTORY.id) {
return new InventoryViewCreator();
} else if (pageId == Page.IMAGES.id) {
return new ImagesViewCreator();
} else if (pageId == Page.IMAGEGALLERY.id) {
return new ImageGalleryCreator();
} else if (pageId == Page.VARIABLES.id) {
return new VariablesViewPageFragment();
}
throw new IllegalStateException(); // cannot happen as long as switch case is enum complete
};
@SuppressLint("SetTextI18n")
static boolean setOfflineHintText(final OnClickListener showHintClickListener, final TextView offlineHintTextView, final String hint, final String personalNote) {
if (null != showHintClickListener) {
final boolean hintGiven = StringUtils.isNotEmpty(hint);
final boolean personalNoteGiven = StringUtils.isNotEmpty(personalNote);
if (hintGiven || personalNoteGiven) {
offlineHintTextView.setText((hintGiven ? hint + (personalNoteGiven ? "\r\n" : "") : "") + (personalNoteGiven ? personalNote : ""));
return true;
}
}
return false;
}
static void updateOfflineBox(final View view, final Geocache cache, final Resources res,
final OnClickListener refreshCacheClickListener,
final OnClickListener dropCacheClickListener,
final OnClickListener storeCacheClickListener,
final OnClickListener showHintClickListener,
final OnLongClickListener moveCacheListener,
final OnLongClickListener storeCachePreselectedListener) {
// offline use
final TextView offlineText = view.findViewById(R.id.offline_text);
final View offlineRefresh = view.findViewById(R.id.offline_refresh);
final View offlineStore = view.findViewById(R.id.offline_store);
final View offlineDrop = view.findViewById(R.id.offline_drop);
final View offlineEdit = view.findViewById(R.id.offline_edit);
// check if hint is available and set onClickListener and hint button visibility accordingly
final boolean hintButtonEnabled = setOfflineHintText(showHintClickListener, view.findViewById(R.id.offline_hint_text), cache.getHint(), cache.getPersonalNote());
final View offlineHint = view.findViewById(R.id.offline_hint);
if (null != offlineHint) {
if (hintButtonEnabled) {
offlineHint.setVisibility(View.VISIBLE);
offlineHint.setClickable(true);
offlineHint.setOnClickListener(showHintClickListener);
} else {
offlineHint.setVisibility(View.GONE);
offlineHint.setClickable(false);
offlineHint.setOnClickListener(null);
}
}
offlineStore.setClickable(true);
offlineStore.setOnClickListener(storeCacheClickListener);
offlineStore.setOnLongClickListener(storeCachePreselectedListener);
offlineDrop.setClickable(true);
offlineDrop.setOnClickListener(dropCacheClickListener);
offlineDrop.setOnLongClickListener(null);
offlineEdit.setOnClickListener(storeCacheClickListener);
if (moveCacheListener != null) {
offlineEdit.setOnLongClickListener(moveCacheListener);
}
offlineRefresh.setVisibility(cache.supportsRefresh() ? View.VISIBLE : View.GONE);
offlineRefresh.setClickable(true);
offlineRefresh.setOnClickListener(refreshCacheClickListener);
if (cache.isOffline()) {
offlineText.setText(Formatter.formatStoredAgo(cache.getDetailedUpdate()));
offlineStore.setVisibility(View.GONE);
offlineDrop.setVisibility(View.VISIBLE);
offlineEdit.setVisibility(View.VISIBLE);
} else {
offlineText.setText(res.getString(R.string.cache_offline_not_ready));
offlineStore.setVisibility(View.VISIBLE);
offlineDrop.setVisibility(View.GONE);
offlineEdit.setVisibility(View.GONE);
}
}
static void updateCacheLists(final View view, final Geocache cache, final Resources res) {
final SpannableStringBuilder builder = new SpannableStringBuilder();
for (final Integer listId : cache.getLists()) {
if (builder.length() > 0) {
builder.append(", ");
}
appendClickableList(builder, view, listId);
}
builder.insert(0, res.getString(R.string.list_list_headline) + " ");
final TextView offlineLists = view.findViewById(R.id.offline_lists);
offlineLists.setText(builder);
offlineLists.setMovementMethod(LinkMovementMethod.getInstance());
}
static void appendClickableList(final SpannableStringBuilder builder, final View view, final Integer listId) {
final int start = builder.length();
builder.append(DataStore.getList(listId).getTitle());
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull final View widget) {
Settings.setLastDisplayedList(listId);
CacheListActivity.startActivityOffline(view.getContext());
}
}, start, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
public Geocache getCache() {
return cache;
}
private static class StoreCacheHandler extends SimpleDisposableHandler {
StoreCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_LOAD_PROGRESS_DETAIL && msg.obj instanceof String) {
updateStatusMsg(R.string.cache_dialog_offline_save_message, (String) msg.obj);
} else {
notifyDataSetChanged(activityRef);
}
}
}
private static final class RefreshCacheHandler extends SimpleDisposableHandler {
RefreshCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_LOAD_PROGRESS_DETAIL && msg.obj instanceof String) {
updateStatusMsg(R.string.cache_dialog_refresh_message, (String) msg.obj);
} else if (msg.what == UPDATE_SHOW_STATUS_TOAST && msg.obj instanceof String) {
showToast((String) msg.obj);
} else {
notifyDataSetChanged(activityRef);
}
}
}
private static final class ChangeNotificationHandler extends SimpleHandler {
ChangeNotificationHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleMessage(final Message msg) {
notifyDataSetChanged(activityRef);
}
}
private static void notifyDataSetChanged(final WeakReference<AbstractActivity> activityRef) {
final CacheDetailActivity activity = (CacheDetailActivity) activityRef.get();
if (activity != null) {
activity.notifyDataSetChanged();
}
}
protected void storeCache(final Set<Integer> listIds) {
final StoreCacheHandler storeCacheHandler = new StoreCacheHandler(CacheDetailActivity.this, progress);
progress.show(this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.disposeMessage());
AndroidRxUtils.networkScheduler.scheduleDirect(() -> cache.store(listIds, storeCacheHandler));
}
public static void editPersonalNote(final Geocache cache, final CacheDetailActivity activity) {
final FragmentManager fm = activity.getSupportFragmentManager();
final EditNoteDialog dialog = EditNoteDialog.newInstance(cache.getPersonalNote(), cache.isPreventWaypointsFromNote());
dialog.show(fm, "fragment_edit_note");
}
@Override
public void onFinishEditNoteDialog(final String note, final boolean preventWaypointsFromNote) {
setNewPersonalNote(note, preventWaypointsFromNote);
}
public void removeWaypointsFromPersonalNote(final Geocache cache) {
final String note = cache.getPersonalNote() == null ? "" : cache.getPersonalNote();
final String newNote = WaypointParser.removeParseableWaypointsFromText(note);
if (newNote != null) {
setNewPersonalNote(newNote);
}
showShortToast(note.equals(newNote) ? R.string.cache_personal_note_removewaypoints_nowaypoints : R.string.cache_personal_note_removedwaypoints);
}
public void storeWaypointsInPersonalNote(final Geocache cache, final int maxPersonalNotesChars) {
final String note = cache.getPersonalNote() == null ? "" : cache.getPersonalNote();
//only user modified waypoints
final List<Waypoint> userModifiedWaypoints = new ArrayList<>();
for (Waypoint w : cache.getWaypoints()) {
if (w.isUserModified()) {
userModifiedWaypoints.add(w);
}
}
if (userModifiedWaypoints.isEmpty()) {
showShortToast(getString(R.string.cache_personal_note_storewaypoints_nowaypoints));
return;
}
//if given maxSize is obviously bogus, then make length unlimited
final int maxSize = maxPersonalNotesChars == 0 ? -1 : maxPersonalNotesChars;
final String newNote = WaypointParser.putParseableWaypointsInText(note, userModifiedWaypoints, cache.getVariables(), maxSize);
if (newNote != null) {
setNewPersonalNote(newNote);
final String newNoteNonShorted = WaypointParser.putParseableWaypointsInText(note, userModifiedWaypoints, cache.getVariables(), -1);
if (newNoteNonShorted.length() > newNote.length()) {
showShortToast(getString(R.string.cache_personal_note_storewaypoints_success_limited, maxSize));
} else {
showShortToast(getString(R.string.cache_personal_note_storewaypoints_success));
}
} else {
showShortToast(getString(R.string.cache_personal_note_storewaypoints_failed, maxSize));
}
}
private void setNewPersonalNote(final String newNote) {
setNewPersonalNote(newNote, cache.isPreventWaypointsFromNote());
}
/**
* Internal method to set new personal note and update all corresponding entities (DB, dialogs etc)
*
* @param newNote new note to set
* @param newPreventWaypointsFromNote new preventWaypointsFromNote flag to set
*/
private void setNewPersonalNote(final String newNote, final boolean newPreventWaypointsFromNote) {
cache.setPersonalNote(newNote);
cache.setPreventWaypointsFromNote(newPreventWaypointsFromNote);
if (cache.addWaypointsFromNote()) {
reinitializePage(Page.WAYPOINTS.id);
/* @todo mb Does above line work?
final PageViewCreator wpViewCreator = getViewCreator(Page.WAYPOINTS);
if (wpViewCreator != null) {
wpViewCreator.notifyDataSetChanged();
}
*/
}
setMenuPreventWaypointsFromNote(cache.isPreventWaypointsFromNote());
final TextView personalNoteView = findViewById(R.id.personalnote);
final View separator = findViewById(R.id.personalnote_button_separator);
if (personalNoteView != null) {
setPersonalNote(personalNoteView, separator, newNote);
} else {
reinitializePage(Page.DESCRIPTION.id);
}
Schedulers.io().scheduleDirect(() -> DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)));
}
private static void setPersonalNote(final TextView personalNoteView, final View separator, final String personalNote) {
personalNoteView.setText(personalNote, TextView.BufferType.SPANNABLE);
if (StringUtils.isNotBlank(personalNote)) {
personalNoteView.setVisibility(View.VISIBLE);
separator.setVisibility(View.VISIBLE);
Linkify.addLinks(personalNoteView, Linkify.MAP_ADDRESSES | Linkify.WEB_URLS);
} else {
personalNoteView.setVisibility(View.GONE);
separator.setVisibility(View.GONE);
}
}
@Override
public void navigateTo() {
startDefaultNavigation();
}
@Override
public void showNavigationMenu() {
NavigationAppFactory.showNavigationMenu(this, cache, null, null);
}
@Override
public void cachesAround() {
CacheListActivity.startActivityCoordinates(this, cache.getCoords(), cache.getName());
}
public void setNeedsRefresh() {
refreshOnResume = true;
}
}
|
package com.sunteam.ebook.view;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import com.sunteam.ebook.R;
import com.sunteam.ebook.entity.ReadMode;
import com.sunteam.ebook.entity.ReverseInfo;
import com.sunteam.ebook.entity.SplitInfo;
import com.sunteam.ebook.util.CodeTableUtils;
import com.sunteam.ebook.util.PublicUtils;
import com.sunteam.ebook.util.TTSUtils;
import com.sunteam.ebook.util.WordExplainUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
/**
* Txt
*
* @author wzp
*
*/
public class TextReaderView extends View implements OnGestureListener, OnDoubleTapListener
{
private static final String TAG = "TextReaderView";
private static final float MARGIN_WIDTH = 0;
private static final float MARGIN_HEIGHT = 0;
private static final String CHARSET_NAME = "GB18030";//GB18030
private Context mContext = null;
private Bitmap mCurPageBitmap = null;
private Canvas mCurPageCanvas = null;
private Paint mPaint = null;
private float mLineSpace = 3.6f;
private float mTextSize = 20.0f;
private int mTextColor = Color.WHITE;
private int mBkColor = Color.BLACK;
private int mReverseColor = Color.RED;
private int mLineCount = 0;
private int mWidth = 0;
private int mHeight = 0;
private float mVisibleWidth;
private float mVisibleHeight;
private boolean mIsFirstPage = false;
private boolean mIsLastPage = false;
private ArrayList<SplitInfo> mSplitInfoList = new ArrayList<SplitInfo>();
private byte[] mMbBuf = null;
private int mLineNumber = 0;
private int mMbBufLen = 0;
private int mCurPage = 1;
private GestureDetector mGestureDetector = null;
private OnPageFlingListener mOnPageFlingListener = null;
private ReadMode mReadMode = ReadMode.READ_MODE_WORD;
private ReverseInfo mReverseInfo = new ReverseInfo();
private WordExplainUtils mWordExplainUtils = new WordExplainUtils();
private HashMap<Character, ArrayList<String> > mMapWordExplain = new HashMap<Character, ArrayList<String>>();
private int mCurReadExplainIndex = 0;
public interface OnPageFlingListener
{
public void onLoadCompleted( int pageCount, int curPage );
public void onPageFlingToTop();
public void onPageFlingToBottom();
public void onPageFlingCompleted( int curPage );
}
public TextReaderView(Context context)
{
super(context);
mContext = context;
mGestureDetector = new GestureDetector( context, this );
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextAlign(Align.LEFT);
}
public TextReaderView(Context context, AttributeSet attrs)
{
super(context, attrs);
initReaderView( context );
}
public TextReaderView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
initReaderView( context );
}
private void initReaderView( Context context )
{
mContext = context;
mGestureDetector = new GestureDetector( context, this );
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextAlign(Align.LEFT);
final float scale = context.getResources().getDisplayMetrics().density/0.75f; //ldpi
mLineSpace *= scale;
mTextSize *= scale;
mWordExplainUtils.init(mContext);
}
public void setOnPageFlingListener( OnPageFlingListener listener )
{
mOnPageFlingListener = listener;
}
public void setReadMode( ReadMode rm )
{
mReadMode = rm;
}
@Override
public void setBackgroundColor( int color )
{
mBkColor = color;
}
public void setTextColor( int color )
{
mTextColor = color;
}
public void setReverseColor( int color )
{
mReverseColor = color;
}
public void setTextSize( float size )
{
mTextSize = size;
}
public void setSpaceSize( int size )
{
mLineSpace = size;
}
public int getBackgroundColor()
{
return mBkColor;
}
public int getTextColor()
{
return mTextColor;
}
public int getReverseColor()
{
return mReverseColor;
}
public float getTextSize()
{
return mTextSize;
}
public float getSpaceSize()
{
return mLineSpace;
}
public int getLineCount()
{
return mLineCount;
}
public boolean isFirstPage()
{
return mIsFirstPage;
}
public boolean isLastPage()
{
return mIsLastPage;
}
public String getFirstLineText()
{
return getLineText(mLineNumber);
}
private String getLineText( final int lineNumber )
{
int size = mSplitInfoList.size();
if( lineNumber >= 0 && lineNumber < size )
{
SplitInfo li = mSplitInfoList.get(lineNumber);
try
{
String str = new String(mMbBuf, li.startPos, li.len, CHARSET_NAME);
if( str != null )
{
str = str.replaceAll("\n", "");
str = str.replaceAll("\r", "");
return str;
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
return "";
}
/**
*
* @param buffer
* buffer
* @param charsetName
*
* @param lineNumber
* ()
*
*/
public void openBook(byte[] buffer, String charsetName, int lineNumber)
{
if( CHARSET_NAME.equalsIgnoreCase(charsetName) )
{
mMbBuf = buffer;
}
else
{
byte[] gb18030 = null;
try
{
gb18030 = new String(buffer, charsetName).getBytes(CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
//gb18030BOMgb18030BOM0x84 0x31 0x95 0x33BOM
if( ( gb18030.length >= 4 ) && ( -124 == gb18030[0] ) && ( 49 == gb18030[1] ) && ( -107 == gb18030[2] ) && ( 51 == gb18030[3] ) )
{
mMbBuf = new byte[gb18030.length-4];
for( int i = 0; i < mMbBuf.length; i++ )
{
mMbBuf[i] = gb18030[i+4];
}
}
else
{
mMbBuf = gb18030;
}
}
mMbBufLen = (int)mMbBuf.length;
mLineNumber = lineNumber;
}
/**
*
*
* @param startPos
*
* @return int
*/
private int getNextParagraphLength( final int startPos )
{
int i = startPos;
byte b0, b1;
if( CHARSET_NAME.equals("utf-16le") )
{
while( i < mMbBufLen - 1 )
{
b0 = mMbBuf[i++];
b1 = mMbBuf[i++];
if( b0 == 0x0a && b1 == 0x00 )
{
break;
}
}
}
else if( CHARSET_NAME.equals("utf-16be") )
{
while( i < mMbBufLen - 1 )
{
b0 = mMbBuf[i++];
b1 = mMbBuf[i++];
if( b0 == 0x00 && b1 == 0x0a )
{
break;
}
}
}
else
{
while( i < mMbBufLen )
{
b0 = mMbBuf[i++];
if( b0 == 0x0a )
{
break;
}
}
}
int len = i - startPos;
return len;
}
private void divideLines()
{
mPaint.setTextSize(mTextSize);
mPaint.setTypeface(Typeface.MONOSPACE);
float asciiWidth = mPaint.measureText(" "); //ascii
int startPos = 0;
while( startPos < mMbBufLen )
{
int len = getNextParagraphLength(startPos);
if( len <= 0 )
{
break;
}
else if( 1 == len )
{
if( 0x0a == mMbBuf[startPos+len-1] )
{
SplitInfo li = new SplitInfo(startPos, len);
mSplitInfoList.add(li);
startPos += len;
continue;
}
}
else if( 2 == len )
{
if( 0x0d == mMbBuf[startPos+len-2] && 0x0a == mMbBuf[startPos+len-1] )
{
SplitInfo li = new SplitInfo(startPos, len);
mSplitInfoList.add(li);
startPos += len;
continue;
}
}
byte[] buffer = new byte[len];
for( int i = 0; i < len; i++ )
{
buffer[i] = mMbBuf[startPos+i];
}
int textWidth = 0;
int start = startPos;
int home = 0;
int i = 0;
for( i = 0; i < buffer.length; i++ )
{
if( 0x0d == buffer[i] || 0x0a == buffer[i] )
{
continue;
}
if( buffer[i] < 0x80 && buffer[i] >= 0x0 ) //ascii
{
textWidth += ((int)asciiWidth);
if( textWidth >= mVisibleWidth )
{
int length = i-home;
SplitInfo li = new SplitInfo(start, length);
mSplitInfoList.add(li);
start += length;
home = i;
i
textWidth = 0;
continue;
}
}
else
{
textWidth += (int)mTextSize;
if( textWidth >= mVisibleWidth )
{
int length = i-home;
SplitInfo li = new SplitInfo(start, length);
mSplitInfoList.add(li);
start += length;
home = i;
i
textWidth = 0;
continue;
}
i++;
}
}
if( textWidth > 0 )
{
int length = i-home;
SplitInfo li = new SplitInfo(start, length);
mSplitInfoList.add(li);
start += length;
textWidth = 0;
}
startPos += len;
}
mCurPage = mLineNumber / mLineCount + 1;
}
public int getPageCount()
{
return ( mSplitInfoList.size() + mLineCount - 1 ) / mLineCount;
}
public boolean nextLine()
{
if( mLineNumber+mLineCount >= mSplitInfoList.size() )
{
mIsLastPage = true;
return false;
}
else
{
mIsLastPage = false;
}
mLineNumber++;
mCurPage = mLineNumber / mLineCount + 1;
return true;
}
public boolean preLine()
{
if( mLineNumber <= 0 )
{
mLineNumber = 0;
mIsFirstPage = true;
return false;
}
else
{
mIsFirstPage = false;
}
mLineNumber
mCurPage = mLineNumber / mLineCount + 1;
return true;
}
public boolean nextPage()
{
if( mLineNumber+mLineCount >= mSplitInfoList.size() )
{
mIsLastPage = true;
return false;
}
else
{
mIsLastPage = false;
}
mLineNumber += mLineCount;
mCurPage++;
return true;
}
public boolean prePage()
{
if( mLineNumber <= 0 )
{
mLineNumber = 0;
mIsFirstPage = true;
return false;
}
else
{
mIsFirstPage = false;
}
mLineNumber -= mLineCount;
if( mLineNumber < 0 )
{
mLineNumber = 0;
}
mCurPage
return true;
}
private void init(Context context)
{
mWidth = getWidth();
mHeight = getHeight();
mVisibleWidth = mWidth - MARGIN_WIDTH * 2;
mVisibleHeight = mHeight - MARGIN_HEIGHT * 2;
mLineCount = (int)( mVisibleHeight / (mTextSize+mLineSpace ) );
if( null == mCurPageBitmap )
{
mCurPageBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
}
if( null == mCurPageCanvas )
{
mCurPageCanvas = new Canvas(mCurPageBitmap);
}
if( 0 == mSplitInfoList.size() )
{
divideLines();
initReverseInfo();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onLoadCompleted(getPageCount(), mCurPage);
}
}
}
private void initReverseInfo()
{
switch( mReadMode )
{
case READ_MODE_NIL:
break;
case READ_MODE_ALL:
break;
case READ_MODE_PARAGRAPH:
break;
case READ_MODE_SENTENCE:
break;
case READ_MODE_WORD:
nextReverseWord(true);
break;
default:
break;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height ;
Drawable bgDrawable = this.getBackground();
if (widthMode == MeasureSpec.EXACTLY) //MATCH_PARENT
{
width = widthSize;
}
else //WARP_CONTENT
{
float bgWidth = bgDrawable.getIntrinsicWidth();
int desired = (int) (getPaddingLeft() + bgWidth + getPaddingRight());
width = desired;
}
if (heightMode == MeasureSpec.EXACTLY) //MATCH_PARENT
{
height = heightSize;
}
else //WARP_CONTENT
{
float bgHeight = bgDrawable.getIntrinsicHeight();
int desired = (int) (getPaddingTop() + bgHeight + getPaddingBottom());
height = desired;
}
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
super.onDraw(canvas);
init(mContext);
mCurPageCanvas.drawColor(mBkColor);
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
int size = mSplitInfoList.size();
if( size > 0 )
{
Paint paint = new Paint();
paint.setColor(mReverseColor);
//FontMetrics
FontMetrics fontMetrics = mPaint.getFontMetrics();
/*
//
float baseX = MARGIN_WIDTH;
float baseY = MARGIN_HEIGHT;
float topY = baseY + fontMetrics.top;
float ascentY = baseY + fontMetrics.ascent;
float descentY = baseY + fontMetrics.descent;
float bottomY = baseY + fontMetrics.bottom;
*/
float x = MARGIN_WIDTH;
float y = MARGIN_HEIGHT;
for( int i = mLineNumber, j = 0; i < size && j < mLineCount; i++, j++ )
{
if( mReverseInfo.len > 0 )
{
SplitInfo si = mSplitInfoList.get(i);
if( ( mReverseInfo.startPos >= si.startPos ) && ( mReverseInfo.startPos < si.startPos+si.len ) )
{
float xx = x;
String str = null;
try
{
str = new String(mMbBuf, si.startPos, mReverseInfo.startPos-si.startPos, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( !TextUtils.isEmpty(str) )
{
xx += mPaint.measureText(str);
}
int len = Math.min(mReverseInfo.len, si.startPos+si.len-mReverseInfo.startPos);
try
{
str = new String(mMbBuf, mReverseInfo.startPos, len, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( "\r\n".equals(str) || "\n".equals(str) )
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), getWidth()-MARGIN_WIDTH, y+(fontMetrics.descent-fontMetrics.top) );
mCurPageCanvas.drawRect(rect, paint);
}
else
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), (xx+mPaint.measureText(str)), y+(fontMetrics.descent-fontMetrics.top) );
mCurPageCanvas.drawRect(rect, paint);
}
}
else if( ( mReverseInfo.startPos < si.startPos ) && ( mReverseInfo.startPos+mReverseInfo.len-1 >= si.startPos ) )
{
float xx = x;
String str = null;
int len = Math.min( si.len, mReverseInfo.startPos + mReverseInfo.len - si.startPos );
try
{
str = new String(mMbBuf, si.startPos, len, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( "\r\n".equals(str) || "\n".equals(str) )
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), getWidth()-MARGIN_WIDTH, y+(fontMetrics.descent-fontMetrics.top) );
mCurPageCanvas.drawRect(rect, paint);
}
else
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), (xx+mPaint.measureText(str)), y+(fontMetrics.descent-fontMetrics.top) );
mCurPageCanvas.drawRect(rect, paint);
}
}
}
float baseY = y - fontMetrics.top;
mCurPageCanvas.drawText(getLineText(i), x, baseY, mPaint); //drawTextbaseXbaseY
y += mTextSize;
y += mLineSpace;
}
}
canvas.drawBitmap(mCurPageBitmap, 0, 0, null);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
return mGestureDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e)
{
// TODO Auto-generated method stub
return true;
}
@Override
public void onShowPress(MotionEvent e)
{
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e)
{
//TODO Auto-generated method stub
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPress(MotionEvent e)
{
// TODO Auto-generated method stub
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
// TODO Auto-generated method stub
final int FLING_MIN_DISTANCE_X = getWidth()/3;
final int FLING_MIN_DISTANCE_Y = getHeight()/3;
if( e1.getX() - e2.getX() > FLING_MIN_DISTANCE_X )
{
right();
}
else if( e2.getX() - e1.getX() > FLING_MIN_DISTANCE_X )
{
left();
}
else if( e1.getY() - e2.getY() > FLING_MIN_DISTANCE_Y )
{
down();
}
else if( e2.getY() - e1.getY() > FLING_MIN_DISTANCE_Y )
{
up();
}
return false;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e)
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e)
{
// TODO Auto-generated method stub
enter();
return false;
}
@Override
public boolean onDoubleTapEvent(MotionEvent e)
{
// TODO Auto-generated method stub
return false;
}
public void down()
{
mCurReadExplainIndex = 0;
switch( mReadMode )
{
case READ_MODE_NIL:
if( nextLine() )
{
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
break;
case READ_MODE_ALL:
break;
case READ_MODE_PARAGRAPH:
break;
case READ_MODE_SENTENCE:
break;
case READ_MODE_WORD:
nextReverseWord(false);
break;
default:
break;
}
}
public void up()
{
mCurReadExplainIndex = 0;
switch( mReadMode )
{
case READ_MODE_NIL:
if( preLine() )
{
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
break;
case READ_MODE_ALL:
break;
case READ_MODE_PARAGRAPH:
break;
case READ_MODE_SENTENCE:
break;
case READ_MODE_WORD:
preReverseWord();
break;
default:
break;
}
}
public void left()
{
mCurReadExplainIndex = 0;
switch( mReadMode )
{
case READ_MODE_NIL:
if( prePage() )
{
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
break;
case READ_MODE_ALL:
break;
case READ_MODE_PARAGRAPH:
break;
case READ_MODE_SENTENCE:
break;
case READ_MODE_WORD:
break;
default:
break;
}
}
public void right()
{
mCurReadExplainIndex = 0;
switch( mReadMode )
{
case READ_MODE_NIL:
if( nextPage() )
{
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
break;
case READ_MODE_ALL:
break;
case READ_MODE_PARAGRAPH:
break;
case READ_MODE_SENTENCE:
break;
case READ_MODE_WORD:
break;
default:
break;
}
}
public void enter()
{
if( mReverseInfo.len > 0 )
{
char ch = PublicUtils.byte2char(mMbBuf, mReverseInfo.startPos);
if( ( ch >= 'A' ) && ( ch <= 'Z') )
{
ch += 0x20;
}
ArrayList<String> list = mMapWordExplain.get(ch);
if( ( null == list ) || ( 0 == list.size() ) )
{
byte[] explain = null;
if( mMbBuf[mReverseInfo.startPos] < 0 )
{
explain = mWordExplainUtils.getWordExplain(0, ch);
}
else
{
explain = mWordExplainUtils.getWordExplain(1, ch);
}
if( null == explain )
{
TTSUtils.getInstance().speak(mContext.getString(R.string.no_explain));
return;
}
else
{
String txt = null;
try
{
txt = new String(explain, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( TextUtils.isEmpty(txt) )
{
TTSUtils.getInstance().speak(mContext.getString(R.string.no_explain));
return;
}
else
{
String[] str = txt.split("=");
if( ( null == str ) || ( str.length < 2 ) )
{
TTSUtils.getInstance().speak(mContext.getString(R.string.no_explain));
return;
}
String[] strExplain = str[1].split(" ");
if( ( null == strExplain ) || ( 0 == strExplain.length ) )
{
TTSUtils.getInstance().speak(mContext.getString(R.string.no_explain));
return;
}
ArrayList<String> list2 = new ArrayList<String>();
if( ( ch >= 'a' ) && ( ch <= 'z') )
{
for( int i = 0; i < strExplain.length; i++ )
{
list2.add(strExplain[i]);
}
list2.add(String.format(mContext.getResources().getString(R.string.en_explain_tips), ch-'a'+1));
}
else
{
for( int i = 0; i < strExplain.length; i++ )
{
list2.add(strExplain[i]+mContext.getResources().getString(R.string.cn_explain_tips)+str[0]);
}
}
mMapWordExplain.put(ch, list2);
}
}
}
list = mMapWordExplain.get(ch);
if( ( list != null ) && ( list.size() > 0 ) )
{
TTSUtils.getInstance().speak(list.get(mCurReadExplainIndex));
if( mCurReadExplainIndex == list.size()-1 )
{
mCurReadExplainIndex = 0;
}
else
{
mCurReadExplainIndex++;
}
}
}
}
private void preReverseWord()
{
int start = mReverseInfo.startPos;
if( start == 0 )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
return;
}
ReverseInfo oldReverseInfo = null;
for( int i = 0; i < mMbBufLen; )
{
ReverseInfo ri = getNextReverseWordInfo( i );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
break;
}
else if( ri.startPos + ri.len == mReverseInfo.startPos )
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
else if( ri.startPos >= mReverseInfo.startPos )
{
mReverseInfo.startPos = oldReverseInfo.startPos;
mReverseInfo.len = oldReverseInfo.len;
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
i += ri.len;
oldReverseInfo = ri;
}
}
private void nextReverseWord(boolean isSpeakPage)
{
ReverseInfo ri = getNextReverseWordInfo( mReverseInfo.startPos+mReverseInfo.len );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(isSpeakPage);
recalcLineNumber(Action.NEXT_LINE);
this.invalidate();
}
}
private ReverseInfo getNextReverseWordInfo( int start )
{
if( start == mMbBufLen-1 )
{
return null;
}
for( int i = start; i < mMbBufLen; i++ )
{
if( mMbBuf[i] < 0 )
{
ReverseInfo ri = new ReverseInfo(i, 2);
return ri;
}
else if( mMbBuf[i] >= 0x0 && mMbBuf[i] < 0x20 )
{
if( 0x0d == mMbBuf[i] )
{
if( ( i+1 < mMbBufLen ) && ( 0x0a == mMbBuf[i+1] ) )
{
ReverseInfo ri = new ReverseInfo(i, 2);
return ri;
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
else if( 0x0a == mMbBuf[i] )
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
else
{
continue;
}
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
return null;
}
private ReverseInfo getNextReverseWordInfo1( int start )
{
if( start == mMbBufLen-1 )
{
return null;
}
for( int i = start; i < mMbBufLen; i++ )
{
if( mMbBuf[i] < 0 )
{
ReverseInfo ri = new ReverseInfo(i, 2);
return ri;
}
else if( isEscape( mMbBuf[i]) )
{
continue;
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
return null;
}
private ReverseInfo getNextReverseWordInfo2( int start )
{
if( start == mMbBufLen-1 )
{
return null;
}
for( int i = start; i < mMbBufLen; i++ )
{
if( mMbBuf[i] < 0 )
{
ReverseInfo ri = new ReverseInfo(i, 2);
return ri;
}
else if( isAlpha( mMbBuf[i] ) )
{
ReverseInfo ri = new ReverseInfo(i, 1);
for( int j = i+1; j < mMbBufLen; j++ )
{
if( isAlpha( mMbBuf[j] ) )
{
ri.len++;
}
else
{
break;
}
}
return ri;
}
else if( isNumber( mMbBuf[i] ) )
{
ReverseInfo ri = new ReverseInfo(i, 1);
for( int j = i+1; j < mMbBufLen; j++ )
{
if( isNumber( mMbBuf[j] ) )
{
ri.len++;
}
else
{
break;
}
}
return ri;
}
else if( isEscape( mMbBuf[i]) )
{
continue;
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
return null;
}
private void readReverseText( boolean isSpeakPage )
{
if( mReverseInfo.len <= 0 )
{
if( isSpeakPage )
{
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips), mCurPage, getPageCount() );
TTSUtils.getInstance().speak(tips);
}
return;
}
Locale locale = mContext.getResources().getConfiguration().locale;
String language = locale.getLanguage();
char code = PublicUtils.byte2char(mMbBuf, mReverseInfo.startPos);
String str = null;
if( "en".equalsIgnoreCase(language) )
{
str = CodeTableUtils.getEnString(code);
}
else
{
str = CodeTableUtils.getCnString(code);
}
if( null != str )
{
TTSUtils.getInstance().speak(str);
}
else
{
try
{
String text = new String(mMbBuf, mReverseInfo.startPos, mReverseInfo.len, CHARSET_NAME);
if( isSpeakPage )
{
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips), mCurPage, getPageCount() );
TTSUtils.getInstance().speak(tips+text);
}
else
{
TTSUtils.getInstance().speak(text);
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
private void recalcLineNumber( Action action )
{
if( mReverseInfo.len <= 0 )
{
return;
}
int size = mSplitInfoList.size();
SplitInfo si = null;
switch( action )
{
case NEXT_LINE:
case NEXT_PAGE:
int curPageLine = Math.min( mLineCount, (size-mLineNumber) );
si = mSplitInfoList.get(mLineNumber+curPageLine-1);
if( mReverseInfo.startPos >= si.startPos+si.len )
{
if( Action.NEXT_LINE == action )
{
if( nextLine() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
}
else
{
if( nextPage() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
}
}
break;
case PRE_LINE:
case PRE_PAGE:
si = mSplitInfoList.get(mLineNumber);
if( mReverseInfo.startPos < si.startPos )
{
if( Action.PRE_LINE == action )
{
if( preLine() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
}
else
{
if( prePage() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
}
}
break;
default:
break;
}
}
private boolean isAlpha( byte ch )
{
if( ( ch >= 'a' && ch <= 'z' ) || ( ch >= 'A' && ch <= 'Z' ) )
{
return true;
}
return false;
}
private boolean isNumber( byte ch )
{
//if( ( ch >= '0' && ch <= '9' ) || ( '.' == ch ) )
if( ch >= '0' && ch <= '9' )
{
return true;
}
return false;
}
private boolean isEscape( byte ch )
{
if( 0x07 == ch || 0x08 == ch || 0x09 == ch || 0x0a == ch || 0x0b == ch || 0x0c == ch || 0x0d == ch )
{
return true;
}
return false;
}
private enum Action
{
NEXT_LINE,
NEXT_PAGE,
PRE_LINE,
PRE_PAGE,
}
}
|
package com.rafkind.paintown.animator;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import org.swixml.SwingEngine;
import javax.swing.filechooser.FileFilter;
import com.rafkind.paintown.animator.CharacterStats;
import com.rafkind.paintown.animator.DrawArea;
import com.rafkind.paintown.exception.*;
import com.rafkind.paintown.*;
public final class Player extends CharacterStats
{
private SwingEngine playerEditor;
private SwingEngine contextEditor;
private SwingEngine controlEditor;
private JPanel context;
private JPanel canvas;
private JPanel controls;
private JTextField nameField;
private JSpinner healthSpinner;
private JPanel jumpSpinner;
private JSpinner jumpSpinner2;
private JPanel speedSpinner;
private JSpinner speedSpinner2;
private JSpinner shadowSpinner;
private JTextField deathSoundField;
private JButton deathSoundButton;
private JTextField landingSoundField;
private JButton landingSoundButton;
private JTextField iconField;
private JButton iconButton;
private JTextField origMapField;
private JButton origMapButton;
private JList remapList;
private JButton addRemapButton;
private JButton removeRemapButton;
private JList animList;
private JButton addAnimButton;
private JButton editAnimButton;
private JButton removeAnimButton;
private DrawArea _drawArea;
private JButton displayToken;
private JButton stopAnim;
private JButton playAnim;
private JSpinner speedAnim;
public SpecialPanel getEditor()
{
return new SpecialPanel((JPanel)playerEditor.getRootComponent(), nameField,this);
}
public DrawArea getDrawArea()
{
return _drawArea;
}
public void saveData(File f) throws LoadException
{
setPath(f);
try
{
FileOutputStream out = new FileOutputStream( f );
new PrintStream( out ).print( getToken().toString() );
out.close();
System.out.println( getToken().toString() );
}
catch(Exception e)
{
throw new LoadException( "Couldn't save!" );
}
}
public void loadData(File f) throws LoadException
{
TokenReader reader = new TokenReader( f );
Token head = reader.nextToken();
if ( ! head.getName().equals( "character" ) ){
throw new LoadException( "Starting token is not 'character'" );
}
setPath(f);
Token nameToken = head.findToken( "name" );
if ( nameToken != null )
{
nameField.setText(nameToken.readString(0));
name = nameToken.readString(0);
}
Token healthToken = head.findToken( "health" );
if ( healthToken != null )
{
healthSpinner.setValue(new Integer(healthToken.readInt(0)));
health = healthToken.readInt(0);
}
Token jumpToken = head.findToken( "jump-velocity" );
if ( jumpToken != null )
{
jumpSpinner2.setValue(new Double(jumpToken.readDouble(0)));
jumpVelocity = jumpToken.readDouble(0);
}
Token speedToken = head.findToken( "speed" );
if ( speedToken != null )
{
speedSpinner2.setValue(new Double(speedToken.readDouble(0)));
speed = speedToken.readDouble(0);
}
Token shadowToken = head.findToken( "shadow" );
if ( shadowToken != null )
{
shadowSpinner.setValue(new Integer(shadowToken.readInt(0)));
shadow = shadowToken.readInt(0);
}
Token diesoundToken = head.findToken( "die-sound" );
if ( diesoundToken != null )
{
deathSoundField.setText(diesoundToken.readString(0));
dieSound = diesoundToken.readString(0);
}
Token landedToken = head.findToken( "landed" );
if ( landedToken != null )
{
landingSoundField.setText(landedToken.readString(0));
landed = landedToken.readString(0);
}
Token iconToken = head.findToken( "icon" );
if ( iconToken != null )
{
iconField.setText(iconToken.readString(0));
icon = iconToken.readString(0);
}
for ( Iterator it = head.findTokens( "remap" ).iterator(); it.hasNext(); ){
Token t = (Token) it.next();
origMapField.setText(t.readString( 0 ));
origMap = t.readString(0);
remap.addElement(t.readString(1));
}
remapList.setListData(remap);
for ( Iterator it = head.findTokens( "anim" ).iterator(); it.hasNext(); ){
Token t = (Token) it.next();
CharacterAnimation charanim = new CharacterAnimation();
charanim.loadData(t);
animations.addElement(charanim);
}
animList.setListData(animations);
}
public Token getToken()
{
Token temp = new Token("character");
temp.addToken(new Token("character"));
temp.addToken(new String[]{"name", "\"" + name + "\""});
temp.addToken(new String[]{"health", Integer.toString(health)});
temp.addToken(new String[]{"jump-velocity", Double.toString(jumpVelocity)});
temp.addToken(new String[]{"speed", Double.toString(speed)});
temp.addToken(new String[]{"type", "Player"});
temp.addToken(new String[]{"shadow", Integer.toString(shadow)});
if(!dieSound.equals(""))temp.addToken(new String[]{"die-sound", dieSound});
if(!landed.equals(""))temp.addToken(new String[]{"landed", landed});
if(!icon.equals(""))temp.addToken(new String[]{"icon", icon});
Iterator mapItor = remap.iterator();
while(mapItor.hasNext())
{
String map = (String)mapItor.next();
temp.addToken(new String[]{"remap", origMap, map});
}
Iterator animItor = animations.iterator();
while(animItor.hasNext())
{
CharacterAnimation anim = (CharacterAnimation)animItor.next();
temp.addToken(anim.getToken());
}
return temp;
}
public Player(Animator anim)
{
super( anim );
playerEditor = new SwingEngine( "animator/base.xml" );
contextEditor = new SwingEngine ( "animator/context.xml");
controlEditor = new SwingEngine( "animator/controls.xml" );
//debugSwixml(playerEditor);
//debugSwixml(contextEditor);
context = (JPanel) playerEditor.find( "context" );
canvas = (JPanel) playerEditor.find( "canvas" );
_drawArea = new DrawArea();
canvas.add(_drawArea);
nameField = (JTextField) contextEditor.find( "name" );
nameField.setText(name);
nameField.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
name = nameField.getText();
}
public void insertUpdate(DocumentEvent e)
{
name = nameField.getText();
}
public void removeUpdate(DocumentEvent e)
{
name = nameField.getText();
}
});
healthSpinner = (JSpinner) contextEditor.find( "health" );
healthSpinner.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
health = ((Integer)healthSpinner.getValue()).intValue();
}
});
jumpSpinner = (JPanel) contextEditor.find( "jump-velocity" );
jumpSpinner2 = new JSpinner(new SpinnerNumberModel(0, -1000, 1000, .01));
jumpSpinner2.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
jumpVelocity = ((Double)jumpSpinner2.getValue()).doubleValue();
}
});
jumpSpinner.add(jumpSpinner2);
speedSpinner = (JPanel) contextEditor.find( "speed" );
speedSpinner2 = new JSpinner(new SpinnerNumberModel(0, -1000, 1000, .01));
speedSpinner.add(speedSpinner2);
speedSpinner2.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
speed = ((Double)speedSpinner2.getValue()).doubleValue();
}
});
shadowSpinner = (JSpinner) contextEditor.find( "shadow" );
shadowSpinner.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
shadow = ((Integer)shadowSpinner.getValue()).intValue();
}
});
deathSoundField = (JTextField) contextEditor.find( "die-sound" );
deathSoundButton = (JButton) contextEditor.find( "change-die-sound" );
deathSoundButton.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
RelativeFileChooser chooser = Animator.getNewFileChooser();
int ret = chooser.open();
if ( ret == RelativeFileChooser.OK ){
final String path = chooser.getPath();
deathSoundField.setText( path );
dieSound = path;
}
}
});
landingSoundField = (JTextField) contextEditor.find( "land-sound" );
landingSoundButton = (JButton) contextEditor.find( "change-land-sound" );
landingSoundButton.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
RelativeFileChooser chooser = Animator.getNewFileChooser();
int ret = chooser.open();
if ( ret == RelativeFileChooser.OK ){
final String path = chooser.getPath();
landingSoundField.setText( path );
landed = path;
}
}
});
iconField = (JTextField) contextEditor.find( "icon" );
iconButton = (JButton) contextEditor.find( "change-icon" );
iconButton.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
RelativeFileChooser chooser = Animator.getNewFileChooser();
int ret = chooser.open();
if ( ret == RelativeFileChooser.OK ){
final String path = chooser.getPath();
iconField.setText( path );
icon = path;
}
}
});
origMapField = (JTextField) contextEditor.find( "original-map" );
origMapButton = (JButton) contextEditor.find( "change-origmap" );
origMapButton.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
RelativeFileChooser chooser = Animator.getNewFileChooser();
int ret = chooser.open();
if ( ret == RelativeFileChooser.OK ){
final String path = chooser.getPath();
origMapField.setText( path );
origMap = path;
}
}
});
remapList = (JList) contextEditor.find( "remaps" );
addRemapButton = (JButton) contextEditor.find( "add-remap" );
addRemapButton.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
RelativeFileChooser chooser = Animator.getNewFileChooser();
int ret = chooser.open();
if ( ret == RelativeFileChooser.OK ){
final String path = chooser.getPath();
remap.addElement( path );
remapList.setListData(remap);
}
}
});
removeRemapButton = (JButton) contextEditor.find( "remove-remap" );
removeRemapButton.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
String temp = (String)remap.elementAt(remapList.getSelectedIndex());
removeMap(temp);
remapList.setListData(remap);
}
});
animList = (JList) contextEditor.find( "anims");
animList.addMouseListener( new MouseAdapter()
{
public void mouseClicked(MouseEvent event)
{
//animList.setListData(animations);
if(!animations.isEmpty())
{
_drawArea = ((CharacterAnimation)animList.getSelectedValue()).getDrawArea();
}
}
});
animList.setCellRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
setText(((CharacterAnimation)value).getName());
setBackground(isSelected ? Color.gray : Color.white);
setForeground(isSelected ? Color.white : Color.black);
return this;
}
});
addAnimButton = (JButton) contextEditor.find( "add-anim" );
addAnimButton.addActionListener( new AbstractAction()
{
public void actionPerformed( ActionEvent event )
{
createAnimation();
animList.setListData(animations);
//System.out.println(getToken().toString());
}
});
editAnimButton = (JButton) contextEditor.find( "edit-anim" );
editAnimButton.addActionListener( new AbstractAction()
{
public void actionPerformed( ActionEvent event )
{
editAnimation(animList.getSelectedIndex());
}
});
removeAnimButton = (JButton) contextEditor.find( "remove-anim" );
removeAnimButton.addActionListener( new AbstractAction()
{
public void actionPerformed( ActionEvent event )
{
removeAnimation(animList.getSelectedIndex());
animList.setListData(animations);
}
});
controls = (JPanel) playerEditor.find( "controls" );
displayToken = (JButton) controlEditor.find( "token" );
displayToken.addActionListener( new AbstractAction()
{
public void actionPerformed( ActionEvent event )
{
final JDialog tempDiag = new JDialog();
tempDiag.setSize(400,400);
final JTextArea tempText = new JTextArea();
final JScrollPane tempPane = new JScrollPane(tempText);
tempDiag.add(tempPane);
tempText.setText(getToken().toString());
tempDiag.show();
}
});
context.add((JComponent)contextEditor.getRootComponent());
controls.add((JComponent)controlEditor.getRootComponent());
}
private void debugSwixml( SwingEngine engine ){
Map all = engine.getIdMap();
System.out.println( "Debugging swixml" );
for ( Iterator it = all.entrySet().iterator(); it.hasNext(); ){
Map.Entry entry = (Map.Entry) it.next();
System.out.println( "Id: " + entry.getKey() + " = " + entry.getValue() );
}
}
}
|
package org.eclipse.birt.report.engine.api;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.report.engine.util.FileUtil;
/**
* Default implementation for writing images in a form that is compatible with a
* web browser's "HTML Complete" save option, i.e., writes images to a
* predefined folder.
*
* ImageDirectory: absolute path save the image into that directy, return the
* aboluste URL of that image.
*
* ImageDirectory: null, treat it as "." ImageDirectory: relative relative to
* the base folder.
*
* BaseFolder: parent folder of the output file, save the file into image
* directory and return the relative path (base on the base folder).
*
* BaseFolder:null, use "." as the base folder and return the aboluste path,
*
*
*/
public class HTMLCompleteImageHandler implements IHTMLImageHandler
{
protected Logger log = Logger.getLogger( HTMLCompleteImageHandler.class
.getName( ) );
private static int count = 0;
private static HashMap map = new HashMap( );
/**
* dummy constructor
*/
public HTMLCompleteImageHandler( )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IHTMLImageHandler#onDesignImage(org.eclipse.birt.report.engine.api2.IImage,
* java.lang.Object)
*/
public String onDesignImage( IImage image, Object context )
{
return handleImage( image, context, "design", true ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IHTMLImageHandler#onDocImage(org.eclipse.birt.report.engine.api2.IImage,
* java.lang.Object)
*/
public String onDocImage( IImage image, Object context )
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IHTMLImageHandler#onURLImage(org.eclipse.birt.report.engine.api2.IImage,
* java.lang.Object)
*/
public String onURLImage( IImage image, Object context )
{
assert ( image != null );
return image.getID( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IHTMLImageHandler#onCustomImage(org.eclipse.birt.report.engine.api2.IImage,
* java.lang.Object)
*/
public String onCustomImage( IImage image, Object context )
{
return handleImage( image, context, "custom", false ); //$NON-NLS-1$
}
/**
* creates a unique tempoary file to store an image
*
* @param imageDir
* directory to put image into
* @param prefix
* file name prefix
* @param postfix
* file name postfix
* @return a Java File Object
*/
protected File createUniqueFile( String imageDir, String prefix,
String postfix )
{
assert prefix != null;
if ( postfix == null )
{
postfix = "";
}
File file = null;
do
{
count++;
file = new File( imageDir + "/" + prefix + count + postfix ); //$NON-NLS-1$
} while ( file.exists( ) );
return new File( imageDir, prefix + count + postfix ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IHTMLImageHandler#onFileImage(org.eclipse.birt.report.engine.api2.IImage,
* java.lang.Object)
*/
public String onFileImage( IImage image, Object context )
{
return handleImage( image, context, "file", true ); //$NON-NLS-1$
}
/**
* handles an image report item and returns an image URL
*
* @param image
* represents the image design information
* @param context
* context information
* @param prefix
* image prefix in URL
* @param needMap
* whether image map is needed
* @return URL for the image
*/
protected String handleImage( IImage image, Object context, String prefix,
boolean needMap )
{
String mapID = null;
if ( needMap )
{
mapID = getImageMapID( image );
if ( map.containsKey( mapID ) )
{
return (String) map.get( mapID );
}
}
String imageDirectory = null;
if ( context != null && ( context instanceof HTMLRenderContext ) )
{
HTMLRenderContext myContext = (HTMLRenderContext) context;
imageDirectory = myContext.getImageDirectory( );
}
if ( imageDirectory == null )
{
imageDirectory = ".";
}
String outputFile = (String) image.getRenderOption( )
.getOutputSetting( ).get( RenderOptionBase.OUTPUT_FILE_NAME );
boolean returnRelativePath = needRelativePath( outputFile,
imageDirectory );
String imageOutputDirectory = getImageOutputDirectory( outputFile,
imageDirectory );
File file = saveImage( image, prefix, imageOutputDirectory );
String outputPath = getOutputPath( returnRelativePath, imageDirectory,
file );
if ( needMap )
{
map.put( mapID, outputPath );
}
return outputPath;
}
private File saveImage( IImage image, String prefix,
String imageOutputDirectory )
{
File file;
synchronized ( HTMLCompleteImageHandler.class )
{
file = createUniqueFile( imageOutputDirectory, prefix, image
.getExtension( ) );
try
{
image.writeImage( file );
}
catch ( IOException e )
{
log.log( Level.SEVERE, e.getMessage( ), e );
}
}
return file;
}
private String getTempFile( )
{
return new File( "." ).getAbsolutePath( );
}
private boolean needRelativePath( String reportOutputFile,
String imageDirectory )
{
if ( reportOutputFile == null )
{
return false;
}
if ( !FileUtil.isRelativePath( imageDirectory ) )
{
return false;
}
return true;
}
private String getImageOutputDirectory( String reportOutputFile,
String imageDirectory )
{
if ( !FileUtil.isRelativePath( imageDirectory ) )
{
return imageDirectory;
}
String reportOutputDirectory;
if ( reportOutputFile == null )
{
reportOutputDirectory = getTempFile( );
}
else
{
reportOutputDirectory = new File( reportOutputFile )
.getAbsoluteFile( ).getParent( );
}
return reportOutputDirectory + File.separator + imageDirectory;
}
private String getOutputPath( boolean needRelativePath,
String imageDirectory, File outputFile )
{
String result = null;
if ( needRelativePath )
{
result = imageDirectory + File.separator + outputFile.getName( );
}
else
{
try
{
result = outputFile.toURL( ).toExternalForm( );
}
catch ( Exception ex )
{
result = outputFile.getAbsolutePath( );
}
}
return result;
}
/**
* returns the unique identifier for the image
*
* @param image
* the image object
* @return the image id
*/
protected String getImageMapID( IImage image )
{
if ( image.getReportRunnable( ) != null )
return image.getReportRunnable( ).hashCode( ) + image.getID( );
return image.getID( );
}
}
|
package org.estatio.module.lease.dom.amortisation;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.joda.time.LocalDate;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.query.QueryDefault;
import org.apache.isis.applib.services.message.MessageService;
import org.apache.isis.applib.services.registry.ServiceRegistry2;
import org.apache.isis.applib.services.repository.RepositoryService;
import org.incode.module.country.dom.impl.Country;
import org.estatio.module.charge.dom.Charge;
import org.estatio.module.lease.dom.Frequency;
import org.estatio.module.lease.dom.Lease;
@DomainService(
nature = NatureOfService.DOMAIN,
repositoryFor = AmortisationSchedule.class
)
public class AmortisationScheduleRepository {
@Programmatic
public List<AmortisationSchedule> listAll() {
return repositoryService.allInstances(AmortisationSchedule.class);
}
@Programmatic
public AmortisationSchedule findUnique(final Lease lease, final Charge charge, final LocalDate startDate, final
BigInteger sequence) {
return repositoryService.uniqueMatch(
new QueryDefault<>(
AmortisationSchedule.class,
"findUnique",
"lease", lease,
"charge", charge,
"startDate", startDate,
"sequence", sequence));
}
@Programmatic
public List<AmortisationSchedule> findByLeaseAndChargeAndStartDate(final Lease lease, final Charge charge, final LocalDate startDate) {
return repositoryService.allMatches(
new QueryDefault<>(
AmortisationSchedule.class,
"findByLeaseAndChargeAndStartDate",
"lease", lease,
"charge", charge,
"startDate", startDate));
}
@Programmatic
public List<AmortisationSchedule> findByLease(final Lease lease) {
return repositoryService.allMatches(
new QueryDefault<>(
AmortisationSchedule.class,
"findByLease",
"lease", lease));
}
@Programmatic
public AmortisationSchedule findOrCreate(
final Lease lease,
final Charge charge,
final BigDecimal scheduledAmount,
final Frequency frequency,
final LocalDate startDate,
final LocalDate endDate,
final BigInteger sequence){
final AmortisationSchedule result = findUnique(lease, charge, startDate, sequence);
if (result == null) return create(lease, charge, scheduledAmount, frequency, startDate, endDate, sequence);
return result;
}
public AmortisationSchedule create(
final Lease lease,
final Charge charge,
final BigDecimal scheduledAmount,
final Frequency frequency,
final LocalDate startDate,
final LocalDate endDate,
final BigInteger sequence){
if (scheduledAmount.compareTo(BigDecimal.ZERO)<0){
messageService.raiseError("Scheduled amount cannot be negative");
return null;
}
final AmortisationSchedule newSchedule = new AmortisationSchedule(lease, charge, scheduledAmount, frequency, startDate, endDate, sequence);
serviceRegistry2.injectServicesInto(newSchedule);
repositoryService.persistAndFlush(newSchedule);
return newSchedule;
}
@Programmatic
public List<AmortisationSchedule> findByCountry(final Country country) {
return listAll()
.stream()
.filter(a->a.getLease().getProperty()!=null)
.filter(a->a.getLease().getProperty().getCountry()==country)
.collect(Collectors.toList());
}
@Inject
RepositoryService repositoryService;
@Inject
ServiceRegistry2 serviceRegistry2;
@Inject
MessageService messageService;
}
|
package org.jboss.as.controller;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CancellationException;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.interfaces.InterfaceCriteria;
import org.jboss.as.controller.parsing.Element;
import org.jboss.as.controller.persistence.ConfigurationPersistenceException;
import org.jboss.as.controller.registry.AttributeAccess.Storage;
import org.jboss.as.controller.registry.OperationEntry.Flag;
import org.jboss.as.protocol.mgmt.RequestProcessingException;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageBundle;
import org.jboss.logging.Messages;
import org.jboss.logging.annotations.Param;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartException;
@MessageBundle(projectCode = "JBAS")
public interface ControllerMessages {
/**
* The messages
*/
ControllerMessages MESSAGES = Messages.getBundle(ControllerMessages.class);
/**
* Creates an exception indicating the {@code name} is already defined.
*
* @param name the name that is already defined.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14630, value = "%s already defined")
XMLStreamException alreadyDefined(String name, @Param Location location);
/**
* Creates an exception indicating the {@code value} has already been declared.
*
* @param name the attribute name.
* @param value the value that has already been declared.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14631, value = "%s %s already declared")
XMLStreamException alreadyDeclared(String name, String value, @Param Location location);
/**
* Creates an exception indicating the {@code value} has already been declared.
*
* @param name the attribute name.
* @param value the value that has already been declared.
* @param parentName the name of the parent.
* @param parentValue the parent value.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14632, value = "A %s %s already declared has already been declared in %s %s")
XMLStreamException alreadyDeclared(String name, String value, String parentName, String parentValue, @Param Location location);
/**
* Creates an exception indicating the {@code value} has already been declared.
*
* @param name1 the first attribute name.
* @param name2 the second attribute name.
* @param value the value that has already been declared.
* @param parentName the name of the parent.
* @param parentValue the parent value.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14633, value = "A %s or a %s %s already declared has already been declared in %s %s")
XMLStreamException alreadyDeclared(String name1, String name2, String value, String parentName, String parentValue, @Param Location location);
@Message(id = 14634, value = "An %s named '%s' is already registered at location '%s'")
IllegalArgumentException alreadyRegistered(String type, String name, String location);
@Message(id = 14635, value = "Ambiguous configuration file name '%s' as there are multiple files in %s that end in %s")
IllegalStateException ambiguousConfigurationFiles(String backupType, File searchDir, String suffix);
@Message(id = 14636, value = "Ambiguous name '%s' in %s: %s")
IllegalArgumentException ambiguousName(String prefix, String dir, Collection<String> files);
/**
* Creates an exception indicating a thread was interrupted waiting for a response for asynch operation.
*
* @return a {@link RequestProcessingException} for the error.
*/
@Message(id = 14637, value = "Thread was interrupted waiting for a response for asynch operation")
RequestProcessingException asynchOperationThreadInterrupted();
/**
* Creates an exception indicating no asynch request with the batch id, represented by the {@code batchId}
* parameter.
*
* @param batchId the batch id.
*
* @return a {@link RequestProcessingException} for the error.
*/
@Message(id = 14638, value = "No asynch request with batch id %d")
RequestProcessingException asynchRequestNotFound(int batchId);
/**
* A message indicating the attribute, represented by the {@code attributeName} parameter, is not writable.
*
* @param attributeName the attribute name.
*
* @return the message.
*/
@Message(id = 14639, value = "Attribute %s is not writable")
String attributeNotWritable(String attributeName);
/**
* A message indicating the attribute, represented by the {@code attributeName} parameter, is a registered child of
* the resource.
*
* @param attributeName the name of the attribute.
* @param resource the resource the attribute is a child of.
*
* @return the message.
*/
@Message(id = 14640, value = "'%s' is a registered child of resource (%s)")
String attributeRegisteredOnResource(String attributeName, ModelNode resource);
/**
* Creates an exception indicating the inability to determine a default name based on the local host name.
*
* @param cause the cause of the error.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 14641, value = "Unable to determine a default name based on the local host name")
RuntimeException cannotDetermineDefaultName(@Cause Throwable cause);
@Message(id = 14642, value = "Could not create %s")
IllegalStateException cannotCreate(String path);
@Message(id = 14643, value = "Could not delete %s")
IllegalStateException cannotDelete(File file);
@Message(id = 14644, value = "Cannot register submodels with a null PathElement")
IllegalArgumentException cannotRegisterSubmodelWithNullPath();
@Message(id = 14645, value = "Cannot register non-runtime-only submodels with a runtime-only parent")
IllegalArgumentException cannotRegisterSubmodel();
/**
* Creates an exception indicating the inability to remove the {@code name}.
*
* @param name the name.
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14646, value = "Cannot remove %s")
OperationFailedRuntimeException cannotRemove(String name);
@Message(id = 14647, value = "Could not rename %s to %s")
IllegalStateException cannotRename(String fromPath, String toPath);
@Message(id = 14648, value = "Cannot write to %s")
IllegalArgumentException cannotWriteTo(String name);
/**
* Creates an exception indicating a child, represented by the {@code childName} parameter, of the parent element,
* represented by the {@code parentName} parameter, has already been declared.
*
* @param childName the child element name.
* @param parentName the parent element name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14649, value = "Child %s of element %s already declared")
XMLStreamException childAlreadyDeclared(String childName, String parentName, @Param Location location);
/**
* Creates an exception indicating the canonical file for the boot file could not be found.
*
* @param cause the cause of the error.
* @param file the boot file.
*
* @return an {@link RuntimeException} for the error.
*/
@Message(id = 14650, value = "Could not get canonical file for boot file: %s")
RuntimeException canonicalBootFileNotFound(@Cause Throwable cause, File file);
@Message(id = 14651, value = "Could not get canonical file for main file: %s")
IllegalStateException canonicalMainFileNotFound(@Cause Throwable cause, File file);
/**
* A message indicating the channel is closed.
*
* @return the message.
*/
@Message(id = 14652, value = "Channel closed")
String channelClosed();
/**
* A message indicating the composite operation failed and was rolled back.
*
* @return the message.
*/
@Message(id = 14653, value = "Composite operation failed and was rolled back. Steps that failed:")
String compositeOperationFailed();
/**
* A message indicating the composite operation was rolled back.
*
* @return the message.
*/
@Message(id = 14654, value = "Composite operation was rolled back")
String compositeOperationRolledBack();
@Message(id = 14655, value = "Configuration files whose complete name is %s are not allowed")
IllegalArgumentException configurationFileNameNotAllowed(String backupType);
@Message(id = 14656, value = "No configuration file ending in %s found in %s")
IllegalStateException configurationFileNotFound(String suffix, File dir);
@Message(id = 14657, value = "No directory %s was found")
IllegalArgumentException directoryNotFound(String pathName);
/**
* Creates an exception indicating either the {@code remoteName} or the {@code localName} domain controller
* configuration must be declared.
*
* @param remoteName the remote element name.
* @param localName the local element name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14658, value = "Either a %s or %s domain controller configuration must be declared.")
XMLStreamException domainControllerMustBeDeclared(String remoteName, String localName, @Param Location location);
/**
* Creates an exception indicating an attribute, represented by the {@code name} parameter, has already been
* declared.
*
* @param name the attribute name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14659, value = "An attribute named '%s' has already been declared")
XMLStreamException duplicateAttribute(String name, @Param Location location);
/**
* Creates an exception indicating a duplicate declaration.
*
* @param name the name of the duplicate entry.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14660, value = "Duplicate %s declaration")
XMLStreamException duplicateDeclaration(String name, @Param Location location);
/**
* Creates an exception indicating a duplicate declaration.
*
* @param name the name of the duplicate entry.
* @param value the duplicate entry.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14661, value = "Duplicate %s declaration %s")
XMLStreamException duplicateDeclaration(String name, String value, @Param Location location);
/**
* Creates an exception indicating ad duplicate path element, represented by the {@code name} parameter, was found.
*
* @param name the name of the duplicate entry.
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14662, value = "Duplicate path element '%s' found")
OperationFailedRuntimeException duplicateElement(String name);
/**
* Creates an exception indicating a duplicate interface declaration.
*
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14663, value = "Duplicate interface declaration")
XMLStreamException duplicateInterfaceDeclaration(@Param Location location);
/**
* Creates an exception indicating an element, represented by the {@code name} parameter, has already been
* declared.
*
* @param name the element name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14664, value = "An element of this type named '%s' has already been declared")
XMLStreamException duplicateNamedElement(String name, @Param Location location);
/**
* Creates an exception indicating a duplicate profile was included.
*
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14665, value = "Duplicate profile included")
XMLStreamException duplicateProfile(@Param Location location);
@Message(id = 14666, value = "Duplicate resource %s")
IllegalStateException duplicateResource(String name);
@Message(id = 14667, value = "Duplicate resource type %s")
IllegalStateException duplicateResourceType(String type);
/**
* A message indicating the element, represented by the {@code name} parameter, is not supported the file,
* represented by the {@code file} parameter.
*
* @param name the name of the element.
* @param fileName the file name.
*
* @return the message.
*/
@Message(id = 14668, value = "Element %s is not supported in a %s file")
String elementNotSupported(String name, String fileName);
/**
* A message indicating an error waiting for Tx commit/rollback.
*
* @return the message.
*/
@Message(id = 14669, value = "Error waiting for Tx commit/rollback")
String errorWaitingForTransaction();
/**
* Creates an exception indicating a failure to initialize the module.
*
* @param cause the cause of the error.
* @param name the name of the module.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 14670, value = "Failed initializing module %s")
RuntimeException failedInitializingModule(@Cause Throwable cause, String name);
/**
* A message indicating the failed services.
*
* @return the message.
*/
@Message(id = 14671, value = "Failed services")
String failedServices();
/**
* Creates an exception indicating a failure to backup the file, represented by the {@code file} parameter.
*
* @param cause the cause of the error.
* @param file the file that failed to backup.
*
* @return a {@link ConfigurationPersistenceException} for the error.
*/
@Message(id = 14672, value = "Failed to back up %s")
ConfigurationPersistenceException failedToBackup(@Cause Throwable cause, File file);
/**
* Creates an exception indicating a failure to create backup copies of configuration the file, represented by the
* {@code file} parameter.
*
* @param cause the cause of the error.
* @param file the configuration file that failed to backup.
*
* @return a {@link ConfigurationPersistenceException} for the error.
*/
@Message(id = 14673, value = "Failed to create backup copies of configuration file %s")
ConfigurationPersistenceException failedToCreateConfigurationBackup(@Cause Throwable cause, File file);
/**
* Creates an exception indicating a failure to load a module.
*
* @param cause the cause of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14674, value = "Failed to load module")
XMLStreamException failedToLoadModule(@Cause Throwable cause);
/**
* Creates an exception indicating a failure to load a module.
*
* @param cause the cause of the error.
* @param name the module name.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = Message.INHERIT, value = "Failed to load module %s")
XMLStreamException failedToLoadModule(@Cause Throwable cause, String name);
/**
* Creates an exception indicating a failure to marshal the configuration.
*
* @param cause the cause of the error.
*
* @return a {@link ConfigurationPersistenceException} for the error.
*/
@Message(id = 14675, value = "Failed to marshal configuration")
ConfigurationPersistenceException failedToMarshalConfiguration(@Cause Throwable cause);
/**
* Creates an exception indicating a failure to parse the configuration.
*
* @param cause the cause of the error.
*
* @return a {@link ConfigurationPersistenceException} for the error.
*/
@Message(id = 14676, value = "Failed to parse configuration")
ConfigurationPersistenceException failedToParseConfiguration(@Cause Throwable cause);
/**
* Logs an error message indicating a failure to persist configuration change.
*
* @param cause the cause of the error.
*
* @return the message.
*/
@Message(id = 14677, value = "Failed to persist configuration change: %s")
String failedToPersistConfigurationChange(String cause);
/**
* Creates an exception indicating a failure to store the configuration.
*
* @param cause the cause of the error.
*
* @return a {@link ConfigurationPersistenceException} for the error.
*/
@Message(id = 14678, value = "Failed to store configuration")
ConfigurationPersistenceException failedToStoreConfiguration(@Cause Throwable cause);
/**
* Creates an exception indicating a failure to take a snapshot of the file, represented by the {@code file}
* parameter.
*
* @param cause the cause of the error.
* @param file the file that failed to take the snapshot of.
* @param snapshot the snapshot file.
*
* @return a {@link ConfigurationPersistenceException} for the error.
*/
@Message(id = 14679, value = "Failed to take a snapshot of %s to %s")
ConfigurationPersistenceException failedToTakeSnapshot(@Cause Throwable cause, File file, File snapshot);
/**
* Creates an exception indicating a failure to write the configuration.
*
* @param cause the cause of the error.
*
* @return a {@link ConfigurationPersistenceException} for the error.
*/
@Message(id = 14680, value = "Failed to write configuration")
ConfigurationPersistenceException failedToWriteConfiguration(@Cause Throwable cause);
@Message(id = 14681, value = "%s does not exist")
IllegalArgumentException fileNotFound(String path1);
@Message(id = 14682, value = "No files beginning with '%s' found in %s")
IllegalArgumentException fileNotFoundWithPrefix(String prefix, String dir);
@Message(id = 14683, value = "%s cannot be used except in a full server boot")
IllegalStateException fullServerBootRequired(Class<?> clazz);
/**
* A message indicating that no included group with the name, represented by the {@code name} parameter, was found.
*
* @param name the name of the group.
*
* @return the message.
*/
@Message(id = 14684, value = "No included group with name %s found")
String groupNotFound(String name);
/**
* A message indicating the interface criteria must be of the type represented by the {@code valueType} parameter.
*
* @param invalidType the invalid type.
* @param validType the valid type.
*
* @return the message.
*/
@Message(id = 14685, value = "Illegal interface criteria type %s; must be %s")
String illegalInterfaceCriteria(ModelType invalidType, ModelType validType);
/**
* A message indicating the value, represented by the {@code valueType} parameter, is invalid for the interface
* criteria, represented by the {@code id} parameter.
*
* @param valueType the type of the invalid value.
* @param id the id of the criteria interface.
* @param validType the valid type.
*
* @return the message.
*/
@Message(id = 14686, value = "Illegal value %s for interface criteria %s; must be %s")
String illegalValueForInterfaceCriteria(ModelType valueType, String id, ModelType validType);
/**
* Creates an exception indicating the resource is immutable.
*
* @return an {@link UnsupportedOperationException} for the error.
*/
@Message(id = 14687, value = "Resource is immutable")
UnsupportedOperationException immutableResource();
/**
* An exception indicating the type is invalid.
*
* @param name the name the invalid type was found for.
* @param validTypes a collection of valid types.
* @param invalidType the invalid type.
*
* @return the exception.
*/
@Message(id = 14688, value = "Wrong type for %s. Expected %s but was %s")
OperationFailedException incorrectType(String name, Collection<ModelType> validTypes, ModelType invalidType);
/**
* A message indicating interrupted while waiting for request.
*
* @return the message.
*/
@Message(id = 14689, value = "Interrupted while waiting for request")
String interruptedWaitingForRequest();
/**
* A message indicating the {@code name} is invalid.
*
* @param name the name of the invalid attribute.
*
* @return the message.
*/
@Message(id = 14690, value = "%s is invalid")
String invalid(String name);
/**
* A message indicating the {@code value} is invalid.
*
* @param cause the cause of the error.
* @param value the invalid value.
* @param name the name of the invalid attribute.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14691, value = "%d is not a valid %s")
XMLStreamException invalid(@Cause Throwable cause, int value, String name, @Param Location location);
/**
* A message indicating the address, represented by the {@code address} parameter, is invalid.
*
* @param address the invalid address.
* @param msg the error message.
*
* @return the message.
*/
@Message(id = 14692, value = "Invalid address %s (%s)")
String invalidAddress(String address, String msg);
/**
* A message indicating the value, represented by the {@code value} parameter, is invalid and must be of the form
* address/mask.
*
* @param value the invalid value.
*
* @return the message.
*/
@Message(id = 14693, value = "Invalid 'value' %s -- must be of the form address/mask")
String invalidAddressMaskValue(String value);
/**
* A message indicating the mask, represented by the {@code mask} parameter, is invalid.
*
* @param mask the invalid mask.
* @param msg the error message.
*
* @return the message.
*/
@Message(id = 14694, value = "Invalid mask %s (%s)")
String invalidAddressMask(String mask, String msg);
/**
* A message indicating the address value, represented by the {@code value} parameter, is invalid.
*
* @param value the invalid address value.
* @param msg the error message.
*
* @return the message.
*/
@Message(id = 14695, value = "Invalid address %s (%s)")
String invalidAddressValue(String value, String msg);
/**
* A message indicating the attribute, represented by the {@code attributeName} parameter, is invalid in
* combination with the {@code combos} parameter.
*
* @param attributeName the attribute name.
* @param combos the combinations.
*
* @return the message.
*/
@Message(id = 14696, value = "%s is invalid in combination with %s")
String invalidAttributeCombo(String attributeName, StringBuilder combos);
/**
* Creates an exception indicating an invalid value, represented by the {@code value} parameter, was found for the
* attribute, represented by the {@code name} parameter.
*
* @param value the invalid value.
* @param name the attribute name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14697, value = "Invalid value '%s' for attribute '%s'")
XMLStreamException invalidAttributeValue(String value, QName name, @Param Location location);
/**
* Creates an exception indicating an invalid value, represented by the {@code value} parameter, was found for the
* attribute, represented by the {@code name} parameter. The value must be between the {@code minInclusive} and
* {@code maxInclusive} values.
*
* @param value the invalid value.
* @param name the attribute name.
* @param minInclusive the minimum value allowed.
* @param maxInclusive the maximum value allowed.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14698, value = "Illegal value %d for attribute '%s' must be between %d and %d (inclusive)")
XMLStreamException invalidAttributeValue(int value, QName name, int minInclusive, int maxInclusive, @Param Location location);
/**
* Creates an exception indicating an invalid integer value, represented by the {@code value} parameter, was found
* for the attribute, represented by the {@code name} parameter.
*
* @param cause the cause of the error.
* @param value the invalid value.
* @param name the attribute name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14699, value = "Illegal value '%s' for attribute '%s' must be an integer")
XMLStreamException invalidAttributeValueInt(@Cause Throwable cause, String value, QName name, @Param Location location);
/**
* A message indicating the pattern, represented by the {@code pattern} parameter, for the interface criteria,
* represented by the {@code name} parameter, is invalid.
*
* @param pattern the pattern.
* @param name the interface criteria.
*
* @return the message.
*/
@Message(id = 14700, value = "Invalid pattern %s for interface criteria %s")
String invalidInterfaceCriteriaPattern(String pattern, String name);
/**
* Creates an exception indicating the {@code key} is invalid.
*
* @param element the path element
* @param key the invalid value.
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14701, value = "Invalid resource address element '%s'. The key '%s' is not valid for an element in a resource address.")
String invalidPathElementKey(String element, String key);
@Message(id = 14702, value = "Load factor must be greater than 0 and less than or equal to 1")
IllegalArgumentException invalidLoadFactor();
/**
* A message indicating the {@code value} parameter is invalid and must have a maximum length, represented by the
* {@code length} parameter.
*
* @param value the invalid value.
* @param name the name of the parameter.
* @param length the maximum length.
*
* @return the message.
*/
@Message(id = 14703, value = "'%s' is an invalid value for parameter %s. Values must have a maximum length of %d characters")
String invalidMaxLength(String value, String name, int length);
/**
* A message indicating the {@code value} parameter is invalid and must have a minimum length, represented by the
* {@code length} parameter.
*
* @param value the invalid value.
* @param name the name of the parameter.
* @param length the minimum length.
*
* @return the message.
*/
@Message(id = 14704, value = "'%s' is an invalid value for parameter %s. Values must have a minimum length of %d characters")
String invalidMinLength(String value, String name, int length);
/**
* A message indicating the {@code size} is an invalid size for the parameter, represented by the {@code name}
* parameter.
*
* @param size the invalid size.
* @param name the name of the parameter.
* @param maxSize the maximum size allowed.
*
* @return the message
*/
@Message(id = 14705, value = "[%d] is an invalid size for parameter %s. A maximum length of [%d] is required")
String invalidMaxSize(int size, String name, int maxSize);
/**
* A message indicating the {@code size} is an invalid size for the parameter, represented by the {@code name}
* parameter.
*
* @param size the invalid size.
* @param name the name of the parameter.
* @param minSize the minimum size allowed.
*
* @return the message
*/
@Message(id = 14706, value = "[%d] is an invalid size for parameter %s. A minimum length of [%d] is required")
String invalidMinSize(int size, String name, int minSize);
/**
* A message indicating the {@code value} is invalid for the parameter, represented by the {@code name} parameter.
*
* @param value the invalid value.
* @param name the name of the parameter.
* @param maxValue the minimum value required.
*
* @return the message.
*/
@Message(id = 14707, value = "%d is an invalid value for parameter %s. A maximum value of %d is required")
String invalidMaxValue(int value, String name, int maxValue);
/**
* A message indicating the {@code value} is invalid for the parameter, represented by the {@code name} parameter.
*
* @param value the invalid value.
* @param name the name of the parameter.
* @param maxValue the minimum value required.
*
* @return the message.
*/
String invalidMaxValue(long value, String name, long maxValue);
/**
* A message indicating the {@code value} is invalid for the parameter, represented by the {@code name} parameter.
*
* @param value the invalid value.
* @param name the name of the parameter.
* @param minValue the minimum value required.
*
* @return the message.
*/
@Message(id = 14708, value = "%d is an invalid value for parameter %s. A minimum value of %d is required")
String invalidMinValue(int value, String name, int minValue);
/**
* A message indicating the {@code value} is invalid for the parameter, represented by the {@code name} parameter.
*
* @param value the invalid value.
* @param name the name of the parameter.
* @param minValue the minimum value required.
*
* @return the message.
*/
String invalidMinValue(long value, String name, long minValue);
@Message(id = 14709, value = "Invalid modification after completed step")
IllegalStateException invalidModificationAfterCompletedStep();
/**
* Creates an exception indicating the {@code value} for the attribute, represented by the {@code name} parameter,
* is not a valid multicast address.
*
* @param value the invalid value.
* @param name the name of the attribute.\
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14710, value = "Value %s for attribute %s is not a valid multicast address")
OperationFailedException invalidMulticastAddress(String value, String name);
/**
* Creates an exception indicating an outbound socket binding cannot have both the {@code localTag} and the
* {@code remoteTag}.
*
* @param name the name of the socket binding.
* @param localTag the local tag.
* @param remoteTag the remote tag.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14711, value = "An outbound socket binding: %s cannot have both %s as well as a %s at the same time")
XMLStreamException invalidOutboundSocketBinding(String name, String localTag, String remoteTag, @Param Location location);
@Message(id = 14712, value = "%s is not a valid value for parameter %s -- must be one of %s")
IllegalArgumentException invalidParameterValue(Flag flag, String name, Collection<Flag> validFlags);
/**
* Creates an exception indicating the {@code value} for the attribute, represented by the {@code name} parameter,
* does not represent a properly hex-encoded SHA1 hash.
*
* @param cause the cause of the error.
* @param value the invalid value.
* @param name the name of the attribute.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14713, value = "Value %s for attribute %s does not represent a properly hex-encoded SHA1 hash")
XMLStreamException invalidSha1Value(@Cause Throwable cause, String value, String name, @Param Location location);
@Message(id = 14714, value = "Stage %s is not valid for context process type %s")
IllegalStateException invalidStage(OperationContext.Stage stage, ProcessType processType);
@Message(id = 14715, value = "Invalid step stage specified")
IllegalArgumentException invalidStepStage();
@Message(id = 14716, value = "Invalid step stage for this context type")
IllegalArgumentException invalidStepStageForContext();
@Message(id = 14717, value = "Can not have a negative size table!")
IllegalArgumentException invalidTableSize();
/**
* A message indicating the type, represented by the {@code type} parameter, is invalid.
*
* @param type the invalid type.
*
* @return the message.
*/
@Message(id = 14718, value = "Invalid type %s")
String invalidType(ModelType type);
/**
* Creates an exception indicating the {@code value} is invalid.
*
* @param element the path element
* @param value the invalid value.
* @param character the invalid character
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14719, value = "Invalid resource address element '%s'. The value '%s' is not valid for an element in a resource address. Character '%s' is not allowed.")
String invalidPathElementValue(String element, String value, Character character);
/**
* A message indicating the {@code value} for the parameter, represented by the {@code name} parameter, is invalid.
*
* @param value the invalid value.
* @param name the name of the parameter.
* @param validValues a collection of valid values.
*
* @return the message.
*/
@Message(id = 14720, value = "Invalid value %s for %s; legal values are %s")
String invalidValue(String value, String name, Collection<?> validValues);
/**
* Creates an exception indicating the {@code value} for the {@code name} must be greater than the minimum value,
* represented by the {@code minValue} parameter.
*
* @param name the name for the value that cannot be negative.
* @param value the invalid value.
* @param minValue the minimum value.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14721, value = "Illegal '%s' value %s -- must be greater than %s")
XMLStreamException invalidValueGreaterThan(String name, int value, int minValue, @Param Location location);
/**
* Creates an exception indicating the {@code value} for the {@code name} cannot be negative.
*
* @param name the name for the value that cannot be negative.
* @param value the invalid value.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14722, value = "Illegal '%s' value %s -- cannot be negative")
XMLStreamException invalidValueNegative(String name, int value, @Param Location location);
/**
* Creates an exception indicating there must be one of the elements, represented by the {@code sb} parameter,
* included.
*
* @param sb the acceptable elements.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14723, value = "Must include one of the following elements: %s")
XMLStreamException missingOneOf(StringBuilder sb, @Param Location location);
/**
* Creates an exception indicating there are missing required attribute(s).
*
* @param sb the missing attributes.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14724, value = "Missing required attribute(s): %s")
XMLStreamException missingRequiredAttributes(StringBuilder sb, @Param Location location);
/**
* Creates an exception indicating there are missing required element(s).
*
* @param sb the missing element.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14725, value = "Missing required element(s): %s")
XMLStreamException missingRequiredElements(StringBuilder sb, @Param Location location);
/**
* Creates an exception indicating an interruption awaiting to load the module.
*
* @param name the name of the module.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14726, value = "Interrupted awaiting loading of module %s")
XMLStreamException moduleLoadingInterrupted(String name);
/**
* Creates an exception indicating an interruption awaiting to initialize the module.
*
* @param name the name of the module.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 14727, value = "Interrupted awaiting initialization of module %s")
RuntimeException moduleInitializationInterrupted(String name);
@Message(id = 14728, value = "Model contains multiple %s nodes")
IllegalStateException multipleModelNodes(String name);
/**
* A message indicating a namespace with the prefix, represented by the {@code prefix} parameter, is already
* registered with the schema URI, represented by the {@code uri} parameter.
*
* @param prefix the namespace prefix.
* @param uri the schema URI.
*
* @return the message.
*/
@Message(id = 14729, value = "Namespace with prefix %s already registered with schema URI %s")
String namespaceAlreadyRegistered(String prefix, String uri);
/**
* A message indicating no namespace with the URI {@code prefix}, was found.
*
* @param prefix the prefix.
*
* @return the message.
*/
@Message(id = 14730, value = "No namespace with URI %s found")
String namespaceNotFound(String prefix);
/**
* A message indicating the element, represented by the {@code element} parameter, does not allow nesting.
*
* @param element the element.
*
* @return the message.
*/
@Message(id = 14731, value = "Nested %s not allowed")
String nestedElementNotAllowed(Element element);
/**
* Creates an exception indicating no active request was found for handling the report represented by the {@code id}
* parameter.
*
* @param id the batch id.
*
* @return a {@link RequestProcessingException} for the error.
*/
@Message(id = 14732, value = "No active request found for handling report %d")
RequestProcessingException noActiveRequestForHandlingReport(int id);
/**
* Creates an exception indicating no active request was found for proxy control represented by the {@code id}
* parameter.
*
* @param id the batch id.
*
* @return a {@link RequestProcessingException} for the error.
*/
@Message(id = 14733, value = "No active request found for proxy operation control %d")
RequestProcessingException noActiveRequestForProxyOperation(int id);
/**
* Creates an exception indicating no active request was found for reading the inputstream report represented by
* the {@code id} parameter.
*
* @param id the batch id.
*
* @return a {@link IOException} for the error.
*/
@Message(id = 14734, value = "No active request found for reading inputstream report %d")
IOException noActiveRequestForReadingInputStreamReport(int id);
@Message(id = 14735, value = "No active step")
IllegalStateException noActiveStep();
/**
* Creates an exception indicating no active transaction found for the {@code id}.
*
* @param id the id.
*
* @return a {@link RequestProcessingException} for the error.
*/
@Message(id = 14736, value = "No active tx found for id %d")
RuntimeException noActiveTransaction(int id);
/**
* A message indicating there is no child registry for the child, represented by the {@code childType} and
* {@code child} parameters.
*
* @param childType the child type.
* @param child the child.
*
* @return the message.
*/
@Message(id = 14737, value = "No child registry for (%s, %s)")
String noChildRegistry(String childType, String child);
/**
* Creates an exception indicating no child type for the {@code name}.
*
* @param name the name.
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14738, value = "No child type %s")
OperationFailedRuntimeException noChildType(String name);
/**
* A message indicating no handler for the step operation, represented by the {@code stepOpName} parameter, at
* {@code address}.
*
* @param stepOpName the step operation name.
* @param address the address.
*
* @return the message.
*/
@Message(id = 14739, value = "No handler for %s at address %s")
String noHandler(String stepOpName, PathAddress address);
/**
* A message indicating that no interface criteria was provided.
*
* @return the message.
*/
@Message(id = 14740, value = "No interface criteria was provided")
String noInterfaceCriteria();
/**
* A message indicating there is no operation handler.
*
* @return the message.
*/
@Message(id = 14741, value = "No operation handler")
String noOperationHandler();
@Message(id = 14742, value = "A node is already registered at '%s%s)'")
IllegalArgumentException nodeAlreadyRegistered(String location, String value);
@Message(id = 14743, value = "%s is not a directory")
IllegalStateException notADirectory(String path);
@Message(id = 14744, value = "No %s%s found for %s")
IllegalStateException notFound(String path, String className, ModuleIdentifier id);
@Message(id = 14745, value = "Cannot execute asynchronous operation without an executor")
IllegalStateException nullAsynchronousExecutor();
/**
* An exception indicating the {@code name} may not be {@code null}.
*
* @param name the name that cannot be {@code null}.
*
* @return the exception.
*/
@Message(id = 14746, value = "%s may not be null")
OperationFailedException nullNotAllowed(String name);
@Message(id = 14747, value = "%s is null")
IllegalArgumentException nullVar(String name);
/**
* Creates a message indicating the operation step.
*
* @param step the step.
*
* @return the message.
*/
@Message(id = Message.NONE, value = "Operation %s")
String operation(String step);
@Message(id = 14748, value = "Operation already complete")
IllegalStateException operationAlreadyComplete();
/**
* A message indicating the operation handler failed.
*
* @param msg the failure message.
*
* @return the message.
*/
@Message(id = 14749, value = "Operation handler failed: %s")
String operationHandlerFailed(String msg);
/**
* A message indicating the operation handler failed to complete.
*
* @return the message.
*/
@Message(id = 14750, value = "Operation handler failed to complete")
String operationHandlerFailedToComplete();
/**
* A message indicating the operation is rolling back.
*
* @return the message.
*/
@Message(id = 14751, value = "Operation rolling back")
String operationRollingBack();
/**
* A message indicating the operation succeeded and is committing.
*
* @return the message.
*/
@Message(id = 14752, value = "Operation succeeded, committing")
String operationSucceeded();
/**
* A message indicating there is no operation, represented by the {@code op} parameter, registered at the address,
* represented by the {@code address} parameter.
*
* @param op the operation.
* @param address the address.
*
* @return the message.
*/
@Message(id = 14753, value = "There is no operation %s registered at address %s")
String operationNotRegistered(String op, PathAddress address);
@Message(id = 14754, value = "An operation reply value type description is required but was not implemented for operation %s")
IllegalStateException operationReplyValueTypeRequired(String operationName);
/**
* A message indicating there was a parsing problem.
*
* @param row the row the problem occurred at.
* @param col the column the problem occurred at.
* @param msg a message to concatenate.
*
* @return the message.
*/
@Message(id = 14755, value = "Parsing problem at [row,col]:[%d ,%d]%nMessage: %s")
String parsingProblem(int row, int col, String msg);
/**
* Creates an exception indicating no configuration persister was injected.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 14756, value = "No configuration persister was injected")
StartException persisterNotInjected();
/**
* Creates an exception indicating the thread was interrupted waiting for the operation to prepare/fail.
*
* @return a {@link RequestProcessingException} for the error.
*/
@Message(id = 14757, value = "Thread was interrupted waiting for the operation to prepare/fail")
RequestProcessingException prepareFailThreadInterrupted();
/**
* Creates an exception indicating the profile has no subsystem configurations.
*
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14758, value = "Profile has no subsystem configurations")
XMLStreamException profileHasNoSubsystems(@Param Location location);
/**
* Creates an exception indicating no profile found for inclusion.
*
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14759, value = "No profile found for inclusion")
XMLStreamException profileNotFound(@Param Location location);
@Message(id = 14760, value = "A proxy handler is already registered at location '%s'")
IllegalArgumentException proxyHandlerAlreadyRegistered(String location);
/**
* Creates an exception indicating a thread was interrupted waiting to read attachment input stream from a remote
* caller.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 14761, value = "Thread was interrupted waiting to read attachment input stream from remote caller")
RuntimeException remoteCallerThreadInterrupted();
/**
* A message indicating that removing services has lead to unsatisfied dependencies.
* <p/>
* ** Note: Use with {@link #removingServiceUnsatisfiedDependencies(String)}
*
* @return the message.
*/
@Message(id = 14762, value = "Removing services has lead to unsatisfied dependencies:")
String removingServiceUnsatisfiedDependencies();
/**
* A message indicating that removing services has lead to unsatisfied dependencies.
* <p/>
* ** Note: Use with {@link #removingServiceUnsatisfiedDependencies()}
*
* @param name the name of the service.
*
* @return the message.
*/
@Message(id = Message.NONE, value = "%nService %s was depended upon by ")
String removingServiceUnsatisfiedDependencies(String name);
/**
* A message indicating the {@code name} is required.
*
* @param name the name of the required attribute.
*
* @return the message.
*/
@Message(id = 14763, value = "%s is required")
String required(String name);
/**
* Creates an exception indicating the {@code name} is reserved.
*
* @param name the name that is reserved.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14764, value = "%s is reserved")
XMLStreamException reserved(String name, @Param Location location);
/**
* A message indicating a resource does not exist.
*
* @param resource the resource.
*
* @return the message.
*/
@Message(id = 14765, value = "Resource does not exist: %s")
String resourceNotFound(ModelNode resource);
/**
* Creates an exception indicating a resource does not exist.
*
* @param ancestor the ancestor path.
* @param address the address.
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14766, value = "Resource %s does not exist; a resource at address %s cannot be created until all ancestor resources have been added")
OperationFailedRuntimeException resourceNotFound(PathAddress ancestor, PathAddress address);
@Message(id = 14767, value = "rollback() has already been invoked")
IllegalStateException rollbackAlreadyInvoked();
/**
* A message indicating a schema with URI, represented by the {@code schemaUri} parameter, is already registered
* with the location, represented by the {@code location} parameter.
*
* @param schemaUri the schema URI.
* @param location the location.
*
* @return the message.
*/
@Message(id = 14768, value = "Schema with URI %s already registered with location %s")
String schemaAlreadyRegistered(String schemaUri, String location);
/**
* A message indicating the schema was not found wit the {@code uri}.
*
* @param uri the schema URI.
*
* @return the message.
*/
@Message(id = 14769, value = "No schema location with URI %s found")
String schemaNotFound(String uri);
/**
* Creates an exception indicating the service install was cancelled.
*
* @return a {@link CancellationException} for the error.
*/
@Message(id = 14770, value = "Service install was cancelled")
CancellationException serviceInstallCancelled();
/**
* A message indicating the missing services.
*
* @param sb the missing services.
*
* @return the message.
*/
@Message(id = Message.NONE, value = "is missing [%s]")
String servicesMissing(StringBuilder sb);
/**
* A message that indicates there are services with missing or unavailable dependencies.
*
* @return the message.
*/
@Message(id = 14771, value = "Services with missing/unavailable dependencies")
String servicesMissingDependencies();
@Message(id = 14772, value = "Get service registry only supported in runtime operations")
IllegalStateException serviceRegistryRuntimeOperationsOnly();
@Message(id = 14773, value = "Service removal only supported in runtime operations")
IllegalStateException serviceRemovalRuntimeOperationsOnly();
/**
* A message for the service status report header.
*
* @return the message.
*/
@Message(id = 14774, value = "Service status report%n")
String serviceStatusReportHeader();
/**
* A message for the service status report indicating new missing or unsatisfied dependencies.
*
* @return the message.
*/
@Message(id = 14775, value = " New missing/unsatisfied dependencies:%n")
String serviceStatusReportDependencies();
/**
* A message for the service status report for missing dependencies.
*
* @param serviceName the name of the service
*
* @return the message.
*/
@Message(id = Message.NONE, value = " %s (missing) dependents: %s %n")
String serviceStatusReportMissing(ServiceName serviceName, String dependents);
/**
* A message for the service status report for unavailable dependencies.
*
* @param serviceName the name of the service
*
* @return the message.
*/
@Message(id = Message.NONE, value = " %s (unavailable) dependents: %s %n")
String serviceStatusReportUnavailable(ServiceName serviceName, String dependents);
/**
* A message for the service status report indicating new corrected service.
*
* @return the message.
*/
@Message(id = 14776, value = " Newly corrected services:%n")
String serviceStatusReportCorrected();
/**
* A message for the service status report for no longer required dependencies.
*
* @param serviceName the name of the service
*
* @return the message.
*/
@Message(id = Message.NONE, value = " %s (no longer required)%n")
String serviceStatusReportNoLongerRequired(ServiceName serviceName);
/**
* A message for the service status report for unavailable dependencies.
*
* @param serviceName the name of the service
*
* @return the message.
*/
@Message(id = Message.NONE, value = " %s (new available)%n")
String serviceStatusReportAvailable(ServiceName serviceName);
/**
* A message for the service status report for failed services.
*
* @return the message.
*/
@Message(id = 14777, value = " Services which failed to start:")
String serviceStatusReportFailed();
@Message(id = 14778, value = "Get service target only supported in runtime operations")
IllegalStateException serviceTargetRuntimeOperationsOnly();
@Message(id = 14779, value = "Stage %s is already complete")
IllegalStateException stageAlreadyComplete(OperationContext.Stage stage);
/**
* A message indicating the step handler failed after completion.
*
* @param handler the handler that failed.
*
* @return the message.
*/
@Message(id = 14780, value = "Step handler %s failed after completion")
String stepHandlerFailed(OperationStepHandler handler);
/**
* A message indicating the step handler for the operation failed handling operation rollback.
*
* @param handler the handler that failed.
* @param op the operation.
* @param address the path address.
* @param msg the error message.
*
* @return the message.
*/
@Message(id = 14781, value = "Step handler %s for operation %s at address %s failed handling operation rollback
String stepHandlerFailedRollback(OperationStepHandler handler, String op, PathAddress address, String msg);
/**
* A message indicating an interruption awaiting subsystem boot operation execution.
*
* @return the message.
*/
@Message(id = 14782, value = "Interrupted awaiting subsystem boot operation execution")
String subsystemBootInterrupted();
/**
* A message indicating the boot operations for the subsystem, represented by the {@code name} parameter, failed
* without explanation.
*
* @param name the name of the subsystem.
*
* @return the message.
*/
@Message(id = 14783, value = "Boot operations for subsystem %s failed without explanation")
String subsystemBootOperationFailed(String name);
/**
* A message indicating a failure executing subsystem boot operations.
*
* @return the message.
*/
@Message(id = 14784, value = "Failed executing subsystem %s boot operations")
String subsystemBootOperationFailedExecuting(String name);
@Message(id = 14785, value = "Table is full!")
IllegalStateException tableIsFull();
/**
* Creates an exception indicating an interruption awaiting a transaction commit or rollback.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 14786, value = "Interrupted awaiting transaction commit or rollback")
RuntimeException transactionInterrupted();
/**
* Creates an exception indicating a timeout occurred waiting for the transaction.
*
* @param type the transaction type.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 14787, value = "A timeout occurred waiting for the transaction to %s")
RuntimeException transactionTimeout(String type);
/**
* Creates an exception indicating an unexpected attribute, represented by the {@code name} parameter, was
* encountered.
*
* @param name the unexpected attribute name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14788, value = "Unexpected attribute '%s' encountered")
XMLStreamException unexpectedAttribute(QName name, @Param Location location);
/**
* Creates an exception indicating an unexpected element, represented by the {@code name} parameter, was
* encountered.
*
* @param name the unexpected element name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14789, value = "Unexpected element '%s' encountered")
XMLStreamException unexpectedElement(QName name, @Param Location location);
/**
* Creates an exception indicating an unexpected end of an element, represented by the {@code name} parameter, was
* encountered.
*
* @param name the unexpected element name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14790, value = "Unexpected end of element '%s' encountered")
XMLStreamException unexpectedEndElement(QName name, @Param Location location);
@Message(id = 14791, value = "Unexpected storage %s")
IllegalStateException unexpectedStorage(Storage storage);
/**
* A message indicating the attribute, represented by the {@code name} parameter, is unknown.
*
* @param name the attribute name.
*
* @return the message.
*/
@Message(id = 14792, value = "Unknown attribute %s")
String unknownAttribute(String name);
/**
* A message indicating there is no known child type with the name, represented by the {@code name} parameter.
*
* @param name the name of the child.
*
* @return the message.
*/
@Message(id = 14793, value = "No known child type named %s")
String unknownChildType(String name);
/**
* Creates an exception indicating the property, represented by the {@code name} parameter, is unknown.
*
* @param name the name of the property.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 14794, value = "Unknown property in interface criteria list: %s")
RuntimeException unknownCriteriaInterfaceProperty(String name);
/**
* A message indicating the interface criteria type, represented by the {@code type} parameter, is unknown.
*
* @param type the unknown criteria type.
*
* @return the message.
*/
@Message(id = 14795, value = "Unknown interface criteria type %s")
String unknownCriteriaInterfaceType(String type);
/**
* Creates an exception indicating the interface, represented by the {@code value} attribute, for the attribute,
* represented by the {@code attributeName} parameter, is unknown on in the element.
*
* @param value the value of the attribute.
* @param attributeName the attribute name.
* @param elementName the element name for the attribute.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14796, value = "Unknown interface %s %s must be declared in element %s")
XMLStreamException unknownInterface(String value, String attributeName, String elementName, @Param Location location);
/**
* Creates an exception indicating an unknown {@code elementName1} {@code value} {@code elementName2} must be
* declared in the element represented by the {@code parentElement} parameter.
*
* @param elementName1 the name of the first element.
* @param value the value.
* @param elementName2 the name of the second element.
* @param parentElement the parent element name.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14797, value = "Unknown %s %s %s must be declared in element %s")
XMLStreamException unknownValueForElement(String elementName1, String value, String elementName2, String parentElement, @Param Location location);
/**
* A message indicating the validation failed.
*
* @param name the parameter name the validation failed on.
*
* @return the message.
*/
@Message(id = 14798, value = "Validation failed for %s")
String validationFailed(String name);
/**
* A message indicating that there are more services than would be practical to display
*
* @param number the number of services that were not displayed
*
* @return the message.
*/
@Message(id = 14799, value = "... and %s more")
String andNMore(int number);
@Message(id = 14800, value = "Invalid value '%s' for attribute '%s' -- valid values are %s")
XMLStreamException invalidAttributeValue(String value, QName name, Set<String> validValues, @Param Location location);
@Message(id = 14801, value = "Caught SecurityException attempting to resolve expression '%s'
String noPermissionToResolveExpression(ModelNode toResolve, SecurityException e);
/**
* Creates an exception message indicating an expression could not be resolved due to no corresponding system property
* or environment variable.
*
* @param toResolve the node being resolved
* @param e the SecurityException
* @return an {@link OperationFailedException} for the caller
*/
@Message(id = 14802, value = "Cannot resolve expression '%s'
String cannotResolveExpression(ModelNode toResolve, IllegalStateException e);
/**
* Creates an exception indicating the resource is a duplicate.
*
* @param address the address of the resource.
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14803, value = "Duplicate resource %s")
OperationFailedRuntimeException duplicateResourceAddress(PathAddress address);
/**
* Creates an exception indicating a resource cannot be removed due to the existence of child resources.
*
* @param children the address elements for the children.
*
* @return an {@link OperationFailedException} for the error.
*/
@Message(id = 14804, value = "Cannot remove resource before removing child resources %s")
OperationFailedException cannotRemoveResourceWithChildren(List<PathElement> children);
@Message(id = 14805, value = "Could not get main file: %s. Specified files must be relative to the configuration dir: %s")
IllegalStateException mainFileNotFound(String name, File configurationDir);
/**
* Creates an exception indicating a resource cannot be found.
*
* @param pathAddress the address for the resource.
*
* @return an {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14807, value = "Management resource '%s' not found")
OperationFailedRuntimeException managementResourceNotFound(PathAddress pathAddress);
/**
* Creates an exception message indicating a child resource cannot be found.
*
* @param childAddress the address element for the child.
*
* @return an message for the error.
*/
@Message(id = 14808, value = "Child resource '%s' not found")
String childResourceNotFound(PathElement childAddress);
@Message(id = 14809, value = "A node is already registered at '%s'")
IllegalArgumentException nodeAlreadyRegistered(String location);
@Message(id = 14810, value = "An attempt was made to unregister extension %s which still has subsystem %s registered")
IllegalStateException removingExtensionWithRegisteredSubsystem(String moduleName, String subsystem);
@Message(id = 14811, value = "An override model registration is not allowed for the root model registration")
IllegalStateException cannotOverrideRootRegistration();
@Message(id = 14812, value = "An override model registration is not allowed for non-wildcard model registrations. This registration is for the non-wildcard name '%s'.")
IllegalStateException cannotOverrideNonWildCardRegistration(String valueName);
@Message(id = 14813, value = "A registration named '*' is not an override model and cannot be unregistered via the unregisterOverrideModel API.")
IllegalArgumentException wildcardRegistrationIsNotAnOverride();
@Message(id = 14814, value = "The root resource registration does not support overrides, so no override can be removed.")
IllegalStateException rootRegistrationIsNotOverridable();
/**
* Creates an exception indicating there is no operation, represented by the {@code op} parameter, registered at the address,
* represented by the {@code address} parameter.
*
* @param op the operation.
* @param address the address.
* @return the message.
*/
@Message(id = 14815, value = "There is no operation %s registered at address %s")
IllegalArgumentException operationNotRegisteredException(String op, PathAddress address);
/**
* Creates a runtime exception indicating there was a failure to recover services during an operation rollback
*
* @param cause the cause of the failure
* @return the runtime exception.
*/
@Message(id = 14816, value = "Failed to recover services during operation rollback")
RuntimeException failedToRecoverServices(@Param OperationFailedException cause);
@Message(id = 14817, value = "A subsystem named '%s' cannot be registered by extension '%s' -- a subsystem with that name has already been registered by extension '%s'.")
IllegalStateException duplicateSubsystem(String subsystemName, String duplicatingModule, String existingModule);
/**
* Creates an exception indicating that the operation is missing one of the standard fields.
*
* @param field the standard field name
* @param operation the operation as a string. May be empty
*/
@Message(id = 14818, value = "Operation has no '%s' field. %s")
IllegalArgumentException validationFailedOperationHasNoField(String field, String operation);
/**
* Creates an exception indicating that the operation has an empty name.
*
* @param operation the operation. May be null
* @param operation the operation as a string. May be empty
*/
@Message(id = 14819, value = "Operation has a null or empty name. %s")
IllegalArgumentException validationFailedOperationHasANullOrEmptyName(String operation);
/**
* Creates an exception indicating that the operation could not be found
*
* @param name the name of the operation
* @param address the operation address
* @param operation the operation as a string. May be empty
*/
@Message(id = 14820, value = "No operation called '%s' at '%s'. %s")
IllegalArgumentException validationFailedNoOperationFound(String name, PathAddress address, String operation);
/**
* Creates an exception indicating that the operation contains a parameter not in its descriptor
*
* @param paramName the name of the parameter in the operation
* @param parameterNames the valid parameter names
* @param operation the operation as a string. May be empty
*/
@Message(id = 14821, value = "Operation contains a parameter '%s' which is not one of the expected parameters %s. %s")
IllegalArgumentException validationFailedActualParameterNotDescribed(String paramName, Set<String> parameterNames, String operation);
/**
* Creates an exception indicating that the operation does not contain a required parameter
*
* @param paramName the name of the required parameter
* @param operation the operation as a string. May be empty
*/
@Message(id = 14822, value = "Required parameter %s is not present. %s")
IllegalArgumentException validationFailedRequiredParameterNotPresent(String paramName, String operation);
/**
* Creates an exception indicating that the operation contains both an alternative and a required parameter
*
* @param alternative the name of the alternative parameter
* @param paramName the name of the required parameter
* @param operation the operation as a string. May be empty
*/
@Message(id = 14823, value = "Alternative parameter '%s' for required parameter '%s' was used. Please use one or the other. %s")
IllegalArgumentException validationFailedRequiredParameterPresentAsWellAsAlternative(String alternative, String paramName, String operation);
/**
* Creates an exception indicating that an operation parameter could not be converted to the required type
*
* @param paramName the name of the required parameter
* @param type the required type
* @param operation the operation as a string. May be empty
*/
@Message(id = 14824, value = "Could not convert the parameter '%s' to a %s. %s")
IllegalArgumentException validationFailedCouldNotConvertParamToType(String paramName, ModelType type, String operation);
/**
* Creates an exception indicating that an operation parameter value is smaller than the allowed minimum value
*
* @param value the name of the required parameter
* @param paramName the name of the required parameter
* @param min the minimum value
* @param operation the operation as a string. May be empty
*/
@Message(id = 14825, value = "The value '%s' passed in for '%s' is smaller than the minimum value '%s'. %s")
IllegalArgumentException validationFailedValueIsSmallerThanMin(Number value, String paramName, Number min, String operation);
/**
* Creates an exception indicating that an operation parameter value is greater than the allowed minimum value
*
* @param value the name of the required parameter
* @param paramName the name of the required parameter
* @param max the minimum value
* @param operation the operation as a string. May be empty
*/
@Message(id = 14826, value = "The value '%s' passed in for '%s' is bigger than the maximum value '%s'. %s")
IllegalArgumentException validationFailedValueIsGreaterThanMax(Number value, String paramName, Number max, String operation);
/**
* Creates an exception indicating that an operation parameter value is shorter than the allowed minimum length
*
* @param value the name of the required parameter
* @param paramName the name of the required parameter
* @param minLength the minimum value
* @param operation the operation as a string. May be empty
*/
@Message(id = 14827, value = "The value '%s' passed in for '%s' is shorter than the minimum length '%s'. %s")
IllegalArgumentException validationFailedValueIsShorterThanMinLength(Object value, String paramName, Object minLength, String operation);
/**
* Creates an exception indicating that an operation parameter value is longer than the allowed maximum length
*
* @param value the name of the required parameter
* @param paramName the name of the required parameter
* @param maxLength the minimum value
* @param operation the operation as a string. May be empty
*/
@Message(id = 14828, value = "The value '%s' passed in for '%s' is longer than the maximum length '%s'. %s")
IllegalArgumentException validationFailedValueIsLongerThanMaxLength(Object value, String paramName, Object maxLength, String operation);
/**
* Creates an exception indicating that an operation parameter list value has an element that is not of the accepted type
*
* @param paramName the name of the required parameter
* @param elementType the expected element type
* @param operation the operation as a string. May be empty
*/
@Message(id = 14829, value = "%s is expected to be a list of %s. %s")
IllegalArgumentException validationFailedInvalidElementType(String paramName, ModelType elementType, String operation);
@Message(id = 14830, value = "'" + ModelDescriptionConstants.REQUIRED + "' parameter: '%s' must be a boolean in the description of the operation at %s: %s")
String invalidDescriptionRequiredFlagIsNotABoolean(String paramName, PathAddress address, ModelNode description);
@Message(id = 14831, value = "Undefined request property '%s' in description of the operation at %s: %s")
String invalidDescriptionUndefinedRequestProperty(String name, PathAddress address, ModelNode description);
@Message(id = 14832, value = "There is no type for parameter '%s' in the description of the operation at %s: %s")
String invalidDescriptionNoParamTypeInDescription(String paramName, PathAddress address, ModelNode description);
@Message(id = 14833, value = "Could not determine the type of parameter '%s' in the description of the operation at %s: %s")
String invalidDescriptionInvalidParamTypeInDescription(String paramName, PathAddress address, ModelNode description);
@Message(id = 14834, value = "The '%s' attribute of the '%s' parameter can not be converted to its type: %s in the description of the operation at %s: %s")
String invalidDescriptionMinMaxForParameterHasWrongType(String minOrMax, String paramName, ModelType expectedType, PathAddress address, ModelNode description);
@Message(id = 14835, value = "The '%s' attribute of the '%s' parameter can not be converted to an integer in the description of the operation at %s: %s")
String invalidDescriptionMinMaxLengthForParameterHasWrongType(String minOrMaxLength, String paramName, PathAddress address, ModelNode description);
/**
* Creates an exception indicating the {@code value} for the {@code name} must be a valid port number.
*
* @param name the name for the value that must be a port number.
* @param value the invalid value.
* @param location the location of the error.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14836, value = "Illegal '%s' value %s -- must be a valid port number")
XMLStreamException invalidPort(String name, String value, @Param Location location);
@Message(id = 14837, value = "Cannot resolve the localhost address to create a UUID-based name for this process")
RuntimeException cannotResolveProcessUUID(@Cause UnknownHostException cause);
/**
* Creates an exception indicating a user tried calling ServiceController.setMode(REMOVE) from an operation handler.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14838, value = "Do not call ServiceController.setMode(REMOVE), use OperationContext.removeService() instead.")
IllegalStateException useOperationContextRemoveService();
/**
* Creates an exception indicating that the value of the specified parameter does not match any of the allowed
* values.
*
* @param value the parameter value.
* @param parameterName the parameter name.
* @param allowedValues a set containing the allowed values.
* @return an {@link OperationFailedException} for the error.
*/
@Message(id = 14839, value="Invalid value %s for %s; legal values are %s")
OperationFailedException invalidEnumValue(String value, String parameterName, Set<?> allowedValues);
/*
* Creates an exception indicating a user tried to directly update the configuration model of a managed domain
* server rather, bypassing the Host Controller.
*
* @param operation the name of the operation
* @param address the address of the operation
*
* @return a {@link OperationFailedRuntimeException} for the error.
*/
@Message(id = 14840, value = "Operation '%s' targeted at resource '%s' was directly invoked by a user. " +
"User operations are not permitted to directly update the persistent configuration of a server in a managed domain.")
OperationFailedRuntimeException modelUpdateNotAuthorized(String operation, PathAddress address);
@Message(id = 14841, value = "An operation handler attempted to access the operation response server results object " +
"on a process type other than '%s'. The current process type is '%s'")
IllegalStateException serverResultsAccessNotAllowed(ProcessType validType, ProcessType processType);
@Message(id = 14842, value = "Can't have both loopback and inet-address criteria")
String cantHaveBothLoopbackAndInetAddressCriteria();
@Message(id = 14843, value = "Can't have both link-local and inet-address criteria")
String cantHaveBothLinkLocalAndInetAddressCriteria();
@Message(id = 14844, value = "Can't have same criteria for both not and inclusion %s")
String cantHaveSameCriteriaForBothNotAndInclusion(InterfaceCriteria interfaceCriteria);
@Message(id = 14845, value = "Invalid value '%s' for attribute '%s' -- no interface configuration with that name exists")
OperationFailedException nonexistentInterface(String attributeValue, String attributeName);
@Message(id = 14846, value = "%s is empty")
IllegalArgumentException emptyVar(String name);
@Message(id = 14847, value = "Could not find a path called '%s'")
IllegalArgumentException pathEntryNotFound(String pathName);
@Message(id = 14848, value="Path entry is read-only: '%s'")
IllegalArgumentException pathEntryIsReadOnly(String pathName);
@Message(id = 14849, value="There is already a path entry called: '%s'")
IllegalArgumentException pathEntryAlreadyExists(String pathName);
@Message(id = 14850, value="Could not find relativeTo path '%s' for relative path '%s'")
IllegalStateException pathEntryNotFoundForRelativePath(String relativePath, String pathName);
@Message(id = 14851, value="Invalid relativePath value '%s'")
IllegalArgumentException invalidRelativePathValue(String relativePath);
@Message(id = 14852, value="'%s' is a Windows absolute path")
IllegalArgumentException pathIsAWindowsAbsolutePath(String path);
@Message(id = 14853, value="Path '%s' is read-only; it cannot be removed")
OperationFailedException cannotRemoveReadOnlyPath(String pathName);
@Message(id = 14854, value="Path '%s' is read-only; it cannot be modified")
OperationFailedException cannotModifyReadOnlyPath(String pathName);
/**
* An exception indicating the {@code name} may not be {@link ModelType#EXPRESSION}.
*
* @param name the name of the attribute or parameter value that cannot be an expression
*
* @return the exception.
*/
@Message(id = 14855, value = "%s may not be ModelType.EXPRESSION")
OperationFailedException expressionNotAllowed(String name);
@Message(id = 14856, value = "PathManager not available on processes of type '%s'")
IllegalStateException pathManagerNotAvailable(ProcessType processType);
/**
* Creates an exception indicating the {@code value} for the attribute, represented by the {@code name} parameter,
* is not a valid multicast address.
*
* @param cause the cause of the error.
* @param value the invalid value.
* @param name the name of the attribute.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 14857, value = "Value %s for attribute %s is not a valid multicast address")
OperationFailedException unknownMulticastAddress(@Cause UnknownHostException cause, String value, String name);
@Message(id = 14858, value="Path '%s' cannot be removed, since the following paths depend on it: %s")
OperationFailedException cannotRemovePathWithDependencies(String pathName, Set<String> dependencies);
@Message(id = 14859, value = "Failed to rename temp file %s to %s")
ConfigurationPersistenceException failedToRenameTempFile(@Cause Throwable cause, File temp, File file);
@Message(id = 14860, value = "Invalid locale format: %s")
String invalidLocaleString(String unparsed);
@Message(id = 14861, value = "<one or more transitive dependencies>")
String transitiveDependencies();
/**
* Creates a message indicating the operation is cancelled.
*
* @return the message.
*/
@Message(id = 14862, value = "Operation cancelled")
String operationCancelled();
/**
* Creates a message indicating the operation is cancelled asynchronously.
*
* @return a {@link CancellationException} for the error.
*/
@Message(id = 14863, value = "Operation cancelled asynchronously")
OperationCancellationException operationCancelledAsynchronously();
@Message(id = 14864, value = "Stream was killed")
IOException streamWasKilled();
@Message(id = 14865, value = "Stream was closed")
IOException streamWasClosed();
@Message(id = 14866, value = "Cannot define both '%s' and '%s'")
OperationFailedException cannotHaveBothParameters(String nameA, String name2);
@Message(id = 14867, value = "Failed to delete file %s")
IllegalStateException couldNotDeleteFile(File file);
@Message(id = 14868, value = "An alias is already registered at location '%s'")
IllegalArgumentException aliasAlreadyRegistered(String location);
@Message(id = 14869, value = "Expected an address under '%s', was '%s'")
IllegalArgumentException badAliasConvertAddress(PathAddress aliasAddress, PathAddress actual);
@Message(id = 14870, value = "Alias target address not found: %s")
IllegalArgumentException aliasTargetResourceRegistrationNotFound(PathAddress targetAddress);
@Message(id = 14871, value = "No operation called '%s' found for alias address '%s' which maps to '%s'")
IllegalArgumentException aliasStepHandlerOperationNotFound(String name, PathAddress aliasAddress, PathAddress targetAddress);
@Message(id = 14872, value = "Resource registration is not an alias")
IllegalStateException resourceRegistrationIsNotAnAlias();
@Message(id = 14873, value = "Model contains fields that are not known in definition, fields: %s, path: %s")
RuntimeException modelFieldsNotKnown(Set<String> fields, PathAddress address);
@Message(id = 14874, value = "Could not marshal attribute as element: %s")
UnsupportedOperationException couldNotMarshalAttributeAsElement(String attributeName);
@Message(id = 14875, value = "Could not marshal attribute as attribute: %s")
UnsupportedOperationException couldNotMarshalAttributeAsAttribute(String attributeName);
@Message(id = 14876, value = "Operation %s invoked against multiple target addresses failed at address %s with failure description %s")
String wildcardOperationFailedAtSingleAddress(String operation, PathAddress address, String failureMessage);
@Message(id = 14877, value = "Operation %s invoked against multiple target addresses failed at address %s. See the operation result for details.")
String wildcardOperationFailedAtSingleAddressWithComplexFailure(String operation, PathAddress address);
@Message(id = 14878, value = "Operation %s invoked against multiple target addresses failed at addresses %s. See the operation result for details.")
String wildcardOperationFailedAtMultipleAddresses(String operation, Set<PathAddress> addresses);
@Message(id = 14879, value = "One or more services were unable to start due to one or more indirect dependencies not being available.")
String missingTransitiveDependencyProblem();
@Message(id = Message.NONE, value = "Services that were unable to start:")
String missingTransitiveDependendents();
@Message(id = Message.NONE, value = "Services that may be the cause:")
String missingTransitiveDependencies();
}
|
package ubic.gemma.web.controller.coexpressionSearch;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.testing.BaseTransactionalSpringContextTest;
import ubic.gemma.web.controller.expression.experiment.ExpressionExperimentVisualizationCommand;
import ubic.gemma.web.controller.expression.experiment.ExpressionExperimentVisualizationController;
/**
* @author joseph
* @version $Id$
*/
public class CoexpressionSearchControllerTest extends BaseTransactionalSpringContextTest {
private static Log log = LogFactory.getLog( CoexpressionSearchController.class.getName() );
/**
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void onSetUpInTransaction() throws Exception {
super.onSetUpInTransaction();
}
/**
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testOnSubmit() throws Exception {
Gene g = this.getTestPeristentGene();
CoexpressionSearchController searchController = ( CoexpressionSearchController ) this
.getBean( "coexpressionSearchController" );
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
CoexpressionSearchCommand command = new CoexpressionSearchCommand();
command.setSearchCriteria( "gene symbol" );
command.setSearchString( g.getOfficialName() );
log.debug( "gene id id " + g.getOfficialName() );
// setComplete();// leave data in database
BindException errors = new BindException( command, "CoexpressionSearchCommand" );
searchController.processFormSubmission( request, response, command, errors );
ModelAndView mav = searchController.onSubmit( request, response, command, errors );
assertEquals( "showCoexpressionSearchResults", mav.getViewName() );
}
}
|
package org.hisp.dhis.android.rules;
import com.google.auto.value.AutoValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
@AutoValue
abstract class RuleExpression {
static final String VARIABLE_PATTERN = "[A#CV]\\{(\\w+.?\\w*)\\}";
static final String FUNCTION_PATTERN = "d2:(\\w+.?\\w*)\\( *(([\\d/\\*\\+\\-%\\. ]+)|" +
"( *'[^']*'))*( *, *(([\\d/\\*\\+\\-%\\. ]+)|'[^']*'))* *\\)";
static final Pattern VARIABLE_PATTERN_COMPILED = Pattern.compile(VARIABLE_PATTERN);
static final Pattern FUNCTION_PATTERN_COMPILED = Pattern.compile(FUNCTION_PATTERN);
@Nonnull
public abstract String expression();
@Nonnull
public abstract List<String> variables();
@Nonnull
public abstract List<String> functions();
@Nonnull
static RuleExpression from(@Nonnull String expression) {
if (expression == null) {
throw new NullPointerException("expression == null");
}
List<String> variables = new ArrayList<>();
List<String> functions = new ArrayList<>();
Matcher variableMatcher = VARIABLE_PATTERN_COMPILED.matcher(expression);
Matcher functionMatcher = FUNCTION_PATTERN_COMPILED.matcher(expression);
// iterate over matched values and aggregate them
while (variableMatcher.find()) {
variables.add(variableMatcher.group());
}
while (functionMatcher.find()) {
functions.add(functionMatcher.group());
}
return new AutoValue_RuleExpression(expression, Collections.unmodifiableList(variables),
Collections.unmodifiableList(functions));
}
}
|
package com.codingchili.core.listener.transport;
import com.codingchili.core.configuration.RestHelper;
import com.codingchili.core.context.CoreContext;
import com.codingchili.core.listener.CoreHandler;
import com.codingchili.core.listener.CoreListener;
import com.codingchili.core.listener.ListenerSettings;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import static com.codingchili.core.configuration.CoreStrings.LOG_AT;
import static com.codingchili.core.configuration.CoreStrings.getBindAddress;
/**
* HTTP/REST transport listener.
*/
public class RestListener implements CoreListener {
private ListenerSettings settings = ListenerSettings.getDefaultSettings();
private final Promise<Router> onRouter = Promise.promise();
private CoreContext core;
private CoreHandler handler;
private Router router;
@Override
public void init(CoreContext core) {
router = Router.router(core.vertx());
router.route().handler(BodyHandler.create().setBodyLimit(settings.getMaxRequestBytes()));
RestHelper.addHeaders(router, settings.isSecure());
router.route().handler(this::packet);
handler.init(core);
this.core = core;
// invoke the callback when router is created from the context.
onRouter.complete(router);
}
/**
* @return exposes the router object for further configuration, manual route setups, fallbacks
* and support for adding a static handler.
*/
public Future<Router> router() {
return onRouter.future();
}
@Override
public CoreListener settings(ListenerSettings settings) {
this.settings = settings;
return this;
}
@Override
public CoreListener handler(CoreHandler handler) {
this.handler = handler;
return this;
}
@Override
public void start(Future<Void> start) {
core.vertx().createHttpServer(settings.getHttpOptions())
.requestHandler(router)
.listen(settings.getPort(), getBindAddress(), listen -> {
if (listen.succeeded()) {
settings.addListenPort(listen.result().actualPort());
handler.start(start);
} else {
start.fail(listen.cause());
}
});
}
@Override
public void stop(Future<Void> stop) {
handler.stop(stop);
}
private void packet(RoutingContext context) {
handler.handle(new RestRequest(context, settings));
}
@Override
public String toString() {
return handler.getClass().getSimpleName() + LOG_AT + handler.address() + " port :" +
settings.getPort();
}
}
|
package org.eclipse.hawkbit.ui.filtermanagement.footer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.ui.filtermanagement.event.CustomFilterUIEvent;
import org.eclipse.hawkbit.ui.filtermanagement.state.FilterManagementUIState;
import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil;
import org.eclipse.hawkbit.ui.utils.I18N;
import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider;
import org.eclipse.hawkbit.ui.utils.SPUIDefinitions;
import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions;
import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.events.EventScope;
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
import com.vaadin.server.FontAwesome;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
/**
* @author Venugopal Boodidadinne(RBEI/BSJ)
*
* Count message label which display current filter details and details
* on pinning.
*/
@SpringComponent
@ViewScope
public class TargetFilterCountMessageLabel extends Label {
private static final long serialVersionUID = -7188528790042766877L;
@Autowired
private FilterManagementUIState filterManagementUIState;
@Autowired
private transient TargetManagement targetManagement;
@Autowired
private I18N i18n;
@Autowired
private transient EventBus.SessionEventBus eventBus;
/**
* PostConstruct method called by spring after bean has been initialized.
*/
@PostConstruct
public void postConstruct() {
applyStyle();
displayTargetFilterMessage();
eventBus.subscribe(this);
}
@PreDestroy
void destroy() {
eventBus.unsubscribe(this);
}
@EventBusListenerMethod(scope = EventScope.SESSION)
void onEvent(final CustomFilterUIEvent custFUIEvent) {
if (custFUIEvent == CustomFilterUIEvent.TARGET_DETAILS_VIEW
|| custFUIEvent == CustomFilterUIEvent.CREATE_NEW_FILTER_CLICK
|| custFUIEvent == CustomFilterUIEvent.EXIT_CREATE_OR_UPDATE_FILTRER_VIEW
|| custFUIEvent == CustomFilterUIEvent.FILTER_TARGET_BY_QUERY) {
UI.getCurrent().access(() -> displayTargetFilterMessage());
}
}
private void applyStyle() {
addStyleName(SPUILabelDefinitions.SP_LABEL_MESSAGE_STYLE);
setContentMode(ContentMode.HTML);
setId(SPUIComponetIdProvider.COUNT_LABEL);
}
private void displayTargetFilterMessage() {
long totalTargets = 0;
if (filterManagementUIState.isCreateFilterViewDisplayed() || filterManagementUIState.isEditViewDisplayed()) {
if (null != filterManagementUIState.getFilterQueryValue()) {
totalTargets = targetManagement
.countTargetByTargetFilterQuery(filterManagementUIState.getFilterQueryValue());
}
final StringBuilder targetMessage = new StringBuilder(i18n.get("label.target.filtered.total"));
if (filterManagementUIState.getTargetsTruncated() != null) {
// set the icon
setIcon(FontAwesome.INFO_CIRCLE);
setDescription(i18n.get("label.target.filter.truncated", filterManagementUIState.getTargetsTruncated(),
SPUIDefinitions.MAX_TARGET_TABLE_ENTRIES));
} else {
setIcon(null);
setDescription(null);
}
targetMessage.append(totalTargets);
targetMessage.append(HawkbitCommonUtil.SP_STRING_SPACE);
targetMessage.append(i18n.get("label.filter.shown"));
if (totalTargets > SPUIDefinitions.MAX_TARGET_TABLE_ENTRIES) {
targetMessage.append(SPUIDefinitions.MAX_TARGET_TABLE_ENTRIES);
} else {
targetMessage.append(HawkbitCommonUtil.SP_STRING_SPACE);
targetMessage.append(totalTargets);
}
setCaption(targetMessage.toString());
}
}
}
|
package com.flowci.core.job.service;
import com.flowci.core.agent.service.AgentService;
import com.flowci.core.common.domain.Variables;
import com.flowci.core.common.git.GitClient;
import com.flowci.core.common.manager.SpringEventManager;
import com.flowci.core.common.rabbit.RabbitQueueOperation;
import com.flowci.core.job.dao.JobDao;
import com.flowci.core.job.domain.ExecutedCmd;
import com.flowci.core.job.domain.Job;
import com.flowci.core.job.event.JobReceivedEvent;
import com.flowci.core.job.event.JobStatusChangeEvent;
import com.flowci.core.job.manager.CmdManager;
import com.flowci.core.job.manager.FlowJobQueueManager;
import com.flowci.core.job.manager.YmlManager;
import com.flowci.core.job.util.StatusHelper;
import com.flowci.core.secret.domain.Secret;
import com.flowci.core.secret.service.SecretService;
import com.flowci.domain.*;
import com.flowci.exception.CIException;
import com.flowci.exception.NotAvailableException;
import com.flowci.exception.NotFoundException;
import com.flowci.sm.Context;
import com.flowci.sm.StateMachine;
import com.flowci.sm.Status;
import com.flowci.sm.Transition;
import com.flowci.tree.*;
import com.flowci.util.StringHelper;
import com.flowci.zookeeper.ZookeeperClient;
import com.google.common.base.Strings;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.log4j.Log4j2;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
@Log4j2
@Service
public class JobActionServiceImpl implements JobActionService {
private static final Status Pending = new Status(Job.Status.PENDING.name());
private static final Status Created = new Status(Job.Status.CREATED.name());
private static final Status Loading = new Status(Job.Status.LOADING.name());
private static final Status Canceled = new Status(Job.Status.CANCELLED.name());
private static final Status Cancelling = new Status(Job.Status.CANCELLING.name());
private static final Status Queued = new Status(Job.Status.QUEUED.name());
private static final Status Running = new Status(Job.Status.RUNNING.name());
private static final Status Timeout = new Status(Job.Status.TIMEOUT.name());
private static final Status Failure = new Status(Job.Status.FAILURE.name());
private static final Status Success = new Status(Job.Status.SUCCESS.name());
// pending
private static final Transition PendingToLoading = new Transition(Pending, Loading);
private static final Transition PendingToCreated = new Transition(Pending, Created);
// loading
private static final Transition LoadingToFailure = new Transition(Loading, Failure);
private static final Transition LoadingToCreated = new Transition(Loading, Queued);
// created
private static final Transition CreatedToQueued = new Transition(Created, Queued);
private static final Transition CreatedToTimeout = new Transition(Created, Timeout);
private static final Transition CreatedToFailure = new Transition(Created, Failure);
// queued
private static final Transition QueuedToCancel = new Transition(Queued, Canceled);
private static final Transition QueuedToRunning = new Transition(Queued, Running);
private static final Transition QueuedToTimeout = new Transition(Queued, Timeout);
private static final Transition QueuedToFailure = new Transition(Queued, Failure);
// running
private static final Transition RunningToRunning = new Transition(Running, Running);
private static final Transition RunningToSuccess = new Transition(Running, Success);
private static final Transition RunningToCancelling = new Transition(Running, Cancelling);
private static final Transition RunningToCancel = new Transition(Running, Canceled);
private static final Transition RunningToTimeout = new Transition(Running, Timeout);
private static final Transition RunningToFailure = new Transition(Running, Failure);
// cancelling
private static final Transition CancellingToCancel = new Transition(Cancelling, Canceled);
private static final StateMachine<JobSmContext> Sm = new StateMachine<>("JOB_STATUS");
@Autowired
private Path repoDir;
@Autowired
private Path tmpDir;
@Autowired
private ZookeeperClient zk;
@Autowired
private JobDao jobDao;
@Autowired
private CmdManager cmdManager;
@Autowired
private SpringEventManager eventManager;
@Autowired
private YmlManager ymlManager;
@Autowired
private FlowJobQueueManager flowJobQueueManager;
@Autowired
private AgentService agentService;
@Autowired
private StepService stepService;
@Autowired
private SecretService secretService;
@EventListener
public void init(ContextRefreshedEvent ignore) {
fromPending();
fromLoading();
fromCreated();
fromQueued();
fromRunning();
fromCancelling();
}
@Override
public void toLoading(Job job) {
on(job, Job.Status.LOADING, null);
}
@Override
public void toCreated(Job job, String yml) {
on(job, Job.Status.CREATED, context -> {
context.yml = yml;
});
}
@Override
public void toStart(Job job) {
on(job, Job.Status.QUEUED, null);
}
@Override
public void toRun(Job job) {
on(job, Job.Status.RUNNING, null);
}
@Override
public void toContinue(Job job, ExecutedCmd step) {
if (job.isCancelling()) {
on(job, Job.Status.CANCELLED, null);
return;
}
on(job, Job.Status.RUNNING, (context) -> {
context.step = step;
});
}
@Override
public void toCancel(Job job, String reason) {
on(job, Job.Status.CANCELLED, context -> {
context.reasonForCancel = reason;
});
}
@Override
public void toTimeout(Job job) {
on(job, Job.Status.TIMEOUT, null);
}
@Override
public void toFailure(Job job, Throwable e) {
on(job, Job.Status.FAILURE, (context) -> {
context.setError(e);
});
}
@Override
public synchronized Job setJobStatusAndSave(Job job, Job.Status newStatus, String message) {
if (job.getStatus() == newStatus) {
return jobDao.save(job);
}
job.setStatus(newStatus);
job.setMessage(message);
job.setStatusToContext(newStatus);
jobDao.save(job);
eventManager.publish(new JobStatusChangeEvent(this, job));
logInfo(job, "status = {}", job.getStatus());
return job;
}
private void fromPending() {
Sm.add(PendingToCreated, context -> {
Job job = context.job;
String yml = context.yml;
setupYamlAndSteps(job, yml);
setJobStatusAndSave(job, Job.Status.CREATED, StringHelper.EMPTY);
});
Sm.add(PendingToLoading, context -> {
Job job = context.job;
setJobStatusAndSave(job, Job.Status.LOADING, null);
try {
context.yml = fetchYamlFromGit(job);
Sm.execute(Loading, Created, context);
} catch (Throwable e) {
context.setError(e);
Sm.execute(Loading, Failure, context);
}
});
}
private void fromLoading() {
Sm.add(LoadingToFailure, context -> {
Job job = context.job;
Throwable err = context.getError();
setJobStatusAndSave(job, Job.Status.FAILURE, err.getMessage());
});
Sm.add(LoadingToCreated, context -> {
Job job = context.job;
String yml = context.yml;
setupYamlAndSteps(job, yml);
setJobStatusAndSave(job, Job.Status.CREATED, StringHelper.EMPTY);
});
}
private void fromCreated() {
Sm.add(CreatedToTimeout, context -> {
Job job = context.job;
setJobStatusAndSave(job, Job.Status.TIMEOUT, "expired before enqueue");
log.debug("[Job: Timeout] {} has expired", job.getKey());
});
Sm.add(CreatedToFailure, context -> {
Job job = context.job;
Throwable err = context.getError();
setJobStatusAndSave(job, Job.Status.FAILURE, err.getMessage());
});
Sm.add(CreatedToQueued, context -> {
Job job = context.job;
if (job.isExpired()) {
Sm.execute(context.getCurrent(), Timeout, context);
return;
}
try {
RabbitQueueOperation manager = flowJobQueueManager.get(job.getQueueName());
setJobStatusAndSave(job, Job.Status.QUEUED, null);
manager.send(job.getId().getBytes(), job.getPriority(), job.getExpire());
logInfo(job, "enqueue");
} catch (Throwable e) {
context.setError(new CIException("Unable to enqueue"));
Sm.execute(context.getCurrent(), Failure, context);
}
});
}
private void fromQueued() {
Function<String, Boolean> canAcquireAgent = (jobId) -> {
Optional<InterProcessLock> lock = lockJob(jobId);
if (!lock.isPresent()) {
JobSmContext context = new JobSmContext();
context.setJob(jobDao.findById(jobId).get());
context.setError(new CIException("unexpected job status while waiting for agent"));
Sm.execute(Queued, Failure, context);
return false;
}
try {
log.debug("Job {} is locked", jobId);
ObjectWrapper<Job> out = new ObjectWrapper<>();
boolean canContinue = canContinue(jobId, out);
Job job = out.getValue();
if (job.isExpired()) {
JobSmContext context = new JobSmContext();
context.setJob(job);
context.setError(new CIException("expired while waiting for agent"));
Sm.execute(Queued, Timeout, context);
return false;
}
return canContinue;
} finally {
releaseLock(lock.get(), jobId);
}
};
Sm.add(QueuedToTimeout, context -> {
Job job = context.job;
Throwable err = context.getError();
setJobStatusAndSave(job, Job.Status.TIMEOUT, err.getMessage());
});
Sm.add(QueuedToCancel, (context) -> {
Job job = context.job;
setJobStatusAndSave(job, Job.Status.CANCELLED, "cancelled while queued up");
});
Sm.add(QueuedToRunning, (context) -> {
Job job = context.job;
eventManager.publish(new JobReceivedEvent(this, job));
Optional<Agent> available = agentService.acquire(job, canAcquireAgent);
available.ifPresent(agent -> {
try {
dispatch(job, agent);
} catch (Throwable e) {
context.setAgentId(agent.getId());
context.setError(e);
Sm.execute(Queued, Failure, context);
}
});
});
Sm.add(QueuedToFailure, (context) -> {
Job job = context.getJob();
String agentId = context.getAgentId();
Throwable e = context.getError();
log.debug("Fail to dispatch job {} to agent {}", job.getId(), agentId, e);
// set current step to exception
String jobId = job.getId();
String nodePath = job.getCurrentPath(); // set in the dispatch
stepService.toStatus(jobId, nodePath, ExecutedCmd.Status.EXCEPTION, null);
setJobStatusAndSave(job, Job.Status.FAILURE, e.getMessage());
agentService.tryRelease(agentId);
});
}
private void fromRunning() {
Sm.add(RunningToRunning, (context) -> {
Job job = context.job;
Optional<InterProcessLock> lock = lockJob(job.getId());
if (!lock.isPresent()) {
log.debug("Fail to lock job {}", job.getId());
context.setError(new CIException("Unexpected status"));
Sm.execute(context.getCurrent(), Failure, context);
return;
}
try {
log.debug("Job {} is locked", job.getId());
// refresh job after lock
context.job = jobDao.findById(job.getId()).get();
toNextStep(context);
} finally {
releaseLock(lock.get(), job.getId());
}
});
Sm.add(RunningToSuccess, (context) -> {
Job job = context.job;
agentService.tryRelease(job.getAgentId());
logInfo(job, "finished with status {}", Success);
setJobStatusAndSave(job, Job.Status.SUCCESS, null);
});
Sm.add(RunningToTimeout, (context) -> {
Job job = context.job;
try {
Agent agent = agentService.get(job.getAgentId());
setRestStepsToSkipped(job);
setJobStatusAndSave(job, Job.Status.TIMEOUT, null);
if (agent.isOnline()) {
CmdIn killCmd = cmdManager.createKillCmd();
agentService.dispatch(killCmd, agent);
agentService.tryRelease(agent.getId());
}
} catch (NotFoundException ignore) {
setJobStatusAndSave(job, Job.Status.TIMEOUT, null);
}
});
// failure from job end or exception
Sm.add(RunningToFailure, (context) -> {
Job job = context.job;
ExecutedCmd step = context.step;
Throwable err = context.getError();
if (Objects.isNull(err)) {
err = new CIException("");
}
String stepErr = step.getError();
if (StringHelper.hasValue(stepErr)) {
err = new CIException(stepErr);
}
stepService.toStatus(job.getId(), step.getNodePath(), ExecutedCmd.Status.EXCEPTION, null);
try {
Agent agent = agentService.get(job.getAgentId());
agentService.tryRelease(agent.getId());
} catch (NotFoundException ignore) {
// ignore agent not found
}
logInfo(job, "finished with status {}", Failure);
setJobStatusAndSave(job, Job.Status.FAILURE, err.getMessage());
});
Sm.add(RunningToCancelling, (context) -> {
Job job = context.job;
Agent agent = agentService.get(job.getAgentId());
CmdIn killCmd = cmdManager.createKillCmd();
setJobStatusAndSave(job, Job.Status.CANCELLING, null);
agentService.dispatch(killCmd, agent);
});
Sm.add(RunningToCancel, (context) -> {
Job job = context.job;
String reason = context.reasonForCancel;
Agent agent = null;
try {
agent = agentService.get(job.getAgentId());
} catch (NotFoundException e) {
setRestStepsToSkipped(job);
setJobStatusAndSave(job, Job.Status.CANCELLED, "agent not found");
return;
}
if (agent.isOnline()) {
Sm.execute(context.getCurrent(), Cancelling, context);
return;
}
agentService.tryRelease(agent.getId());
setRestStepsToSkipped(job);
setJobStatusAndSave(job, Job.Status.CANCELLED, reason);
});
}
private void fromCancelling() {
Sm.add(CancellingToCancel, context -> {
Job job = context.job;
Agent agent = agentService.get(job.getAgentId());
agentService.tryRelease(agent.getId());
setRestStepsToSkipped(job);
setJobStatusAndSave(job, Job.Status.CANCELLED, null);
});
}
private void setupYamlAndSteps(Job job, String yml) {
FlowNode root = YmlParser.load(job.getFlowName(), yml);
job.setCurrentPath(root.getPathAsString());
job.setAgentSelector(root.getSelector());
job.getContext().merge(root.getEnvironments(), false);
ymlManager.create(job, yml);
stepService.init(job);
}
private void setRestStepsToSkipped(Job job) {
List<ExecutedCmd> steps = stepService.list(job);
for (ExecutedCmd step : steps) {
if (step.isRunning() || step.isPending()) {
stepService.toStatus(step, ExecutedCmd.Status.SKIPPED, null);
}
}
}
private void on(Job job, Job.Status target, Consumer<JobSmContext> configContext) {
Status current = new Status(job.getStatus().name());
Status to = new Status(target.name());
JobSmContext context = new JobSmContext().setJob(job);
if (configContext != null) {
configContext.accept(context);
}
Sm.execute(current, to, context);
}
private String fetchYamlFromGit(Job job) {
final String gitUrl = job.getGitUrl();
if (!StringHelper.hasValue(gitUrl)) {
throw new NotAvailableException("Git url is missing");
}
final Path dir = getFlowRepoDir(gitUrl, job.getYamlRepoBranch());
try {
GitClient client = new GitClient(gitUrl, tmpDir, getSimpleSecret(job.getCredentialName()));
client.klone(dir, job.getYamlRepoBranch());
} catch (Exception e) {
throw new NotAvailableException("Unable to fetch yaml config for flow");
}
String[] files = dir.toFile().list((currentDir, fileName) ->
(fileName.endsWith(".yaml") || fileName.endsWith(".yml")) && fileName.startsWith(".flowci"));
if (files == null || files.length == 0) {
throw new NotAvailableException("Unable to find yaml file in repo");
}
try {
byte[] ymlInBytes = Files.readAllBytes(Paths.get(dir.toString(), files[0]));
return new String(ymlInBytes);
} catch (IOException e) {
throw new NotAvailableException("Unable to read yaml file in repo").setExtra(job);
}
}
/**
* Get flow repo path: {repo dir}/{flow id}
*/
private Path getFlowRepoDir(String repoUrl, String branch) {
String b64 = Base64.getEncoder().encodeToString(repoUrl.getBytes());
return Paths.get(repoDir.toString(), b64 + "_" + branch);
}
private SimpleSecret getSimpleSecret(String credentialName) {
if (Strings.isNullOrEmpty(credentialName)) {
return null;
}
final Secret secret = secretService.get(credentialName);
return secret.toSimpleSecret();
}
/**
* Dispatch job to agent when Queue to Running
*/
private void dispatch(Job job, Agent agent) {
NodeTree tree = ymlManager.getTree(job);
StepNode next = tree.next(NodePath.create(job.getCurrentPath()));
// do not accept job without regular steps
if (Objects.isNull(next)) {
log.debug("Next node cannot be found when process job {}", job);
return;
}
String nextPath = next.getPathAsString();
log.debug("Next step of job {} is {}", job.getId(), next.getName());
// set path, agent id, agent name and status to job
job.setCurrentPath(nextPath);
job.setAgentId(agent.getId());
job.setAgentSnapshot(agent);
// set executed cmd step to running
ExecutedCmd nextCmd = stepService.toStatus(job.getId(), nextPath, ExecutedCmd.Status.RUNNING, null);
// dispatch job to agent queue
CmdIn cmd = cmdManager.createShellCmd(job, next, nextCmd);
setJobStatusAndSave(job, Job.Status.RUNNING, null);
agentService.dispatch(cmd, agent);
logInfo(job, "send to agent: step={}, agent={}", next.getName(), agent.getName());
}
private void toNextStep(JobSmContext context) {
Job job = context.job;
ExecutedCmd execCmd = context.step;
// save executed cmd
stepService.resultUpdate(execCmd);
log.debug("Executed cmd {} been recorded", execCmd);
NodePath currentPath = NodePath.create(execCmd.getNodePath());
// verify job node path is match cmd node path
if (!currentPath.equals(NodePath.create(job.getCurrentPath()))) {
log.error("Invalid executed cmd callback: does not match job current node path");
return;
}
NodeTree tree = ymlManager.getTree(job);
StepNode node = tree.get(currentPath);
updateJobTime(job, execCmd, tree, node);
updateJobStatusAndContext(job, node, execCmd);
// to next step
Optional<StepNode> next = findNext(tree, node, execCmd.isSuccess());
if (next.isPresent()) {
String nextPath = next.get().getPathAsString();
job.setCurrentPath(nextPath);
ExecutedCmd nextCmd = stepService.toStatus(job.getId(), nextPath, ExecutedCmd.Status.RUNNING, null);
context.setStep(nextCmd);
try {
Agent agent = agentService.get(job.getAgentId());
CmdIn cmd = cmdManager.createShellCmd(job, next.get(), nextCmd);
setJobStatusAndSave(job, Job.Status.RUNNING, null);
agentService.dispatch(cmd, agent);
logInfo(job, "send to agent: step={}, agent={}", next.get().getName(), agent.getName());
return;
} catch (Throwable e) {
log.debug("Fail to dispatch job {} to agent {}", job.getId(), job.getAgentId(), e);
context.setError(e);
Sm.execute(context.getCurrent(), Failure, context);
return;
}
}
// to finish status
Job.Status statusFromContext = job.getStatusFromContext();
Sm.execute(context.getCurrent(), new Status(statusFromContext.name()), context);
}
private void updateJobTime(Job job, ExecutedCmd execCmd, NodeTree tree, StepNode node) {
if (tree.isFirst(node.getPath())) {
job.setStartAt(execCmd.getStartAt());
}
job.setFinishAt(execCmd.getFinishAt());
}
private void updateJobStatusAndContext(Job job, StepNode node, ExecutedCmd cmd) {
// merge output to job context
Vars<String> context = job.getContext();
context.merge(cmd.getOutput());
context.put(Variables.Job.StartAt, job.startAtInStr());
context.put(Variables.Job.FinishAt, job.finishAtInStr());
context.put(Variables.Job.Steps, stepService.toVarString(job, node));
// after status not apart of job status
if (!node.isAfter()) {
job.setStatusToContext(StatusHelper.convert(cmd));
}
}
private Optional<StepNode> findNext(NodeTree tree, Node current, boolean isSuccess) {
StepNode next = tree.next(current.getPath());
if (Objects.isNull(next)) {
return Optional.empty();
}
// find step from after
if (!isSuccess && !next.isAfter()) {
return findNext(tree, next, false);
}
return Optional.of(next);
}
private boolean canContinue(String jobId, ObjectWrapper<Job> out) {
Job job = jobDao.findById(jobId).get();
out.setValue(job);
if (job.isExpired()) {
return false;
}
if (job.isCancelling()) {
return false;
}
return !job.isDone();
}
private void logInfo(Job job, String message, Object... params) {
log.info("[Job] " + job.getKey() + " " + message, params);
}
private Optional<InterProcessLock> lockJob(String jobId) {
return zk.lock("/jobs/" + jobId, 10);
}
private void releaseLock(InterProcessLock lock, String jobId) {
try {
if (lock.isAcquiredInThisProcess()) {
lock.release();
log.debug("Job {} is released", jobId);
}
} catch (Exception warn) {
log.warn(warn);
}
}
@Getter
@Setter
@Accessors(chain = true)
private static class JobSmContext extends Context {
private Job job;
public String yml;
private ExecutedCmd step;
private String agentId;
private String reasonForCancel;
}
}
|
package com.twelvemonkeys.imageio.plugins.jpeg;
import com.twelvemonkeys.imageio.metadata.jpeg.JPEG;
import javax.imageio.IIOException;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageInputStreamImpl;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import static com.twelvemonkeys.lang.Validate.notNull;
final class JPEGSegmentImageInputStream extends ImageInputStreamImpl {
// TODO: Rewrite JPEGSegment (from metadata) to store stream pos/length, and be able to replay data, and use instead of Segment?
// TODO: Change order of segments, to make sure APP0/JFIF is always before APP14/Adobe? What about EXIF?
// TODO: Insert fake APP0/JFIF if needed by the reader?
// TODO: Sort out ICC_PROFILE issues (duplicate sequence numbers etc)?
final private ImageInputStream stream;
private final List<Segment> segments = new ArrayList<Segment>(64);
private int currentSegment = -1;
private Segment segment;
JPEGSegmentImageInputStream(final ImageInputStream stream) {
this.stream = notNull(stream, "stream");
}
private Segment fetchSegment() throws IOException {
// Stream init
if (currentSegment == -1) {
streamInit();
}
else {
segment = segments.get(currentSegment);
}
if (streamPos >= segment.end()) {
// Go forward in cache
int cachedSegment = currentSegment;
while (++cachedSegment < segments.size()) {
currentSegment = cachedSegment;
segment = segments.get(currentSegment);
if (streamPos >= segment.start && streamPos < segment.end()) {
segment.seek(stream, streamPos);
return segment;
}
}
stream.seek(segment.realEnd());
// Scan forward
while (true) {
long realPosition = stream.getStreamPosition();
int trash = 0;
int marker = stream.readUnsignedByte();
// Skip bad padding before the marker
while (marker != 0xff) {
marker = stream.readUnsignedByte();
trash++;
realPosition++;
}
if (trash != 0) {
// NOTE: We previously allowed these bytes to pass through to the native reader, as it could cope
// and issued the correct warning. However, the native metadata chokes on it, so we'll mask it out.
// TODO: Issue warning from the JPEGImageReader, telling how many bytes we skipped
}
marker = 0xff00 | stream.readUnsignedByte();
// Skip over 0xff padding between markers
while (marker == 0xffff) {
realPosition++;
marker = 0xff00 | stream.readUnsignedByte();
}
// We are now handling all important segments ourselves, except APP1/Exif and APP14/Adobe,
// as these segments affects image decoding.
boolean appSegmentMarker = isAppSegmentMarker(marker);
boolean isApp14Adobe = marker == JPEG.APP14 && isAppSegmentWithId("Adobe", stream);
boolean isApp1Exif = marker == JPEG.APP1 && isAppSegmentWithId("Exif", stream);
if (appSegmentMarker && !(isApp1Exif || isApp14Adobe)) {
int length = stream.readUnsignedShort(); // Length including length field itself
stream.seek(realPosition + 2 + length); // Skip marker (2) + length
}
else {
if (marker == JPEG.EOI) {
segment = new Segment(marker, realPosition, segment.end(), 2);
segments.add(segment);
}
else {
long length;
if (marker == JPEG.SOS) {
// Treat rest of stream as a single segment (scanning for EOI is too much work)
// TODO: For progressive, there will be more than one SOS...
length = Long.MAX_VALUE - realPosition;
}
else {
// Length including length field itself
length = 2 + stream.readUnsignedShort();
}
if (isApp14Adobe && length != 16) {
// Need to rewrite this segment, so that it gets length 16 and discard the remaining bytes...
segment = new AdobeAPP14Replacement(realPosition, segment.end(), length, stream);
}
else {
segment = new Segment(marker, realPosition, segment.end(), length);
}
segments.add(segment);
}
currentSegment = segments.size() - 1;
if (streamPos >= segment.start && streamPos < segment.end()) {
segment.seek(stream, streamPos);
break;
}
else {
stream.seek(segment.realEnd());
// Else continue forward scan
}
}
}
}
else if (streamPos < segment.start) {
// Go back in cache
int cachedSegment = currentSegment;
while (--cachedSegment >= 0) {
currentSegment = cachedSegment;
segment = segments.get(currentSegment);
if (streamPos >= segment.start && streamPos < segment.end()) {
segment.seek(stream, streamPos);
break;
}
}
}
else {
segment.seek(stream, streamPos);
}
return segment;
}
private static boolean isAppSegmentWithId(final String segmentId, final ImageInputStream stream) throws IOException {
notNull(segmentId, "segmentId");
stream.mark();
try {
int length = stream.readUnsignedShort(); // Length including length field itself
byte[] data = new byte[Math.min(segmentId.length() + 1, length - 2)];
stream.readFully(data);
return segmentId.equals(asNullTerminatedAsciiString(data, 0));
}
finally {
stream.reset();
}
}
static String asNullTerminatedAsciiString(final byte[] data, final int offset) {
for (int i = 0; i < data.length - offset; i++) {
if (data[offset + i] == 0 || i > 255) {
return asAsciiString(data, offset, offset + i);
}
}
return null;
}
static String asAsciiString(final byte[] data, final int offset, final int length) {
return new String(data, offset, length, Charset.forName("ascii"));
}
private void streamInit() throws IOException {
stream.seek(0);
int soi = stream.readUnsignedShort();
if (soi != JPEG.SOI) {
throw new IIOException(String.format("Not a JPEG stream (starts with: 0x%04x, expected SOI: 0x%04x)", soi, JPEG.SOI));
}
else {
segment = new Segment(soi, 0, 0, 2);
segments.add(segment);
currentSegment = segments.size() - 1;
}
}
static boolean isAppSegmentMarker(final int marker) {
return marker >= JPEG.APP0 && marker <= JPEG.APP15;
}
private void repositionAsNecessary() throws IOException {
if (segment == null || streamPos < segment.start || streamPos >= segment.end()) {
try {
fetchSegment();
}
catch (EOFException ignore) {
// This might happen if the segment lengths in the stream are bad.
// We MUST leave internal state untouched in this case.
// We ignore this exception here, but client code will get
// an EOFException (or -1 return code) on subsequent reads.
}
}
}
@Override
public int read() throws IOException {
bitOffset = 0;
repositionAsNecessary();
int read = segment.read(stream);
if (read != -1) {
streamPos++;
}
return read;
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
bitOffset = 0;
// NOTE: There is a bug in the JPEGMetadata constructor (JPEGBuffer.loadBuf() method) that expects read to
// always read len bytes. Therefore, this is more complicated than it needs to... :-/
int total = 0;
while (total < len) {
repositionAsNecessary();
long bytesLeft = segment.end() - streamPos; // If no more bytes after reposition, we're at EOF
int count = bytesLeft == 0 ? -1 : segment.read(stream, b, off + total, (int) Math.min(len - total, bytesLeft));
if (count == -1) {
// EOF
if (total == 0) {
return -1;
}
break;
}
else {
streamPos += count;
total += count;
}
}
return total;
}
@SuppressWarnings({"FinalizeDoesntCallSuperFinalize"})
@Override
protected void finalize() throws Throwable {
// Empty finalizer (for improved performance; no need to call super.finalize() in this case)
}
static class Segment {
final int marker;
final long realStart;
final long start;
final long length;
Segment(final int marker, final long realStart, final long start, final long length) {
this.marker = marker;
this.realStart = realStart;
this.start = start;
this.length = length;
}
long realEnd() {
return realStart + length;
}
long end() {
return start + length;
}
public void seek(final ImageInputStream stream, final long newPos) throws IOException {
stream.seek(realStart + newPos - start);
}
public int read(final ImageInputStream stream) throws IOException {
return stream.read();
}
public int read(final ImageInputStream stream, byte[] b, int off, int len) throws IOException {
return stream.read(b, off, len);
}
@Override
public String toString() {
return String.format("0x%04x[%d-%d]", marker, realStart, realEnd());
}
}
static final class AdobeAPP14Replacement extends ReplacementSegment {
AdobeAPP14Replacement(final long realStart, final long start, final long realLength, final ImageInputStream stream) throws IOException {
super(JPEG.APP14, realStart, start, realLength, createMarkerFixedLength(stream));
}
private static byte[] createMarkerFixedLength(final ImageInputStream stream) throws IOException {
byte[] segmentData = new byte[16];
segmentData[0] = (byte) ((JPEG.APP14 >> 8) & 0xff);
segmentData[1] = (byte) (JPEG.APP14 & 0xff);
segmentData[2] = (byte) 0;
segmentData[3] = (byte) 14;
stream.readFully(segmentData, 4, segmentData.length - 4);
return segmentData;
}
}
static class ReplacementSegment extends Segment {
final long realLength;
final byte[] data;
int pos;
ReplacementSegment(final int marker, final long realStart, final long start, final long realLength, final byte[] replacementData) {
super(marker, realStart, start, replacementData.length);
this.realLength = realLength;
this.data = replacementData;
}
@Override
long realEnd() {
return realStart + realLength;
}
@Override
public void seek(final ImageInputStream stream, final long newPos) throws IOException {
pos = (int) (newPos - start);
super.seek(stream, newPos);
}
@Override
public int read(final ImageInputStream stream) {
return data[pos++] & 0xff;
}
@Override
public int read(final ImageInputStream stream, byte[] b, int off, int len) {
int length = Math.min(data.length - pos, len);
System.arraycopy(data, pos, b, off, length);
pos += length;
return length;
}
}
}
|
package com.ebp.owat.lib.datastructure.matrix.Linked;
import com.ebp.owat.lib.datastructure.matrix.Linked.utils.Direction;
import com.ebp.owat.lib.datastructure.matrix.Linked.utils.LinkedMatrixNode;
import com.ebp.owat.lib.datastructure.matrix.Linked.utils.nodePosition.FixedNode;
import com.ebp.owat.lib.datastructure.matrix.Linked.utils.nodePosition.NodePosition;
import com.ebp.owat.lib.datastructure.matrix.Matrix;
import com.ebp.owat.lib.datastructure.matrix.utils.MatrixValidator;
import com.ebp.owat.lib.datastructure.matrix.utils.coordinate.DistanceCalc;
import com.ebp.owat.lib.datastructure.matrix.utils.coordinate.MatrixCoordinate;
import com.ebp.owat.lib.datastructure.set.LongLinkedList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class LinkedMatrix<T> extends Matrix<T> {
/**
* The frequency of how often reference nodes are added.
*/
private static final long ADD_REFERENCE_FREQUENCY = 100;
/** The number of elements held in the matrix. */
protected long numElementsHeld = 0;
private long curAddCount = 0;
/**
* @return If the added node should be made a reference.
*/
private boolean addedNode(){
this.curAddCount++;
if(curAddCount >= ADD_REFERENCE_FREQUENCY){
this.curAddCount = 0;
return true;
}
return false;
}
/** The nodes we have to keep track of. */
protected Collection<NodePosition<T>> referenceNodes = new LinkedList<>();
private void initFirstNode(){
if(this.hasRowsCols()){
throw new IllegalStateException("Cannot init nodes when we already have them.");
}
LinkedMatrixNode<T> headNode = new LinkedMatrixNode<>();
this.numCols++;
this.numRows++;
for(FixedNode.FixedPosition curPos : FixedNode.FixedPosition.values()){
this.referenceNodes.add(
new FixedNode<>(this, headNode, curPos)
);
}
}
/**
* Inits this matrix if needed.
* @return If this actually init'ed the matrix.
*/
private boolean initIfNoRowsCols(){
if(!this.hasRowsCols()){
this.initFirstNode();
return true;
}
return false;
}
/**
* Resets all the node positions in the matrix.
* @return If any of the positions moved.
*/
private boolean resetNodePositions(){
boolean movedNodes = false;
for(NodePosition<T> curPos : this.referenceNodes){
movedNodes |= curPos.resetPosition();
}
return movedNodes;
}
/**
* Gets the node closest to the coordinate given.
* @param coord The coordinate we want to get.
* @return The node closest node to the coordinate given.
*/
private NodePosition<T> getClosestHeldPosition(MatrixCoordinate coord){
NodePosition<T> output = null;
for(NodePosition<T> curPosition : this.referenceNodes){
if(output == null){
output = curPosition;
continue;
}
if(DistanceCalc.nodeIsCloserThan(coord, curPosition, output)){
output = curPosition;
}
}
if(output == null){
//TODO:: handle this better?
throw new IllegalStateException("No nodes held.");
}
return output.clone();
}
/**
* Gets the matrixNode at the coordinate given.
* @param coord The coordinate of the node to get.
* @return The node at the coordinate given.
*/
private LinkedMatrixNode<T> getMatrixNode(MatrixCoordinate coord){
MatrixValidator.throwIfNotOnMatrix(this, coord);
NodePosition<T> curPosition = this.getClosestHeldPosition(coord);
while(!curPosition.baseCoordEquals(coord)){
if(curPosition.getY() > coord.getY()){
curPosition.moveNorth();
}
if(curPosition.getY() < coord.getY()){
curPosition.moveSouth();
}
if(curPosition.getX() > coord.getX()){
curPosition.moveEast();
}
if(curPosition.getX() < coord.getX()){
curPosition.moveWest();
}
}
return curPosition.getNode();
}
private LinkedMatrixNode<T> getMatrixNode(long xIn, long yIn){
return this.getMatrixNode(new MatrixCoordinate(this, xIn, yIn));
}
@Override
public void addRow() {
if(this.initIfNoRowsCols()){
return;
}
this.numRows++;
LinkedMatrixNode<T> lastNode = new LinkedMatrixNode<>();
lastNode.setNorth(this.getMatrixNode(new MatrixCoordinate(this, 0, this.getNumRows())));
for(long l = 1; l < this.getNumCols(); l++){
LinkedMatrixNode<T> curNode = new LinkedMatrixNode<>();
lastNode.setEast(curNode);
curNode.getWest().getNorth().getEast().setSouth(curNode);
if(this.addedNode()){
this.referenceNodes.add(new NodePosition<>(this, curNode));
}
lastNode = curNode;
}
this.resetNodePositions();
}
@Override
public boolean addRows(Collection<T> valuesIn) {
//TODO
return false;
}
@Override
public void addCol() {
if(this.initIfNoRowsCols()){
return;
}
this.numCols++;
LinkedMatrixNode<T> lastNode = new LinkedMatrixNode<>();
lastNode.setEast(this.getMatrixNode(new MatrixCoordinate(this, this.getNumCols(), 0)));
for(long l = 1; l < this.getNumRows(); l++){
LinkedMatrixNode<T> curNode = new LinkedMatrixNode<>();
lastNode.setWest(curNode);
curNode.getNorth().getEast().getSouth().setWest(curNode);
if(this.addedNode()){
this.referenceNodes.add(new NodePosition<>(this, curNode));
}
lastNode = curNode;
}
this.resetNodePositions();
}
@Override
public boolean addCols(Collection<T> valuesIn) {
//TODO
return false;
}
@Override
public List<T> removeRow(long rowIndex) throws IndexOutOfBoundsException {
//TODO
return null;
}
@Override
public List<T> removeCol(long colIndex) throws IndexOutOfBoundsException {
//TODO
return null;
}
@Override
public T setValue(MatrixCoordinate nodeToReplace, T newValue) {
LinkedMatrixNode<T> node = this.getMatrixNode(nodeToReplace);
T valToReturn = node.getValue();
node.setValue(newValue);
this.numElementsHeld++;
return valToReturn;
}
@Override
public boolean hasValue(MatrixCoordinate coordinate) {
LinkedMatrixNode<T> node = this.getMatrixNode(coordinate);
return node.hasValue();
}
@Override
public T clearNode(MatrixCoordinate nodeToClear) {
LinkedMatrixNode<T> node = this.getMatrixNode(nodeToClear);
this.numElementsHeld
return node.clearValue();
}
@Override
public List<T> replaceRow(MatrixCoordinate matrixCoordinate, Collection<T> newValues) throws IndexOutOfBoundsException {
//TODO
return null;
}
@Override
public List<T> replaceCol(MatrixCoordinate matrixCoordinate, Collection<T> newValues) throws IndexOutOfBoundsException {
//TODO
return null;
}
@Override
public long numElements() {
return this.numElementsHeld;
}
@Override
public T get(MatrixCoordinate coordIn) {
return this.getMatrixNode(coordIn).getValue(this.getDefaultValue());
}
@Override
public List<T> getCol(MatrixCoordinate coordIn) {
MatrixValidator.throwIfNotOnMatrix(this, coordIn);
LongLinkedList<T> output = new LongLinkedList<>();
LinkedMatrixNode<T> node = this.getMatrixNode(coordIn.getX(), 0);
output.add(node.getValue());
do{
node = node.getDir(Direction.SOUTH);
output.add(node.getValue());
}while(!node.isBorder(Direction.SOUTH));
return output;
}
@Override
public List<T> getRow(MatrixCoordinate coordIn) {
MatrixValidator.throwIfNotOnMatrix(this, coordIn);
LongLinkedList<T> output = new LongLinkedList<>();
LinkedMatrixNode<T> node = this.getMatrixNode(0, coordIn.getY());
output.add(node.getValue());
do{
node = node.getDir(Direction.EAST);
output.add(node.getValue());
}while(!node.isBorder(Direction.EAST));
return output;
}
@Override
public Matrix<T> getSubMatrix(MatrixCoordinate topLeft, long height, long width) {
//TODO
return null;
}
@Override
public void replaceSubMatrix(Matrix<T> matrix, MatrixCoordinate topLeft, long height, long width) {
//TODO
}
}
|
package org.mskcc.cbio.portal.scripts;
import org.mskcc.cbio.portal.dao.*;
import org.mskcc.cbio.portal.model.*;
import org.mskcc.cbio.portal.util.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
/**
* Code to Import Copy Number Alteration or MRNA Expression Data.
*
* @author Ethan Cerami
*/
public class ImportTabDelimData {
private HashSet<Long> importedGeneSet = new HashSet<Long>();
private static Logger logger = Logger.getLogger(ImportTabDelimData.class);
/**
* Barry Target Line: A constant currently used to indicate the RAE method.
*/
public static final String BARRY_TARGET = "Barry";
/**
* Consensus Target Line: A constant currently used to indicate consensus of multiple
* CNA calling algorithms.
*/
public static final String CONSENSUS_TARGET = "consensus";
private File mutationFile;
private String targetLine;
private int geneticProfileId;
private GeneticProfile geneticProfile;
private HashSet<String> microRnaIdSet;
/**
* Constructor.
*
* @param dataFile Data File containing CNA data.
* @param targetLine The line we want to import.
* If null, all lines are imported.
* @param geneticProfileId GeneticProfile ID.
*/
public ImportTabDelimData(File dataFile, String targetLine, int geneticProfileId) {
this.mutationFile = dataFile;
this.targetLine = targetLine;
this.geneticProfileId = geneticProfileId;
}
/**
* Constructor.
*
* @param dataFile Data File containing CNA data.
* @param geneticProfileId GeneticProfile ID.
*/
public ImportTabDelimData(File dataFile, int geneticProfileId) {
this.mutationFile = dataFile;
this.geneticProfileId = geneticProfileId;
}
/**
* Import the CNA Data.
*
* @throws IOException IO Error.
* @throws DaoException Database Error.
*/
public void importData() throws IOException, DaoException {
geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId);
FileReader reader = new FileReader(mutationFile);
BufferedReader buf = new BufferedReader(reader);
String headerLine = buf.readLine();
String parts[] = headerLine.split("\t");
int sampleStartIndex = getStartIndex(parts);
int hugoSymbolIndex = getHugoSymbolIndex(parts);
int entrezGeneIdIndex = getEntrezGeneIdIndex(parts);
String sampleIds[];
// Branch, depending on targetLine setting
if (targetLine == null) {
sampleIds = new String[parts.length - sampleStartIndex];
System.arraycopy(parts, sampleStartIndex, sampleIds, 0, parts.length - sampleStartIndex);
} else {
sampleIds = new String[parts.length - sampleStartIndex];
System.arraycopy(parts, sampleStartIndex, sampleIds, 0, parts.length - sampleStartIndex);
}
ImportDataUtil.addPatients(sampleIds, geneticProfileId);
ImportDataUtil.addSamples(sampleIds, geneticProfileId);
ProgressMonitor.setCurrentMessage("Import tab delimited data for " + sampleIds.length + " samples.");
// Add Samples to the Database
ArrayList <Integer> orderedSampleList = new ArrayList<Integer>();
ArrayList <Integer> filteredSampleIndices = new ArrayList<Integer>();
for (int i = 0; i < sampleIds.length; i++) {
Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(),
StableIdUtil.getSampleId(sampleIds[i]));
if (sample == null) {
assert StableIdUtil.isNormal(sampleIds[i]);
filteredSampleIndices.add(i);
continue;
}
if (!DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId)) {
DaoSampleProfile.addSampleProfile(sample.getInternalId(), geneticProfileId);
}
orderedSampleList.add(sample.getInternalId());
}
DaoGeneticProfileSamples.addGeneticProfileSamples(geneticProfileId, orderedSampleList);
String line = buf.readLine();
int numRecordsStored = 0;
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance();
boolean discritizedCnaProfile = geneticProfile!=null
&& geneticProfile.getGeneticAlterationType() == GeneticAlterationType.COPY_NUMBER_ALTERATION
&& geneticProfile.showProfileInAnalysisTab();
boolean rppaProfile = geneticProfile!=null
&& geneticProfile.getGeneticAlterationType() == GeneticAlterationType.PROTEIN_LEVEL
&& "Composite.Element.Ref".equalsIgnoreCase(parts[0]);
Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents = null;
long cnaEventId = 0;
if (discritizedCnaProfile) {
existingCnaEvents = new HashMap<CnaEvent.Event, CnaEvent.Event>();
for (CnaEvent.Event event : DaoCnaEvent.getAllCnaEvents()) {
existingCnaEvents.put(event, event);
}
cnaEventId = DaoCnaEvent.getLargestCnaEventId();
MySQLbulkLoader.bulkLoadOn();
}
int lenParts = parts.length;
while (line != null) {
ProgressMonitor.incrementCurValue();
ConsoleUtil.showProgress();
// Ignore lines starting with
if (!line.startsWith("#") && line.trim().length() > 0) {
parts = line.split("\t",-1);
if (parts.length>lenParts) {
if (line.split("\t").length>lenParts) {
System.err.println("The following line has more fields (" + parts.length
+ ") than the headers(" + lenParts + "): \n"+parts[0]);
}
}
String values[] = (String[]) ArrayUtils.subarray(parts, sampleStartIndex, parts.length>lenParts?lenParts:parts.length);
values = filterOutNormalValues(filteredSampleIndices, values);
String hugo = parts[hugoSymbolIndex];
if (hugo!=null && hugo.isEmpty()) {
hugo = null;
}
String entrez = null;
if (entrezGeneIdIndex!=-1) {
entrez = parts[entrezGeneIdIndex];
}
if (entrez!=null && !entrez.matches("[0-9]+")) {
entrez = null;
}
if (hugo != null || entrez != null) {
if (hugo != null && (hugo.contains("
// Ignore gene IDs separated by ///. This indicates that
// the line contains information regarding multiple genes, and
// we cannot currently handle this.
// the line contains information regarding an unknown gene, and
// we cannot currently handle this.
logger.debug("Ignoring gene ID: " + hugo);
} else {
List<CanonicalGene> genes = null;
if (entrez!=null) {
CanonicalGene gene = daoGene.getGene(Long.parseLong(entrez));
if (gene!=null) {
genes = Arrays.asList(gene);
}
}
if (genes==null && hugo != null) {
if (rppaProfile) {
genes = parseRPPAGenes(hugo);
} else {
// deal with multiple symbols separate by |, use the first one
int ix = hugo.indexOf("|");
if (ix>0) {
hugo = hugo.substring(0, ix);
}
genes = daoGene.guessGene(hugo);
}
}
if (genes == null || genes.isEmpty()) {
genes = Collections.emptyList();
}
// If no target line is specified or we match the target, process.
if (targetLine == null || parts[0].equals(targetLine)) {
if (genes.isEmpty()) {
// if gene is null, we might be dealing with a micro RNA ID
if (hugo != null && hugo.toLowerCase().contains("-mir-")) {
// if (microRnaIdSet.contains(geneId)) {
// storeMicroRnaAlterations(values, daoMicroRnaAlteration, geneId);
// numRecordsStored++;
// } else {
ProgressMonitor.logWarning("microRNA is not known to me: [" + hugo
+ "]. Ignoring it "
+ "and all tab-delimited data associated with it!");
} else {
String gene = (hugo != null) ? hugo : entrez;
ProgressMonitor.logWarning("Gene not found: [" + gene
+ "]. Ignoring it "
+ "and all tab-delimited data associated with it!");
}
} else if (genes.size()==1) {
if (discritizedCnaProfile) {
long entrezGeneId = genes.get(0).getEntrezGeneId();
int n = values.length;
if (n==0)
System.out.println();
int i = values[0].equals(""+entrezGeneId) ? 1:0;
for (; i<n; i++) {
// temporary solution -- change partial deletion back to full deletion.
if (values[i].equals(GeneticAlterationType.PARTIAL_DELETION)) {
values[i] = GeneticAlterationType.HOMOZYGOUS_DELETION;
}
if (values[i].equals(GeneticAlterationType.AMPLIFICATION)
// || values[i].equals(GeneticAlterationType.GAIN)
// || values[i].equals(GeneticAlterationType.ZERO)
// || values[i].equals(GeneticAlterationType.HEMIZYGOUS_DELETION)
|| values[i].equals(GeneticAlterationType.HOMOZYGOUS_DELETION)) {
CnaEvent cnaEvent = new CnaEvent(orderedSampleList.get(i), geneticProfileId, entrezGeneId, Short.parseShort(values[i]));
if (existingCnaEvents.containsKey(cnaEvent.getEvent())) {
cnaEvent.setEventId(existingCnaEvents.get(cnaEvent.getEvent()).getEventId());
DaoCnaEvent.addCaseCnaEvent(cnaEvent, false);
} else {
cnaEvent.setEventId(++cnaEventId);
DaoCnaEvent.addCaseCnaEvent(cnaEvent, true);
existingCnaEvents.put(cnaEvent.getEvent(), cnaEvent.getEvent());
}
}
}
}
storeGeneticAlterations(values, daoGeneticAlteration, genes.get(0));
numRecordsStored++;
} else {
for (CanonicalGene gene : genes) {
if (gene.isMicroRNA() || rppaProfile) { // for micro rna or protein data, duplicate the data
storeGeneticAlterations(values, daoGeneticAlteration, gene);
}
}
}
}
}
}
}
line = buf.readLine();
}
if (MySQLbulkLoader.isBulkLoad()) {
MySQLbulkLoader.flushAll();
}
if (numRecordsStored == 0) {
throw new DaoException ("Something has gone wrong! I did not save any records" +
" to the database!");
}
}
private void storeGeneticAlterations(String[] values, DaoGeneticAlteration daoGeneticAlteration,
CanonicalGene gene) throws DaoException {
// Check that we have not already imported information regarding this gene.
// This is an important check, because a GISTIC or RAE file may contain
// multiple rows for the same gene, and we only want to import the first row.
if (!importedGeneSet.contains(gene.getEntrezGeneId())) {
daoGeneticAlteration.addGeneticAlterations(geneticProfileId, gene.getEntrezGeneId(), values);
importedGeneSet.add(gene.getEntrezGeneId());
}
}
private List<CanonicalGene> parseRPPAGenes(String antibodyWithGene) throws DaoException {
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
String[] parts = antibodyWithGene.split("\\|");
String[] symbols = parts[0].split(" ");
String arrayId = parts[1];
List<CanonicalGene> genes = new ArrayList<CanonicalGene>();
for (String symbol : symbols) {
CanonicalGene gene = daoGene.getNonAmbiguousGene(symbol, null);
if (gene!=null) {
genes.add(gene);
}
}
Pattern p = Pattern.compile("(p[STY][0-9]+)");
Matcher m = p.matcher(arrayId);
String type, residue;
if (!m.find()) {
type = "protein_level";
return genes;
} else {
type = "phosphorylation";
residue = m.group(1);
return importPhosphoGene(genes, residue);
}
}
private List<CanonicalGene> importPhosphoGene(List<CanonicalGene> genes, String residue) throws DaoException {
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
List<CanonicalGene> phosphoGenes = new ArrayList<CanonicalGene>();
for (CanonicalGene gene : genes) {
Set<String> aliases = new HashSet<String>();
aliases.add("rppa-phospho");
aliases.add("phosphoprotein");
aliases.add("phospho"+gene.getStandardSymbol());
String phosphoSymbol = gene.getStandardSymbol()+"_"+residue;
CanonicalGene phosphoGene = daoGene.getGene(phosphoSymbol);
if (phosphoGene==null) {
phosphoGene = new CanonicalGene(phosphoSymbol, aliases);
phosphoGene.setType(CanonicalGene.PHOSPHOPROTEIN_TYPE);
phosphoGene.setCytoband(gene.getCytoband());
daoGene.addGene(phosphoGene);
}
phosphoGenes.add(phosphoGene);
}
return phosphoGenes;
}
private int getHugoSymbolIndex(String[] headers) {
return targetLine==null ? 0 : 1;
}
private int getEntrezGeneIdIndex(String[] headers) {
for (int i = 0; i<headers.length; i++) {
if (headers[i].equalsIgnoreCase("Entrez_Gene_Id")) {
return i;
}
}
return -1;
}
private int getStartIndex(String[] headers) {
int startIndex = targetLine==null ? 1 : 2;
for (int i=startIndex; i<headers.length; i++) {
String h = headers[i];
if (!h.equalsIgnoreCase("Gene Symbol") &&
!h.equalsIgnoreCase("Hugo_Symbol") &&
!h.equalsIgnoreCase("Entrez_Gene_Id") &&
!h.equalsIgnoreCase("Locus ID") &&
!h.equalsIgnoreCase("Cytoband") &&
!h.equalsIgnoreCase("Composite.Element.Ref")) {
return i;
}
}
return startIndex;
}
private String[] filterOutNormalValues(ArrayList <Integer> filteredSampleIndices, String[] values)
{
ArrayList<String> filteredValues = new ArrayList<String>();
for (int lc = 0; lc < values.length; lc++) {
if (!filteredSampleIndices.contains(lc)) {
filteredValues.add(values[lc]);
}
}
return filteredValues.toArray(new String[filteredValues.size()]);
}
}
|
package org.mskcc.cbio.portal.scripts;
import org.mskcc.cbio.portal.dao.*;
import org.mskcc.cbio.portal.model.*;
import org.mskcc.cbio.portal.util.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Code to Import Copy Number Alteration, MRNA Expression Data, or protein RPPA data
*
* @author Ethan Cerami
*/
public class ImportTabDelimData {
private HashSet<Long> importedGeneSet = new HashSet<Long>();
private static Logger logger = Logger.getLogger(ImportTabDelimData.class);
private File mutationFile;
private String targetLine;
private int geneticProfileId;
private GeneticProfile geneticProfile;
/**
* Constructor.
*
* @param dataFile Data File containing Copy Number Alteration, MRNA Expression Data, or protein RPPA data
* @param targetLine The line we want to import.
* If null, all lines are imported.
* @param geneticProfileId GeneticProfile ID.
*
* @deprecated : TODO shall we deprecate this feature (i.e. the targetLine)?
*/
public ImportTabDelimData(File dataFile, String targetLine, int geneticProfileId) {
this.mutationFile = dataFile;
this.targetLine = targetLine;
this.geneticProfileId = geneticProfileId;
}
/**
* Constructor.
*
* @param dataFile Data File containing Copy Number Alteration, MRNA Expression Data, or protein RPPA data
* @param geneticProfileId GeneticProfile ID.
*/
public ImportTabDelimData(File dataFile, int geneticProfileId) {
this.mutationFile = dataFile;
this.geneticProfileId = geneticProfileId;
}
/**
* Import the Copy Number Alteration, MRNA Expression Data, or protein RPPA data
*
* @throws IOException IO Error.
* @throws DaoException Database Error.
*/
public void importData(int numLines) throws IOException, DaoException {
geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId);
FileReader reader = new FileReader(mutationFile);
BufferedReader buf = new BufferedReader(reader);
String headerLine = buf.readLine();
String parts[] = headerLine.split("\t");
int numRecordsToAdd = 0;
try {
//Whether data regards CNA or RPPA:
boolean discritizedCnaProfile = geneticProfile!=null
&& geneticProfile.getGeneticAlterationType() == GeneticAlterationType.COPY_NUMBER_ALTERATION
&& geneticProfile.showProfileInAnalysisTab();
boolean rppaProfile = geneticProfile!=null
&& geneticProfile.getGeneticAlterationType() == GeneticAlterationType.PROTEIN_LEVEL
&& "Composite.Element.Ref".equalsIgnoreCase(parts[0]);
int hugoSymbolIndex = getHugoSymbolIndex(parts);
int entrezGeneIdIndex = getEntrezGeneIdIndex(parts);
int rppaGeneRefIndex = getRppaGeneRefIndex(parts);
int sampleStartIndex = getStartIndex(parts, hugoSymbolIndex, entrezGeneIdIndex, rppaGeneRefIndex);
if (rppaProfile) {
if (rppaGeneRefIndex == -1)
throw new RuntimeException("Error: the following column should be present for RPPA data: Composite.Element.Ref");
}
else if (hugoSymbolIndex == -1 && entrezGeneIdIndex == -1)
throw new RuntimeException("Error: at least one of the following columns should be present: Hugo_Symbol or Entrez_Gene_Id");
String sampleIds[];
sampleIds = new String[parts.length - sampleStartIndex];
System.arraycopy(parts, sampleStartIndex, sampleIds, 0, parts.length - sampleStartIndex);
//TODO - lines below should be removed. Agreed with JJ to remove this as soon as MSK moves to new validation
//procedure. In this new procedure, Patients and Samples should only be added
//via the corresponding ImportClinicalData process. Furthermore, the code below is wrong as it assumes one
//sample per patient, which is not always the case.
ImportDataUtil.addPatients(sampleIds, geneticProfileId);
int nrUnknownSamplesAdded = ImportDataUtil.addSamples(sampleIds, geneticProfileId);
if (nrUnknownSamplesAdded > 0) {
ProgressMonitor.logWarning("WARNING: Number of samples added on the fly because they were missing in clinical data: " + nrUnknownSamplesAdded);
}
ProgressMonitor.setCurrentMessage(" --> total number of samples: " + sampleIds.length);
ProgressMonitor.setCurrentMessage(" --> total number of data lines: " + (numLines-1));
// link Samples to the genetic profile
ArrayList <Integer> orderedSampleList = new ArrayList<Integer>();
ArrayList <Integer> filteredSampleIndices = new ArrayList<Integer>();
for (int i = 0; i < sampleIds.length; i++) {
Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(),
StableIdUtil.getSampleId(sampleIds[i]));
if (sample == null) {
assert StableIdUtil.isNormal(sampleIds[i]);
filteredSampleIndices.add(i);
continue;
}
if (!DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId)) {
DaoSampleProfile.addSampleProfile(sample.getInternalId(), geneticProfileId);
}
orderedSampleList.add(sample.getInternalId());
}
DaoGeneticProfileSamples.addGeneticProfileSamples(geneticProfileId, orderedSampleList);
//Gene cache:
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
//Object to insert records in the generic 'genetic_alteration' table:
DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance();
//cache for data found in cna_event' table:
Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents = null;
if (discritizedCnaProfile) {
existingCnaEvents = new HashMap<CnaEvent.Event, CnaEvent.Event>();
for (CnaEvent.Event event : DaoCnaEvent.getAllCnaEvents()) {
existingCnaEvents.put(event, event);
}
MySQLbulkLoader.bulkLoadOn();
}
int lenParts = parts.length;
String line = buf.readLine();
while (line != null) {
ProgressMonitor.incrementCurValue();
ConsoleUtil.showProgress();
if (parseLine(line, lenParts, sampleStartIndex,
hugoSymbolIndex, entrezGeneIdIndex, rppaGeneRefIndex,
rppaProfile, discritizedCnaProfile,
daoGene,
filteredSampleIndices, orderedSampleList,
existingCnaEvents, daoGeneticAlteration))
numRecordsToAdd++;
line = buf.readLine();
}
if (MySQLbulkLoader.isBulkLoad()) {
MySQLbulkLoader.flushAll();
}
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
buf.close();
if (numRecordsToAdd == 0) {
throw new DaoException ("Something has gone wrong! I did not save any records" +
" to the database!");
}
}
}
private boolean parseLine(String line, int nrColumns, int sampleStartIndex,
int hugoSymbolIndex, int entrezGeneIdIndex, int rppaGeneRefIndex,
boolean rppaProfile, boolean discritizedCnaProfile,
DaoGeneOptimized daoGene,
List <Integer> filteredSampleIndices, List <Integer> orderedSampleList,
Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents, DaoGeneticAlteration daoGeneticAlteration
) throws DaoException {
boolean recordStored = false;
// Ignore lines starting with
if (!line.startsWith("#") && line.trim().length() > 0) {
String[] parts = line.split("\t",-1);
if (parts.length>nrColumns) {
if (line.split("\t").length>nrColumns) {
System.err.println("The following line has more fields (" + parts.length
+ ") than the headers(" + nrColumns + "): \n"+parts[0]);
}
}
String values[] = (String[]) ArrayUtils.subarray(parts, sampleStartIndex, parts.length>nrColumns?nrColumns:parts.length);
values = filterOutNormalValues(filteredSampleIndices, values);
String geneSymbol = null;
if (hugoSymbolIndex != -1) {
geneSymbol = parts[hugoSymbolIndex];
}
//RPPA:
if (rppaGeneRefIndex != -1) {
geneSymbol = parts[rppaGeneRefIndex];
}
if (geneSymbol!=null && geneSymbol.isEmpty()) {
geneSymbol = null;
}
String entrez = null;
if (entrezGeneIdIndex!=-1) {
entrez = parts[entrezGeneIdIndex];
}
if (entrez!=null && !entrez.matches("-?[0-9]+")) {
entrez = null;
}
//If all are empty, skip line:
if (geneSymbol == null && entrez == null) {
ProgressMonitor.logWarning("Ignoring line with no Hugo_Symbol or Entrez_Id " + (rppaProfile? "or Composite.Element.REF ":"") + "value");
return false;
}
else {
if (geneSymbol != null && (geneSymbol.contains("
// Ignore gene IDs separated by ///. This indicates that
// the line contains information regarding multiple genes, and
// we cannot currently handle this.
// the line contains information regarding an unknown gene, and
// we cannot currently handle this.
ProgressMonitor.logWarning("Ignoring gene ID: " + geneSymbol);
} else {
List<CanonicalGene> genes = null;
//If rppa, parse genes from "Composite.Element.REF" column:
if (rppaProfile) {
genes = parseRPPAGenes(geneSymbol);
}
else {
//try entrez:
if (entrez!=null) {
CanonicalGene gene = daoGene.getGene(Long.parseLong(entrez));
if (gene!=null) {
genes = Arrays.asList(gene);
}
}
//no entrez, try hugo:
if (genes==null && geneSymbol != null) {
// deal with multiple symbols separate by |, use the first one
int ix = geneSymbol.indexOf("|");
if (ix>0) {
geneSymbol = geneSymbol.substring(0, ix);
}
genes = daoGene.getGene(geneSymbol, true);
}
}
if (genes == null || genes.isEmpty()) {
genes = Collections.emptyList();
}
// If no target line is specified or we match the target, process.
if (targetLine == null || parts[0].equals(targetLine)) {
if (genes.isEmpty()) {
// if gene is null, we might be dealing with a micro RNA ID
if (geneSymbol != null && geneSymbol.toLowerCase().contains("-mir-")) {
// if (microRnaIdSet.contains(geneId)) {
// storeMicroRnaAlterations(values, daoMicroRnaAlteration, geneId);
// numRecordsStored++;
// } else {
ProgressMonitor.logWarning("microRNA is not known to me: [" + geneSymbol
+ "]. Ignoring it "
+ "and all tab-delimited data associated with it!");
} else {
String gene = (geneSymbol != null) ? geneSymbol : entrez;
ProgressMonitor.logWarning("Gene not found: [" + gene
+ "]. Ignoring it "
+ "and all tab-delimited data associated with it!");
}
} else if (genes.size()==1) {
if (discritizedCnaProfile) {
long entrezGeneId = genes.get(0).getEntrezGeneId();
int n = values.length;
if (n==0)
System.out.println();
int i = values[0].equals(""+entrezGeneId) ? 1:0;
for (; i<n; i++) {
// temporary solution -- change partial deletion back to full deletion.
if (values[i].equals(GeneticAlterationType.PARTIAL_DELETION)) {
values[i] = GeneticAlterationType.HOMOZYGOUS_DELETION;
}
if (values[i].equals(GeneticAlterationType.AMPLIFICATION)
// || values[i].equals(GeneticAlterationType.GAIN) >> skipping GAIN, ZERO, HEMIZYGOUS_DELETION to minimize size of dataset in DB
// || values[i].equals(GeneticAlterationType.ZERO)
// || values[i].equals(GeneticAlterationType.HEMIZYGOUS_DELETION)
|| values[i].equals(GeneticAlterationType.HOMOZYGOUS_DELETION)) {
CnaEvent cnaEvent = new CnaEvent(orderedSampleList.get(i), geneticProfileId, entrezGeneId, Short.parseShort(values[i]));
if (existingCnaEvents.containsKey(cnaEvent.getEvent())) {
cnaEvent.setEventId(existingCnaEvents.get(cnaEvent.getEvent()).getEventId());
DaoCnaEvent.addCaseCnaEvent(cnaEvent, false);
} else {
//cnaEvent.setEventId(++cnaEventId); not needed anymore, column now has AUTO_INCREMENT
DaoCnaEvent.addCaseCnaEvent(cnaEvent, true);
existingCnaEvents.put(cnaEvent.getEvent(), cnaEvent.getEvent());
}
}
}
}
storeGeneticAlterations(values, daoGeneticAlteration, genes.get(0));
recordStored = true;
} else {
//TODO - review: is this still correct?
for (CanonicalGene gene : genes) {
if (gene.isMicroRNA() || rppaProfile) { // for micro rna or protein data, duplicate the data
storeGeneticAlterations(values, daoGeneticAlteration, gene);
recordStored = true;
}
}
if (!recordStored) {
//this means that genes.size() > 1 and data was not rppa or microRNA, so it is not defined how to deal with
//the ambiguous alias list. Report this:
ProgressMonitor.logWarning("Gene symbol " + geneSymbol + " found to be ambiguous. Record will be skipped for this gene.");
}
}
}
}
}
}
return recordStored;
}
private void storeGeneticAlterations(String[] values, DaoGeneticAlteration daoGeneticAlteration,
CanonicalGene gene) throws DaoException {
// Check that we have not already imported information regarding this gene.
// This is an important check, because a GISTIC or RAE file may contain
// multiple rows for the same gene, and we only want to import the first row.
if (!importedGeneSet.contains(gene.getEntrezGeneId())) {
daoGeneticAlteration.addGeneticAlterations(geneticProfileId, gene.getEntrezGeneId(), values);
importedGeneSet.add(gene.getEntrezGeneId());
}
else {
//TODO - review this part - maybe it should be an Exception instead of just a warning.
ProgressMonitor.logWarning("Gene " + gene.getHugoGeneSymbolAllCaps() + " found to be duplicated in your file. Duplicated row will be ignored!");
}
}
private List<CanonicalGene> parseRPPAGenes(String antibodyWithGene) throws DaoException {
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
String[] parts = antibodyWithGene.split("\\|");
String[] symbols = parts[0].split(" ");
String arrayId = parts[1];
List<CanonicalGene> genes = new ArrayList<CanonicalGene>();
for (String symbol : symbols) {
CanonicalGene gene = daoGene.getNonAmbiguousGene(symbol, null);
if (gene!=null) {
genes.add(gene);
}
else {
ProgressMonitor.logWarning("Gene " + symbol + " not found in DB. Record will be skipped for this gene.");
}
}
Pattern p = Pattern.compile("(p[STY][0-9]+)");
Matcher m = p.matcher(arrayId);
String residue;
if (!m.find()) {
//type is "protein_level":
return genes;
} else {
//type is "phosphorylation":
residue = m.group(1);
return importPhosphoGene(genes, residue);
}
}
private List<CanonicalGene> importPhosphoGene(List<CanonicalGene> genes, String residue) throws DaoException {
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
List<CanonicalGene> phosphoGenes = new ArrayList<CanonicalGene>();
for (CanonicalGene gene : genes) {
Set<String> aliases = new HashSet<String>();
aliases.add("rppa-phospho");
aliases.add("phosphoprotein");
aliases.add("phospho"+gene.getStandardSymbol());
String phosphoSymbol = gene.getStandardSymbol()+"_"+residue;
CanonicalGene phosphoGene = daoGene.getGene(phosphoSymbol);
if (phosphoGene==null) {
phosphoGene = new CanonicalGene(phosphoSymbol, aliases);
phosphoGene.setType(CanonicalGene.PHOSPHOPROTEIN_TYPE);
phosphoGene.setCytoband(gene.getCytoband());
daoGene.addGene(phosphoGene);
}
phosphoGenes.add(phosphoGene);
}
return phosphoGenes;
}
private int getHugoSymbolIndex(String[] headers) {
for (int i = 0; i<headers.length; i++) {
if (headers[i].equalsIgnoreCase("Hugo_Symbol")) {
return i;
}
}
return -1;
}
private int getEntrezGeneIdIndex(String[] headers) {
for (int i = 0; i<headers.length; i++) {
if (headers[i].equalsIgnoreCase("Entrez_Gene_Id")) {
return i;
}
}
return -1;
}
private int getRppaGeneRefIndex(String[] headers) {
for (int i = 0; i<headers.length; i++) {
if (headers[i].equalsIgnoreCase("Composite.Element.Ref")) {
return i;
}
}
return -1;
}
private int getStartIndex(String[] headers, int hugoSymbolIndex, int entrezGeneIdIndex, int rppaGeneRefIndex) {
int startIndex = -1;
for (int i=0; i<headers.length; i++) {
String h = headers[i];
//if the column is not one of the gene symbol/gene ide columns or other pre-sample columns:
if (!h.equalsIgnoreCase("Gene Symbol") &&
!h.equalsIgnoreCase("Hugo_Symbol") &&
!h.equalsIgnoreCase("Entrez_Gene_Id") &&
!h.equalsIgnoreCase("Locus ID") &&
!h.equalsIgnoreCase("Cytoband") &&
!h.equalsIgnoreCase("Composite.Element.Ref")) {
//and the column is found after hugoSymbolIndex and entrezGeneIdIndex:
if (i > hugoSymbolIndex && i > entrezGeneIdIndex && i > rppaGeneRefIndex) {
//then we consider this the start of the sample columns:
startIndex = i;
break;
}
}
}
if (startIndex == -1)
throw new RuntimeException("Could not find a sample column in the file");
return startIndex;
}
private String[] filterOutNormalValues(List <Integer> filteredSampleIndices, String[] values)
{
ArrayList<String> filteredValues = new ArrayList<String>();
for (int lc = 0; lc < values.length; lc++) {
if (!filteredSampleIndices.contains(lc)) {
filteredValues.add(values[lc]);
}
}
return filteredValues.toArray(new String[filteredValues.size()]);
}
}
|
package org.jtalks.jcommune.web.controller;
import org.jtalks.jcommune.model.entity.Post;
import org.jtalks.jcommune.service.PostService;
import org.jtalks.jcommune.service.TopicService;
import org.jtalks.jcommune.service.exceptions.NotFoundException;
import org.jtalks.jcommune.web.dto.BreadcrumbBuilder;
import org.jtalks.jcommune.web.dto.PostDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
/**
* @author Osadchuck Eugeny
* @author Kravchenko Vitaliy
* @author Kirill Afonin
*/
@Controller
public class PostController {
public static final String TOPIC_ID = "topicId";
public static final String BRANCH_ID = "branchId";
public static final String POST_ID = "postId";
private final TopicService topicService;
private final PostService postService;
private BreadcrumbBuilder breadcrumbBuilder = new BreadcrumbBuilder();
/**
* Constructor. Injects {@link TopicService}.
*
* @param topicService {@link TopicService} instance to be injected
* @param postService {@link PostService} instance to be injected
*/
@Autowired
public PostController(TopicService topicService, PostService postService) {
this.topicService = topicService;
this.postService = postService;
}
/**
* This method allows us to set the breadcrumb builder.
* This can be useful for testing to mock/stub the real builder.
*
* @param breadcrumbBuilder builder to be used when constructing breadcrumb objects
*/
public void setBreadcrumbBuilder(BreadcrumbBuilder breadcrumbBuilder) {
this.breadcrumbBuilder = breadcrumbBuilder;
}
/**
* Redirect user to confirmation page.
*
* @param topicId topic id, this in topic which contains post which should be deleted
* @param postId post id to delete
* @param branchId branch containing topic
* @return {@code ModelAndView} with to parameter topicId and postId
*/
@RequestMapping(method = RequestMethod.GET, value = "/branch/{branchId}/topic/{topicId}/post/{postId}/delete")
public ModelAndView deleteConfirmPage(@PathVariable("topicId") Long topicId,
@PathVariable("postId") Long postId,
@PathVariable("branchId") Long branchId) {
return new ModelAndView("deletePost")
.addObject("topicId", topicId)
.addObject("postId", postId)
.addObject("branchId", branchId);
}
/**
* Delete post by given id.
*
* @param topicId topic id, this in topic which contains post which should be deleted
* also used for redirection back to topic.
* @param postId post
* @param branchId branch containing topic
* @return redirect to topic page
* @throws org.jtalks.jcommune.service.exceptions.NotFoundException
* when topic or post not found
*/
@RequestMapping(method = RequestMethod.DELETE, value = "/branch/{branchId}/topic/{topicId}/post/{postId}")
public ModelAndView delete(@PathVariable("topicId") Long topicId,
@PathVariable("postId") Long postId,
@PathVariable("branchId") Long branchId) throws NotFoundException {
topicService.deletePost(topicId, postId);
return new ModelAndView(new StringBuilder()
.append("redirect:/topic/")
.append(topicId)
.append(".html").toString());
}
/**
* Edit post by given id.
*
* @param topicId topic id
* @param postId post id
* @param branchId branch containing topic
* @return redirect to post form page
* @throws org.jtalks.jcommune.service.exceptions.NotFoundException
* when topic or post not found
*/
@RequestMapping(value = "/branch/{branchId}/topic/{topicId}/post/{postId}/edit", method = RequestMethod.GET)
public ModelAndView edit(@PathVariable(BRANCH_ID) Long branchId,
@PathVariable(TOPIC_ID) Long topicId,
@PathVariable(POST_ID) Long postId) throws NotFoundException {
Post post = postService.get(postId);
return new ModelAndView("postForm")
.addObject("postDto", PostDto.getDtoFor(post))
.addObject(BRANCH_ID, branchId)
.addObject(TOPIC_ID, topicId)
.addObject(POST_ID, postId)
.addObject("breadcrumbList", breadcrumbBuilder.getForumBreadcrumb(topicService.get(topicId)));
}
/**
* Save post.
*
* @param postDto Dto populated in form
* @param result validation result
* @param branchId hold the current branchId
* @param topicId the current topicId
* @param postId the current postId
* @return {@code ModelAndView} object which will be redirect to topic page
* if saved successfully or show form with error message
* @throws org.jtalks.jcommune.service.exceptions.NotFoundException
* when topic, branch or post not found
*/
@RequestMapping(value = "/branch/{branchId}/topic/{topicId}/post/{postId}/save", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView save(@Valid @ModelAttribute PostDto postDto,
BindingResult result,
@PathVariable(BRANCH_ID) Long branchId,
@PathVariable(TOPIC_ID) Long topicId,
@PathVariable(POST_ID) Long postId) throws NotFoundException {
if (result.hasErrors()) {
return new ModelAndView("postForm")
.addObject(BRANCH_ID, branchId)
.addObject(TOPIC_ID, topicId)
.addObject(POST_ID, postId);
}
topicService.savePost(topicId, postDto.getId(), postDto.getBodyText());
return new ModelAndView("redirect:/branch/" + branchId + "/topic/" + topicId + ".html");
}
}
|
package com.atlassian.jira.plugins.dvcs.listener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import com.atlassian.crowd.model.event.UserEvent;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.event.web.action.admin.UserAddedEvent;
import com.atlassian.jira.plugins.dvcs.model.Organization;
import com.atlassian.jira.plugins.dvcs.service.OrganizationService;
import com.atlassian.jira.plugins.dvcs.service.remote.DvcsCommunicator;
import com.atlassian.jira.plugins.dvcs.service.remote.DvcsCommunicatorProvider;
public class DvcsAddUserListener implements InitializingBean
{
private static final String SPLITTER = ":";
private static final Logger log = LoggerFactory.getLogger(DvcsAddUserListener.class);
public static String ORGANIZATION_SELECTOR_REQUEST_PARAM = "dvcs_org_selector";
public static String USERNAME_PARAM = "username";
public static String EMAIL_PARAM = "email";
private final EventPublisher eventPublisher;
private final OrganizationService organizationService;
private final DvcsCommunicatorProvider communicatorProvider;
public DvcsAddUserListener(EventPublisher eventPublisher, OrganizationService organizationService, DvcsCommunicatorProvider communicatorProvider)
{
super();
this.eventPublisher = eventPublisher;
this.organizationService = organizationService;
this.communicatorProvider = communicatorProvider;
}
@EventListener
public void onUserAddViaInterface(UserAddedEvent event)
{
Map<String, String[]> parameters = event.getRequestParameters();
String[] organizationIdsAndGroupSlugs = parameters.get(ORGANIZATION_SELECTOR_REQUEST_PARAM);
if (organizationIdsAndGroupSlugs == null || organizationIdsAndGroupSlugs.length == 0)
{
return;
}
Collection<Invitations> invitationsFor = toInvitations(organizationIdsAndGroupSlugs);
String username = parameters.get(USERNAME_PARAM)[0];
String email = parameters.get(EMAIL_PARAM)[0];
// invite
invite(username, email, invitationsFor);
}
private Collection<Invitations> toInvitations(String[] organizationIdsAndGroupSlugs)
{
Map<Integer, Invitations> orgIdsToInvitations = new HashMap<Integer, DvcsAddUserListener.Invitations>();
for (String requestParamToken : organizationIdsAndGroupSlugs)
{
String [] tokens = requestParamToken.split(SPLITTER);
Integer orgId = Integer.parseInt(tokens [0]);
String slug = tokens[1];
Invitations existingInvitations = orgIdsToInvitations.get(orgId);
// first time organization ?
if (existingInvitations == null) {
Invitations newInvitations = new Invitations();
newInvitations.organizaton = organizationService.get(orgId, false);
orgIdsToInvitations.put(orgId, newInvitations);
existingInvitations = newInvitations;
}
existingInvitations.groupSlugs.add(slug);
}
return orgIdsToInvitations.values();
}
@EventListener
public void onUserAddViaCrowd(UserEvent event)
{
String username = event.getUser().getName();
String email = event.getUser().getEmailAddress();
List<Organization> defaultOrganizations = organizationService.getAutoInvitionOrganizations();
if (CollectionUtils.isEmpty(defaultOrganizations))
{
return;
}
// invite
}
private void invite(String username, String email, Collection<Invitations> invitations)
{
if (CollectionUtils.isNotEmpty(invitations)) {
for (Invitations invitation : invitations)
{
Collection<String> groupSlugs = invitation.groupSlugs;
Organization organizaton = invitation.organizaton;
invite(username, email, organizaton, groupSlugs);
}
}
}
private void invite(String username, String email, Organization organization, Collection<String> groupSlugs)
{
if (CollectionUtils.isNotEmpty(groupSlugs)) {
DvcsCommunicator communicator = communicatorProvider.getCommunicator(organization.getDvcsType());
communicator.inviteUser(organization, groupSlugs, email);
}
}
@Override
public void afterPropertiesSet() throws Exception
{
eventPublisher.register(this);
}
static class Invitations {
Organization organizaton;
Collection<String> groupSlugs = new ArrayList<String>();
}
}
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import com.redhat.ceylon.compiler.js.JsCompiler;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Package;
/**
* Some hack before a proper unit test harness is put in place
*
* @author Emmanuel Bernard <[email protected]>
*/
public class MainForJsTest {
private static final class JsModuleCompiler extends JsCompiler {
private final Map<Package, PrintWriter> output;
private JsModuleCompiler(TypeChecker tc, Map<Package, PrintWriter> output) {
super(tc);
this.output = output;
}
@Override
protected Writer getWriter(PhasedUnit pu) {
Package pkg = pu.getPackage();
PrintWriter writer = output.get(pkg);
if (writer==null) {
try {
File file = new File("build/test/node_modules/"+
toOutputPath(pkg));
file.getParentFile().mkdirs();
if (file.exists()) file.delete();
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
writer = new PrintWriter(fileWriter);
output.put(pkg, writer);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
return writer;
}
@Override
protected void finish() {
for (PrintWriter writer: output.values()) {
writer.flush();
writer.close();
}
}
}
static boolean opt = false;
public static void main(String[] args) throws Exception {
for (String arg: args) {
if (arg.equals("optimize")) {
System.out.println("performance optimized code");
opt=true;
}
}
final Map<Package,PrintWriter> output = new HashMap<Package, PrintWriter>();
TypeChecker typeChecker = new TypeCheckerBuilder()
.verbose(false)
.addSrcDirectory(new File("test"))
.addSrcDirectory(new File("../ceylon.language/test"))
.getTypeChecker();
typeChecker.process();
if (typeChecker.getErrors() > 0) {
System.exit(1);
}
JsCompiler jsc = new JsModuleCompiler(typeChecker, output).optimize(opt).stopOnErrors(false);
jsc.generate();
jsc.printErrors(System.out);
validateOutput(typeChecker);
}
static void validateOutput(TypeChecker typeChecker)
throws FileNotFoundException, IOException {
int count=0;
for (PhasedUnit pu: typeChecker.getPhasedUnits().getPhasedUnits()) {
Package pkg = pu.getPackage();
File generated = new File("build/test/node_modules/" + toOutputPath(pkg));
File test = new File("test/"+ toTestPath(pkg));
if (test.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(test));
BufferedReader outputReader = new BufferedReader(new FileReader(generated));
int i=0;
while (reader.ready() && outputReader.ready()) {
i++;
String actual = outputReader.readLine();
String expected = reader.readLine();
if (!expected.equals(actual) && !expected.trim().startsWith("
System.err.println("error at " + test.getPath() + ":" + i);
System.err.println("expected: " + expected);
System.err.println(" actual: " + actual);
break;
}
}
count++;
}
}
System.out.println("ran " + count + " tests");
}
private static String toOutputPath(Package pkg) {
String pkgName = pkg.getNameAsString();
if (pkgName.isEmpty()) pkgName = "default";
String modName = pkg.getModule().getNameAsString();
return modName.replace('.', '/') +
(pkg.getModule().isDefault() ?
"/" : "/" + pkg.getModule().getVersion() ) +
pkgName + ".js";
}
private static String toTestPath(Package pkg) {
String pkgName = pkg.getNameAsString();
if (pkgName.isEmpty()) pkgName = "default";
return pkgName.replace('.', '/') + "/" + pkgName + (opt? ".jsopt" : "") + ".js";
}
}
|
package icepick;
import android.os.Bundle;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;
@PrepareForTest(Bundle.class) @RunWith(PowerMockRunner.class)
public class IcepickTest {
static final String KEY = "key";
static final String VALUE = "value";
static final String ANOTHER_VALUE = "anotherValue";
final Bundle state = PowerMockito.mock(Bundle.class);
final ClassToInject classToInject = new ClassToInject();
@Test public void saveState() throws Exception {
Icepick.saveInstanceState(classToInject, state);
verify(state).putString(KEY, VALUE);
}
@Test public void restoreState() throws Exception {
when(state.getString(KEY)).thenReturn(ANOTHER_VALUE);
Icepick.restoreInstanceState(classToInject, state);
assertEquals(ANOTHER_VALUE, classToInject.string);
}
static class ClassToInject {
String string = VALUE;
}
@SuppressWarnings("unused")
static class ClassToInject$$Icicle implements StateHelper<Bundle> {
@Override public Bundle saveInstanceState(Object obj, Bundle outState) {
ClassToInject target = (ClassToInject) obj;
outState.putString(KEY, target.string);
return outState;
}
@Override public Bundle restoreInstanceState(Object obj, Bundle saveInstanceState) {
ClassToInject target = (ClassToInject) obj;
target.string = saveInstanceState.getString(KEY);
return saveInstanceState;
}
}
}
|
package nl.b3p.viewer.config.app;
import java.util.*;
import javax.persistence.*;
import nl.b3p.viewer.config.security.User;
import nl.b3p.viewer.config.services.BoundingBox;
import nl.b3p.viewer.config.services.GeoService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Matthijs Laan
*/
@Entity
@Table(
uniqueConstraints=
@UniqueConstraint(columnNames={"name", "version"})
)
public class Application {
@Id
private Long id;
@Basic(optional=false)
private String name;
@Column(length=30)
private String version;
@Lob
private String layout;
@ElementCollection
@JoinTable(joinColumns=@JoinColumn(name="username"))
private Map<String,String> details = new HashMap<String,String>();
@ManyToOne
private User owner;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "crs.name", column = @Column(name="start_crs")),
@AttributeOverride(name = "minx", column = @Column(name="start_minx")),
@AttributeOverride(name = "maxx", column = @Column(name="start_maxx")),
@AttributeOverride(name = "miny", column = @Column(name="start_miny")),
@AttributeOverride(name = "maxy", column = @Column(name="start_maxy"))
})
private BoundingBox startExtent;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "crs.name", column = @Column(name="max_crs")),
@AttributeOverride(name = "minx", column = @Column(name="max_minx")),
@AttributeOverride(name = "maxx", column = @Column(name="max_maxx")),
@AttributeOverride(name = "miny", column = @Column(name="max_miny")),
@AttributeOverride(name = "maxy", column = @Column(name="max_maxy"))
})
private BoundingBox maxExtent;
private boolean authenticatedRequired;
@ManyToOne(cascade=CascadeType.ALL)
private Level root;
@OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, mappedBy="application")
private Set<ConfiguredComponent> components = new HashSet<ConfiguredComponent>();
// <editor-fold defaultstate="collapsed" desc="getters and setters">
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLayout() {
return layout;
}
public void setLayout(String layout) {
this.layout = layout;
}
public Map<String, String> getDetails() {
return details;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
public boolean isAuthenticatedRequired() {
return authenticatedRequired;
}
public void setAuthenticatedRequired(boolean authenticatedRequired) {
this.authenticatedRequired = authenticatedRequired;
}
public Set<ConfiguredComponent> getComponents() {
return components;
}
public void setComponents(Set<ConfiguredComponent> components) {
this.components = components;
}
public BoundingBox getMaxExtent() {
return maxExtent;
}
public void setMaxExtent(BoundingBox maxExtent) {
this.maxExtent = maxExtent;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public Level getRoot() {
return root;
}
public void setRoot(Level root) {
this.root = root;
}
public BoundingBox getStartExtent() {
return startExtent;
}
public void setStartExtent(BoundingBox startExtent) {
this.startExtent = startExtent;
}
//</editor-fold>
/**
* Create a JSON representation for use in browser to start this application
* @return
*/
public String toJSON() throws JSONException {
JSONObject o = new JSONObject();
o.put("id", id);
o.put("name", name);
if(layout != null) {
o.put("layout", new JSONObject(layout));
}
JSONObject d = new JSONObject();
o.put("details", d);
for(Map.Entry<String,String> e: details.entrySet()) {
d.put(e.getKey(), e.getValue());
}
if(startExtent != null) {
o.put("startExtent", startExtent.toJSONObject());
}
if(maxExtent != null) {
o.put("maxExtent", maxExtent.toJSONObject());
}
/* TODO check readers */
if(root != null) {
o.put("rootLevel", root.getId().toString());
JSONObject levels = new JSONObject();
o.put("levels", levels);
JSONObject appLayers = new JSONObject();
o.put("appLayers", appLayers);
JSONArray selectedContent = new JSONArray();
o.put("selectedContent", selectedContent);
List selectedObjects = new ArrayList();
walkAppTreeForJSON(levels, appLayers, selectedObjects, root, false);
Collections.sort(selectedObjects, new Comparator() {
@Override
public int compare(Object lhs, Object rhs) {
Integer lhsIndex, rhsIndex;
if(lhs instanceof Level) {
lhsIndex = ((Level)lhs).getSelectedIndex();
} else {
lhsIndex = ((ApplicationLayer)lhs).getSelectedIndex();
}
if(rhs instanceof Level) {
rhsIndex = ((Level)rhs).getSelectedIndex();
} else {
rhsIndex = ((ApplicationLayer)rhs).getSelectedIndex();
}
return lhsIndex.compareTo(rhsIndex);
}
});
for(Object obj: selectedObjects) {
JSONObject j = new JSONObject();
if(obj instanceof Level) {
j.put("type", "level");
j.put("id", ((Level)obj).getId().toString());
} else {
j.put("type", "appLayer");
j.put("id", ((ApplicationLayer)obj).getId().toString());
}
selectedContent.put(j);
}
Map<GeoService,Set<String>> usedLayersByService = new HashMap<GeoService,Set<String>>();
visitLevelForUsedServicesLayers(root, usedLayersByService);
if(!usedLayersByService.isEmpty()) {
JSONObject services = new JSONObject();
o.put("services", services);
for(Map.Entry<GeoService,Set<String>> entry: usedLayersByService.entrySet()) {
GeoService gs = entry.getKey();
Set<String> usedLayers = entry.getValue();
services.put(gs.getId().toString(), gs.toJSONObject(usedLayers));
}
}
}
JSONObject c = new JSONObject();
o.put("components", c);
for(ConfiguredComponent comp: components) {
c.put(comp.getName(), comp.toJSON());
}
return o.toString(4);
}
private static void walkAppTreeForJSON(JSONObject levels, JSONObject appLayers, List selectedContent, Level l, boolean parentIsBackground) throws JSONException {
JSONObject o = l.toJSONObject();
o.put("background", l.isBackground() || parentIsBackground);
levels.put(l.getId().toString(), o);
if(l.getSelectedIndex() != null) {
selectedContent.add(l);
}
for(ApplicationLayer al: l.getLayers()) {
o = al.toJSONObject();
o.put("background", l.isBackground() || parentIsBackground);
appLayers.put(al.getId().toString(), o);
if(al.getSelectedIndex() != null) {
selectedContent.add(al);
}
}
for(Level child: l.getChildren()) {
walkAppTreeForJSON(levels, appLayers, selectedContent, child, l.isBackground());
}
}
private static void visitLevelForUsedServicesLayers(Level l, Map<GeoService,Set<String>> usedLayersByService) {
for(ApplicationLayer al: l.getLayers()) {
GeoService gs = al.getService();
Set<String> usedLayers = usedLayersByService.get(gs);
if(usedLayers == null) {
usedLayers = new HashSet<String>();
usedLayersByService.put(gs, usedLayers);
}
usedLayers.add(al.getLayerName());
}
for(Level child: l.getChildren()) {
visitLevelForUsedServicesLayers(child, usedLayersByService);
}
}
}
|
package org.apache.fop.apps;
import java.lang.reflect.*;
// Imported SAX classes
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
// Imported java.io classes
import java.io.*;
// FOP
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.tools.xslt.XSLTransform;
/**
* XSLTInputHandler basically takes an xmlfile and transforms it with an xsltfile
* and the resulting xsl:fo document is input for Fop.
*/
public class XSLTInputHandler extends InputHandler {
File xmlfile, xsltfile;
boolean useOldTransform = false;
public XSLTInputHandler (File xmlfile, File xsltfile ) {
this.xmlfile = xmlfile;
this.xsltfile = xsltfile;
}
/**
* overwrites the method of the super class to return the xmlfile
*/
public InputSource getInputSource () {
if (useOldTransform) {
try {
java.io.Writer writer;
java.io.Reader reader;
File tmpFile = null;
// create a Writer
// the following is an ugly hack to allow processing of larger files
// if xml file size is larger than 500 kb write the fo:file to disk
if ((xmlfile.length()) > 500000) {
tmpFile = new File(xmlfile.getName()+".fo.tmp");
writer = new FileWriter(tmpFile);
} else {
writer = new StringWriter();
}
XSLTransform.transform(xmlfile.getCanonicalPath(), xsltfile.getCanonicalPath(), writer);
writer.flush();
writer.close();
if (tmpFile != null) {
reader = new FileReader(tmpFile);
} else {
// create a input source containing the xsl:fo file which can be fed to Fop
reader = new StringReader(writer.toString());
}
return new InputSource(reader);
}
catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
else {
return fileInputSource(xmlfile);
}
}
/**
* This looks to see if the Trax api is supported and uses that to
* get an XMLFilter. Otherwise, it falls back to using DOM documents
*
*/
public XMLReader getParser() {
XMLReader result = null;
try {
// try trax first
Class transformer = Class.forName("javax.xml.transform.Transformer");
transformer = Class.forName("org.apache.fop.apps.TraxInputHandler");
Class[] argTypes = { File.class, File.class };
Method getFilterMethod = transformer.getMethod("getXMLFilter",argTypes);
File[] args = {xmlfile, xsltfile};
Object obj = getFilterMethod.invoke(null,args);
if (obj instanceof XMLReader) {
result = (XMLReader)obj;
}
}
catch (ClassNotFoundException ex){
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
// otherwise, use DOM documents via our XSLTransform tool class old style
if (result == null) {
useOldTransform = true;
result = createParser();
}
return result;
}
}
|
package org.eclipse.kura.linux.clock;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.eclipse.kura.KuraErrorCode;
import org.eclipse.kura.KuraException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavaNtpClockSyncProvider extends AbstractNtpClockSyncProvider {
private static final Logger logger = LoggerFactory.getLogger(JavaNtpClockSyncProvider.class);
// Concrete Methods
@Override
protected boolean syncClock() throws KuraException {
boolean ret = false;
// connect and get the delta
NTPUDPClient ntpClient = new NTPUDPClient();
ntpClient.setDefaultTimeout(this.ntpTimeout);
try {
ntpClient.open();
InetAddress ntpHostAddr = InetAddress.getByName(this.ntpHost);
TimeInfo info = ntpClient.getTime(ntpHostAddr, this.ntpPort);
this.lastSync = new Date();
info.computeDetails();
info.getComments().forEach(comment -> logger.debug("Clock sync compute comment: {}", comment));
List<String> computeErrors = info.getComments().stream().filter(comment -> comment.contains("Error:"))
.collect(Collectors.toList());
Long delayValue = info.getDelay();
if (delayValue != null && delayValue.longValue() < 1000 && computeErrors.isEmpty()) {
this.listener.onClockUpdate(info.getOffset());
ret = true;
} else {
logger.error("Incorrect clock sync. Delay value({}), clock will not be updated", info.getDelay());
}
} catch (IOException e) {
logger.warn(
"Error while synchronizing System Clock with NTP host {}. Please verify network connectivity ...",
this.ntpHost);
} catch (Exception e) {
throw new KuraException(KuraErrorCode.CONNECTION_FAILED, e);
} finally {
ntpClient.close();
}
return ret;
}
}
|
package org.bdgp.OpenHiCAMM;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.ImageWindow;
import ij.plugin.PlugIn;
import ij.process.ByteProcessor;
import ij.process.ImageConverter;
import ij.process.ImageProcessor;
import java.awt.Color;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.lang.System;
import org.micromanager.MMStudio;
import org.micromanager.api.Autofocus;
import org.micromanager.api.ScriptInterface;
import org.micromanager.utils.AutofocusBase;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MMException;
import mmcorej.CMMCore;
import mmcorej.TaggedImage;
import edu.mines.jtk.dsp.FftComplex;
import edu.mines.jtk.dsp.FftReal;
public class FastFFTAutoFocus extends AutofocusBase implements PlugIn, Autofocus {
// NOTES:
// gui = MMStudio, mmc = MMCore, acq = AcquisitionWrapperEngine
// gui.getAutofocus()
// mmc.getPosition(mmc.getFocusDevice());
// mmc.setPosition(mmc.getFocusDevice(), 200);
// gui.getAutofocus().fullFocus(); gui.doSnap();
// mmc.setExposure(mmc.getExposure()*Math.pow(Integer.parseInt(mmc.getProperty(mmc.getCameraDevice(),"Binning"))/4.0,2))
// mmc.setProperty(mmc.getCameraDevice(),"Binning","4")
// mmc.setProperty(mmc.getCameraDevice(),"PixelType","Grayscale")
public static Boolean verbose_ = true; // displaying debug info or not
public static final String KEY_SIZE_FIRST = "1st step size";
public static final String KEY_NUM_FIRST = "1st step number";
public static final String KEY_SIZE_SECOND = "2nd step size";
public static final String KEY_NUM_SECOND = "2nd step number";
public static final String KEY_THRES = "Threshold";
public static final String KEY_CROP_SIZE = "Crop ratio";
public static final String KEY_CHANNEL = "Channel";
//private static final String AF_SETTINGS_NODE = "micro-manager/extensions/autofocus";
public static final String AF_DEVICE_NAME = "FastFFT";
public static final String KEY_MIN_AUTOFOCUS = "minAutoFocus";
public static final String KEY_MAX_AUTOFOCUS = "maxAutoFocus";
/*private ImagePlus outputRough = null;
private ImageStack outputStackRough = null;
private ImagePlus outputFine = null;
private ImageStack outputStackFine = null;*/
public CMMCore core_;
public ImageProcessor ipCurrent_ = null;
public double ADAPTIVE_DIST_DIFF = 20.0;
public double SIZE_FIRST = 10.0;
public int NUM_FIRST = 20; // +/- #of snapshot
public double SIZE_SECOND = 1.0;
public int NUM_SECOND = 10;
public double THRES = 0.02;
public double CROP_SIZE = 0.2;
public String CHANNEL="";
public double WAIT_FOR_DEVICE_THRESHOLD = 1.0;
public int WAIT_FOR_DEVICE_SLEEP = 100;
private double indx = 0; //snapshot show new window iff indx = 1
private double curDist;
private double baseDist;
private Double prevBestDist;
private Double bestDist;
private double curSh;
//private double curShScale; //sharpness rescaling factor
private double bestSh;
private boolean liveMode;
// variables for skipping autofocus every acquisition
public int skipCounter = -1;
public static final int MAX_SKIP = 25;
// XXX: remove me
// private int imageNum=0;
Double minAutoFocus;
Double maxAutoFocus;
public FastFFTAutoFocus() {
super();
this.skipCounter = -1;
// set-up properties
createProperty(KEY_SIZE_FIRST, Double.toString(SIZE_FIRST));
createProperty(KEY_NUM_FIRST, Integer.toString(NUM_FIRST));
createProperty(KEY_SIZE_SECOND, Double.toString(SIZE_SECOND));
createProperty(KEY_NUM_SECOND, Integer.toString(NUM_SECOND));
createProperty(KEY_THRES, Double.toString(THRES));
createProperty(KEY_CROP_SIZE, Double.toString(CROP_SIZE));
createProperty(KEY_CHANNEL, CHANNEL);
createProperty(KEY_MIN_AUTOFOCUS, "");
createProperty(KEY_MAX_AUTOFOCUS, "");
createProperty("autofocusDuration", new Long(0).toString());
createProperty("liveMode", "yes");
loadSettings();
}
public void run(String arg)
{
// make sure minAutoFocus and maxAutoFocus is set
if (minAutoFocus == null || maxAutoFocus == null) applySettings();
if (minAutoFocus == null) throw new RuntimeException("minAutofocus is null!");
if (maxAutoFocus == null) throw new RuntimeException("maxAutofocus is null!");
// only run autofocus every MAX_SKIP acquisitions
if (bestDist != null && prevBestDist != null && Math.abs(bestDist - prevBestDist) <= ADAPTIVE_DIST_DIFF) {
skipCounter++;
if (skipCounter > MAX_SKIP) skipCounter = 0;
if (skipCounter != 0) {
if (verbose_) IJ.log(String.format("Skipping autofocus %d/%d", skipCounter, MAX_SKIP));
return;
}
}
else {
skipCounter = -1;
}
bestSh = 0;
//
if (verbose_ == null) {
if (arg.compareTo("silent") == 0)
verbose_ = false;
else
verbose_ = true;
}
if (core_ == null)
{
// if core object is not set attempt to get its global handle
core_ = MMStudio.getInstance().getMMCore();
}
if (core_ == null)
{
IJ.error("Unable to get Micro-Manager Core API handle.\n" +
"If this module is used as ImageJ plugin, Micro-Manager Studio must be running first!");
return;
}
//
try
{
// core_.setShutterOpen(true);
// core_.setAutoShutter(false);
//
//core_.setConfig("Channel", CHANNEL);
core_.waitForSystem();
//core_.waitForDevice(core_.getShutterDevice());
// Inserted by Stephan Preibisch
// get the set exposure time and current binning
double exposure = core_.getExposure();
String binning = core_.getProperty(core_.getCameraDevice(), "Binning");
int bin = Integer.parseInt(binning);
// // get pixel depth
String bits = core_.getProperty(core_.getCameraDevice(), "PixelType");
// // enable 4x4 binning and adjust the exposure
double focusBin = 4.0;
double exposureFactor = (bin/focusBin) * (bin/focusBin);
if (!liveMode) {
if (verbose_) IJ.log("Setting Exposure to "+ exposure * exposureFactor +"....");
core_.setExposure(exposure * exposureFactor);
if (verbose_) IJ.log("Setting Binning to 4....");
core_.setProperty(core_.getCameraDevice(), "Binning", "4");
if (verbose_) IJ.log("Setting Camera to 8bit ...");
core_.setProperty(core_.getCameraDevice(), "PixelType", "Grayscale");
}
else {
if (core_.isSequenceRunning()) {
core_.stopSequenceAcquisition();
Thread.sleep(WAIT_FOR_DEVICE_SLEEP);
}
core_.clearCircularBuffer();
core_.startContinuousSequenceAcquisition(0);
}
// XXX: remove me
// { double bestDist = 0.0, bestScore = 0.0;
// long startTime = new Date().getTime();
// for (int i = -100; i <= 100; i += 2) {
// core_.setPosition(core_.getFocusDevice(), (double)i);
// Double curDist = core_.getPosition(), lastDist = null;
// while (!curDist.equals(lastDist)) {
// lastDist = curDist;
// curDist = core_.getPosition();
// Thread.sleep(25);
// snapSingleImage();
// double score = computeScore(ipCurrent_);
// if (bestScore < score) {
// bestScore = score;
// bestDist = i;
// IJ.log(String.format("FastFFT\tscore\t%s\t%s\t%s", imageNum, i, score));
// core_.stopSequenceAcquisition();
// core_.setPosition(core_.getFocusDevice(), bestDist);
// Double curDist = core_.getPosition(), lastDist = null;
// while (!curDist.equals(lastDist)) {
// lastDist = curDist;
// curDist = core_.getPosition();
// Thread.sleep(25);
// IJ.log(String.format("FastFFT\tcurDist\t%s\t%s", imageNum, core_.getPosition(core_.getFocusDevice())));
// IJ.log(String.format("FastFFT\tbest_score\t%s\t%s\t%s", imageNum, bestDist, bestScore));
// IJ.log(String.format("FastFFT\ttime\t%s\t%s", imageNum++, new Date().getTime()-startTime));
// if (true) return;
//set z-distance to the lowest z-distance of the stack
final int MAX_TRIES = 10;
int tries = 0;
while (tries < MAX_TRIES) {
try { curDist = core_.getPosition(core_.getFocusDevice()); break; }
catch (Throwable e) { Thread.sleep(WAIT_FOR_DEVICE_SLEEP); ++tries; }
}
baseDist = curDist - SIZE_FIRST * NUM_FIRST;
core_.setPosition(core_.getFocusDevice(), baseDist);
core_.waitForDevice(core_.getFocusDevice());
Thread.sleep(WAIT_FOR_DEVICE_SLEEP);
// End of insertion
// Rough search
prevBestDist = bestDist;
for (int i = 0; i < 2 * NUM_FIRST + 1; i++)
{
if (minAutoFocus == null || maxAutoFocus == null ||
(minAutoFocus <= baseDist + i * SIZE_FIRST && baseDist + i * SIZE_FIRST <= maxAutoFocus))
{
core_.setPosition(core_.getFocusDevice(), baseDist + i * SIZE_FIRST);
core_.waitForDevice(core_.getFocusDevice());
Thread.sleep(WAIT_FOR_DEVICE_SLEEP);
// indx =1;
snapSingleImage();
// indx =0;
try { curDist = core_.getPosition(core_.getFocusDevice()); }
catch (Throwable e) { Thread.sleep(WAIT_FOR_DEVICE_SLEEP); continue; }
////curSh = sharpNess(ipCurrent_);
//curSh = computeFFT(ipCurrent_, 10, 15, 0.75);
//curShScale = computeFFT(ipCurrent_, 9, 10, 0.75); //local rescaling
//curSh = curSh / curShScale;
curSh = computeFFT(ipCurrent_, 15, 80, 1);
if (verbose_) IJ.log(String.format("setPosition: %.5f, real: %.5f, curSh: %.5f", baseDist + i * SIZE_FIRST, curDist, curSh));
if (curSh > bestSh || bestDist == null)
{
bestSh = curSh;
bestDist = curDist;
if (verbose_) IJ.log(String.format("Found new bestDist: %.5f, bestSh: %.5f", bestDist, bestSh));
}
/*else if (bestSh - curSh > THRES * bestSh && bestDist < 5000)
{
break;
}*/
}
}
if (bestDist == null) throw new RuntimeException("baseDist is outside of min/max range!");
baseDist = bestDist - SIZE_SECOND * NUM_SECOND;
core_.setPosition(core_.getFocusDevice(), baseDist);
Thread.sleep(WAIT_FOR_DEVICE_SLEEP);
//bestSh = 0;
//Fine search
for (int i = 0; i < 2 * NUM_SECOND + 1; i++)
{
if (minAutoFocus == null || maxAutoFocus == null ||
(minAutoFocus <= baseDist + i * SIZE_SECOND && baseDist + i * SIZE_SECOND <= maxAutoFocus))
{
core_.setPosition(core_.getFocusDevice(), baseDist + i * SIZE_SECOND);
core_.waitForDevice(core_.getFocusDevice());
Thread.sleep(WAIT_FOR_DEVICE_SLEEP);
// indx =1;
snapSingleImage();
// indx =0;
try { curDist = core_.getPosition(core_.getFocusDevice()); }
catch (Throwable e) { Thread.sleep(WAIT_FOR_DEVICE_SLEEP); continue; }
//curSh = sharpNess(ipCurrent_);
//curSh = computeFFT(ipCurrent_, 10, 15, 0.75);
//curShScale = computeFFT(ipCurrent_, 9, 10, 0.75); //local rescaling
//curSh = curSh / curShScale;
curSh = computeFFT(ipCurrent_, 15, 80, 1);
if (verbose_) IJ.log(String.format("setPosition: %.5f, real: %.5f, curSh: %.5f", baseDist + i * SIZE_SECOND, curDist, curSh));
if (curSh > bestSh || bestDist == null)
{
bestSh = curSh;
bestDist = curDist;
if (verbose_) IJ.log(String.format("Found new bestDist: %.5f, bestSh: %.5f", bestDist, bestSh));
}
/*else if (bestSh - curSh > THRES * bestSh && bestDist < 5000)
{
break;
}*/
}
}
// Inserted by Stephan Preibisch
if (!liveMode) {
// reset binning and re-adjust the exposure
if (verbose_) IJ.log("ReSet Exposure....");
core_.setExposure(exposure);
if (verbose_) IJ.log("ReSet Binning....");
core_.setProperty(core_.getCameraDevice(), "Binning", binning);
if (verbose_) IJ.log("ReSet Camera Bits....");
core_.setProperty(core_.getCameraDevice(), "PixelType", bits);
}
else {
core_.stopSequenceAcquisition();
}
// End of insertion
if (bestDist != null) {
if (verbose_) IJ.log(String.format("*** FOUND BEST bestDist: %.5f, bestSh: %.5f", bestDist, bestSh));
core_.setPosition(core_.getFocusDevice(), bestDist);
core_.waitForDevice(core_.getFocusDevice());
}
Thread.sleep(WAIT_FOR_DEVICE_SLEEP);
// indx =1;
//if (verbose_) snapSingleImage();
// indx =0;
// core_.setShutterOpen(false);
// core_.setAutoShutter(true);
//Thread.sleep(10000);
}
catch (Exception e)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
IJ.error(sw.toString());
e.printStackTrace();
}
}
public FloatArray2D ImageToFloatArray(ImageProcessor ip)
{
if (ip == null)
{
System.out.println("Image is empty.");
return null;
}
int width = ip.getWidth();
int height = ip.getHeight();
if (width * height == 0)
{
System.out.println("Image is empty.");
return null;
}
if (ip.getPixels() instanceof int[])
{
System.out.println("RGB images supported at the moment.");
return null;
}
FloatArray2D pixels = new FloatArray2D(width, height);
int count;
if (ip.getPixels() instanceof byte[])
{
byte[] pixelTmp = (byte[]) ip.getPixels();
count = 0;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
pixels.data[pixels.getPos(x, y)] = (float) (pixelTmp[count++] & 0xff);
}
else if (ip.getPixels() instanceof short[])
{
short[] pixelTmp = (short[]) ip.getPixels();
count = 0;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
pixels.data[pixels.getPos(x, y)] = (float) (pixelTmp[count++] & 0xffff);
}
else // instance of float[]
{
float[] pixelTmp = (float[]) ip.getPixels();
count = 0;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
pixels.data[pixels.getPos(x, y)] = pixelTmp[count++];
}
return pixels;
}
private FloatArray2D zeroPad(FloatArray2D ip, int width, int height)
{
FloatArray2D image = new FloatArray2D(width, height);
int offsetX = (width - ip.width) / 2;
int offsetY = (height - ip.height) / 2;
if (offsetX < 0)
{
IJ.error("Stitching_3D.ZeroPad(): Zero-Padding size in X smaller than image! " + width + " < " + ip.width);
return null;
}
if (offsetY < 0)
{
IJ.error("Stitching_3D.ZeroPad(): Zero-Padding size in Y smaller than image! " + height + " < " + ip.height);
return null;
}
for (int y = 0; y < ip.height; y++)
for (int x = 0; x < ip.width; x++)
image.set(ip.get(x, y), x + offsetX, y + offsetY);
return image;
}
private FloatArray2D pffft2D(FloatArray2D values, boolean scale)
{
int height = values.height;
int width = values.width;
int complexWidth = (width / 2 + 1) * 2;
FloatArray2D result = new FloatArray2D(complexWidth, height);
//do fft's in x direction
float[] tempIn = new float[width];
float[] tempOut;
FftReal fft = new FftReal(width);
for (int y = 0; y < height; y++)
{
tempOut = new float[complexWidth];
for (int x = 0; x < width; x++)
tempIn[x] = values.get(x, y);
fft.realToComplex( -1, tempIn, tempOut);
if (scale)
fft.scale(width, tempOut);
for (int x = 0; x < complexWidth; x++)
result.set(tempOut[x], x, y);
}
// do fft's in y-direction on the complex numbers
tempIn = new float[height * 2];
FftComplex fftc = new FftComplex(height);
for (int x = 0; x < complexWidth / 2; x++)
{
tempOut = new float[height * 2];
for (int y = 0; y < height; y++)
{
tempIn[y * 2] = result.get(x * 2, y);
tempIn[y * 2 + 1] = result.get(x * 2 + 1, y);
}
fftc.complexToComplex( -1, tempIn, tempOut);
for (int y = 0; y < height; y++)
{
result.set(tempOut[y * 2], x * 2, y);
result.set(tempOut[y * 2 + 1], x * 2 + 1, y);
}
}
return result;
}
public static void rearrangeFFT(FloatArray2D values)
{
float[] fft = values.data;
int w = values.width;
int h = values.height;
int halfDimYRounded = ( int )( h / 2 );
float buffer[] = new float[w];
int pos1, pos2;
for (int y = 0; y < halfDimYRounded; y++)
{
// copy upper line
pos1 = y * w;
for (int x = 0; x < w; x++)
buffer[x] = fft[pos1++];
// copy lower line to upper line
pos1 = y * w;
pos2 = (y+halfDimYRounded) * w;
for (int x = 0; x < w; x++)
fft[pos1++] = fft[pos2++];
// copy buffer to lower line
pos1 = (y+halfDimYRounded) * w;
for (int x = 0; x < w; x++)
fft[pos1++] = buffer[x];
}
}
public static float[] computePowerSpectrum(float[] complex)
{
int wComplex = complex.length / 2;
float[] powerSpectrum = new float[wComplex];
for (int pos = 0; pos < wComplex; pos++)
powerSpectrum[pos] = (float)Math.sqrt(Math.pow(complex[pos*2],2) + Math.pow(complex[pos*2 + 1],2));
return powerSpectrum;
}
public static double gLog(double z, double c)
{
if (c == 0)
return z;
else
return Math.log10((z + Math.sqrt(z * z + c * c)) / 2.0);
}
public static void gLogImage(float[] image, float c)
{
for (int i = 0; i < image.length; i++)
image[i] = (float)gLog(image[i], c);
}
/**
*
* @param ip - ImageProcessor to determine the grade of sharpness from
* @param minPercent - Where the bandpass starts [in %], a good guess is 15
* @param maxPercent - Where the bandpass ends [in %], a good guess is 80
* @param starPercent - How much of the center to cut out [in %], a good guess is 1
* @return Amount of detail on linear scale, the higher the more content
*/
public double computeFFT(ImageProcessor ip, double minPercent, double maxPercent, double starPercent)
{
// Convert to Float Datastructure
FloatArray2D img = ImageToFloatArray(ip);
// Zero Padding
int widthZP = FftReal.nfftFast(img.width);
int heightZP = FftComplex.nfftFast(img.height);
img = zeroPad(img, widthZP, heightZP);
// Fourier Transform
FloatArray2D fft = pffft2D(img, false);
FloatArray2D power = new FloatArray2D( computePowerSpectrum(fft.data), fft.width/2, fft.height);
// Rearrange
rearrangeFFT(power);
// Log of Power
gLogImage(power.data, 2);
// Simple statistics
double sum = 0;
int count = 0;
double radius = Math.sqrt((power.height/2D)*(power.height/2D) + power.width*power.width);
double minRadius = radius * (minPercent / 100.0);
double maxRadius = radius * (maxPercent / 100.0);
double minRadiusSquare = minRadius * minRadius;
double maxRadiusSquare = maxRadius * maxRadius;
double centerY = power.height/2;
double yThreshold1 = centerY - (power.height * (starPercent / 200.0));
double yThreshold2 = centerY + (power.height * (starPercent / 200.0));
double xThreshold = power.width * (starPercent / 100.0);
int arrayPos = 0;
for (int y = 0; y < power.height; y++)
{
if (y < yThreshold1 || y > yThreshold2)
{
arrayPos = power.getPos(0, y);
for (int x = 0; x < power.width; x++)
{
// compute distance to center
double distY = y - centerY;
double distanceSquare = x * x + distY * distY;
// check radi and check starPercent x
if (distanceSquare > minRadiusSquare && distanceSquare < maxRadiusSquare && x > xThreshold)
{
sum += power.data[arrayPos];
count++;
}
arrayPos++;
}
}
}
sum /= (double)count;
power.data = img.data = null;
power = img = null;
System.gc();
return sum;
}
//take a snapshot and save pixel values in ipCurrent_
public boolean snapSingleImage()
{
try
{
if (liveMode) {
TaggedImage img = core_.getLastTaggedImage();
ImageProcessor ip = null;
if (img != null) ip = ImageUtils.makeProcessor(img);
while (img == null || ip == null || ip.getPixels() == null) {
img = core_.getLastTaggedImage();
if (img != null) ip = ImageUtils.makeProcessor(img);
Thread.sleep(WAIT_FOR_DEVICE_SLEEP);
}
ImagePlus implus = new ImagePlus(String.valueOf(curDist), ip);
new ImageConverter(implus).convertToGray8();
ipCurrent_ = implus.getProcessor();
}
else {
core_.snapImage();
TaggedImage img = core_.getTaggedImage();
ImagePlus implus = new ImagePlus(String.valueOf(curDist), ImageUtils.makeProcessor(img));
new ImageConverter(implus).convertToGray8();
ipCurrent_ = implus.getProcessor();
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
IJ.error(sw.toString());
return false;
}
return true;
}
//making a new window for a new snapshot.
public ImagePlus newWindow()
{
ImagePlus implus;
ImageProcessor ip;
//long byteDepth = core_.getBytesPerPixel();
//if (byteDepth == 1) {
// ip = new ByteProcessor((int) core_.getImageWidth(), (int) core_.getImageHeight());
//else {
// ip = new ShortProcessor((int) core_.getImageWidth(), (int) core_.getImageHeight());
ip = new ByteProcessor((int) core_.getImageWidth(), (int) core_.getImageHeight());
ip.setColor(Color.black);
ip.fill();
implus = new ImagePlus(String.valueOf(curDist), ip);
if (indx == 1)
{
if (verbose_)
{
// create image window if we are in the verbose mode
new ImageWindow(implus);
}
}
return implus;
}
public double fullFocus()
{
Date startTime = new Date();
try {
run("silent");
}
finally {
try {
Date endTime = new Date();
Long autofocusDuration = new Long(this.getPropertyValue("autofocusDuration"));
this.setPropertyValue("autofocusDuration", new Long(
endTime.getTime() - startTime.getTime() + autofocusDuration).toString());
}
catch (MMException e) {throw new RuntimeException(e);}
}
//run("");
return 0;
}
public String getVerboseStatus()
{
return new String("OK");
}
public double incrementalFocus()
{
Date startTime = new Date();
try {
run("silent");
}
finally {
try {
Date endTime = new Date();
Long autofocusDuration = new Long(this.getPropertyValue("autofocusDuration"));
this.setPropertyValue("autofocusDuration", new Long(
endTime.getTime() - startTime.getTime() + autofocusDuration).toString());
}
catch (MMException e) {throw new RuntimeException(e);}
}
//run("");
return 0;
}
public void setMMCore(CMMCore core)
{
core_ = core;
}
@Override
public void applySettings() {
try {
// reset the skip counter
skipCounter = -1;
bestDist = null;
prevBestDist = null;
SIZE_FIRST = Double.parseDouble(getPropertyValue(KEY_SIZE_FIRST));
NUM_FIRST = Integer.parseInt(getPropertyValue(KEY_NUM_FIRST));
SIZE_SECOND = Double.parseDouble(getPropertyValue(KEY_SIZE_SECOND));
NUM_SECOND = Integer.parseInt(getPropertyValue(KEY_NUM_SECOND));
THRES = Double.parseDouble(getPropertyValue(KEY_THRES));
CROP_SIZE = Double.parseDouble(getPropertyValue(KEY_CROP_SIZE));
CHANNEL = getPropertyValue(KEY_CHANNEL);
minAutoFocus = getPropertyValue(KEY_MIN_AUTOFOCUS).equals("")? null :
Double.parseDouble(getPropertyValue(KEY_MIN_AUTOFOCUS));
maxAutoFocus = getPropertyValue(KEY_MAX_AUTOFOCUS).equals("")? null :
Double.parseDouble(getPropertyValue(KEY_MAX_AUTOFOCUS));
liveMode = "yes".equals(getPropertyValue("liveMode"));
setPropertyValue("autofocusDuration", new Long(0).toString());
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (MMException e) {
e.printStackTrace();
}
}
private abstract class FloatArray
{
public float data[] = null;
public abstract FloatArray clone();
}
private class FloatArray2D extends FloatArray
{
// public float data[] = null;
public int width = 0;
public int height = 0;
public FloatArray2D(int width, int height)
{
data = new float[width * height];
this.width = width;
this.height = height;
}
public FloatArray2D(float[] data, int width, int height)
{
this.data = data;
this.width = width;
this.height = height;
}
public FloatArray2D clone()
{
FloatArray2D clone = new FloatArray2D(width, height);
System.arraycopy(this.data, 0, clone.data, 0, this.data.length);
return clone;
}
public int getPos(int x, int y)
{
return x + width * y;
}
public float get(int x, int y)
{
return data[getPos(x, y)];
}
public void set(float value, int x, int y)
{
data[getPos(x, y)] = value;
}
}
@Override
public double computeScore(ImageProcessor impro) {
return computeFFT(impro, 15, 80, 1);
}
@Override
public double getCurrentFocusScore() {
return computeFFT(ipCurrent_, 15, 80, 1);
}
@Override
public void setApp(ScriptInterface app) {
this.core_ = app.getMMCore();
}
@Override
public void focus(double arg0, int arg1, double arg2, int arg3) throws MMException {
throw new MMException("OBSOLETE - do not use");
}
@Override
public String getDeviceName() {
return AF_DEVICE_NAME;
}
@Override
public int getNumberOfImages() {
return 0;
}
}
|
package com.matthewtamlin.spyglass.library.handler_processors;
import android.content.res.TypedArray;
import com.matthewtamlin.spyglass.library.handler_annotations.BooleanHandler;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
public class BooleanAttributeProcessor implements AttributeProcessor<Boolean, BooleanHandler> {
@Override
public boolean attributeValueIsAvailable(
final TypedArray attrs,
final BooleanHandler annotation) {
checkNotNull(attrs, "Argument 'attrs' cannot be null.");
checkNotNull(annotation, "Argument 'annotation' cannot be null.");
// Try with different defaults and compare the results to determine if the value is present
final boolean reading1 = attrs.getBoolean(annotation.attributeId(), false);
final boolean reading2 = attrs.getBoolean(annotation.attributeId(), true);
final boolean defaultConsistentlyReturned = (reading1 == false) && (reading2 == true);
return !defaultConsistentlyReturned;
}
@Override
public Boolean getAttributeValue(final TypedArray attrs, final BooleanHandler annotation) {
checkNotNull(attrs, "Argument 'attrs' cannot be null.");
checkNotNull(annotation, "Argument 'annotation' cannot be null.");
if (attributeValueIsAvailable(attrs, annotation)) {
return attrs.getBoolean(annotation.attributeId(), false);
} else {
throw new RuntimeException("No attribute found for ID " + annotation.attributeId());
}
}
@Override
public boolean attributeIsMandatory(final BooleanHandler annotation) {
checkNotNull(annotation, "Argument 'annotation' cannot be null.");
return annotation.mandatory();
}
}
|
package org.biojava.bio.seq.impl;
import org.biojava.bio.seq.*;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import org.biojava.bio.*;
import org.biojava.utils.*;
import org.biojava.bio.seq.homol.*;
/**
* Wrap up default sets of Feature implementations.
*
* @author Thomas Down
* @author Greg Cox
* @author Keith James
* @since 1.1
*/
public class FeatureImpl {
/**
* Default implementation of FeatureRealizer, which wraps simple
* implementations of Feature and StrandedFeature. This is the
* default FeatureRealizer used by SimpleSequence and ViewSequence,
* and may also be used by others. When building new FeatureRealizers,
* you may wish to use this as a `fallback' realizer, and benefit from
* the Feature and StrandedFeature implementations.
*/
public final static FeatureRealizer DEFAULT;
static {
SimpleFeatureRealizer d = new SimpleFeatureRealizer() {
public Object writeReplace() {
try {
return new StaticMemberPlaceHolder(SimpleFeatureRealizer.class.getField("DEFAULT"));
} catch (NoSuchFieldException ex) {
throw new BioError(ex);
}
}
} ;
try {
d.addImplementation(Feature.Template.class,
SimpleFeature.class);
d.addImplementation(StrandedFeature.Template.class,
SimpleStrandedFeature.class);
d.addImplementation(HomologyFeature.Template.class,
SimpleHomologyFeature.class);
d.addImplementation(SimilarityPairFeature.Template.class,
SimpleSimilarityPairFeature.class);
d.addImplementation(RemoteFeature.Template.class,
SimpleRemoteFeature.class);
d.addImplementation(FramedFeature.Template.class,
SimpleFramedFeature.class);
} catch (BioException ex) {
throw new BioError(ex, "Couldn't initialize default FeatureRealizer");
}
DEFAULT = d;
}
}
|
package org.biojava.bio.symbol;
import java.util.*;
import java.lang.reflect.*;
import java.io.*;
import org.biojava.utils.*;
import org.biojava.bio.*;
import org.biojava.bio.seq.io.*;
class EmptyAlphabet implements FiniteAlphabet, Serializable {
public String getName() {
return "Empty Alphabet";
}
public Annotation getAnnotation() {
return Annotation.EMPTY_ANNOTATION;
}
public boolean contains(Symbol s) {
return s == AlphabetManager.getGapSymbol();
}
public void validate(Symbol sym) throws IllegalSymbolException {
throw new IllegalSymbolException(
"The empty alphabet does not contain symbol " + sym.getName());
}
public SymbolParser getParser(String name) throws NoSuchElementException {
throw new NoSuchElementException("There is no parser for the empty alphabet. Attempted to retrieve " + name);
}
public int size() {
return 0;
}
public List getAlphabets() {
return Collections.EMPTY_LIST;
}
public Symbol getSymbol(List syms) throws IllegalSymbolException {
if(syms.size() != 0) {
throw new IllegalSymbolException("The empty alphabet contains nothing");
}
return AlphabetManager.getGapSymbol();
}
public Symbol getAmbiguity(Set syms) throws IllegalSymbolException {
for(Iterator i = syms.iterator(); i.hasNext(); ) {
this.validate((Symbol) i.next());
}
return AlphabetManager.getGapSymbol();
}
public Symbol getGapSymbol()
{
return AlphabetManager.getGapSymbol();
}
public Iterator iterator() {
return SymbolList.EMPTY_LIST.iterator();
}
public SymbolList symbols() {
return SymbolList.EMPTY_LIST;
}
public void addSymbol(Symbol sym) throws IllegalSymbolException {
throw new IllegalSymbolException(
"Can't add symbols to alphabet: " + sym.getName() +
" in " + getName()
);
}
public void removeSymbol(Symbol sym) throws IllegalSymbolException {
throw new IllegalSymbolException(
"Can't remove symbols from alphabet: " + sym.getName() +
" in " + getName()
);
}
public void addChangeListener(ChangeListener cl) {}
public void addChangeListener(ChangeListener cl, ChangeType ct) {}
public void removeChangeListener(ChangeListener cl) {}
public void removeChangeListener(ChangeListener cl, ChangeType ct) {}
private Object writeReplace() throws ObjectStreamException {
try {
return new StaticMemberPlaceHolder(Alphabet.class.getField("EMPTY_ALPHABET"));
} catch (NoSuchFieldException nsfe) {
throw new NotSerializableException(nsfe.getMessage());
}
}
}
|
package org.wildfly.extension.messaging.activemq;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.dmr.ModelType.BOOLEAN;
import static org.jboss.dmr.ModelType.INT;
import static org.jboss.dmr.ModelType.LIST;
import static org.jboss.dmr.ModelType.LONG;
import static org.jboss.dmr.ModelType.STRING;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.FILTER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.QUEUE;
import static org.wildfly.extension.messaging.activemq.ActiveMQActivationService.rollbackOperationIfServerNotActive;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.createNonEmptyStringAttribute;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.resolveFilter;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.runtimeOnlyOperation;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.runtimeReadOnlyOperation;
import static org.wildfly.extension.messaging.activemq.logging.MessagingLogger.ROOT_LOGGER;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.operations.validation.ParameterValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
public abstract class AbstractQueueControlHandler<T> extends AbstractRuntimeOnlyHandler {
private static ResourceDescriptionResolver RESOLVER = MessagingExtension.getResourceDescriptionResolver(QUEUE);
public static final String LIST_MESSAGES = "list-messages";
public static final String LIST_MESSAGES_AS_JSON = "list-messages-as-json";
public static final String COUNT_MESSAGES = "count-messages";
public static final String REMOVE_MESSAGE = "remove-message";
public static final String REMOVE_MESSAGES = "remove-messages";
public static final String EXPIRE_MESSAGES = "expire-messages";
public static final String EXPIRE_MESSAGE = "expire-message";
public static final String SEND_MESSAGE_TO_DEAD_LETTER_ADDRESS = "send-message-to-dead-letter-address";
public static final String SEND_MESSAGES_TO_DEAD_LETTER_ADDRESS = "send-messages-to-dead-letter-address";
public static final String CHANGE_MESSAGE_PRIORITY = "change-message-priority";
public static final String CHANGE_MESSAGES_PRIORITY = "change-messages-priority";
public static final String MOVE_MESSAGE = "move-message";
public static final String MOVE_MESSAGES = "move-messages";
public static final String LIST_MESSAGE_COUNTER = "list-message-counter";
public static final String LIST_MESSAGE_COUNTER_AS_JSON = "list-message-counter-as-json";
public static final String LIST_MESSAGE_COUNTER_AS_HTML = "list-message-counter-as-html";
public static final String RESET_MESSAGE_COUNTER = "reset-message-counter";
public static final String LIST_MESSAGE_COUNTER_HISTORY = "list-message-counter-history";
public static final String LIST_MESSAGE_COUNTER_HISTORY_AS_JSON = "list-message-counter-history-as-json";
public static final String LIST_MESSAGE_COUNTER_HISTORY_AS_HTML = "list-message-counter-history-as-html";
public static final String PAUSE = "pause";
public static final String RESUME = "resume";
public static final String LIST_CONSUMERS = "list-consumers";
public static final String LIST_CONSUMERS_AS_JSON = "list-consumers-as-json";
public static final String LIST_SCHEDULED_MESSAGES = "list-scheduled-messages";
public static final String LIST_SCHEDULED_MESSAGES_AS_JSON = LIST_SCHEDULED_MESSAGES + "-as-json";
public static final String LIST_DELIVERING_MESSAGES = "list-delivering-messages";
public static final String LIST_DELIVERING_MESSAGES_AS_JSON = LIST_DELIVERING_MESSAGES + "-as-json";
public static final ParameterValidator PRIORITY_VALIDATOR = new IntRangeValidator(0, 9, false, false);
private static final AttributeDefinition OTHER_QUEUE_NAME = createNonEmptyStringAttribute("other-queue-name");
private static final AttributeDefinition REJECT_DUPLICATES = SimpleAttributeDefinitionBuilder.create("reject-duplicates", BOOLEAN)
.setRequired(false)
.build();
private static final AttributeDefinition NEW_PRIORITY = SimpleAttributeDefinitionBuilder.create("new-priority", INT)
.setValidator(PRIORITY_VALIDATOR)
.build();
protected abstract AttributeDefinition getMessageIDAttributeDefinition();
protected abstract AttributeDefinition[] getReplyMessageParameterDefinitions();
public void registerOperations(final ManagementResourceRegistration registry, ResourceDescriptionResolver resolver) {
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGES, resolver)
.setParameters(FILTER)
.setReplyType(LIST)
.setReplyParameters(getReplyMessageParameterDefinitions())
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGES_AS_JSON, RESOLVER)
.setParameters(FILTER)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(COUNT_MESSAGES, RESOLVER)
.setParameters(FILTER)
.setReplyType(LONG)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(REMOVE_MESSAGE, RESOLVER)
.setParameters(getMessageIDAttributeDefinition())
.setReplyType(BOOLEAN)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(REMOVE_MESSAGES, RESOLVER)
.setParameters(CommonAttributes.FILTER)
.setReplyType(INT)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(EXPIRE_MESSAGE, RESOLVER)
.setParameters(getMessageIDAttributeDefinition())
.setReplyType(BOOLEAN)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(EXPIRE_MESSAGES, RESOLVER)
.setParameters(FILTER)
.setReplyType(INT)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(SEND_MESSAGE_TO_DEAD_LETTER_ADDRESS, RESOLVER)
.setParameters(getMessageIDAttributeDefinition())
.setReplyType(BOOLEAN)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(SEND_MESSAGES_TO_DEAD_LETTER_ADDRESS, RESOLVER)
.setParameters(FILTER)
.setReplyType(INT)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(CHANGE_MESSAGE_PRIORITY, RESOLVER)
.setParameters(getMessageIDAttributeDefinition(), NEW_PRIORITY)
.setReplyType(BOOLEAN)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(CHANGE_MESSAGES_PRIORITY, RESOLVER)
.setParameters(FILTER, NEW_PRIORITY)
.setReplyType(INT)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(MOVE_MESSAGE, RESOLVER)
.setParameters(getMessageIDAttributeDefinition(), OTHER_QUEUE_NAME, REJECT_DUPLICATES)
.setReplyType(INT)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(MOVE_MESSAGES, RESOLVER)
.setParameters(FILTER, OTHER_QUEUE_NAME, REJECT_DUPLICATES)
.setReplyType(INT)
.build(),
this);
// TODO dmr-based LIST_MESSAGE_COUNTER
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGE_COUNTER_AS_JSON, RESOLVER)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGE_COUNTER_AS_HTML, RESOLVER)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(RESET_MESSAGE_COUNTER, RESOLVER)
.build(),
this);
// TODO dmr-based LIST_MESSAGE_COUNTER_HISTORY
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGE_COUNTER_HISTORY_AS_JSON, RESOLVER)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGE_COUNTER_HISTORY_AS_HTML, RESOLVER)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(PAUSE, RESOLVER)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(RESUME, RESOLVER)
.build(),
this);
// TODO LIST_CONSUMERS
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_CONSUMERS_AS_JSON, RESOLVER)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_DELIVERING_MESSAGES, resolver)
.setReplyType(LIST)
.setReplyParameters(getReplyMapConsumerMessageParameterDefinition())
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_DELIVERING_MESSAGES_AS_JSON, resolver)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_SCHEDULED_MESSAGES, resolver)
.setReplyType(LIST)
.setReplyParameters(getReplyMessageParameterDefinitions())
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_SCHEDULED_MESSAGES_AS_JSON, resolver)
.setReplyType(STRING)
.build(),
this);
}
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
if (rollbackOperationIfServerNotActive(context, operation)) {
return;
}
final String operationName = operation.require(ModelDescriptionConstants.OP).asString();
final String queueName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue();
final ServiceName activeMQServiceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
boolean readOnly = context.getResourceRegistration().getOperationFlags(PathAddress.EMPTY_ADDRESS, operationName).contains(OperationEntry.Flag.READ_ONLY);
ServiceController<?> activeMQService = context.getServiceRegistry(!readOnly).getService(activeMQServiceName);
ActiveMQServer server = ActiveMQServer.class.cast(activeMQService.getValue());
final DelegatingQueueControl<T> control = getQueueControl(server, queueName);
if (control == null) {
PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
}
boolean reversible = false;
Object handback = null;
try {
if (LIST_MESSAGES.equals(operationName)) {
String filter = resolveFilter(context, operation);
String json = control.listMessagesAsJSON(filter);
context.getResult().set(ModelNode.fromJSONString(json));
} else if (LIST_MESSAGES_AS_JSON.equals(operationName)) {
String filter = resolveFilter(context, operation);
context.getResult().set(control.listMessagesAsJSON(filter));
} else if (LIST_DELIVERING_MESSAGES.equals(operationName)) {
String json = control.listDeliveringMessagesAsJSON();
context.getResult().set(ModelNode.fromJSONString(json));
} else if (LIST_DELIVERING_MESSAGES_AS_JSON.equals(operationName)) {
context.getResult().set(control.listDeliveringMessagesAsJSON());
} else if (LIST_SCHEDULED_MESSAGES.equals(operationName)) {
String json = control.listScheduledMessagesAsJSON();
context.getResult().set(ModelNode.fromJSONString(json));
} else if (LIST_SCHEDULED_MESSAGES_AS_JSON.equals(operationName)) {
context.getResult().set(control.listScheduledMessagesAsJSON());
} else if (COUNT_MESSAGES.equals(operationName)) {
String filter = resolveFilter(context, operation);
context.getResult().set(control.countMessages(filter));
} else if (REMOVE_MESSAGE.equals(operationName)) {
ModelNode id = getMessageIDAttributeDefinition().resolveModelAttribute(context, operation);
context.getResult().set(control.removeMessage(id));
} else if (REMOVE_MESSAGES.equals(operationName)) {
String filter = resolveFilter(context, operation);
context.getResult().set(control.removeMessages(filter));
} else if (EXPIRE_MESSAGES.equals(operationName)) {
String filter = resolveFilter(context, operation);
context.getResult().set(control.expireMessages(filter));
} else if (EXPIRE_MESSAGE.equals(operationName)) {
ModelNode id = getMessageIDAttributeDefinition().resolveModelAttribute(context, operation);
context.getResult().set(control.expireMessage(id));
} else if (SEND_MESSAGE_TO_DEAD_LETTER_ADDRESS.equals(operationName)) {
ModelNode id = getMessageIDAttributeDefinition().resolveModelAttribute(context, operation);
context.getResult().set(control.sendMessageToDeadLetterAddress(id));
} else if (SEND_MESSAGES_TO_DEAD_LETTER_ADDRESS.equals(operationName)) {
String filter = resolveFilter(context, operation);
context.getResult().set(control.sendMessagesToDeadLetterAddress(filter));
} else if (CHANGE_MESSAGE_PRIORITY.equals(operationName)) {
ModelNode id = getMessageIDAttributeDefinition().resolveModelAttribute(context, operation);
int priority = NEW_PRIORITY.resolveModelAttribute(context, operation).asInt();
context.getResult().set(control.changeMessagePriority(id, priority));
} else if (CHANGE_MESSAGES_PRIORITY.equals(operationName)) {
String filter = resolveFilter(context, operation);
int priority = NEW_PRIORITY.resolveModelAttribute(context, operation).asInt();
context.getResult().set(control.changeMessagesPriority(filter, priority));
} else if (MOVE_MESSAGE.equals(operationName)) {
ModelNode id = getMessageIDAttributeDefinition().resolveModelAttribute(context, operation);
String otherQueue = OTHER_QUEUE_NAME.resolveModelAttribute(context, operation).asString();
ModelNode rejectDuplicates = REJECT_DUPLICATES.resolveModelAttribute(context, operation);
if (rejectDuplicates.isDefined()) {
context.getResult().set(control.moveMessage(id, otherQueue, rejectDuplicates.asBoolean()));
} else {
context.getResult().set(control.moveMessage(id, otherQueue));
}
} else if (MOVE_MESSAGES.equals(operationName)) {
String filter = resolveFilter(context, operation);
String otherQueue = OTHER_QUEUE_NAME.resolveModelAttribute(context, operation).asString();
ModelNode rejectDuplicates = REJECT_DUPLICATES.resolveModelAttribute(context, operation);
if (rejectDuplicates.isDefined()) {
context.getResult().set(control.moveMessages(filter, otherQueue, rejectDuplicates.asBoolean()));
} else {
context.getResult().set(control.moveMessages(filter, otherQueue));
}
} else if (LIST_MESSAGE_COUNTER_AS_JSON.equals(operationName)) {
context.getResult().set(control.listMessageCounter());
} else if (LIST_MESSAGE_COUNTER_AS_HTML.equals(operationName)) {
context.getResult().set(control.listMessageCounterAsHTML());
} else if (LIST_MESSAGE_COUNTER_HISTORY_AS_JSON.equals(operationName)) {
context.getResult().set(control.listMessageCounterHistory());
} else if (LIST_MESSAGE_COUNTER_HISTORY_AS_HTML.equals(operationName)) {
context.getResult().set(control.listMessageCounterHistoryAsHTML());
} else if (RESET_MESSAGE_COUNTER.equals(operationName)) {
control.resetMessageCounter();
context.getResult(); // undefined
} else if (PAUSE.equals(operationName)) {
control.pause();
reversible = true;
context.getResult(); // undefined
} else if (RESUME.equals(operationName)) {
control.resume();
reversible = true;
context.getResult(); // undefined
} else if (LIST_CONSUMERS_AS_JSON.equals(operationName)) {
context.getResult().set(control.listConsumersAsJSON());
} else {
// TODO dmr-based LIST_MESSAGE_COUNTER, LIST_MESSAGE_COUNTER_HISTORY, LIST_CONSUMERS
handback = handleAdditionalOperation(operationName, operation, context, control.getDelegate());
reversible = handback == null;
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
context.getFailureDescription().set(e.getLocalizedMessage());
}
OperationContext.RollbackHandler rh;
if (reversible) {
final Object rhHandback = handback;
rh = new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
try {
if (PAUSE.equals(operationName)) {
control.resume();
} else if (RESUME.equals(operationName)) {
control.pause();
} else {
revertAdditionalOperation(operationName, operation, context, control.getDelegate(), rhHandback);
}
} catch (Exception e) {
ROOT_LOGGER.revertOperationFailed(e, getClass().getSimpleName(),
operation.require(ModelDescriptionConstants.OP).asString(),
PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)));
}
}
};
} else {
rh = OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER;
}
context.completeStep(rh);
}
protected AttributeDefinition[] getReplyMapConsumerMessageParameterDefinition() {
return new AttributeDefinition[]{
createNonEmptyStringAttribute("consumerName"),
new ObjectListAttributeDefinition.Builder("elements",
new ObjectTypeAttributeDefinition.Builder("element", getReplyMessageParameterDefinitions()).build())
.build()
};
}
protected abstract DelegatingQueueControl<T> getQueueControl(ActiveMQServer server, String queueName);
protected abstract Object handleAdditionalOperation(final String operationName, final ModelNode operation,
final OperationContext context, T queueControl) throws OperationFailedException;
protected abstract void revertAdditionalOperation(final String operationName, final ModelNode operation,
final OperationContext context, T queueControl, Object handback);
protected final void throwUnimplementedOperationException(final String operationName) {
// Bug
throw MessagingLogger.ROOT_LOGGER.unsupportedOperation(operationName);
}
/**
* Exposes the method signatures that are common between {@link org.apache.activemq.api.core.management.QueueControl}
* and {@link org.apache.activemq.api.jms.management.JMSQueueControl}.
*/
public interface DelegatingQueueControl<T> {
T getDelegate();
String listMessagesAsJSON(String filter) throws Exception;
long countMessages(String filter) throws Exception;
boolean removeMessage(ModelNode id) throws Exception;
int removeMessages(String filter) throws Exception;
int expireMessages(String filter) throws Exception;
boolean expireMessage(ModelNode id) throws Exception;
boolean sendMessageToDeadLetterAddress(ModelNode id) throws Exception;
int sendMessagesToDeadLetterAddress(String filter) throws Exception;
boolean changeMessagePriority(ModelNode id, int priority) throws Exception;
int changeMessagesPriority(String filter, int priority) throws Exception;
boolean moveMessage(ModelNode id, String otherQueue) throws Exception;
boolean moveMessage(ModelNode id, String otherQueue, boolean rejectDuplicates) throws Exception;
int moveMessages(String filter, String otherQueue) throws Exception;
int moveMessages(String filter, String otherQueue, boolean rejectDuplicates) throws Exception;
String listMessageCounter() throws Exception;
void resetMessageCounter() throws Exception;
String listMessageCounterAsHTML() throws Exception;
String listMessageCounterHistory() throws Exception;
String listMessageCounterHistoryAsHTML() throws Exception;
void pause() throws Exception;
void resume() throws Exception;
String listConsumersAsJSON() throws Exception;
String listScheduledMessagesAsJSON() throws Exception;
String listDeliveringMessagesAsJSON() throws Exception;
}
}
|
package org.exist.xquery;
import org.exist.memtree.DocumentBuilderReceiver;
import org.exist.memtree.MemTreeBuilder;
import org.exist.memtree.NodeImpl;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xquery.value.Type;
import org.xml.sax.SAXException;
/**
* Implements a dynamic document constructor. Creates a new
* document node with its own node identity.
*
* @author wolf
*/
public class DocumentConstructor extends NodeConstructor {
private final Expression content;
/**
* @param context
*/
public DocumentConstructor(XQueryContext context, Expression contentExpr) {
super(context);
this.content = contentExpr;
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#analyze(org.exist.xquery.Expression)
*/
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
contextInfo.setParent(this);
content.analyze(contextInfo);
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
*/
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
if (contextItem != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
}
Sequence contentSeq = content.eval(contextSequence, contextItem);
context.pushDocumentContext();
MemTreeBuilder builder = context.getDocumentBuilder();
DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
try {
if(!contentSeq.isEmpty()) {
StringBuffer buf = null;
SequenceIterator i = contentSeq.iterate();
Item next = i.nextItem();
while(next != null) {
context.proceed(this, builder);
if(next.getType() == Type.ATTRIBUTE ||
next.getType() == Type.NAMESPACE ||
next.getType() == Type.DOCUMENT)
throw new XPathException(getASTNode(), "Found a node of type " + Type.getTypeName(next.getType()) +
" inside a document constructor");
// if item is an atomic value, collect the string values of all
// following atomic values and seperate them by a space.
if (Type.subTypeOf(next.getType(), Type.ATOMIC)) {
if(buf == null)
buf = new StringBuffer();
else if (buf.length() > 0)
buf.append(' ');
buf.append(next.getStringValue());
next = i.nextItem();
// if item is a node, flush any collected character data and
// copy the node to the target doc.
} else if (Type.subTypeOf(next.getType(), Type.NODE)) {
if (buf != null && buf.length() > 0) {
receiver.characters(buf);
buf.setLength(0);
}
next.copyTo(context.getBroker(), receiver);
next = i.nextItem();
}
//TODO : design like below ? -pb
/*
//TODO : wondering whether we shouldn't iterate over a nodeset as the specs would tend to say. -pb
SequenceIterator i = contentSeq.iterate();
Item next = i.nextItem();
while(next != null) {
context.proceed(this, builder);
if (Type.subTypeOf(next.getType(), Type.NODE)) {
//flush any collected character data
if (buf != null && buf.length() > 0) {
receiver.characters(buf);
buf.setLength(0);
}
// copy the node to the target doc
if(next.getType() == Type.ATTRIBUTE) {
throw new XPathException(getASTNode(), "XPTY0004 : Found a node of type " +
Type.getTypeName(next.getType()) + " inside a document constructor");
} else if (next.getType() == Type.DOCUMENT) {
//TODO : definitely broken, but that's the way to do
for (int j = 0 ; j < ((DocumentImpl)next).getChildCount(); j++) {
((DocumentImpl)next).getNode(j).copyTo(context.getBroker(), receiver);
}
} else if (Type.subTypeOf(next.getType(), Type.TEXT)) {
//TODO
buf.append("#text");
} else {
next.copyTo(context.getBroker(), receiver);
}
} else {
if(buf == null)
buf = new StringBuffer();
//else if (buf.length() > 0)
// buf.append(' ');
buf.append(next.getStringValue());
}
next = i.nextItem();
*/
}
// flush remaining character data
if (buf != null && buf.length() > 0) {
receiver.characters(buf);
buf.setLength(0);
}
}
} catch(SAXException e) {
throw new XPathException(getASTNode(),
"Encountered SAX exception while processing document constructor: "
+ ExpressionDumper.dump(this));
}
context.popDocumentContext();
NodeImpl node = builder.getDocument();
if (context.getProfiler().isEnabled())
context.getProfiler().end(this, "", node);
return node;
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper)
*/
public void dump(ExpressionDumper dumper) {
dumper.display("document {");
dumper.startIndent();
//TODO : is this the required syntax ?
content.dump(dumper);
dumper.endIndent();
dumper.nl().display("}");
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append("document {");
//TODO : is this the required syntax ?
result.append(content.toString());
result.append("} ");
return result.toString();
}
public void resetState() {
super.resetState();
content.resetState();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inceptus.subsystems;
/**
*
* @author inceptus
*/
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.camera.AxisCamera.ExposureT;
import edu.wpi.first.wpilibj.camera.AxisCamera.WhiteBalanceT;
import edu.wpi.first.wpilibj.camera.AxisCameraException;
import edu.wpi.first.wpilibj.image.*;
import edu.wpi.first.wpilibj.image.Image;
/**
* Identifies rectangular targets on back boards using Axis camera. Processing
* images and getting target information are in separate methods to allow for
* the processing to occur in its own thread if desired.
*
*/
/*
* Team 2264 10.22.64.11 Admin; root Team 2265 10.22.65.11 Admin; root
*/
public class TargetFinder {
private final int redLow = 200;
private final int redHigh = 256;
private final int greenLow = 0;
private final int greenHigh = 100;
private final int blueLow = 0;
private final int blueHigh = 100;
private final int bboxWidthMin = 400;
private final int bboxHeightMin = 400;
private final float inertiaXMin = .5f;//originally .32f
private final float inertiaYMin = .25f;//originally .18f
private final double ratioMin = 1;
private final double ratioMax = 2;
private final int camBrightness = 0;
private final int camColor = 100;
private final WhiteBalanceT camWhiteBalance = WhiteBalanceT.automatic;
private final ExposureT camExposure = ExposureT.hold;
public static final int IMAGE_WIDTH = 320;
public static final int IMAGE_HEIGHT = 240;
AxisCamera cam;
private Target highTarget = Target.NullTarget;
private Target target1 = Target.NullTarget;
private Target target2 = Target.NullTarget;
private Target target3 = Target.NullTarget;
private Target target4 = Target.NullTarget;
private CriteriaCollection boxCriteria;
private CriteriaCollection inertiaCriteria;
public TargetFinder() {
System.out.println("TargetFinder() begin " + Timer.getFPGATimestamp());
cam = AxisCamera.getInstance();
cam.writeResolution(AxisCamera.ResolutionT.k320x240);
cam.writeBrightness(camBrightness);
cam.writeColorLevel(camColor);
cam.writeWhiteBalance(camWhiteBalance);
cam.writeExposureControl(camExposure);
cam.writeMaxFPS(15);
cam.writeExposurePriority(AxisCamera.ExposurePriorityT.none);
cam.writeCompression(50);
//System.out.println("TargetFinder() * " + cam.toString() + "[" + Timer.getFPGATimestamp());
boxCriteria = new CriteriaCollection();
inertiaCriteria = new CriteriaCollection();
boxCriteria.addCriteria(NIVision.MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH,
30, bboxWidthMin, false);
boxCriteria.addCriteria(NIVision.MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT,
40, bboxHeightMin, false);
inertiaCriteria.addCriteria(NIVision.MeasurementType.IMAQ_MT_NORM_MOMENT_OF_INERTIA_XX,
0, inertiaXMin, true);
inertiaCriteria.addCriteria(NIVision.MeasurementType.IMAQ_MT_NORM_MOMENT_OF_INERTIA_YY,
0, inertiaYMin, true);
Timer.delay(7);
}
private void addTarget(Target t) {
// Fill the first empty target slot.
if (target1.isNull()) {
target1 = t;
} else if (target2.isNull()) {
target2 = t;
} else if (target3.isNull()) {
target3 = t;
} else if (target4.isNull()) {
target4 = t;
}
}
public boolean processImage() {
boolean debugWriteImages = true;
boolean success = cam.freshImage();
if (success) {
try {
System.out.println("In Try loop");
ColorImage im = cam.getImage();
System.out.println("Got image");
if (debugWriteImages) {
im.write("image1.jpg");
System.out.println("Wrote color image");
}
BinaryImage thresholdIm = im.thresholdRGB(redLow, redHigh,
greenLow, greenHigh,
blueLow, blueHigh);
if (debugWriteImages) {
thresholdIm.write("image2.jpg");
System.err.println("Wrote Threshold Image");
}
BinaryImage filteredBoxIm = thresholdIm.particleFilter(boxCriteria);
ParticleAnalysisReport[] xparticles = filteredBoxIm.getOrderedParticleAnalysisReports();
System.out.println(xparticles.length + " particles at " + Timer.getFPGATimestamp());
BinaryImage filteredInertiaIm = filteredBoxIm.particleFilter(inertiaCriteria);
ParticleAnalysisReport[] particles = filteredInertiaIm.getOrderedParticleAnalysisReports();
System.out.println(particles.length + " particles at " + Timer.getFPGATimestamp());
// Loop through targets, find highest one.
// Targets aren't found yet.
highTarget = Target.NullTarget;
target1 = Target.NullTarget;
target2 = Target.NullTarget;
target3 = Target.NullTarget;
target4 = Target.NullTarget;
System.out.println("Targets created");
double minY = IMAGE_HEIGHT; // Minimum y <-> higher in image.
for (int i = 0; i < particles.length; i++) {
Target t = new Target(i, particles[i]);
if (t.ratio > ratioMin && t.ratio < ratioMax) {
addTarget(t);
if (t.centerY <= minY) {
highTarget = t;
}
}
System.out.println("Target " + i + ": (" + t.centerX + "," + t.centerY + ") Distance: " + getDistance(t));
}
System.out.println("Best target: " + highTarget.index);
System.out.println("Distance to the target: " + getDistance(highTarget));
if (debugWriteImages) {
filteredBoxIm.write("image3.jpg");
filteredInertiaIm.write("image4.jpg");
System.out.println("Wrote Images");
}
// Free memory from images.
im.free();
thresholdIm.free();
filteredBoxIm.free();
filteredInertiaIm.free();
} catch (AxisCameraException ex) {
System.out.println("Axis Camera Exception Gotten" + ex.getMessage());
ex.printStackTrace();
} catch (NIVisionException ex) {
System.out.println("NIVision Exception Gotten - " + ex.getMessage());
ex.printStackTrace();
}
}
return success;
}
//Method assumes the camera is looking at the rectangle straight on: can be adjusted later
public double getDistance(Target t) {
boolean debugMyProc = true;
double result;
if (debugMyProc)
{
writeDebug("t.rawBboxHeight=" + t.rawBboxHeight);
writeDebug("Center x, y (" + t.centerX + "," + t.centerY + ")");
writeDebug("Cornerr x, y (" + t.rawBboxCornerX + "," + t.rawBboxCornerY + ")");
}
result = 3185.6 / (t.rawBboxHeight * Math.tan(0.4101));
return (result * 1.0125);
}
public Target getHighestTarget() {
return highTarget;
}
public Target getTarget1() {
return target1;
}
public Target getTarget2() {
return target2;
}
public Target getTarget3() {
return target3;
}
public Target getTarget4() {
return target4;
}
private void writeDebug(String pMsg)
{
System.out.println(pMsg);
}
}
|
package org.jitsi.service.neomedia;
/**
* The <tt>MediaType</tt> enumeration contains a list of media types
* currently known to and handled by the <tt>MediaService</tt>.
*
* @author Emil Ivov
*/
public enum MediaType
{
/**
* Represents an AUDIO media type.
*/
AUDIO("audio"),
/**
* Represents a VIDEO media type.
*/
VIDEO("video"),
/**
* Represents a DATA media type.
*/
DATA("data");
/**
* The name of this <tt>MediaType</tt>.
*/
private final String mediaTypeName;
/**
* Creates a <tt>MediaType</tt> instance with the specified name.
*
* @param mediaTypeName the name of the <tt>MediaType</tt> we'd like to
* create.
*/
private MediaType(String mediaTypeName)
{
this.mediaTypeName = mediaTypeName;
}
/**
* Returns the name of this MediaType (e.g. "audio" or "video"). The name
* returned by this method is meant for use by session description
* mechanisms such as SIP/SDP or XMPP/Jingle.
*
* @return the name of this MediaType (e.g. "audio" or "video").
*/
@Override
public String toString()
{
return mediaTypeName;
}
public static MediaType parseString(String mediaTypeName)
throws IllegalArgumentException
{
if(AUDIO.toString().equals(mediaTypeName))
return AUDIO;
if(VIDEO.toString().equals(mediaTypeName))
return VIDEO;
if(DATA.toString().equals(mediaTypeName))
return DATA;
throw new IllegalArgumentException(
mediaTypeName + " is not a currently supported MediaType");
}
}
|
package org.loklak.api.server;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.elasticsearch.search.sort.SortOrder;
import org.loklak.data.AbstractIndexEntry;
import org.loklak.data.DAO;
import org.loklak.data.QueryEntry;
import org.loklak.harvester.SourceType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SuggestServlet extends HttpServlet {
private static final long serialVersionUID = 8578478303032749879L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RemoteAccess.Post post = RemoteAccess.evaluate(request);
// manage DoS
if (post.isDoS_blackout()) {response.sendError(503, "your request frequency is too high"); return;}
String callback = post.get("callback", "");
boolean jsonp = callback != null && callback.length() > 0;
boolean local = post.isLocalhostAccess();
boolean minified = post.get("minified", false);
boolean delete = post.get("delete", false);
int count = post.get("count", 10); // number of queries
String query = post.get("q", ""); // to get a list of queries which match; to get all latest: leave q empty
String source = post.get("source", "all"); // values: all,query,geo
String orders = post.get("order", query.length() == 0 ? "desc" : "asc").toUpperCase();
SortOrder order = SortOrder.valueOf(orders);
String orderby = post.get("orderby", query.length() == 0 ? "retrieval_next" : "query_count");
int timezoneOffset = post.get("timezoneOffset", 0);
Date since = post.get("since", (Date) null, timezoneOffset);
Date until = post.get("until", (Date) null, timezoneOffset);
String selectby = post.get("selectby", "retrieval_next");
List<QueryEntry> queryList = new ArrayList<>();
if ((source.equals("all") || source.equals("query")) && query.length() >= 0) {
queryList.addAll(DAO.SearchLocalQueries(query, count, orderby, order, since, until, selectby));
}
if (delete && local && queryList.size() > 0) {
for (QueryEntry qe: queryList) DAO.deleteQuery(qe.getQuery(), qe.getSourceType());
queryList.clear();
queryList.addAll(DAO.SearchLocalQueries(query, count, orderby, order, since, until, selectby));
}
if (source.equals("all") || source.equals("geo")) {
String[] suggestions = DAO.geoNames.suggest(query, count, 1);
if (suggestions.length < 4) suggestions = DAO.geoNames.suggest(query, count, 2);
for (String s: suggestions) {
QueryEntry qe = new QueryEntry(s, 0, Long.MAX_VALUE, SourceType.IMPORT, false);
queryList.add(qe);
}
}
post.setResponse(response, "application/javascript");
// generate json
Map<String, Object> m = new LinkedHashMap<String, Object>();
Map<String, Object> metadata = new LinkedHashMap<String, Object>();
metadata.put("count", queryList == null ? "0" : Integer.toString(queryList.size()));
metadata.put("query", query);
metadata.put("order", orders);
metadata.put("orderby", orderby);
if (since != null) metadata.put("since", AbstractIndexEntry.utcFormatter.print(since.getTime()));
if (until != null) metadata.put("until", AbstractIndexEntry.utcFormatter.print(until.getTime()));
if (since != null || until != null) metadata.put("selectby", selectby);
metadata.put("client", post.getClientHost());
m.put("search_metadata", metadata);
List<Object> queries = new ArrayList<>();
if (queryList != null) {
for (QueryEntry t: queryList) {
queries.add(t.toMap());
}
}
m.put("queries", queries);
// write json
ServletOutputStream sos = response.getOutputStream();
if (jsonp) sos.print(callback + "(");
sos.print(minified ? new ObjectMapper().writer().writeValueAsString(m) : new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(m));
if (jsonp) sos.println(");");
sos.println();
}
}
|
package org.pentaho.di.trans.steps.mail;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.activation.DataHandler;
import javax.activation.URLDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.FileSelector;
import org.apache.commons.vfs.FileType;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
/**
* Send mail step.
* based on Mail job entry
* @author Samatar
* @since 28-07-2008
*/
public class Mail extends BaseStep implements StepInterface
{
private MailMeta meta;
private MailData data;
public Mail(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(MailMeta)smi;
data=(MailData)sdi;
Object[] r=getRow(); // get row, set busy!
if (r==null) // no more input to be expected...
{
setOutputDone();
return false;
}
if(first)
{
first=false;
// get the RowMeta
data.previousRowMeta = getInputRowMeta().clone();
// Check is filename field is provided
if (Const.isEmpty(meta.getDestination()))
throw new KettleException(Messages.getString("Mail.Log.DestinationFieldEmpty"));
// Check is replyname field is provided
if (Const.isEmpty(meta.getReplyAddress()))
throw new KettleException(Messages.getString("Mail.Log.ReplyFieldEmpty"));
// Check is SMTP server is provided
if (Const.isEmpty(meta.getServer()))
throw new KettleException(Messages.getString("Mail.Log.ServerFieldEmpty"));
// Check Attached filenames when dynamic
if (meta.isDynamicFilename() && Const.isEmpty(meta.getDynamicFieldname()))
throw new KettleException(Messages.getString("Mail.Log.DynamicFilenameFielddEmpty"));
// Check Attached zipfilename when dynamic
if (meta.isZipFilenameDynamic() && Const.isEmpty(meta.getDynamicZipFilenameField()))
throw new KettleException(Messages.getString("Mail.Log.DynamicZipFilenameFieldEmpty"));
if(meta.isZipFiles() && Const.isEmpty(meta.getZipFilename()))
throw new KettleException(Messages.getString("Mail.Log.ZipFilenameEmpty"));
// check authentication
if(meta.isUsingAuthentication()) {
// check authentication user
if (Const.isEmpty(meta.getAuthenticationUser()))
throw new KettleException(Messages.getString("Mail.Log.AuthenticationUserFieldEmpty"));
// check authentication pass
if (Const.isEmpty(meta.getAuthenticationPassword()))
throw new KettleException(Messages.getString("Mail.Log.AuthenticationPasswordFieldEmpty"));
}
// cache the position of the destination field
if (data.indexOfDestination<0) {
String realDestinationFieldname=meta.getDestination();
data.indexOfDestination =data.previousRowMeta.indexOfValue(realDestinationFieldname);
if (data.indexOfDestination<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindDestinationField",realDestinationFieldname)); //$NON-NLS-1$ //$NON-NLS-2$
}
if (!Const.isEmpty(meta.getDestinationCc())) {
// cache the position of the Cc field
if (data.indexOfDestinationCc<0) {
String realDestinationCcFieldname=meta.getDestinationCc();
data.indexOfDestinationCc =data.previousRowMeta.indexOfValue(realDestinationCcFieldname);
if (data.indexOfDestinationCc<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindDestinationCcField",realDestinationCcFieldname)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// BCc
if (!Const.isEmpty(meta.getDestinationCc())) {
// cache the position of the BCc field
if (data.indexOfDestinationBCc<0) {
String realDestinationBCcFieldname=meta.getDestinationBCc();
data.indexOfDestinationBCc =data.previousRowMeta.indexOfValue(realDestinationBCcFieldname);
if (data.indexOfDestinationBCc<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindDestinationBCcField",realDestinationBCcFieldname)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Sender Name
if (!Const.isEmpty(meta.getReplyName())){
// cache the position of the sender field
if (data.indexOfSenderName<0){
String realSenderName=meta.getReplyName();
data.indexOfSenderName =data.previousRowMeta.indexOfValue(realSenderName);
if (data.indexOfSenderName<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindReplyNameField",realSenderName)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Sender address
// cache the position of the sender field
if (data.indexOfSenderAddress<0) {
String realSenderAddress=meta.getReplyAddress();
data.indexOfSenderAddress =data.previousRowMeta.indexOfValue(realSenderAddress);
if (data.indexOfSenderAddress<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindReplyAddressField",realSenderAddress)); //$NON-NLS-1$ //$NON-NLS-2$
}
// Reply to
if (!Const.isEmpty(meta.getReplyToAddresses())){
// cache the position of the reply to field
if (data.indexOfReplyToAddresses<0){
String realReplyToAddresses=meta.getReplyToAddresses();
data.indexOfReplyToAddresses =data.previousRowMeta.indexOfValue(realReplyToAddresses);
if (data.indexOfReplyToAddresses<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindReplyToAddressesField",realReplyToAddresses)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Contact Person
if (!Const.isEmpty(meta.getContactPerson())) {
// cache the position of the destination field
if (data.indexOfContactPerson<0) {
String realContactPerson=meta.getContactPerson();
data.indexOfContactPerson =data.previousRowMeta.indexOfValue(realContactPerson);
if (data.indexOfContactPerson<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindContactPersonField",realContactPerson)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Contact Phone
if (!Const.isEmpty(meta.getContactPhone())){
// cache the position of the destination field
if (data.indexOfContactPhone<0){
String realContactPhone=meta.getContactPhone();
data.indexOfContactPhone =data.previousRowMeta.indexOfValue(realContactPhone);
if (data.indexOfContactPhone<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindContactPhoneField",realContactPhone)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// cache the position of the Server field
if (data.indexOfServer<0){
String realServer=meta.getServer();
data.indexOfServer =data.previousRowMeta.indexOfValue(realServer);
if (data.indexOfServer<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindServerField",realServer)); //$NON-NLS-1$ //$NON-NLS-2$
}
// Port
if (!Const.isEmpty(meta.getPort())){
// cache the position of the port field
if (data.indexOfPort<0){
String realPort=meta.getPort();
data.indexOfPort =data.previousRowMeta.indexOfValue(realPort);
if (data.indexOfPort<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindPortField",realPort)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Authentication
if(meta.isUsingAuthentication()){
// cache the position of the Authentication user field
if (data.indexOfAuthenticationUser<0){
String realAuthenticationUser=meta.getAuthenticationUser();
data.indexOfAuthenticationUser =data.previousRowMeta.indexOfValue(realAuthenticationUser);
if (data.indexOfAuthenticationUser<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindAuthenticationUserField",realAuthenticationUser)); //$NON-NLS-1$ //$NON-NLS-2$
}
// cache the position of the Authentication password field
if (data.indexOfAuthenticationPass<0){
String realAuthenticationPassword=meta.getAuthenticationPassword();
data.indexOfAuthenticationPass =data.previousRowMeta.indexOfValue(realAuthenticationPassword);
if (data.indexOfAuthenticationPass<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindAuthenticationPassField",realAuthenticationPassword)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Mail Subject
if (!Const.isEmpty(meta.getSubject())){
// cache the position of the subject field
if (data.indexOfSubject<0){
String realSubject=meta.getSubject();
data.indexOfSubject =data.previousRowMeta.indexOfValue(realSubject);
if (data.indexOfSubject<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindSubjectField",realSubject)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Mail Comment
if (!Const.isEmpty(meta.getComment())){
// cache the position of the comment field
if (data.indexOfComment<0){
String realComment=meta.getComment();
data.indexOfComment =data.previousRowMeta.indexOfValue(realComment);
if (data.indexOfComment<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotFindCommentField",realComment)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Dynamic Zipfilename
if (meta.isZipFilenameDynamic()){
// cache the position of the attached source filename field
if (data.indexOfDynamicZipFilename<0){
String realZipFilename=meta.getDynamicZipFilenameField();
data.indexOfDynamicZipFilename =data.previousRowMeta.indexOfValue(realZipFilename);
if (data.indexOfDynamicZipFilename<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotSourceAttachedZipFilenameField",realZipFilename)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
data.zipFileLimit=Const.toLong(environmentSubstitute(meta.getZipLimitSize()), 0);
if(data.zipFileLimit>0) data.zipFileLimit=data.zipFileLimit*1048576;
if(!meta.isZipFilenameDynamic()) data.ZipFilename=environmentSubstitute(meta.getZipFilename());
// Attached files
if(meta.isDynamicFilename()){
// cache the position of the attached source filename field
if (data.indexOfSourceFilename<0){
String realSourceattachedFilename=meta.getDynamicFieldname();
data.indexOfSourceFilename =data.previousRowMeta.indexOfValue(realSourceattachedFilename);
if (data.indexOfSourceFilename<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotSourceAttachedFilenameField",realSourceattachedFilename)); //$NON-NLS-1$ //$NON-NLS-2$
}
// cache the position of the attached wildcard field
if(!Const.isEmpty(meta.getSourceWildcard())){
if (data.indexOfSourceWildcard<0){
String realSourceattachedWildcard=meta.getDynamicWildcard();
data.indexOfSourceWildcard =data.previousRowMeta.indexOfValue(realSourceattachedWildcard);
if (data.indexOfSourceWildcard<0)
throw new KettleException(Messages.getString("Mail.Exception.CouldnotSourceAttachedWildcard",realSourceattachedWildcard)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}else
{
// static attached filenames
data.realSourceFileFoldername=environmentSubstitute(meta.getSourceFileFoldername()) ;
data.realSourceWildcard=environmentSubstitute(meta.getSourceWildcard()) ;
}
} // end if first
boolean sendToErrorRow=false;
String errorMessage = null;
try{
// get values
String maildestination= data.previousRowMeta.getString(r,data.indexOfDestination);
String maildestinationCc= null;
if(data.indexOfDestinationCc>-1) maildestinationCc=data.previousRowMeta.getString(r,data.indexOfDestinationCc);
String maildestinationBCc= null;
if(data.indexOfDestinationBCc>-1) maildestinationBCc=data.previousRowMeta.getString(r,data.indexOfDestinationBCc);
String mailsendername= null;
if(data.indexOfSenderName>-1) mailsendername=data.previousRowMeta.getString(r,data.indexOfSenderName);
String mailsenderaddress=data.previousRowMeta.getString(r,data.indexOfSenderAddress);
// reply addresses
String mailreplyToAddresses= null;
if(data.indexOfReplyToAddresses>-1) mailreplyToAddresses=data.previousRowMeta.getString(r,data.indexOfReplyToAddresses);
String contactperson= null;
if(data.indexOfContactPerson>-1) contactperson=data.previousRowMeta.getString(r,data.indexOfContactPerson);
String contactphone= null;
if(data.indexOfContactPhone>-1) contactphone=data.previousRowMeta.getString(r,data.indexOfContactPhone);
String servername=data.previousRowMeta.getString(r,data.indexOfServer);
int port=-1;
if(data.indexOfPort>-1) port= Const.toInt(""+data.previousRowMeta.getInteger(r,data.indexOfPort),-1);
String authuser=null;
if(data.indexOfAuthenticationUser>-1) authuser=data.previousRowMeta.getString(r,data.indexOfAuthenticationUser);
String authpass=null;
if(data.indexOfAuthenticationPass>-1) authpass=data.previousRowMeta.getString(r,data.indexOfAuthenticationPass);
String subject=null;
if(data.indexOfSubject>-1) subject=data.previousRowMeta.getString(r,data.indexOfSubject);
String comment=null;
if(data.indexOfComment>-1) comment=data.previousRowMeta.getString(r,data.indexOfComment);
// send email...
sendMail(r,servername, port,mailsenderaddress,mailsendername,maildestination,
maildestinationCc,maildestinationBCc,contactperson,contactphone,
authuser,authpass,subject,comment,mailreplyToAddresses);
putRow(getInputRowMeta(), r); // copy row to possible alternate rowset(s).); // copy row to output rowset(s);
if (log.isRowLevel()) log.logRowlevel(toString(), Messages.getString("Mail.Log.LineNumber",getLinesRead()+" : "+getInputRowMeta().getString(r)));
} catch (Exception e)
{
if (getStepMeta().isDoingErrorHandling()){
sendToErrorRow = true;
errorMessage = e.toString();
}
else {
throw new KettleException(Messages.getString("Mail.Error.General"), e);
}
if (sendToErrorRow){
// Simply add this row to the error row
putError(getInputRowMeta(), r, 1, errorMessage, null, "MAIL001");
}
}
return true;
}
private int Round(long value)
{
try {
return Math.round(value);
}catch(Exception e)
{
return -1;
}
}
public void sendMail(Object[] r,String server, int port,
String senderAddress,String senderName,String destination,String destinationCc,
String destinationBCc,
String contactPerson, String contactPhone,
String authenticationUser,String authenticationPassword,
String mailsubject, String comment, String replyToAddresses) throws Exception
{
// Send an e-mail...
// create some properties and get the default Session
String protocol = "smtp";
if (meta.isUsingAuthentication()) {
if (meta.getSecureConnectionType().equals("TLS")){
// Allow TLS authentication
data.props.put("mail.smtp.starttls.enable","true");
}
else{
protocol = "smtps";
// required to get rid of a SSL exception :
// nested exception is:
// javax.net.ssl.SSLException: Unsupported record version Unknown
data.props.put("mail.smtps.quitwait", "false");
}
}
data.props.put("mail." + protocol + ".host", server);
if (port!=-1) data.props.put("mail." + protocol + ".port", port);
boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;
if (debug) data.props.put("mail.debug", "true");
if (meta.isUsingAuthentication()) data.props.put("mail." + protocol + ".auth", "true");
Session session = Session.getInstance(data.props);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set message priority
if (meta.isUsePriority()) {
String priority_int="1";
if (meta.getPriority().equals("low")) priority_int="3";
if (meta.getPriority().equals("normal")) priority_int="2";
msg.setHeader("X-Priority",priority_int); //(String)int between 1= high and 3 = low.
msg.setHeader("Importance", meta.getImportance());
//seems to be needed for MS Outlook.
//where it returns a string of high /normal /low.
}
// set Email sender
String email_address = senderAddress;
if (!Const.isEmpty(email_address)){
// get sender name
if(!Const.isEmpty(senderName)) email_address=senderName+'<'+email_address+'>';
msg.setFrom(new InternetAddress(email_address));
} else {
throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled"));
}
// Set reply to
if (!Const.isEmpty(replyToAddresses))
{
// get replay to
// Split the mail-address: space separated
String[] reply_Address_List =replyToAddresses.split(" ");
InternetAddress[] address = new InternetAddress[reply_Address_List.length];
for (int i = 0; i < reply_Address_List.length; i++)
address[i] = new InternetAddress(reply_Address_List[i]);
// To add the real reply-to
msg.setReplyTo(address);
}
// Split the mail-address: space separated
String destinations[] = destination.split(" ");
InternetAddress[] address = new InternetAddress[destinations.length];
for (int i = 0; i < destinations.length; i++)
address[i] = new InternetAddress(destinations[i]);
msg.setRecipients(Message.RecipientType.TO, address);
String realdestinationCc=destinationCc;
if (!Const.isEmpty(realdestinationCc))
{
// Split the mail-address Cc: space separated
String destinationsCc[] = realdestinationCc.split(" ");
InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
for (int i = 0; i < destinationsCc.length; i++)
addressCc[i] = new InternetAddress(destinationsCc[i]);
msg.setRecipients(Message.RecipientType.CC, addressCc);
}
String realdestinationBCc=destinationBCc;
if (!Const.isEmpty(realdestinationBCc))
{
// Split the mail-address BCc: space separated
String destinationsBCc[] = realdestinationBCc.split(" ");
InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
for (int i = 0; i < destinationsBCc.length; i++)
addressBCc[i] = new InternetAddress(destinationsBCc[i]);
msg.setRecipients(Message.RecipientType.BCC, addressBCc);
}
if (mailsubject!=null) msg.setSubject(mailsubject);
msg.setSentDate(new Date());
StringBuffer messageText = new StringBuffer();
if (comment != null) messageText.append(comment).append(Const.CR).append(Const.CR);
if (meta.getIncludeDate())
messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") +": ").append(XMLHandler.date2string(new Date())).append(Const.CR).append(
Const.CR);
if (!meta.isOnlySendComment()
&& (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))){
messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
messageText.append("
messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact")+" : ").append(contactPerson).append(Const.CR);
messageText.append(Messages.getString("Mail.Log.Comment.Tel") + " : ").append(contactPhone).append(Const.CR);
messageText.append(Const.CR);
}
data.parts = new MimeMultipart();
MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
// 1st part
if (meta.isUseHTML()){
if (!Const.isEmpty(meta.getEncoding()))
part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
else
part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
} else
part1.setText(messageText.toString());
data.parts.addBodyPart(part1);
// attached files
if(meta.isDynamicFilename()) setAttachedFilesList(r,log);
else setAttachedFilesList(null,log);
msg.setContent(data.parts);
Transport transport = null;
try {
transport = session.getTransport(protocol);
if (meta.isUsingAuthentication()) {
if (port!=-1){
transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""),
Const.NVL(authenticationPassword, ""));
}else {
transport.connect(Const.NVL(server, ""), Const.NVL(
authenticationUser, ""), Const.NVL(authenticationPassword, ""));
}
} else {
transport.connect();
}
transport.sendMessage(msg, msg.getAllRecipients());
} finally {
if (transport != null) transport.close();
}
}
private void setAttachedFilesList(Object[] r,LogWriter log) throws Exception
{
String realSourceFileFoldername=null;
String realSourceWildcard=null;
FileObject sourcefile=null;
FileObject file=null;
ZipOutputStream zipOutputStream = null;
File masterZipfile = null;
if(meta.isZipFilenameDynamic()) data.ZipFilename=data.previousRowMeta.getString(r,data.indexOfDynamicZipFilename);
try{
if(meta.isDynamicFilename()) {
// dynamic attached filenames
if(data.indexOfSourceFilename>-1)
realSourceFileFoldername= data.previousRowMeta.getString(r,data.indexOfSourceFilename);
if(data.indexOfSourceWildcard>-1)
realSourceWildcard= data.previousRowMeta.getString(r,data.indexOfSourceWildcard);
}else {
// static attached filenames
realSourceFileFoldername=data.realSourceFileFoldername ;
realSourceWildcard=data.realSourceWildcard;
}
if(!Const.isEmpty(realSourceFileFoldername)){
sourcefile=KettleVFS.getFileObject(realSourceFileFoldername);
if(sourcefile.exists()){
long FileSize=0;
FileObject list[]=null;
if(sourcefile.getType()==FileType.FILE)
{
list = new FileObject[1];
list[0]=sourcefile;
}
else
list = sourcefile.findFiles(new TextFileSelector (sourcefile.toString(),realSourceWildcard));
if(list.length>0){
boolean zipFiles=meta.isZipFiles();
if(zipFiles && data.zipFileLimit==0){
masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
+ data.ZipFilename);
zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));
}
for ( int i=0; i < list.length; i++ ) {
file=KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));
if(zipFiles){
if(data.zipFileLimit==0)
{
ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
zipOutputStream.putNextEntry(zipEntry);
// Now put the content of this file into this archive...
BufferedInputStream inputStream = new BufferedInputStream(file.getContent().getInputStream());
int c;
while ((c = inputStream.read()) >= 0)
{
zipOutputStream.write(c);
}
inputStream.close();
zipOutputStream.closeEntry();
}else
FileSize+=file.getContent().getSize();
}else
{
addAttachedFilePart(file);
}
} // end for
if(zipFiles) {
if(log.isDebug()) log.logDebug(toString() ,Messages.getString("Mail.Log.FileSize",""+FileSize));
if(log.isDebug()) log.logDebug(toString() ,Messages.getString("Mail.Log.LimitSize",""+data.zipFileLimit));
if(data.zipFileLimit>0 && FileSize>data.zipFileLimit){
masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
+ data.ZipFilename);
zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));
for ( int i=0; i < list.length; i++ ) {
file=KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));
ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
zipOutputStream.putNextEntry(zipEntry);
// Now put the content of this file into this archive...
BufferedInputStream inputStream = new BufferedInputStream(file.getContent().getInputStream());
int c;
while ((c = inputStream.read()) >= 0)
{
zipOutputStream.write(c);
}
inputStream.close();
zipOutputStream.closeEntry();
}
}
if(data.zipFileLimit>0 && FileSize>data.zipFileLimit || data.zipFileLimit==0)
{
file=KettleVFS.getFileObject(masterZipfile.getAbsolutePath());
addAttachedFilePart(file);
}
}
}
}else{
log.logError(toString(),Messages.getString("Mail.Error.SourceFileFolderNotExists",realSourceFileFoldername));
}
}
}catch(Exception e)
{
log.logError(toString(),e.getMessage());
}
finally{
if(sourcefile!=null){try{sourcefile.close();}catch(Exception e){}}
if(file!=null){try{file.close();}catch(Exception e){}}
if (zipOutputStream != null){
try{
zipOutputStream.finish();
zipOutputStream.close();
} catch (IOException e)
{
log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString());
}
}
}
}
private void addAttachedFilePart(FileObject file) throws Exception
{
// create a data source
MimeBodyPart files = new MimeBodyPart();
// create a data source
URLDataSource fds = new URLDataSource(file.getURL());
// get a data Handler to manipulate this file type;
files.setDataHandler(new DataHandler(fds));
// include the file in the data source
files.setFileName(file.getName().getBaseName());
// add the part with the file in the BodyPart();
data.parts.addBodyPart(files);
if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("Mail.Log.AttachedFile",fds.getName()));
}
private class TextFileSelector implements FileSelector
{
LogWriter log = LogWriter.getInstance();
String file_wildcard=null,source_folder=null;
public TextFileSelector(String sourcefolderin,String filewildcard)
{
if ( !Const.isEmpty(sourcefolderin))
source_folder=sourcefolderin;
if ( !Const.isEmpty(filewildcard))
file_wildcard=filewildcard;
}
public boolean includeFile(FileSelectInfo info)
{
boolean returncode=false;
try
{
if (!info.getFile().toString().equals(source_folder))
{
// Pass over the Base folder itself
String short_filename= info.getFile().getName().getBaseName();
if (info.getFile().getParent().equals(info.getBaseFolder()) ||
((!info.getFile().getParent().equals(info.getBaseFolder()) && meta.isIncludeSubFolders())))
{
if((info.getFile().getType() == FileType.FILE && file_wildcard==null) ||
(info.getFile().getType() == FileType.FILE && file_wildcard!=null && GetFileWildcard(short_filename,file_wildcard)))
returncode=true;
}
}
}
catch (Exception e)
{
log.logError(toString(), Messages.getString("Mail.Error.FindingFiles", info.getFile().toString(),e.getMessage()));
returncode= false;
}
return returncode;
}
public boolean traverseDescendents(FileSelectInfo info)
{
return true;
}
}
private boolean GetFileWildcard(String selectedfile, String wildcard)
{
Pattern pattern = null;
boolean getIt=true;
if (!Const.isEmpty(wildcard))
{
pattern = Pattern.compile(wildcard);
// First see if the file matches the regular expression!
if (pattern!=null)
{
Matcher matcher = pattern.matcher(selectedfile);
getIt = matcher.matches();
}
}
return getIt;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(MailMeta)smi;
data=(MailData)sdi;
if (super.init(smi, sdi)){
// Add init code here.
return true;
}
return false;
}
// Run is were the action happens!
// Run is were the action happens!
public void run()
{
BaseStep.runStepThread(this, meta, data);
}
}
|
package org.smblott.intentradio;
import android.app.Service;
import android.content.Intent;
import android.content.Context;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.StrictMode;
import android.app.PendingIntent;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Notification.Builder;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build.VERSION;
public class IntentPlayer extends Service
implements
OnBufferingUpdateListener,
OnInfoListener,
OnErrorListener,
OnPreparedListener,
OnAudioFocusChangeListener
{
private static final boolean play_disabled = false;
private static final int note_id = 100;
private static Context context = null;
private static PendingIntent pending = null;
private static String app_name = null;
private static String app_name_long = null;
private static String intent_play = null;
private static String intent_stop = null;
private static String intent_pause = null;
private static String intent_restart = null;
private static String name = null;
private static String url = null;
private static Playlist pltask = null;
private static MediaPlayer player = null;
private static Builder builder = null;
private static Notification note = null;
private static NotificationManager note_manager = null;
private static AudioManager audio_manager = null;
@Override
public void onCreate() {
context = getApplicationContext();
Logger.init(context);
app_name = getString(R.string.app_name);
app_name_long = getString(R.string.app_name_long);
intent_play = getString(R.string.intent_play);
intent_stop = getString(R.string.intent_stop);
intent_pause = getString(R.string.intent_pause);
intent_restart = getString(R.string.intent_restart);
note_manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
pending = PendingIntent.getBroadcast(context, 0, new Intent(intent_stop), 0);
audio_manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
builder =
new Notification.Builder(context)
.setSmallIcon(R.drawable.intent_radio)
.setPriority(Notification.PRIORITY_HIGH)
.setContentIntent(pending)
.setContentTitle(app_name_long)
// not available in API 16...
// .setShowWhen(false)
;
}
public void onDestroy()
{
stop();
Logger.state("off");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if ( intent == null || ! intent.hasExtra("action") )
return done();
if ( intent.hasExtra("debug") )
Logger.state(intent.getStringExtra("debug"));
if ( ! Counter.still(intent.getIntExtra("counter", Counter.now())) )
return done();
String action = intent.getStringExtra("action");
log("Action: ", action);
if ( action.equals(intent_stop) ) return stop();
if ( action.equals(intent_pause) ) return pause();
if ( action.equals(intent_restart) ) return restart();
if ( action.equals(intent_play) )
{
url = getString(R.string.default_url);
name = getString(R.string.default_name);
if ( intent.hasExtra("url") )
{
url = intent.getStringExtra("url");
name = intent.hasExtra("name") ? intent.getStringExtra("name") : url;
}
else if ( intent.hasExtra("name") )
name = intent.getStringExtra("name");
log("Name: ", name);
log("URL: ", url);
return play(url);
}
log("unknown action: ", action);
return done();
}
public void play(String url, int then)
{
if ( Counter.still(then) )
play(url);
}
private int play(String url)
{
stop();
if ( url == null )
{ toast("No URL."); return done(); }
// Playlists...
if ( url.endsWith(PlaylistPls.suffix) )
pltask = new PlaylistPls(this);
if ( url.endsWith(PlaylistM3u.suffix) )
pltask = new PlaylistM3u(this);
if ( pltask != null )
{
log("Playlist: ", url);
pltask.execute(url);
return done();
}
// Set up media player...
log("Play: ", url);
toast(name);
if ( play_disabled )
return stop();
builder.setOngoing(true).setContentText("Connecting...");
note = builder.build();
int focus = audio_manager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if ( focus != AudioManager.AUDIOFOCUS_REQUEST_GRANTED )
return stop("Failed to get audio focus!");
WifiLocker.lock(context, app_name_long);
player = new MediaPlayer();
player.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
// Listeners...
player.setOnPreparedListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnInfoListener(this);
player.setOnErrorListener(this);
// Launch...
startForeground(note_id, note);
log("Connecting...");
try
{
player.setDataSource(context, Uri.parse(url));
player.prepareAsync();
}
catch (Exception e)
{ return stop("Initialisation error."); }
return done();
}
private int stop()
{ return stop(true,null); }
private int stop(String msg)
{ return stop(false,msg); }
private int stop(boolean kill_note, String text)
{
// Time moves on...
Counter.time_passes();
// Kill any outstanding asynchronous playlist task...
if ( pltask != null )
{
pltask.cancel(true);
pltask = null;
}
// Stop player...
if ( player != null )
{
log("Stopping player...");
player.stop();
player.reset();
player.release();
player = null;
WifiLocker.unlock();
}
// Kill or keep notification...
stopForeground(true);
if ( kill_note || text == null || text.length() == 0 )
note = null;
else
notificate(text,false);
return done();
}
private int pause()
{
Counter.time_passes();
if ( player != null && player.isPlaying() )
{
player.pause();
notificate("Paused.");
}
return done();
}
private int restart()
{
Counter.time_passes();
if ( player != null && ! player.isPlaying() )
{
player.start();
notificate();
}
return done();
}
int done()
{ return START_NOT_STICKY; }
public void onPrepared(MediaPlayer a_player)
{
if ( a_player == player )
{
log("Prepared, starting....");
player.start();
notificate();
}
}
public void onBufferingUpdate(MediaPlayer player, int percent)
{
if ( 0 <= percent && percent <= 100 )
log("Buffering: ", ""+percent, "%");
}
public boolean onInfo(MediaPlayer player, int what, int extra)
{
log("onInfo: ", ""+what);
String msg = "Buffering: " + what;
switch (what)
{
case MediaPlayer.MEDIA_INFO_BUFFERING_END:
log(msg, "/end");
notificate();
return true;
// not available in API 16...
// case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
// msg += "/media unsupported"; break;
case MediaPlayer.MEDIA_INFO_BUFFERING_START:
msg += "/start..."; break;
case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
msg += "/bad interleaving"; break;
case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
msg += "/media not seekable"; break;
case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
msg += "/media info update"; break;
default:
return true;
}
notificate(msg);
toast(msg);
return true;
}
public boolean onError(MediaPlayer player, int what, int extra)
{
String msg = "onError...(" + what + ")";
toast(msg);
stop("Error: " + what + ".");
return true;
}
public void onAudioFocusChange(int change)
{
Counter.time_passes();
log("onAudioFocusChange: ", ""+change);
if ( player != null )
switch (change)
{
case AudioManager.AUDIOFOCUS_GAIN:
log("Audio focus: AUDIOFOCUS_GAIN");
restart();
player.setVolume(1.0f, 1.0f);
notificate();
break;
case AudioManager.AUDIOFOCUS_LOSS:
log("Audio focus: AUDIOFOCUS_LOSS");
stop("Audio focus lost, streaming stopped.");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
log("Audio focus: AUDIOFOCUS_LOSS_TRANSIENT");
pause();
notificate("Focus lost, paused...");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
log("Audio focus: AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
player.setVolume(0.1f, 0.1f);
notificate("Focus lost, quiet mode...");
break;
default:
log("Audio focus: unhandled");
break;
}
}
private void notificate()
{ notificate(null); }
private void notificate(String msg)
{ notificate(msg,true); }
private void notificate(String msg, boolean ongoing)
{
if ( note != null )
{
note = builder
.setOngoing(ongoing)
.setContentText(msg == null ? name : msg)
.build();
note_manager.notify(note_id, note);
}
}
private void log(String... msg)
{ Logger.log(msg); }
private void toast(String msg)
{ Logger.toast(msg); }
public IBinder onBind(Intent intent)
{ return null; }
}
|
package org.ssgwt.client.ui.form;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.ssgwt.client.validation.FormValidator;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Label;
/**
* Dynamic form that allows fields extending the InputField interface to be added an creates the field with a label
*
* @author Johannes Gryffenberg<[email protected]>
* @since 12 July 2012
*
* @param <T> The object type the Dynamic form uses to get values from updates the value of the fields on
*/
public class DynamicForm<T> extends Composite {
/**
* The field component that is used to display the field label, the field and the required star if the field is required
*
* @author Johannes Gryffenberg<[email protected]>
* @since 12 July 2012
*/
private class Field extends Composite {
/**
* The label of the field
*/
private final Label fieldLabel = new Label();
/**
* The the flow panel that holds the label and the inputFieldContainer
*/
private final FlowPanel container = new FlowPanel();
/**
* The input field
*/
private InputField inputField;
/**
* The required start label
*/
private final Label requiredStar = new Label("*");
/**
* The flow panel that holds the input field and the required star
*/
private final FlowPanel inputFieldContainer = new FlowPanel();
/**
* Flag to indicate if the field is embedded
*/
private boolean embeded = false;
/**
* Class constructor
*
* @param inputField - The input field that should be displayed on the dynamic form
* @param label - The label that should be displayed above the input field
*/
public Field(InputField inputField, String label) {
this(inputField, label, false);
}
/**
* Class constructor
*
* @param inputField - The input field that should be displayed on the dynamic form
* @param label - The label that should be displayed above the input field
* @param customStyleName - The custom style to apply to the field
*/
public Field(InputField inputField, String label, String customStyleName) {
this(inputField, label, false, customStyleName);
}
/**
* Class constructor
*
* @param inputField - The input field that should be displayed on the dynamic form
* @param label - The label that should be displayed above the input field
* @param embeded - Whether the component is an embeded object or not
*/
public Field(InputField inputField, String label, boolean embeded) {
this(inputField, label, embeded, layout, "");
}
/**
* Class constructor
*
* @param inputField - The input field that should be displayed on the dynamic form
* @param label - The label that should be displayed above the input field
* @param embeded - Whether the component is an embeded object or not
* @param customStyleName - The custom style to apply to the field
*/
public Field(InputField inputField, String label, boolean embeded, String customStyleName) {
this(inputField, label, embeded, layout, customStyleName);
}
/**
* Class constructor
*
* @param inputField - The input field that should be displayed on the dynamic form
* @param label - The label that should be displayed above the input field
* @param embeded - Whether the component is an embeded object or not
* @param layout - The layout of the field
*/
public Field(InputField inputField, String label, boolean embeded, int layout) {
this(inputField, label, embeded, layout, "");
}
/**
* Class constructor
*
* @param inputField - The input field that should be displayed on the dynamic form
* @param label - The label that should be displayed above the input field
* @param embeded - Whether the component is an embeded object or not
* @param layout - The layout of the field. If an incorrect value is passed, it will default to vertical
* @param customStyleName - The custom style to apply to the field
*/
public Field(InputField inputField, String label, boolean embeded, int layout, String customStyleName) {
initWidget(container);
this.embeded = embeded;
this.inputField = inputField;
this.fieldLabel.setText(label);
if (!this.fieldLabel.getText().equals("")) {
this.container.add(this.fieldLabel);
}
this.fieldLabel.addStyleName(labelStyleName);
this.container.add(this.inputFieldContainer);
this.inputFieldContainer.add(this.inputField.getInputFieldWidget());
this.inputFieldContainer.add(this.requiredStar);
this.requiredStar.setVisible(this.inputField.isRequired());
this.inputField.getInputFieldWidget().addStyleName(inputFieldStyleName);
if (!customStyleName.equals("")) {
this.addStyleName(customStyleName);
}
if (this.embeded) {
this.container.setStyleName(containerEmbeddedStyleName);
this.inputField.getInputFieldWidget().addStyleName(inputFieldAdditionalEmbeddedStyleName);
} else {
this.inputField.getInputFieldWidget().addStyleName(inputFieldAdditionalNormalStyleName);
this.container.addStyleName(containerDefaultStyleName);
this.requiredStar.addStyleName(requiredIndicatorStyle);
this.inputField.setReadOnly(readOnly);
}
switch (layout) {
case DynamicForm.LAYOUT_HORIZONTAL:
//Add style to make components align horizontally
this.container.addStyleName(horizontalDefaultStyleName);
this.container.setWidth("");
break;
case DynamicForm.LAYOUT_VERTICAL:
default:
if (customStyleName.equals("")) {
this.inputField.getInputFieldWidget().setWidth(fieldWidth);
}
break;
}
}
}
/**
* The flag that indicates whether the fields on the form is read only
*/
private boolean readOnly;
/**
* The main container of the component
*/
private final FlowPanel mainConatiner = new FlowPanel();
/**
* HashMap that holds the Field object used for each input field
*/
private final HashMap<InputField, Field> fields = new HashMap<InputField, Field>();
/**
* The data object that holds the data t
*/
private T dataObject;
/**
* The default style name for the labels of the dynamic form
*/
public static final String DEFAULT_LABEL_STYLE = "ssGwt-Label";
/**
* The default style name for the input fields on the dynamic form
*/
public static final String DEFAULT_INPUT_FIELD_STYLE = "ssGwt-Input";
/**
* The default style name for the required indicator on the dynamic form
*/
public static final String DEFAULT_REQUIRED_INDICATOR_STYLE = "ssGwt-RequiredIndicator";
/**
* The default style name for the horizontal display style for the dynamic form
*/
public static final String DEFAULT_HORIZONTAL_CONTAINER_STYLE = "ssGwt-HorizontalDisplay";
/**
* The default style name for the default container on the dynamic form
*/
public static final String DEFAULT_CONTAINER_STYLE = "ssGwt-DefaultContainer";
/**
* The default style name for the Embedded container on the dynamic form
*/
public static final String DEFAULT_CONTAINER_EMBEDDED_STYLE = "ssGwt-EmbeddedContainer";
/**
* The default style name for the normal input fields on the dynamic form
*/
public static final String DEFAULT_ADDITIONAL_NORMAL_INPUT_FIELD_STYLE = "ssGwt-InputExtraNormal";
/**
* The default style name for the embedded input fields on the dynamic form
*/
public static final String DEFAULT_ADDITIONAL_EMBEDDED_INPUT_FIELD_STYLE = "ssGwt-InputExtraEmbedded";
/**
* Another layout on the dynamic form
*/
public static final int LAYOUT_HORIZONTAL = 0;
/**
* The default layout on the dynamic form
*/
public static final int LAYOUT_VERTICAL = 1;
/**
* The default width of the input fields
*/
public static final String DEFAULT_FIELD_WIDTH = "230px";
/**
* The style name for the labels of the dynamic form
*/
private String labelStyleName;
/**
* The style name for the embedded container of the dynamic form
*/
private String containerEmbeddedStyleName;
/**
* The style name for the default container of the dynamic form
*/
private String containerDefaultStyleName;
/**
* The style name for the input fields on the dynamic form
*/
private String inputFieldStyleName;
/**
* Additional style name for non-embedded field
*/
private String inputFieldAdditionalNormalStyleName;
/**
* Additional style name for embedded field
*/
private String inputFieldAdditionalEmbeddedStyleName;
/**
* Additional style name for horizontal fields
*/
private String horizontalDefaultStyleName;
/**
* The style name for the required indicator on the dynamic form
*/
private String requiredIndicatorStyle;
/**
* The validator used to validate the form
*/
FormValidator formValidator = new FormValidator();
/**
* The width of the input fields
*/
private String fieldWidth;
/**
* Used to store the value of the layout
*/
private int layout;
/**
* Class constructor
*/
public DynamicForm() {
this(DEFAULT_LABEL_STYLE, DEFAULT_INPUT_FIELD_STYLE, DEFAULT_REQUIRED_INDICATOR_STYLE, DEFAULT_FIELD_WIDTH, LAYOUT_VERTICAL);
}
/**
* Class constructor for just the layout
*
* @param layout - The layout to use
*/
public DynamicForm(int layout) {
this(DEFAULT_LABEL_STYLE, DEFAULT_INPUT_FIELD_STYLE, DEFAULT_REQUIRED_INDICATOR_STYLE, DEFAULT_FIELD_WIDTH, layout);
}
/**
* Class constructor
*
* @param fieldWidth - The width of the input fields
*/
public DynamicForm(String fieldWidth) {
this(DEFAULT_LABEL_STYLE, DEFAULT_INPUT_FIELD_STYLE, DEFAULT_REQUIRED_INDICATOR_STYLE, fieldWidth, LAYOUT_VERTICAL);
}
/**
* Class constructor
*
* @param labelStyleName - The style name for the labels of the dynamic form
* @param inputFieldStyleName - The style name for the input fields on the dynamic form
* @param requiredIndicatorStyle - The style name for the required indicator on the dynamic form
*/
public DynamicForm(String labelStyleName, String inputFieldStyleName, String requiredIndicatorStyle) {
this(labelStyleName, inputFieldStyleName, requiredIndicatorStyle, DEFAULT_FIELD_WIDTH, LAYOUT_VERTICAL);
}
/**
* Class constructor
*
* @param labelStyleName - The style name for the labels of the dynamic form
* @param inputFieldStyleName - The style name for the input fields on the dynamic form
* @param requiredIndicatorStyle - The style name for the required indicator on the dynamic form
* @param fieldWidth - The width of the input fields
* @param layout - The layout of the field
*/
public DynamicForm(String labelStyleName, String inputFieldStyleName, String requiredIndicatorStyle, String fieldWidth, int layout) {
initWidget(mainConatiner);
this.labelStyleName = labelStyleName;
this.inputFieldStyleName = inputFieldStyleName;
this.requiredIndicatorStyle = requiredIndicatorStyle;
this.fieldWidth = fieldWidth;
this.layout = layout;
//set defaults for additional styles
this.containerDefaultStyleName = DEFAULT_CONTAINER_STYLE;
this.containerEmbeddedStyleName = DEFAULT_CONTAINER_EMBEDDED_STYLE;
this.inputFieldAdditionalEmbeddedStyleName = DEFAULT_ADDITIONAL_EMBEDDED_INPUT_FIELD_STYLE;
this.inputFieldAdditionalNormalStyleName = DEFAULT_ADDITIONAL_NORMAL_INPUT_FIELD_STYLE;
this.horizontalDefaultStyleName = DEFAULT_HORIZONTAL_CONTAINER_STYLE;
}
/**
* Sets that data object for the form
*
* @param dataObject - The data object used
*/
public void setData(T dataObject) {
this.dataObject = dataObject;
updateFieldData();
}
/**
* Retrieves the passed in object with the field data updated on the object
*
* @return The passed in object with the field data updated on the object
*/
public T getData() {
updateDataObject();
return dataObject;
}
/**
* Updates the data object that was set using the setData function with the data in the fields
*/
protected void updateDataObject() {
for(InputField<T, ?> field : fields.keySet()) {
if (String.class.equals(field.getReturnType())) {
((InputField<T, String>)field).setValue(dataObject, ((HasValue<String>)field).getValue());
} else if (Date.class.equals(field.getReturnType())) {
((InputField<T, Date>)field).setValue(dataObject, ((HasValue<Date>)field).getValue());
} else if (List.class.equals(field.getReturnType())) {
((InputField<T, List>)field).setValue(dataObject, ((HasValue<List>)field).getValue());
} else if (Boolean.class.equals(field.getReturnType())) {
((InputField<T, Boolean>)field).setValue(dataObject, ((HasValue<Boolean>)field).getValue());
}
}
}
/**
* Updates the fields with the data that was set using the setData function
*/
protected void updateFieldData() {
for(InputField<T, ?> field : fields.keySet()) {
if (String.class.equals(field.getReturnType())) {
((HasValue<String>)field).setValue(((InputField<T, String>)field).getValue(dataObject));
} else if (Date.class.equals(field.getReturnType())) {
((HasValue<Date>)field).setValue(((InputField<T, Date>)field).getValue(dataObject));
} else if (List.class.equals(field.getReturnType())) {
((HasValue<List>)field).setValue(((InputField<T, List>)field).getValue(dataObject));
} else if (Boolean.class.equals(field.getReturnType())) {
((HasValue<Boolean>)field).setValue(((InputField<T, Boolean>)field).getValue(dataObject));
}
}
}
/**
* Adds a input field to the Dynamic form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
*/
public void addField(InputField<T, ?> inputField, String label) {
addField(inputField, label, false, "");
}
/**
* Adds a input field to the Dynamic form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
* @param customStyleName - The custom style to apply to the field
*/
public void addField(InputField<T, ?> inputField, String label, String customStyleName) {
addField(inputField, label, false, customStyleName);
}
/**
* Adds a input field to the Dynamic form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
* @param embeded - Whether the component is an embeded object or not
*/
public void addField(InputField<T, ?> inputField, String label, boolean embeded) {
addField(inputField, label, embeded, "");
}
/**
* Adds a input field to the Dynamic form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
* @param embeded - Whether the component is an embeded object or not
* @param customStyleName - The custom style to apply to the field
*/
public void addField(InputField<T, ?> inputField, String label, boolean embeded, String customStyleName) {
drawField(inputField, label, embeded, customStyleName);
}
/**
* Removes a field from the Dynamic form
*
* @param inputField - The input field that should be removed from the Dynamic form
*/
public void removeField(InputField<T, ?> inputField) {
mainConatiner.remove(fields.get(inputField));
fields.remove(inputField);
}
/**
* Sets a field to visible or invisible
*
* @param inputField - The field that we will affect with this function
* @param visible - true|false
*/
public void displayField(InputField<T, ?> inputField, boolean visible) {
fields.get(inputField).setVisible(visible);
}
/**
* Validates the form and returns a string the first validation error if there is any errors
*
* @return The validation error message
*/
public String doValidation() {
return formValidator.doValidation();
}
/**
* Draws the field on the form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
*/
private void drawField(InputField<T, ?> inputField, String label) {
drawField(inputField, label, false, "");
}
/**
* Draws the field on the form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
* @param customStyleName - The custom style to apply to the field
*/
private void drawField(InputField<T, ?> inputField, String label, String customStyleName) {
drawField(inputField, label, false, customStyleName);
}
/**
* Draws the field on the form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
* @param embeded - Whether the component is an embeded object or not
*/
private void drawField(InputField<T, ?> inputField, String label, boolean embeded) {
drawField(inputField, label, embeded, "");
}
/**
* Draws the field on the form
*
* @param inputField - The input field that should be added to the form
* @param label - The label that should be display above the field
* @param embeded - Whether the component is an embeded object or not
* @param customStyleName - The custom style to apply to the field
*/
private void drawField(InputField<T, ?> inputField, String label, boolean embeded, String customStyleName) {
Field fieldInfo = new Field(inputField, label, embeded, customStyleName);
mainConatiner.add(fieldInfo);
fields.put(inputField, fieldInfo);
}
/**
* Updates styles of the fields and hides the required star if the required state of a field changes
*/
public void redraw() {
for (Field field : fields.values()) {
field.fieldLabel.addStyleName(labelStyleName);
field.inputField.getInputFieldWidget().addStyleName(inputFieldStyleName);
field.requiredStar.addStyleName(requiredIndicatorStyle);
field.requiredStar.setVisible(field.inputField.isRequired());
field.inputField.setReadOnly(this.readOnly);
}
}
/**
* Adds validation criteria to a input field
*
* @param inputField - The input field that should be validated
* @param validatorReferenceName - The reference name for the validation
* @param config - Validation configuration settings
*/
public void addFieldValidation(InputField<T, ?> inputField, String validatorReferenceName, HashMap<String, ?> config) {
formValidator.addField(validatorReferenceName, inputField.getInputFieldWidget(), config);
}
/**
* Adds validation criteria to a input field
*
* @param inputField - The input field that should be validated
* @param validatorReferenceName - The reference name for the validation
* @param config - Validation configuration settings
* @param errorMessage - The error message to be displayed
*/
public void addFieldValidation(InputField<T, ?> inputField, String validatorReferenceName, HashMap<String, ?> config, String errorMessage) {
formValidator.addField(validatorReferenceName, inputField.getInputFieldWidget(), config, errorMessage);
}
/**
* Adds validation criteria to a input field
*
* @param inputField - The input field that should be validated
* @param validatorReferenceName - The reference name for the validation
* @param config - Validation configuration settings
* @param errorMessage - The error message to be displayed
* @param errorStyleName - the error style type
*/
public void addFieldValidation(InputField<T, ?> inputField, String validatorReferenceName, HashMap<String, ?> config, String errorMessage, String errorStyleName) {
formValidator.addField(validatorReferenceName, inputField.getInputFieldWidget(), config, errorMessage, errorStyleName);
}
/**
* Retrieves the style name for the labels of the dynamic form
*
* @return The style name for the labels of the dynamic form
*/
public String getLabelStyleName() {
return labelStyleName;
}
/**
* Sets the style name for the labels of the dynamic form
*
* @param labelStyleName - The style name for the labels of the dynamic form
*/
public void setLabelStyleName(String labelStyleName) {
this.labelStyleName = labelStyleName;
redraw();
}
/**
* Sets the default container style name.
* This is non-emebed style for the container. that contains the fields
*
* @param defaultContainerStyleName - the default container style name
*/
public void setDefaultContainerStyleName(String defaultContainerStyleName) {
this.containerDefaultStyleName = defaultContainerStyleName;
redraw();
}
/**
* Retrieves the default container style name
*
* @return the default container style name
*/
public String getDefaultContainerStyleName() {
return containerDefaultStyleName;
}
/**
* Sets the embedded container style name that contains the fields
*
* @param embeddedContainerStyleName - the embedded container style name that contains the fields
*/
public void setEmbeddedContainerStyleName(String embeddedContainerStyleName) {
this.containerEmbeddedStyleName = embeddedContainerStyleName;
redraw();
}
/**
* Retrieves the embedded container style name
*
* @return the embedded container style name
*/
public String getEmbeddedContainerStyleName() {
return containerEmbeddedStyleName;
}
/**
* Sets the style name for the embedded input fields on the dynamic form
*
* @param inputFieldAdditionalEmbeddedStyleName - the additional style name for the embedded input fields on the dynamic form
*/
public void setInputFieldAdditionalEmbeddedStyleName(
String inputFieldAdditionalEmbeddedStyleName) {
this.inputFieldAdditionalEmbeddedStyleName = inputFieldAdditionalEmbeddedStyleName;
redraw();
}
/**
* Retrieves the style name for the input fields on the dynamic form
*
* @return The style name for the input fields on the dynamic form
*/
public String getInputFieldAdditionalEmbeddedStyleName() {
return inputFieldAdditionalEmbeddedStyleName;
}
/**
* Sets the style name for the input fields on the dynamic form
*
* @param inputFieldAdditionalNormalStyleName - the additional style name for the input fields on the dynamic form
*/
public void setInputFieldAdditionalNormalStyleName(
String inputFieldAdditionalNormalStyleName) {
this.inputFieldAdditionalNormalStyleName = inputFieldAdditionalNormalStyleName;
redraw();
}
/**
* Retrieves the style name for the input fields on the dynamic form
*
* @return The style name for the input fields on the dynamic form
*/
public String getInputFieldAdditionalNormalStyleName() {
return inputFieldAdditionalNormalStyleName;
}
/**
* Retrieves the style name for the input fields on the dynamic form
*
* @return The style name for the input fields on the dynamic form
*/
public String getInputFieldStyleName() {
return inputFieldStyleName;
}
/**
* Sets the style name for the input fields on the dynamic form
*
* @param inputFieldStyleName - The style name for the input fields on the dynamic form
*/
public void setInputFieldStyleName(String inputFieldStyleName) {
this.inputFieldStyleName = inputFieldStyleName;
redraw();
}
/**
* Retrieve the style name for the required indicator on the dynamic form
*
* @return The style name for the required indicator on the dynamic form
*/
public String getRequiredIndicatorStyle() {
return requiredIndicatorStyle;
}
/**
* Sets the style name for the required indicator on the dynamic form
*
* @param requiredIndicatorStyle - The style name for the required indicator on the dynamic form
*/
public void setRequiredIndicatorStyle(String requiredIndicatorStyle) {
this.requiredIndicatorStyle = requiredIndicatorStyle;
redraw();
}
/**
* Set all the fields on the form as readOnly
*
* @param readOnly - Flag to indicate whether the fields should be read only
*/
public void setFieldsReadOnly(boolean readOnly) {
this.readOnly = readOnly;
redraw();
}
/**
* Retrieve the flag that indicates whether the fields on the form is read only
*
* @return The flag that indicates whether the fields on the form is read only
*/
public boolean isFieldsReadOnly() {
return this.readOnly;
}
/**
* Set a fields visibility
*
* @param inputField - The input field
* @param visible - True to disply the field|false to hide a field
*/
public void setFieldVisible(InputField<T, ?> inputField, boolean visible) {
if (fields.containsKey(inputField)) {
fields.get(inputField).setVisible(visible);
}
}
/**
* Set global dynamic form keyboard keydown handler on each field.
*
* @param handler - The handler type apply to the fields
*/
public void setKeyDownFieldsHandler(KeyDownHandler handler) {
for (InputField inputField : fields.keySet()) {
inputField.getInputFieldWidget().addDomHandler(handler, KeyDownEvent.getType());
}
}
}
|
package org.usfirst.frc.team4533.robot;
import org.usfirst.frc.team4533.robot.subsystems.ClimbSystem;
import org.usfirst.frc.team4533.robot.subsystems.DriveSystem;
import org.usfirst.frc.team4533.robot.subsystems.ShooterSystem;
import org.usfirst.frc.team4533.robot.utils.SensorData;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Preferences;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
//public static OI oi;
public static DriveSystem drive;
public static ClimbSystem climb;
public static ShooterSystem shooter;
public static OI oi;
private CommandGroup autonomousCommand;
public SendableChooser seedChooser;
public static int seed;
public static int maxSpeed;
Preferences prefs;
// Sensors
public static double heading; // Arduino : 9DOF Magnetometer
public static double rearDistance; // Arduino : LIDAR-LITE v3
public static String pixyGuidance; // Arduino : PIXY Camera
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
String bot = "Practice";
if (bot.equals("Practice")) {
RobotMap.setPracticeBot();
}
drive = new DriveSystem();
climb = new ClimbSystem();
shooter = new ShooterSystem();
oi = new OI();
seedChooser = new SendableChooser();
//seedChooser.addDefault("5", );
//seedChooser.addObject("1", this.DriveSystem.getControlSpeed(2,4));//seed=1
//seedChooser.addObject("2", seed = 2);
//seedChooser.addObject("8", seed = 8);
prefs = Preferences.getInstance();
seed = 5;
maxSpeed = 100;
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
SmartDashboard.putBoolean("Gear", DriveSystem.hasGear());
SmartDashboard.putBoolean("Climber On?", ClimbSystem.isOn());
SmartDashboard.putNumber("Front Distance", DriveSystem.ultraSonic());
String messageOfTheDay = "don't do school stay in drugs";
SmartDashboard.putString("Message Of The Day", messageOfTheDay);
SmartDashboard.putString("PIXY", DriveSystem.pixyValue());
SmartDashboard.putNumber("LIDAR", DriveSystem.lidarValue());
//arduino.update();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
|
package org.usfirst.frc.team5275.robot;
import org.usfirst.frc.team5275.robot.OI;
import org.usfirst.frc.team5275.robot.commands.BKAuto;
import org.usfirst.frc.team5275.robot.commands.LeftGear;
import org.usfirst.frc.team5275.robot.commands.MechDrive;
import org.usfirst.frc.team5275.robot.commands.MiddleGear;
import org.usfirst.frc.team5275.robot.commands.RightGear;
import org.usfirst.frc.team5275.robot.commands.Stop;
import org.usfirst.frc.team5275.robot.commands.TankDrive;
import org.usfirst.frc.team5275.robot.subsystems.DriveTrain;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
*
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*
*
*
*/
public class Robot extends IterativeRobot {
public static OI oi;
double slider;
Command tempCommand;
Command autonomousCommand;
Command teleopCommand;
Command DriveSystem;
Command DriveSYS;
public Command Tank = new TankDrive();
public Command MechDrive = new MechDrive();
public Command Middle = new MiddleGear();
public Command Right = new RightGear();
public Command BKAuto = new BKAuto();
public Command Stop = new Stop();
public Timer Time = new Timer();
//public Command = new ();
// public Command QSwitch = new QSwitch();
SendableChooser<Command> autocon;
SendableChooser<Command> DRSYS;
SendableChooser<Command> telecon;
public static DriveTrain drive = new DriveTrain();
public static RobotDrive PWMDrive = new RobotDrive(Robot.drive.LF,Robot.drive.LB,Robot.drive.RF,Robot.drive.RB);
public static RobotDrive CANDrive = new RobotDrive(Robot.drive.SRX1,Robot.drive.SRX2,Robot.drive.SRX3,Robot.drive.SRX4);
LiveWindowSendable LFT;
/* void SmartDashboard() {
SendableChooser<Command> autocon;
SendableChooser<Command> DRSYS;
SendableChooser<Command> telecon;
};
*/
Boolean i = false;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
oi = new OI();
// CameraServer cServer = CameraServer.getInstance();
//cServer.startAutomaticCapture("FrontCamera", 0);
//Not working choosers
autocon = new SendableChooser<Command>();
autocon.addDefault("Middle", new MiddleGear());
autocon.addObject("Right Gear", new RightGear());
autocon.addObject("Left Gear", new LeftGear());
autocon.addObject("Backward", new BKAuto());
SmartDashboard.putData("Auto Selector", autocon);
DRSYS = new SendableChooser<Command>();
DRSYS.addDefault("Tank", new TankDrive());
DRSYS.addObject("Mech", new MechDrive());
SmartDashboard.putData("Drive system", DRSYS);
telecon = new SendableChooser<Command>();
telecon.addDefault("Single Stick", new TankDrive());
telecon.addObject("Twin Stick (Don't Use)", new MechDrive());
SmartDashboard.putData("Control Mode", telecon);
boolean C = SmartDashboard.containsKey("Auto selector");
SmartDashboard.containsKey("Auto selector");
System.out.println(C);
/*
CameraServer server = CameraServer.getInstance();
server.startAutomaticCapture(0);
*/
/*
Robot.drive.SRX1.enable();
Robot.drive.SRX2.enable();
Robot.drive.SRX3.enable();
Robot.drive.SRX4.enable();
//Robot.drive.SRX1.
//Robot.drive.SRX1.
Robot.drive.SRX1.changeControlMode(TalonControlMode.PercentVbus);
Robot.drive.SRX2.changeControlMode(TalonControlMode.PercentVbus);
Robot.drive.SRX3.changeControlMode(TalonControlMode.PercentVbus);
Robot.drive.SRX4.changeControlMode(TalonControlMode.PercentVbus);
*/
}
/*
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
// Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
// autonomousCommand = (Command) autocon.getSelected();
/* String autoSelected = SmartDashboard.getString("Auto Selector", "Default");
switch(autoSelected) {
case "My Auto":
autonomousCommand = new FWAuto();
break;
case "Default Auto":
default:
autonomousCommand = new FWAuto();
break;
}
*/
// schedule the autonomous command (example)
// if (autonomousCommand != null)
// autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
/**
* Choosers for the default dashboard.
* Look in the Basic Tab
*
* You can add information to the Dashboard by changing .get to .put
* and by putting a value into the spot after the key
*
* The Following three lines show this.
**/
SmartDashboard.putString("DB/String 3", "Showing");
SmartDashboard.putNumber("DB/Slider 3", 2.5);
SmartDashboard.putBoolean("DB/Button 3", true);
/*if (SmartDashboard.getBoolean("DB/Slider 3", false) == true) {
System.out.println("Slider 3 is true");
}
if (SmartDashboard.getNumber("DB/Slider 0", 0.0) == 1) {
//Left.start();
boolean v1 = true;
if (v1 == true) {
System.out.println("Left Side");
v1 = false;
}
}
if (SmartDashboard.getNumber("DB/Slider 0", 0.0) == 2) {
Middle.start();
boolean v2 = true;
if (v2 == true) {
System.out.println("Middle Slot");
v2 = false;
}
} else if (SmartDashboard.getNumber("DB/Slider 0", 0.0) == 3) {
BKAuto.start();
boolean v3 = true;
if (v3 == true) {
System.out.println("Right Side");
v3 = false;
}
} else {
Stop.start();
};
String Auto = SmartDashboard.getString("DB/String 0", "");
if (Auto.equalsIgnoreCase("Out")) {
System.out.println("It works");
} else {
System.out.println(Auto);
};
*/
tempCommand = autocon.getSelected();
tempCommand.start();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
DriveSystem = (Command) DRSYS.getSelected();
DriveSystem.start();
teleopCommand = (Command) telecon.getSelected();
teleopCommand.start();
/*
Robot.drive.SRX1.enable();
Robot.drive.SRX2.enable();
Robot.drive.SRX3.enable();
Robot.drive.SRX4.enable();
//Robot.drive.SRX1.
//Robot.drive.SRX1.
Robot.drive.SRX1.getControlMode();
Robot.drive.SRX2.getControlMode();
Robot.drive.SRX3.getControlMode();
Robot.drive.SRX4.getControlMode();
*/
System.out.println("robot started");
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
// Scheduler.getInstance().run();
// teleop.start();
//Tank.start();
slider = oi.rightS.getRawAxis(3);
slider = -(slider - 1) / 2;
//TODO The above code needs to be tested. try printing the value of slider.
String Drive = SmartDashboard.getString("DB/String 5", "");
System.out.println(slider);
if (Drive.equalsIgnoreCase("PWM Mech")) {
PWMDrive.mecanumDrive_Cartesian(slider*oi.rightS.getX(), slider*oi.rightS.getY(), slider*oi.rightS.getTwist(), 0);
// Mecanum Drive Using PWM slots
System.out.println("PWM Mech Drive");
} else { //(Drive.equalsIgnoreCase("CAN Mech"))
CANDrive.mecanumDrive_Cartesian(slider*oi.rightS.getX(), slider*oi.rightS.getY(), slider*oi.rightS.getZ(),0);
// Mecanum Drive Using CAN Speed Controllers
System.out.println("PWM CAN Drive");
}
/*else if (Drive.equalsIgnoreCase("PWM Tank")) {
PWMDrive.tankDrive(slider*oi.leftS.getY(), slider*oi.rightS.getY());
// Tank Drive Using PWM slots
} else if (Drive.equalsIgnoreCase("CAN Tank")) {
CANDrive.tankDrive(slider*oi.leftS.getY(), slider*oi.rightS.getY());
// Tank Drive Using CAN Speed Controllers
};*/
if (Robot.oi.BL6.get() == true){
Robot.drive.Out.set(0.4);
} else if (Robot.oi.BL7.get() == true){
Robot.drive.Out.set(-0.5);
} else if (Robot.oi.BL8.get() == true) {
Robot.drive.Out.set(1);
} else {
Robot.drive.Out.set(0.0);
}
// Double i = 1;
if (Robot.oi.BL4.get() == true) {
Robot.drive.Winch.set(-0.5);
} else if(Robot.oi.BL2.get() == true) {
Robot.drive.Winch.set(-1);
} else if(Robot.oi.BL5.get() == true) {
Robot.drive.Winch.set(0.5);
} else if(Robot.oi.BL3.get() == true) {
Robot.drive.Winch.set(1);
} else {
Robot.drive.Winch.set(0.0);
}
if (Robot.oi.BL11.get() == true){
Robot.drive.Sweep.set(-0.45);
} else if (Robot.oi.BL10.get() == true){
Robot.drive.Sweep.set(0.5);
} else if (Robot.oi.BL9.get() == true) {
Robot.drive.Sweep.set(1);
} else {
Robot.drive.Sweep.set(0.0);
}
//OI.triggerR.whenActive(QSwitch);
// Robot.drive.Con.set(0.5*oi.leftS.getY());
/*
double s1 = Robot.drive.SRX1.getSpeed();
double s2 = Robot.drive.SRX2.getSpeed();
double s3 = Robot.drive.SRX3.getSpeed();
double s4 = Robot.drive.SRX4.getSpeed();
//Robot.drive.SRX1.get
System.out.print(s1);
System.out.print(s2);
System.out.print(s3);
System.out.print(s4);
*/
// Robot.drive.Test.
/* Robot.drive.SRX1.get();
Robot.drive.SRX2.get();
Robot.drive.SRX3.get();
Robot.drive.SRX4.get();
Robot.drive.SRX1.set(OI.rightS.getY());
*/
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
|
package org.yuanheng.cookcc.lexer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.yuanheng.cookcc.doc.ShortcutDoc;
import org.yuanheng.cookcc.exception.*;
/**
* Hand written rule parser.
*
* @author Heng Yuan
* @version $Id$
*/
public class RuleParser
{
private final static Pattern m_replaceName = Pattern.compile ("\\{[a-zA-Z_][a-zA-Z0-9_-]*[}]");
private final Lexer m_lexer;
private final NFAFactory m_nfaFactory;
private final CCL m_ccl;
private final boolean m_nocase;
private int m_trailContext;
private boolean m_varLen;
private int m_ruleLen;
private boolean m_bol;
private boolean[] m_singletonCharSet;
private boolean[] m_cclCharSet;
private RuleLexer m_lex;
private int m_lineNumber;
private class RuleLexer
{
private String m_input;
private String m_currentStr;
private int m_pos;
public RuleLexer (String input)
{
m_input = input;
m_currentStr = input;
m_pos = 0;
}
public boolean isEmpty ()
{
return m_pos == m_currentStr.length ();
}
public Character ifMatchEsc ()
{
if (!ifMatch ('\\'))
return null;
--m_pos;
int[] escPos = new int[]{ m_pos };
char ch = CCL.esc (m_currentStr, escPos);
m_pos = escPos[0];
return new Character (ch);
}
public boolean ifMatchReplaceName ()
{
if (!ifMatch ('{'))
return false;
--m_pos; // rewind the forward;
m_currentStr = m_currentStr.substring (m_pos);
m_pos = 0;
Matcher matcher = m_replaceName.matcher (m_currentStr);
if (!matcher.find (0) || matcher.start () != 0)
return false;
int index = m_currentStr.indexOf ('}');
String name = m_currentStr.substring (1, index);
ShortcutDoc shortcut = m_lexer.getDocument ().getLexer ().getShortcut (name);
if (shortcut == null)
throw new UnknownNameException (m_lineNumber, name, m_input);
m_currentStr = "(" + shortcut.getPattern () + ")" + m_currentStr.substring (index + 1);
return true;
}
public void unread (String str)
{
m_currentStr = str + m_currentStr.substring (m_pos);
m_pos = 0;
}
public boolean ifMatch (String str)
{
if ((m_currentStr.length () - m_pos) < str.length ())
return false;
int len = str.length ();
int offset = m_pos;
for (int i = 0; i < len; ++i)
if (m_currentStr.charAt (offset++) != str.charAt (i))
return false;
m_pos = offset;
return true;
}
public boolean ifMatch (char ch)
{
if (m_pos >= m_currentStr.length () || m_currentStr.charAt (m_pos) != ch)
return false;
++m_pos;
return true;
}
public Character ifMatch (boolean[] charSet)
{
Character ch;
if (m_pos >= m_currentStr.length () || !charSet[m_currentStr.charAt (m_pos)])
return null;
ch = new Character (m_currentStr.charAt (m_pos));
++m_pos;
return ch;
}
public void match (char ch)
{
if (m_pos >= m_currentStr.length () || m_currentStr.charAt (m_pos) != ch)
throw new LookaheadException (m_lineNumber, m_ccl, ch, m_input, m_pos);
++m_pos;
}
public String getInput ()
{
return m_input;
}
public int getPos ()
{
return m_pos;
}
}
public RuleParser (Lexer lexer, NFAFactory nfaFactory)
{
this (lexer, nfaFactory, false);
}
public RuleParser (Lexer lexer, NFAFactory nfaFactory, boolean nocase)
{
m_lexer = lexer;
m_nfaFactory = nfaFactory;
m_ccl = nfaFactory.getCCL ();
m_nocase = nocase;
m_trailContext = 0;
m_varLen = false;
m_ruleLen = 0;
m_bol = false;
m_singletonCharSet = CCL.subtract (m_ccl.ANY.clone (), m_ccl.parseCCL ("[/|*+?.(){}]]"));
m_cclCharSet = CCL.subtract (m_ccl.ANY.clone (), m_ccl.parseCCL ("[-\\]\\n]"));
}
public boolean isBOL ()
{
return m_bol;
}
public NFA parse (int lineNumber, String input)
{
m_lineNumber = lineNumber;
m_lex = new RuleLexer (input);
if (m_lex.ifMatch ('^'))
m_bol = true;
NFA head = parseRegex ();
if (head == null)
throw new InvalidRegExException (lineNumber, input);
if (m_lex.ifMatch ('/'))
{
if (NFA.hasTrail (m_trailContext))
throw new MultipleTrailContextException (lineNumber, input);
if (m_varLen)
m_ruleLen = 0;
m_trailContext = NFA.setTrailContext (m_ruleLen, !m_varLen, false);
NFA tail = parseRegex ();
if (m_lex.ifMatch ('$'))
{
NFA eol = m_lexer.getEOL ();
if (tail == null)
tail = eol;
else
tail = tail.cat (eol);
++m_ruleLen;
}
if (tail == null)
throw new ParserException (lineNumber, "unexpected '/'");
if ((m_trailContext & NFA.TRAIL_MASK) != NFA.TRAIL_FIXHEAD)
{
if (m_varLen)
throw new VariableTrailContextException (lineNumber, input);
else
m_trailContext = NFA.setTrailContext (m_ruleLen, false, true);
}
head = head.cat (tail);
}
else if (m_lex.ifMatch ('$'))
{
if (NFA.hasTrail (m_trailContext))
throw new MultipleTrailContextException (lineNumber, input);
m_trailContext = NFA.setTrailContext (1, false, true);
head = head.cat (m_nfaFactory.createNFA ('\n', null));
}
head.setState (m_lexer.incCaseCounter (), lineNumber, m_trailContext, true);
return head;
}
private NFA parseRegex ()
{
m_varLen = false;
m_ruleLen = 0;
NFA head = parseSeries ();
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
while (m_lex.ifMatch ('|'))
{
NFA tail = parseSeries ();
if (tail == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
head = head.or (tail);
}
return head;
}
private NFA parseSeries ()
{
NFA head = parseSingleton (null);
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
NFA tail;
while ((tail = parseSingleton (null)) != null)
head = head.cat (tail);
return head;
}
private NFA parseSingleton (NFA head)
{
while (true)
{
if (head == null)
{
boolean[] ccl;
Character ch;
if (m_lex.ifMatch ('.'))
{
++m_ruleLen;
head = m_nfaFactory.createNFA (NFA.ISCCL, m_ccl.ANY);
}
else if (m_lex.ifMatch ("<<EOF>>"))
{
if (!m_lex.isEmpty ())
throw new LookaheadException (m_lineNumber, m_ccl, m_ccl.EOF, m_lex.getInput (), m_lex.getPos ());
head = m_nfaFactory.createNFA (m_ccl.EOF, null);
}
else if (m_lex.ifMatchReplaceName ())
{
continue;
}
else if ((ccl = parseFullCCL ()) != null)
{
++m_ruleLen;
head = m_nfaFactory.createNFA (NFA.ISCCL, ccl);
}
else if (m_lex.ifMatch ('"'))
{
head = parseString ();
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
m_lex.match ('"');
}
else if (m_lex.ifMatch ('('))
{
head = parseRegex ();
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
m_lex.match (')');
}
else if ((ch = parseChar (m_singletonCharSet)) != null)
{
++m_ruleLen;
if (m_nocase)
{
char c = ch.charValue ();
ccl = m_ccl.EMPTY.clone ();
ccl[c] = true;
if (c >= 'a' && c <= 'z')
ccl[c - 'a' + 'A'] = true;
else if (c >= 'A' && c <= 'Z')
ccl[c - 'A' + 'a'] = true;
head = m_nfaFactory.createNFA (NFA.ISCCL, ccl);
}
else
head = m_nfaFactory.createNFA (ch.charValue (), null);
}
else
return null;
}
else
{
if (m_lex.ifMatch ('*'))
{
m_varLen = true;
head = head.star ();
}
else if (m_lex.ifMatch ('+'))
{
m_varLen = true;
head = head.plus ();
}
else if (m_lex.ifMatch ('?'))
{
m_varLen = true;
head = head.q ();
}
if (m_lex.ifMatchReplaceName ())
{
continue;
}
else if (m_lex.ifMatch ('{'))
{
Integer number = parseNumber ();
if (number == null || number.intValue () < 0)
throw new BadIterationException (m_lineNumber, number);
if (m_lex.ifMatch ('}'))
head = head.repeat (number);
else
{
int min, max;
min = number.intValue ();
m_lex.match (',');
number = parseNumber ();
if (number == null)
max = -1;
else
max = number.intValue ();
head = head.repeat (min, max);
m_lex.match ('}');
}
}
else
break;
}
}
return head;
}
private Character parseChar (boolean[] charSet)
{
Character ch = m_lex.ifMatchEsc ();
if (ch == null)
ch = m_lex.ifMatch (charSet);
return ch;
}
private Integer parseNumber ()
{
Character ch;
boolean neg = false;
if (m_lex.ifMatch ('-'))
neg = true;
int number;
if ((ch = parseChar (m_ccl.DIGIT)) == null)
throw new LookaheadException (m_lineNumber, m_ccl, m_ccl.DIGIT, m_lex.getInput (), m_lex.getPos ());
number = ch.charValue () - '0';
while ((ch = parseChar (m_ccl.DIGIT)) != null)
number = number * 10 + ch.charValue () - '0';
if (neg)
number = -number;
return new Integer (number);
}
private NFA parseString ()
{
NFA head = null;
Character ch;
while ((ch = parseChar (m_singletonCharSet)) != null)
{
++m_ruleLen;
NFA tail;
if (m_nocase)
{
char c = ch.charValue ();
boolean[] ccl = m_ccl.EMPTY.clone ();
ccl[c] = true;
if (c >= 'a' && c <= 'z')
ccl[c - 'a' + 'A'] = true;
else if (c >= 'A' && c <= 'Z')
ccl[c - 'A' + 'a'] = true;
tail = m_nfaFactory.createNFA (NFA.ISCCL, ccl);
}
else
tail = m_nfaFactory.createNFA (ch.charValue (), null);
if (head == null)
head = tail;
else
head = head.cat (tail);
}
return head;
}
private boolean[] parseFullCCL ()
{
if (!m_lex.ifMatch ('['))
return null;
boolean neg = false;
if (m_lex.ifMatch ('^'))
neg = true;
boolean[] ccl = m_ccl.EMPTY.clone ();
ccl = parseCCL (ccl);
if (m_nocase)
{
for (int i = 'a'; i <= 'z'; ++i)
{
if (ccl[i])
ccl[i - 'a' + 'A'] = true;
if (ccl[i - 'a' + 'A'])
ccl[i] = true;
}
}
if (neg)
CCL.negate (ccl);
m_lex.match (']');
return ccl;
}
private boolean[] parseCCL (boolean[] ccl)
{
while (parseCCE (ccl) != null ||
parseCCLChar (ccl) != null)
;
return ccl;
}
private boolean[] parseCCLChar (boolean[] ccl)
{
Character start = parseChar (m_cclCharSet);
if (start == null)
return null;
if (!m_lex.ifMatch ('-'))
{
ccl[start.charValue ()] = true;
return ccl;
}
Character end = parseChar (m_cclCharSet);
if (end == null)
throw new LookaheadException (m_lineNumber, m_ccl, m_cclCharSet, m_lex.getInput (), m_lex.getPos ());
for (int i = start.charValue (); i <= end.charValue (); ++i)
ccl[i] = true;
return ccl;
}
private boolean[] parseCCE (boolean[] ccl)
{
if (m_lex.ifMatch ("[:lower:]"))
return CCL.merge (ccl, m_ccl.LOWER);
if (m_lex.ifMatch ("[:upper:]"))
return CCL.merge (ccl, m_ccl.UPPER);
if (m_lex.ifMatch ("[:ascii:]"))
return CCL.merge (ccl, m_ccl.ASCII);
if (m_lex.ifMatch ("[:alpha:]"))
return CCL.merge (ccl, m_ccl.ALPHA);
if (m_lex.ifMatch ("[:digit:]"))
return CCL.merge (ccl, m_ccl.DIGIT);
if (m_lex.ifMatch ("[:alnum:]"))
return CCL.merge (ccl, m_ccl.ALNUM);
if (m_lex.ifMatch ("[:punct:]"))
return CCL.merge (ccl, m_ccl.PUNCT);
if (m_lex.ifMatch ("[:graph:]"))
return CCL.merge (ccl, m_ccl.GRAPH);
if (m_lex.ifMatch ("[:print:]"))
return CCL.merge (ccl, m_ccl.PRINT);
if (m_lex.ifMatch ("[:blank:]"))
return CCL.merge (ccl, m_ccl.BLANK);
if (m_lex.ifMatch ("[:cntrl:]"))
return CCL.merge (ccl, m_ccl.CNTRL);
if (m_lex.ifMatch ("[:xdigit:]"))
return CCL.merge (ccl, m_ccl.XDIGIT);
if (m_lex.ifMatch ("[:space:]"))
return CCL.merge (ccl, m_ccl.SPACE);
return null;
}
}
|
package org.zoodb.index.critbit;
/**
* This version of CritBit uses Copy-On-Write to create new versions of the tree
* following each write operation.
*
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A concurrency enabled version of the CritBit64 tree.
* The implementation uses copy-on-write concurrency, therefore locking occurs only during updates,
* read-access is never locked.
*
* Currently write/update access is limited to one thread at a time.
* Read access guarantees full snapshot consistency for all read access including iterators.
*
* Version 1.3.3
* - Fixed 64COW iterators returning empty Entry for queries that shouldn't return anything.
*
* Version 1.3.2
* - Improved mask checking in QueryWithMask
*
* Version 1.3.1
* - Fixed issue #3 where iterators won't work with 'null' as values.
*
* Version 1.0: initial implementation
*
* @author bvancea
*
* @param <V>
*/
public class CritBit64COW<V> implements Iterable<V> {
private final int DEPTH = 64;
private final Lock writeLock = new ReentrantLock();
private AtomicInfo<V> info = new AtomicInfo<>();
private static class Node<V> {
//TODO replace posDiff with posMask
// --> Possibly easier to calculate (non-log?)
// --> Similarly powerful....
//TODO merge loPost & loVal!
V loVal;
V hiVal;
Node<V> lo;
Node<V> hi;
//the following contain either the actual key or the prefix for sub-nodes
long loPost;
long hiPost;
byte posDiff;
Node(long loPost, V loVal, long hiPost, V hiVal, int posDiff) {
this.loPost = loPost;
this.loVal = loVal;
this.hiPost = hiPost;
this.hiVal = hiVal;
this.posDiff = (byte) posDiff;
}
Node(Node<V> original) {
this.loVal = original.loVal;
this.hiVal = original.hiVal;
this.lo = original.lo;
this.hi = original.hi;
this.loPost = original.loPost;
this.hiPost = original.hiPost;
this.posDiff = original.posDiff;
}
}
private static class AtomicInfo<V> {
private Node<V> root;
//the following contains either the actual key or the prefix for the sub-node
private long rootKey;
private V rootVal;
private int size;
public AtomicInfo<V> copy() {
AtomicInfo<V> c = new AtomicInfo<>();
c.root = this.root;
c.rootKey = this.rootKey;
c.rootVal = this.rootVal;
c.size = this.size;
return c;
}
}
private CritBit64COW() {
//private
}
/**
* Create a 1D crit-bit tree with 64 bit key length.
* @return a 1D crit-bit tree
*/
public static <V> CritBit64COW<V> create() {
return new CritBit64COW<V>();
}
public CritBit64COW<V> copy() {
CritBit64COW<V> critBitCopy = create();
critBitCopy.info = this.info.copy();
return critBitCopy;
}
/**
* Add a key value pair to the tree or replace the value if the key already exists.
* @param key
* @param val
* @return The previous value or {@code null} if there was no previous value
*/
public V put(long key, V val) {
try {
writeLock.lock();
AtomicInfo<V> newInfo = this.info.copy();
V ret = doPut(key, val, newInfo);
this.info = newInfo;
return ret;
} finally {
writeLock.unlock();;
}
}
private V doPut(long key, V val, AtomicInfo<V> newInfo) {
AtomicInfo<V> currentInfo = this.info;
int size = currentInfo.size;
if (size == 0) {
newInfo.rootKey = key;
newInfo.rootVal = val;
newInfo.size++;
return null;
}
if (size == 1) {
Node<V> n2 = createNode(key, val, info.rootKey, info.rootVal);
if (n2 == null) {
V prev = currentInfo.rootVal;
newInfo.rootVal = val;
return prev;
}
newInfo.root = n2;
newInfo.rootKey = extractPrefix(key, n2.posDiff - 1);
newInfo.rootVal = null;
newInfo.size++;
return null;
}
Node<V> n = newInfo.root;
int parentPosDiff = -1;
long prefix = newInfo.rootKey;
Node<V> parent = null;
boolean isCurrentChildLo = false;
while (true) {
//perform copy on write
n = new Node<V>(n);
if (parent != null) {
if (isCurrentChildLo) {
parent.lo = n;
} else {
parent.hi = n;
}
} else {
newInfo.root = n;
}
//insertion
if (parentPosDiff + 1 != n.posDiff) {
//split in prefix?
int posDiff = compare(key, prefix);
if (posDiff < n.posDiff && posDiff != -1) {
Node<V> newSub;
long subPrefix = extractPrefix(prefix, posDiff - 1);
if (BitTools.getBit(key, posDiff)) {
newSub = new Node<V>(prefix, null, key, val, posDiff);
newSub.lo = n;
} else {
newSub = new Node<V>(key, val, prefix, null, posDiff);
newSub.hi = n;
}
if (parent == null) {
newInfo.rootKey = subPrefix;
newInfo.root = newSub;
} else if (isCurrentChildLo) {
parent.loPost = subPrefix;
parent.lo = newSub;
} else {
parent.hiPost = subPrefix;
parent.hi = newSub;
}
newInfo.size++;
return null;
}
}
//prefix matches, so now we check sub-nodes and postfixes
if (BitTools.getBit(key, n.posDiff)) {
if (n.hi != null) {
prefix = n.hiPost;
parent = n;
n = n.hi;
isCurrentChildLo = false;
} else {
Node<V> n2 = createNode(key, val, n.hiPost, n.hiVal);
if (n2 == null) {
V prev = n.hiVal;
n.hiVal = val;
return prev;
}
n.hi = n2;
n.hiPost = extractPrefix(key, n2.posDiff - 1);
n.hiVal = null;
newInfo.size++;
return null;
}
} else {
if (n.lo != null) {
prefix = n.loPost;
parent = n;
n = n.lo;
isCurrentChildLo = true;
} else {
Node<V> n2 = createNode(key, val, n.loPost, n.loVal);
if (n2 == null) {
V prev = n.loVal;
n.loVal = val;
return prev;
}
n.lo = n2;
n.loPost = extractPrefix(key, n2.posDiff - 1);
n.loVal = null;
newInfo.size++;
return null;
}
}
parentPosDiff = n.posDiff;
}
}
public void printTree() {
System.out.println("Tree: \n" + toString());
}
@Override
public String toString() {
AtomicInfo<V> info = this.info;
if (info.size == 0) {
return "- -";
}
if (info.root == null) {
return "-" + BitTools.toBinary(info.rootKey, 64) + " v=" + info.rootVal;
}
Node<V> n = info.root;
StringBuilder s = new StringBuilder();
printNode(n, s, "", 0, info.rootKey);
return s.toString();
}
private void printNode(Node<V> n, StringBuilder s, String level, int currentDepth, long infix) {
char NL = '\n';
if (currentDepth != n.posDiff) {
s.append(level + "n: " + currentDepth + "/" + n.posDiff + " " +
BitTools.toBinary(infix, 64) + NL);
} else {
s.append(level + "n: " + currentDepth + "/" + n.posDiff + " i=0" + NL);
}
if (n.lo != null) {
printNode(n.lo, s, level + "-", n.posDiff+1, n.loPost);
} else {
s.append(level + " " + BitTools.toBinary(n.loPost, 64) + " v=" + n.loVal + NL);
}
if (n.hi != null) {
printNode(n.hi, s, level + "-", n.posDiff+1, n.hiPost);
} else {
s.append(level + " " + BitTools.toBinary(n.hiPost,64) + " v=" + n.hiVal + NL);
}
}
public boolean checkTree() {
AtomicInfo<V> info = this.info;
if (info.root == null) {
if (info.size > 1) {
System.err.println("root node = null AND size = " + info.size);
return false;
}
return true;
}
return checkNode(info.root, 0, info.rootKey);
}
private boolean checkNode(Node<V> n, int firstBitOfNode, long prefix) {
//check prefix
if (n.posDiff < firstBitOfNode) {
System.err.println("prefix with len=0 detected!");
return false;
}
if (n.lo != null) {
if (!doesPrefixMatch(n.posDiff-1, n.loPost, prefix)) {
System.err.println("lo: prefix mismatch");
return false;
}
checkNode(n.lo, n.posDiff+1, n.loPost);
}
if (n.hi != null) {
if (!doesPrefixMatch(n.posDiff-1, n.hiPost, prefix)) {
System.err.println("hi: prefix mismatch");
return false;
}
checkNode(n.hi, n.posDiff+1, n.hiPost);
}
return true;
}
private Node<V> createNode(long k1, V val1, long k2, V val2) {
int posDiff = compare(k1, k2);
if (posDiff == -1) {
return null;
}
if (BitTools.getBit(k2, posDiff)) {
return new Node<V>(k1, val1, k2, val2, posDiff);
} else {
return new Node<V>(k2, val2, k1, val1, posDiff);
}
}
/**
*
* @param v
* @param endPos last bit of prefix, counting starts with 0 for 1st bit
* @return The prefix.
*/
private static long extractPrefix(long v, int endPos) {
long inf = v;
//avoid shifting by 64 bit which means 0 shifting in Java!
if (endPos < 63) {
inf &= ~((-1L) >>> (1+endPos)); // & 0x3f == %64
}
return inf;
}
/**
*
* @param v
* @return True if the prefix matches the value or if no prefix is defined
*/
private boolean doesPrefixMatch(int posDiff, long v, long prefix) {
if (posDiff > 0) {
return (v ^ prefix) >>> (64-posDiff) == 0;
}
return true;
}
/**
* Compares two values.
* @param v1
* @param v2
* @return Position of the differing bit, or -1 if both values are equal
*/
private static int compare(long v1, long v2) {
return (v1 == v2) ? -1 : Long.numberOfLeadingZeros(v1 ^ v2);
}
/**
* Get the size of the tree.
* @return the number of keys in the tree
*/
public int size() {
return info.size;
}
/**
* Check whether a given key exists in the tree.
* @param key
* @return {@code true} if the key exists otherwise {@code false}
*/
public boolean contains(long key) {
AtomicInfo<V> info = this.info;
int size = info.size;
if (size == 0) {
return false;
}
if (size == 1) {
return key == info.rootKey;
}
Node<V> n = info.root;
long prefix = info.rootKey;
while (doesPrefixMatch(n.posDiff, key, prefix)) {
//prefix matches, so now we check sub-nodes and postfixes
if (BitTools.getBit(key, n.posDiff)) {
if (n.hi != null) {
prefix = n.hiPost;
n = n.hi;
continue;
}
return key == n.hiPost;
} else {
if (n.lo != null) {
prefix = n.loPost;
n = n.lo;
continue;
}
return key == n.loPost;
}
}
return false;
}
/**
* Get the value for a given key.
* @param key
* @return the values associated with {@code key} or {@code null} if the key does not exist.
*/
public V get(long key) {
AtomicInfo<V> info = this.info;
if (info.size == 0) {
return null;
}
if (info.size == 1) {
return (key == info.rootKey) ? info.rootVal : null;
}
Node<V> n = info.root;
long prefix = info.rootKey;
while (doesPrefixMatch(n.posDiff, key, prefix)) {
//prefix matches, so now we check sub-nodes and postfixes
if (BitTools.getBit(key, n.posDiff)) {
if (n.hi != null) {
prefix = n.hiPost;
n = n.hi;
continue;
}
return (key == n.hiPost) ? n.hiVal : null;
} else {
if (n.lo != null) {
prefix = n.loPost;
n = n.lo;
continue;
}
return (key == n.loPost) ? n.loVal : null;
}
}
return null;
}
/**
* Remove a key and its value
* @param key
* @return The value of the key of {@code null} if the value was not found.
*/
public V remove(long key) {
try {
writeLock.lock();
if (contains(key)) {
AtomicInfo<V> newInfo = info.copy();
V ret = doRemove(key, newInfo);
this.info = newInfo;
return ret;
} else {
return null;
}
} finally {
writeLock.unlock();
}
}
private V doRemove(long key, AtomicInfo<V> newInfo) {
AtomicInfo<V> info = this.info;
if (info.size == 0) {
return null;
}
if (info.size == 1) {
if (key == info.rootKey) {
newInfo.size
newInfo.rootKey = 0;
V prev = info.rootVal;
info.rootVal = null;
return prev;
}
return null;
}
Node<V> n = info.root;
Node<V> parent = null;
boolean isParentHigh = false;
long prefix = info.rootKey;
while (doesPrefixMatch(n.posDiff, key, prefix)) {
//perform copy on write
n = new Node<V>(n);
if (parent != null) {
if (!isParentHigh) {
parent.lo = n;
} else {
parent.hi = n;
}
} else {
newInfo.root = n;
}
//prefix matches, so now we check sub-nodes and postfixes
if (BitTools.getBit(key, n.posDiff)) {
if (n.hi != null) {
isParentHigh = true;
prefix = n.hiPost;
parent = n;
n = n.hi;
continue;
} else {
if (key != n.hiPost) {
return null;
}
//match! --> delete node
//replace data in parent node
updateParentAfterRemove(newInfo, parent, n.loPost, n.loVal, n.lo, isParentHigh);
return n.hiVal;
}
} else {
if (n.lo != null) {
isParentHigh = false;
prefix = n.loPost;
parent = n;
n = n.lo;
continue;
} else {
if (key != n.loPost) {
return null;
}
//match! --> delete node
//replace data in parent node
//for new prefixes...
updateParentAfterRemove(newInfo, parent, n.hiPost, n.hiVal, n.hi, isParentHigh);
return n.loVal;
}
}
}
return null;
}
private void updateParentAfterRemove(AtomicInfo<V> newInfo, Node<V> parent, long newPost, V newVal,
Node<V> newSub, boolean isParentHigh) {
newPost = (newSub == null) ? newPost : extractPrefix(newPost, newSub.posDiff-1);
if (parent == null) {
newInfo.rootKey = newPost;
newInfo.rootVal = newVal;
newInfo.root = newSub;
} else if (isParentHigh) {
parent.hiPost = newPost;
parent.hiVal = newVal;
parent.hi = newSub;
} else {
parent.loPost = newPost;
parent.loVal = newVal;
parent.lo = newSub;
}
newInfo.size
}
@Override
public CBIterator<V> iterator() {
return new CBIterator<V>(this, DEPTH);
}
public static class CBIterator<V> implements Iterator<V> {
private long nextKey = 0;
private V nextValue = null;
private boolean hasNext = true;
private final Node<V>[] stack;
//0==read_lower; 1==read_upper; 2==go_to_parent
private static final byte READ_LOWER = 0;
private static final byte READ_UPPER = 1;
private static final byte RETURN_TO_PARENT = 2;
private final byte[] readHigherNext;
private int stackTop = -1;
@SuppressWarnings("unchecked")
public CBIterator(CritBit64COW<V> cb, int DEPTH) {
this.stack = new Node[DEPTH];
this.readHigherNext = new byte[DEPTH]; // default = false
AtomicInfo<V> info = cb.info;
if (info.size == 0) {
//Tree is empty
hasNext = false;
return;
}
if (info.size == 1) {
nextValue = info.rootVal;
nextKey = info.rootKey;
return;
}
stack[++stackTop] = info.root;
findNext();
}
private void findNext() {
while (stackTop >= 0) {
Node<V> n = stack[stackTop];
//check lower
if (readHigherNext[stackTop] == READ_LOWER) {
readHigherNext[stackTop] = READ_UPPER;
if (n.lo == null) {
nextValue = n.loVal;
nextKey = n.loPost;
return;
} else {
stack[++stackTop] = n.lo;
readHigherNext[stackTop] = READ_LOWER;
continue;
}
}
//check upper
if (readHigherNext[stackTop] == READ_UPPER) {
readHigherNext[stackTop] = RETURN_TO_PARENT;
if (n.hi == null) {
nextValue = n.hiVal;
nextKey = n.hiPost;
--stackTop;
return;
//proceed to move up a level
} else {
stack[++stackTop] = n.hi;
readHigherNext[stackTop] = READ_LOWER;
continue;
}
}
//proceed to move up a level
--stackTop;
}
//Finished
nextValue = null;
nextKey = 0;
hasNext = false;
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
V ret = nextValue;
findNext();
return ret;
}
public long nextKey() {
if (!hasNext()) {
throw new NoSuchElementException();
}
long ret = nextKey;
findNext();
return ret;
}
public Entry<V> nextEntry() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<V> ret = new Entry<V>(nextKey, nextValue);
findNext();
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Queries the tree for entries with min<=key<=max.
* @param min
* @param max
* @return An iterator over the matching entries.
*/
public QueryIterator<V> query(long min, long max) {
return new QueryIterator<V>(this, min, max, DEPTH);
}
public static class QueryIterator<V> implements Iterator<V> {
private final long minOrig;
private final long maxOrig;
private long nextKey = 0;
private V nextValue = null;
private boolean hasNext = true;
private final Node<V>[] stack;
//0==read_lower; 1==read_upper; 2==go_to_parent
private static final byte READ_LOWER = 0;
private static final byte READ_UPPER = 1;
private static final byte RETURN_TO_PARENT = 2;
private final byte[] readHigherNext;
private final long[] prefixes;
private int stackTop = -1;
@SuppressWarnings("unchecked")
public QueryIterator(CritBit64COW<V> cb, long minOrig, long maxOrig, int DEPTH) {
this.stack = new Node[DEPTH];
this.readHigherNext = new byte[DEPTH]; // default = false
this.prefixes = new long[DEPTH];
this.minOrig = minOrig;
this.maxOrig = maxOrig;
AtomicInfo<V> info = cb.info;
if (info.size == 0) {
//Tree is empty
hasNext = false;
return;
}
if (info.size == 1) {
hasNext = checkMatchFullIntoNextVal(info.rootKey, info.rootVal);
return;
}
Node<V> n = info.root;
if (!checkMatch(info.rootKey, n.posDiff-1)) {
hasNext = false;
return;
}
stack[++stackTop] = info.root;
prefixes[stackTop] = info.rootKey;
findNext();
}
private void findNext() {
while (stackTop >= 0) {
Node<V> n = stack[stackTop];
//check lower
if (readHigherNext[stackTop] == READ_LOWER) {
readHigherNext[stackTop] = READ_UPPER;
long valTemp = BitTools.set0(prefixes[stackTop], n.posDiff);
if (checkMatch(valTemp, n.posDiff)) {
if (n.lo == null) {
if (checkMatchFullIntoNextVal(n.loPost, n.loVal)) {
return;
}
//proceed to check upper
} else {
stack[++stackTop] = n.lo;
prefixes[stackTop] = n.loPost;
readHigherNext[stackTop] = READ_LOWER;
continue;
}
}
}
//check upper
if (readHigherNext[stackTop] == READ_UPPER) {
readHigherNext[stackTop] = RETURN_TO_PARENT;
long valTemp = BitTools.set1(prefixes[stackTop], n.posDiff);
if (checkMatch(valTemp, n.posDiff)) {
if (n.hi == null) {
if (checkMatchFullIntoNextVal(n.hiPost, n.hiVal)) {
--stackTop;
return;
}
//proceed to move up a level
} else {
stack[++stackTop] = n.hi;
prefixes[stackTop] = n.hiPost;
readHigherNext[stackTop] = READ_LOWER;
continue;
}
}
}
//proceed to move up a level
--stackTop;
}
//Finished
nextValue = null;
nextKey = 0;
hasNext = false;
}
/**
* Full comparison on the parameter. Assigns the parameter to 'nextVal' if comparison
* fits.
* @param keyTemplate
* @return Whether we have a match or not
*/
private boolean checkMatchFullIntoNextVal(long keyTemplate, V value) {
if ((minOrig > keyTemplate) || (keyTemplate > maxOrig)) {
return false;
}
nextValue = value;
nextKey = keyTemplate;
return true;
}
private boolean checkMatch(long keyTemplate, int currentDepth) {
int toIgnore = 63 - currentDepth;
long mask = (-1L) << toIgnore;
if ((minOrig & mask) > (keyTemplate & mask)) {
return false;
}
if ((keyTemplate & mask) > (maxOrig & mask)) {
return false;
}
return true;
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
V ret = nextValue;
findNext();
return ret;
}
public long nextKey() {
if (!hasNext()) {
throw new NoSuchElementException();
}
long ret = nextKey;
findNext();
return ret;
}
public Entry<V> nextEntry() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<V> ret = new Entry<V>(nextKey, nextValue);
findNext();
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Queries the tree for entries with min<=key<=max. Unlike the normal query, this
* query also excludes all elements with (key|min)!=key and (key&max!=max).
* See PH-Tree for a discussion.
* @param min
* @param max
* @return An iterator over the matching entries.
*/
public QueryIteratorMask<V> queryWithMask(long min, long max) {
return new QueryIteratorMask<V>(this, min, max, DEPTH);
}
public static class QueryIteratorMask<V> implements Iterator<V> {
private final long minOrig;
private final long maxOrig;
private long nextKey = 0;
private V nextValue = null;
private boolean hasNext = true;
private final Node<V>[] stack;
//0==read_lower; 1==read_upper; 2==go_to_parent
private static final byte READ_LOWER = 0;
private static final byte READ_UPPER = 1;
private static final byte RETURN_TO_PARENT = 2;
private final byte[] readHigherNext;
private final long[] prefixes;
private int stackTop = -1;
@SuppressWarnings("unchecked")
public QueryIteratorMask(CritBit64COW<V> cb, long minOrig, long maxOrig, int DEPTH) {
this.stack = new Node[DEPTH];
this.readHigherNext = new byte[DEPTH]; // default = false
this.prefixes = new long[DEPTH];
this.minOrig = minOrig;
this.maxOrig = maxOrig;
AtomicInfo<V> info = cb.info;
if (info.size == 0) {
//Tree is empty
hasNext = false;
return;
}
if (info.size == 1) {
hasNext = checkMatchFullIntoNextVal(info.rootKey, info.rootVal);
return;
}
Node<V> n = info.root;
if (!checkMatch(info.rootKey, n.posDiff-1)) {
hasNext = false;
return;
}
stack[++stackTop] = info.root;
prefixes[stackTop] = info.rootKey;
findNext();
}
private void findNext() {
while (stackTop >= 0) {
Node<V> n = stack[stackTop];
//check lower
if (readHigherNext[stackTop] == READ_LOWER) {
readHigherNext[stackTop] = READ_UPPER;
long valTemp = BitTools.set0(prefixes[stackTop], n.posDiff);
if (checkMatch(valTemp, n.posDiff)) {
if (n.lo == null) {
if (checkMatchFullIntoNextVal(n.loPost, n.loVal)) {
return;
}
//proceed to check upper
} else {
stack[++stackTop] = n.lo;
prefixes[stackTop] = n.loPost;
readHigherNext[stackTop] = READ_LOWER;
continue;
}
}
}
//check upper
if (readHigherNext[stackTop] == READ_UPPER) {
readHigherNext[stackTop] = RETURN_TO_PARENT;
long valTemp = BitTools.set1(prefixes[stackTop], n.posDiff);
if (checkMatch(valTemp, n.posDiff)) {
if (n.hi == null) {
if (checkMatchFullIntoNextVal(n.hiPost, n.hiVal)) {
--stackTop;
return;
}
//proceed to move up a level
} else {
stack[++stackTop] = n.hi;
prefixes[stackTop] = n.hiPost;
readHigherNext[stackTop] = READ_LOWER;
continue;
}
}
}
//proceed to move up a level
--stackTop;
}
//Finished
nextValue = null;
nextKey = 0;
hasNext = false;
}
/**
* Full comparison on the parameter. Assigns the parameter to 'nextVal' if comparison
* fits.
* @param keyTemplate
* @return Whether we have a match or not
*/
private boolean checkMatchFullIntoNextVal(long keyTemplate, V value) {
if (((keyTemplate | minOrig) & maxOrig) != keyTemplate) {
return false;
}
nextValue = value;
nextKey = keyTemplate;
return true;
}
private boolean checkMatch(long keyTemplate, int currentDepth) {
int toIgnore = 63 - currentDepth;
return (((keyTemplate | minOrig) & maxOrig) ^ keyTemplate) >>> toIgnore == 0;
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
V ret = nextValue;
findNext();
return ret;
}
public long nextKey() {
if (!hasNext()) {
throw new NoSuchElementException();
}
long ret = nextKey;
findNext();
return ret;
}
public Entry<V> nextEntry() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<V> ret = new Entry<V>(nextKey, nextValue);
findNext();
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public static class Entry<V> {
private final long key;
private final V value;
Entry(long key, V value) {
this.key = key;
this.value = value;
}
public long key() {
return key;
}
public V value() {
return value;
}
}
}
|
package com.xqbase.java;/* ListSorts.java */
import com.xqbase.java.list.LinkedQueue;
import com.xqbase.java.list.QueueEmptyException;
import java.util.Random;
public class ListSorts {
private final static int SORTSIZE = 10;
/**
* makeQueueOfQueues() makes a queue of queues, each containing one item
* of q. Upon completion of this method, q is empty.
*
* @param q is a LinkedQueue of objects.
* @return a LinkedQueue containing LinkedQueue objects, each of which
* contains one object from q.
*/
public static LinkedQueue makeQueueOfQueues(LinkedQueue q) {
LinkedQueue queue = new LinkedQueue();
try {
while (!q.isEmpty()) {
LinkedQueue newQueue = new LinkedQueue();
newQueue.enqueue(q.dequeue());
queue.enqueue(newQueue);
}
} catch (QueueEmptyException e) {
System.out.println("Empty queue exception");
}
return queue;
}
/**
* mergeSortedQueues() merges two sorted queues into a third. On completion
* of this method, q1 and q2 are empty, and their items have been merged
* into the returned queue.
*
* @param q1 is LinkedQueue of Comparable objects, sorted from smallest
* to largest.
* @param q2 is LinkedQueue of Comparable objects, sorted from smallest
* to largest.
* @return a LinkedQueue containing all the Comparable objects from q1
* and q2 (and nothing else), sorted from smallest to largest.
*/
public static LinkedQueue mergeSortedQueues(LinkedQueue q1, LinkedQueue q2) {
if (q1 == null || q1.isEmpty())
return q2;
if (q2 == null || q2.isEmpty())
return q1;
try {
LinkedQueue q3 = new LinkedQueue();
if (((Comparable) q2.front()).compareTo(q1.nth(q1.size())) > 0) {
q3.append(q1);
q3.append(q2);
return q3;
}
if (((Comparable) q1.front()).compareTo(q2.nth(q2.size())) > 0) {
q3.append(q2);
q3.append(q1);
return q3;
}
while (!q1.isEmpty() && !q2.isEmpty()) {
Object o1 = q1.front();
Object o2 = q2.front();
int c = ((Comparable) o1).compareTo(o2);
if (c < 0) {
q3.enqueue(q1.dequeue());
} else if (c > 0) {
q3.enqueue(q2.dequeue());
} else {
q3.enqueue(q1.dequeue());
q3.enqueue(q2.dequeue());
}
}
while (!q1.isEmpty()) {
q3.enqueue(q1.dequeue());
}
while (!q2.isEmpty()) {
q3.enqueue(q2.dequeue());
}
return q3;
} catch (QueueEmptyException e) {
System.out.println("Queue is empty");
return null;
}
}
/**
* partition() partitions qIn using the pivot item. On completion of
* this method, qIn is empty, and its items have been moved to qSmall,
* qEquals, and qLarge, according to their relationship to the pivot.
*
* @param qIn is a LinkedQueue of Comparable objects.
* @param pivot is a Comparable item used for partitioning.
* @param qSmall is a LinkedQueue, in which all items less than pivot
* will be enqueued.
* @param qEquals is a LinkedQueue, in which all items equal to the pivot
* will be enqueued.
* @param qLarge is a LinkedQueue, in which all items greater than pivot
* will be enqueued.
*/
public static void partition(LinkedQueue qIn, Comparable pivot,
LinkedQueue qSmall, LinkedQueue qEquals,
LinkedQueue qLarge) {
try {
while (!qIn.isEmpty()) {
Object o = qIn.dequeue();
if (pivot.compareTo(o) > 0) {
qSmall.enqueue(o);
} else if (pivot.compareTo(o) == 0) {
qEquals.enqueue(o);
} else {
qLarge.enqueue(o);
}
}
} catch (QueueEmptyException e) {
System.out.println("Queue empty exception");
}
}
/**
* mergeSort() sorts q from smallest to largest using mergesort.
*
* @param q is a LinkedQueue of Comparable objects.
*/
public static void mergeSort(LinkedQueue q) {
LinkedQueue queueOfQueues = makeQueueOfQueues(q);
try {
while (queueOfQueues.size() != 1) {
LinkedQueue q1 = (LinkedQueue) queueOfQueues.dequeue();
LinkedQueue q2 = (LinkedQueue) queueOfQueues.dequeue();
queueOfQueues.enqueue(mergeSortedQueues(q1, q2));
}
q.enqueue(queueOfQueues.front());
} catch (QueueEmptyException e) {
System.out.println("Queue is empty");
}
}
/**
* quickSort() sorts q from smallest to largest using quicksort.
*
* @param q is a LinkedQueue of Comparable objects.
*/
public static void quickSort(LinkedQueue q) {
if (q == null || q.isEmpty())
return;
Random random = new Random();
Object pivot = q.nth(random.nextInt(q.size()) + 1);
LinkedQueue smallerQueue = new LinkedQueue();
LinkedQueue equalQueue = new LinkedQueue();
LinkedQueue largeQueue = new LinkedQueue();
partition(q, (Comparable) pivot, smallerQueue, equalQueue, largeQueue);
quickSort(smallerQueue);
quickSort(largeQueue);
q.append(smallerQueue);
q.append(equalQueue);
q.append(largeQueue);
}
/**
* makeRandom() builds a LinkedQueue of the indicated size containing
* Integer items. The items are randomly chosen between 0 and size - 1.
*
* @param size is the size of the resulting LinkedQueue.
*/
public static LinkedQueue makeRandom(int size) {
LinkedQueue q = new LinkedQueue();
for (int i = 0; i < size; i++) {
q.enqueue(new Integer((int) (size * Math.random())));
}
return q;
}
/**
* main() performs some tests on mergesort and quicksort. Feel free to add
* more tests of your own to make sure your algorithms works on boundary
* cases. Your test code will not be graded.
*/
public static void main(String[] args) {
/**
* Test mergeSort&quickSort
*/
LinkedQueue q = makeRandom(SORTSIZE);
System.out.println(q.toString());
mergeSort(q);
System.out.println(q.toString());
q = makeRandom(SORTSIZE);
System.out.println(q.toString());
quickSort(q);
System.out.println(q.toString());
q = makeRandom(1);
System.out.println(q.toString());
mergeSort(q);
System.out.println(q.toString());
q = makeRandom(1);
System.out.println(q.toString());
quickSort(q);
System.out.println(q.toString());
q = makeRandom(0);
System.out.println(q.toString());
mergeSort(q);
System.out.println(q.toString());
q = makeRandom(0);
System.out.println(q.toString());
quickSort(q);
System.out.println(q.toString());
/**
* Performance testing.
*/
Timer stopWatch = new Timer();
q = makeRandom(SORTSIZE);
stopWatch.start();
mergeSort(q);
stopWatch.stop();
System.out.println("Mergesort time, " + SORTSIZE + " Integers: " +
stopWatch.elapsed() + " msec.");
stopWatch.reset();
q = makeRandom(SORTSIZE);
stopWatch.start();
quickSort(q);
stopWatch.stop();
System.out.println("Quicksort time, " + SORTSIZE + " Integers: " +
stopWatch.elapsed() + " msec.");
/**
* The quickSort&mergeSort we implement are both stable. Since
* there is no equal items position change.
*/
}
}
|
package imj3.draft.segmentation2;
import static imj3.draft.segmentation2.DataSourceArrayProperty.CLASS;
import static imj3.draft.segmentation2.DataSourceArrayProperty.INPUT;
import imj3.core.Channels;
import imj3.draft.machinelearning.Classification;
import imj3.draft.machinelearning.Classifier;
import imj3.draft.machinelearning.ClassifierClass;
import imj3.draft.machinelearning.DataSource;
import imj3.draft.machinelearning.KMeansClustering;
import imj3.draft.machinelearning.Measure;
import imj3.draft.machinelearning.NearestNeighborClassifier;
import imj3.draft.machinelearning.StreamingClustering;
import imj3.draft.machinelearning.NearestNeighborClassifier.Prototype;
import imj3.draft.segmentation2.Analyze.LinearTransform.Transformed;
import imj3.tools.AwtImage2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import net.sourceforge.aprog.swing.SwingTools;
import net.sourceforge.aprog.tools.CommandLineArgumentsParser;
import net.sourceforge.aprog.tools.IllegalInstantiationException;
import net.sourceforge.aprog.tools.Tools;
/**
* @author codistmonk (creation 2015-02-06)
*/
public final class Analyze {
private Analyze() {
throw new IllegalInstantiationException();
}
/**
* @param commandLineArguments
* <br>Unused
*/
public static final void main(final String[] commandLineArguments) {
final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments);
final File file = new File(arguments.get("file", ""));
final BufferedImage image = AwtImage2D.awtRead(file.getPath());
SwingTools.show(image, file.getName(), false);
if (false) {
final BufferedImageMeanSource mean = new BufferedImageMeanSource(image, 2, 1, 2);
SwingTools.show(awtImage(mean, INPUT), "Mean", false);
SwingTools.show(awtImage(new BufferedImageMaxSource(image, 2, 1, 2), INPUT), "Max", false);
SwingTools.show(awtImage(new ClassifiedImageDataSource<>(mean, new StreamingClustering(Measure.Predefined.L1_ES, 8).cluster(mean)), CLASS), "Indirect (streaming)", false);
SwingTools.show(awtImage(new ClassifiedImageDataSource<>(mean, new KMeansClustering(Measure.Predefined.L1_ES, 8, 6).cluster(mean)), CLASS), "Indirect (k-means)", false);
}
if (true) {
final BufferedImageRawSource source = new BufferedImageRawSource(image, 4);
final DataSource<Prototype> trainingSet = source;
final NearestNeighborClassifier quantizer = new StreamingClustering(Measure.Predefined.L1_ES, 8).cluster(trainingSet);
final ClassifiedImageDataSource<Prototype, Prototype> quantized = new ClassifiedImageDataSource<>(source, quantizer);
final LinearTransform rgbRenderer = new LinearTransform(Measure.Predefined.L1_ES, newRGBRenderingMatrix(source.getPatchPixelCount()));
final ClassifiedImageDataSource<Prototype, Transformed> rendered = new ClassifiedImageDataSource<>(quantized, rgbRenderer);
SwingTools.show(awtImage(rendered, CLASS), "Quantized (streaming) -> rendered", false);
}
}
public static final double[][] newRGBRenderingMatrix(final int inputPatchPixelCount) {
final double[][] result = new double[3][];
final int n = 3 * inputPatchPixelCount;
for (int i = 0; i < 3; ++i) {
final double[] row = new double[n];
for (int j = i; j < n; j += 3) {
row[j] = 1.0 / inputPatchPixelCount;
}
result[i] = row;
}
return result;
}
public static final BufferedImage awtImage(final ImageDataSource<?> source, final DataSourceArrayProperty property) {
return awtImage(source, property, null);
}
public static final BufferedImage awtImage(final ImageDataSource<?> source, final DataSourceArrayProperty property, final BufferedImage result) {
final int dimension = property.getDimension(source);
if (dimension != 1 && dimension != 3) {
throw new IllegalArgumentException();
}
final int width = source.sizeX();
final int height = source.sizeY();
final BufferedImage actualResult = result != null ? result : new BufferedImage(
width, height, BufferedImage.TYPE_INT_ARGB);
int pixel = 0;
for (final Classification<?> c : source) {
final int x = pixel % width;
final int y = pixel / width;
final double[] input = property.getArray(c);
final int rgb = dimension == 1 ? gray(input) : argb(input);
actualResult.setRGB(x, y, rgb);
++pixel;
}
return actualResult;
}
public static final int argb(final double[] rgb) {
return Channels.Predefined.a8r8g8b8(0xFF, int8(rgb[0]), int8(rgb[1]), int8(rgb[2]));
}
public static final int gray(final double[] rgb) {
final int gray = int8(rgb[0]);
return Channels.Predefined.a8r8g8b8(0xFF, gray, gray, gray);
}
public static final int int8(final double value0255) {
return ((int) value0255) & 0xFF;
}
/**
* @author codistmonk (creation 2015-02-06)
*/
public static final class LinearTransform implements Classifier<LinearTransform.Transformed> {
private final double[][] matrix;
private final ClassifierClass.Measure<Transformed> transformedMeasure;
public LinearTransform(final Measure measure, double[][] matrix) {
this.matrix = matrix;
this.transformedMeasure = new ClassifierClass.Measure.Default<>(measure);
}
public final double[][] getMatrix() {
return this.matrix;
}
public final int getMatrixRowCount() {
return this.getMatrix().length;
}
public final int getMatrixColumnCount() {
return this.getMatrix()[0].length;
}
@Override
public final ClassifierClass.Measure<Transformed> getClassMeasure() {
return this.transformedMeasure;
}
@Override
public final Classification<Transformed> classify(final double... input) {
final int n = this.getMatrixRowCount();
final double[] datum = new double[n];
for (int i = 0; i < n; ++i) {
datum[i] = dot(this.getMatrix()[i], input);
}
return new Classification<>(input, new Transformed(datum), 0.0);
}
@Override
public final int getClassDimension(final int inputDimension) {
if (inputDimension == this.getMatrixColumnCount()) {
return this.getMatrixRowCount();
}
Tools.debugPrint(inputDimension, this.getMatrixRowCount(), this.getMatrixColumnCount());
throw new IllegalArgumentException();
}
private static final long serialVersionUID = -1314577713442253655L;
public static final double dot(final double[] v1, final double[] v2) {
final int n = v1.length;
double result = 0.0;
for (int i = 0; i < n; ++i) {
result += v1[i] * v2[i];
}
return result;
}
/**
* @author codistmonk (creation 2015-02-06)
*/
public static final class Transformed implements ClassifierClass {
private final double[] datum;
public Transformed(final double[] datum) {
this.datum = datum;
}
@Override
public final double[] toArray() {
return this.datum;
}
private static final long serialVersionUID = 5806137995866347277L;
}
}
}
|
package lv.ctco.cukesrest;
import com.google.inject.*;
import com.yammer.dropwizard.*;
import com.yammer.dropwizard.config.*;
import lv.ctco.cukesrest.gadgets.*;
import lv.ctco.cukesrest.healthcheck.*;
public class SampleApplication extends Service<SampleConfiguration> {
public static void main(String[] args) throws Exception {
new SampleApplication().run(args);
}
@Override
public void initialize(Bootstrap<SampleConfiguration> bootstrap) {
bootstrap.setName("cukes-rest-sample-app");
}
@Override
public void run(SampleConfiguration configuration, Environment environment) {
Injector injector = Guice.createInjector();
environment.addResource(injector.getInstance(GadgetResource.class));
environment.addResource(injector.getInstance(StaticTypesResource.class));
environment.addResource(injector.getInstance(CustomHeadersResource.class));
environment.addHealthCheck(injector.getInstance(SampleHealthCheck.class));
}
}
|
package io.oversky524.myhttp;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.LinkedHashMap;
import java.util.Map;
public class Connection {
private static final boolean DEBUG = true;
private Map<Request, Response> requests = new LinkedHashMap<>();
private Socket mSocket;
private long mIdleAt = Long.MAX_VALUE;
public long idleAt(){ return mIdleAt; }
public void setIdleAt(long idleAt){ mIdleAt = idleAt; }
Connection(String host, int port){
try {
mSocket = new Socket(host, port);
mSocket.setSoTimeout(5 * 1000);
if(DEBUG){
System.out.println(mSocket + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean shouldClose(long aliveDuration){
if(mIdleAt == Long.MAX_VALUE) return false;
if(mIdleAt + aliveDuration <= System.nanoTime() || readTest()) return true;
return false;
}
public Response put(Request request){
Response response = new Response();
requests.put(request, response);
mIdleAt = Long.MAX_VALUE;
return response;
}
public void release(Request request){
requests.remove(request);
if(requests.isEmpty()) mIdleAt = System.nanoTime();
}
public Socket getSocket(){ return mSocket; }
public boolean isIdle(){
boolean empty = requests.isEmpty();
/*if(empty){
mIdleAt =
}*/
return empty;
}
public void closeSafely(){
try {
if(mSocket != null) mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
if(DEBUG) System.out.println(mSocket + " is closed safely");
}
private boolean readTest(){
boolean result = false;
try {
int readTimeout = mSocket.getSoTimeout();
try {
mSocket.setSoTimeout(1);
if(mSocket.getInputStream().read() == -1) result = true;
} catch (IOException e) {
e.printStackTrace();
result = !(e instanceof SocketTimeoutException);
} finally {
mSocket.setSoTimeout(readTimeout);
}
} catch (SocketException e) {
e.printStackTrace();
}
return result;
}
}
|
package org.eclipse.paho.client.mqttv3.internal;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.logging.Logger;
import org.eclipse.paho.client.mqttv3.logging.LoggerFactory;
/**
* A network module for connecting over SSL.
*/
public class SSLNetworkModule extends TCPNetworkModule {
private String[] enabledCiphers;
private int handshakeTimeoutSecs;
final static String className = SSLNetworkModule.class.getName();
Logger log = LoggerFactory.getLogger(LoggerFactory.MQTT_CLIENT_MSG_CAT,className);
/**
* Constructs a new SSLNetworkModule using the specified host and
* port. The supplied SSLSocketFactory is used to supply the network
* socket.
*/
public SSLNetworkModule(SSLSocketFactory factory, String host, int port, String resourceContext) {
super(factory, host, port, resourceContext);
log.setResourceName(resourceContext);
}
/**
* Returns the enabled cipher suites.
*/
public String[] getEnabledCiphers() {
return enabledCiphers;
}
/**
* Sets the enabled cipher suites on the underlying network socket.
*/
public void setEnabledCiphers(String[] enabledCiphers) {
final String methodName = "setEnabledCiphers";
this.enabledCiphers = enabledCiphers;
if ((socket != null) && (enabledCiphers != null)) {
if (log.isLoggable(Logger.FINE)) {
String ciphers = "";
for (int i=0;i<enabledCiphers.length;i++) {
if (i>0) {
ciphers+=",";
}
ciphers+=enabledCiphers[i];
}
//@TRACE 260=setEnabledCiphers ciphers={0}
log.fine(className,methodName,"260",new Object[]{ciphers});
}
((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
}
}
public void setSSLhandshakeTimeout(int timeout) {
super.setConnectTimeout(timeout);
this.handshakeTimeoutSecs = timeout;
}
public void start() throws IOException, MqttException {
super.start();
setEnabledCiphers(enabledCiphers);
int soTimeout = socket.getSoTimeout();
if ( soTimeout == 0 ) {
// RTC 765: Set a timeout to avoid the SSL handshake being blocked indefinitely
socket.setSoTimeout(this.handshakeTimeoutSecs*1000);
}
((SSLSocket)socket).startHandshake();
// reset timeout to default value
socket.setSoTimeout(soTimeout);
}
}
|
package org.lamport.tla.toolbox.tool.tlc.ui.editor.page;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.IMessageManager;
import org.eclipse.ui.forms.SectionPart;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationConstants;
import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationDefaults;
import org.lamport.tla.toolbox.tool.tlc.model.Assignment;
import org.lamport.tla.toolbox.tool.tlc.model.Model;
import org.lamport.tla.toolbox.tool.tlc.model.TypedSet;
import org.lamport.tla.toolbox.tool.tlc.ui.TLCUIActivator;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.DataBindingManager;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.ModelEditor;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.results.ResultPage;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableConstantSectionPart;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableSectionPart;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableTableSectionPart;
import org.lamport.tla.toolbox.tool.tlc.ui.preference.ITLCPreferenceConstants;
import org.lamport.tla.toolbox.tool.tlc.ui.preference.TLCPreferenceInitializer;
import org.lamport.tla.toolbox.tool.tlc.ui.util.DirtyMarkingListener;
import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper;
import org.lamport.tla.toolbox.tool.tlc.ui.util.SemanticHelper;
import org.lamport.tla.toolbox.tool.tlc.util.ModelHelper;
import org.lamport.tla.toolbox.util.HelpButton;
import org.lamport.tla.toolbox.util.IHelpConstants;
import org.lamport.tla.toolbox.util.UIHelper;
import tla2sany.semantic.ModuleNode;
import util.TLCRuntime;
/**
* Main model page represents information for most users
* <br>
* This class is a a sub-class of the BasicFormPage and is used to represent the first tab of the
* multi-page-editor which is used to edit the model files.
*
*
* @author Simon Zambrovski
* This is the FormPage class for the Model Overview tabbed page of
* the model editor.
*/
public class MainModelPage extends BasicFormPage implements IConfigurationConstants, IConfigurationDefaults
{
public static final String ID = "MainModelPage";
public static final String TITLE = "Model Overview";
private static final String INIT_NEXT_COMBO_LABEL = "Initial predicate and next-state";
private static final String TEMPORAL_FORMULA_COMBO_LABEL = "Temporal formula";
private static final String NO_SPEC_COMBO_LABEL = "No behavior spec";
private static final String[] VARIABLE_BEHAVIOR_COMBO_ITEMS = { INIT_NEXT_COMBO_LABEL, TEMPORAL_FORMULA_COMBO_LABEL,
NO_SPEC_COMBO_LABEL };
private static final String[] NO_VARIABLE_BEHAVIOR_COMBO_ITEMS = { NO_SPEC_COMBO_LABEL };
static final String CLOUD_CONFIGURATION_KEY = "jclouds";
private static final String TLC_PROFILE_LOCAL_SEPARATOR = "\u2014\u2014 Local \u2014\u2014";
private static final String TLC_PROFILE_REMOTE_SEPARATOR = "\u2014\u2014 Remote \u2014\u2014";
private static final String CUSTOM_TLC_PROFILE_DISPLAY_NAME = "Custom";
private static final String CUSTOM_TLC_PROFILE_PREFERENCE_VALUE = "local custom";
private static final String[] TLC_PROFILE_DISPLAY_NAMES;
static {
final TLCConsumptionProfile[] profiles = TLCConsumptionProfile.values();
final int size = profiles.length;
TLC_PROFILE_DISPLAY_NAMES = new String[size + 2];
TLC_PROFILE_DISPLAY_NAMES[0] = TLC_PROFILE_LOCAL_SEPARATOR;
int indexIncrement = 1;
boolean haveStartedRemoteProfiles = false;
for (int i = 0; i < size; i++) {
if (profiles[i].profileIsForRemoteWorkers() && !haveStartedRemoteProfiles) {
TLC_PROFILE_DISPLAY_NAMES[i + indexIncrement] = TLC_PROFILE_REMOTE_SEPARATOR;
haveStartedRemoteProfiles = true;
indexIncrement++;
}
TLC_PROFILE_DISPLAY_NAMES[i + indexIncrement] = profiles[i].getDisplayName();
}
}
private Combo behaviorCombo;
private SourceViewer commentsSource;
private SourceViewer initFormulaSource;
private SourceViewer nextFormulaSource;
// private SourceViewer fairnessFormulaSource;
private SourceViewer specSource;
private Button checkDeadlockButton;
private Combo tlcProfileCombo;
private AtomicInteger lastSelectedTLCProfileIndex;
// We cache this since want to reference it frequently on heap slider drag
private AtomicBoolean currentProfileIsAdHoc;
private Spinner workers;
private Scale maxHeapSize;
private AtomicBoolean programmaticallySettingWorkerParameters;
/**
* Widgets related to distributed mode configuration
*/
private Spinner distributedFPSetCountSpinner;
private Spinner distributedNodesCountSpinner;
private Text resultMailAddressText;
private Combo networkInterfaceCombo;
private TableViewer invariantsTable;
private TableViewer propertiesTable;
private TableViewer constantTable;
/**
* section expanding adapter
* {@link Hyperlink#getHref()} must deliver the section id as described in {@link DataBindingManager#bindSection(ExpandableComposite, String, String)}
*/
protected HyperlinkAdapter sectionExpandingAdapter = new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e)
{
String sectionId = (String) e.getHref();
// first switch to the page (and construct it if not yet
// constructed)
getEditor().setActivePage(AdvancedModelPage.ID);
// then expand the section
expandSection(sectionId);
}
};
/**
* Used to interpolate y-values for memory scale
*/
private final Interpolator linearInterpolator;
/**
* Stacked composites for displaying options based on user selection in combo boxes
*/
private Composite behaviorOptions;
private Composite distributedOptions;
/**
* constructs the main model page
* @param editor
*/
public MainModelPage(FormEditor editor)
{
super(editor, MainModelPage.ID, MainModelPage.TITLE,
"icons/full/model_options_" + IMAGE_TEMPLATE_TOKEN + ".png");
this.helpId = IHelpConstants.MAIN_MODEL_PAGE;
// available system memory
final long phySysMem = TLCRuntime.getInstance().getAbsolutePhysicalSystemMemory(1.0d);
// 0.) Create LinearInterpolator with two additional points 0,0 and 1,0 which
int s = 0;
double[] x = new double[6];
double[] y = new double[x.length];
// base point
y[s] = 0d;
x[s++] = 0d;
// 1.) Minumum TLC requirements
// Use hard-coded minfpmemsize value * 4 * 10 regardless of how big the
// model is. *4 because .25 mem is used for FPs
double lowerLimit = ( (TLCRuntime.MinFpMemSize / 1024 / 1024 * 4d) / phySysMem) / 2;
x[s] = lowerLimit;
y[s++] = 0d;
// Current bloat in software is assumed to grow according to Moore's law =>
// 2^((Year-1993)/ 2)+2)
// (1993 as base results from a statistic of windows OS memory requirements)
final int currentYear = Calendar.getInstance().get(Calendar.YEAR);
double estimateSoftwareBloatInMBytes = Math.pow(2, ((currentYear - 1993) / 3) + 3.5);
// 2.) Optimal range
x[s] = lowerLimit * 2d;
y[s++] = 1.0d;
x[s] = 1.0d - (estimateSoftwareBloatInMBytes / phySysMem);
y[s++] = 1.0d;
// 3.) Calculate OS reserve
double upperLimit = 1.0d - (estimateSoftwareBloatInMBytes / phySysMem) / 2;
x[s] = upperLimit;
y[s++] = 0d;
// base point
x[s] = 1d;
y[s] = 0d;
linearInterpolator = new Interpolator(x, y);
currentProfileIsAdHoc = new AtomicBoolean(false);
programmaticallySettingWorkerParameters = new AtomicBoolean(false);
}
/**
* @see BasicFormPage#loadData()
*/
protected void loadData() throws CoreException
{
final Model model = getModel();
final int specType = model.getAttribute(MODEL_BEHAVIOR_SPEC_TYPE, MODEL_BEHAVIOR_TYPE_DEFAULT);
// set up the radio buttons
setSpecSelection(specType);
// closed spec
String modelSpecification = model.getAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION, EMPTY_STRING);
Document closedDoc = new Document(modelSpecification);
this.specSource.setDocument(closedDoc);
// init
String modelInit = model.getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT, EMPTY_STRING);
Document initDoc = new Document(modelInit);
this.initFormulaSource.setDocument(initDoc);
// next
String modelNext = model.getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT, EMPTY_STRING);
Document nextDoc = new Document(modelNext);
this.nextFormulaSource.setDocument(nextDoc);
// fairness
// String modelFairness =
// model.getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_FAIRNESS,
// EMPTY_STRING);
// Document fairnessDoc = new Document(modelFairness);
// this.fairnessFormulaSource.setDocument(fairnessDoc);
// check deadlock
boolean checkDeadlock = model.getAttribute(MODEL_CORRECTNESS_CHECK_DEADLOCK,
MODEL_CORRECTNESS_CHECK_DEADLOCK_DEFAULT);
this.checkDeadlockButton.setSelection(checkDeadlock);
// invariants
List<String> serializedList = model.getAttribute(MODEL_CORRECTNESS_INVARIANTS, new Vector<String>());
FormHelper.setSerializedInput(invariantsTable, serializedList);
// properties
serializedList = model.getAttribute(MODEL_CORRECTNESS_PROPERTIES, new Vector<String>());
FormHelper.setSerializedInput(propertiesTable, serializedList);
// constants from the model
List<String> savedConstants = model.getAttribute(MODEL_PARAMETER_CONSTANTS, new Vector<String>());
FormHelper.setSerializedInput(constantTable, savedConstants);
if (!savedConstants.isEmpty()) {
expandSection(SEC_WHAT_IS_THE_MODEL);
}
final int threadCount;
final int memoryPercentage;
currentProfileIsAdHoc.set(false);
if (model.hasAttribute(TLC_RESOURCES_PROFILE)) {
final String tlcProfile = model.getAttribute(TLC_RESOURCES_PROFILE, (String)null);
if (tlcProfile.equals(CUSTOM_TLC_PROFILE_PREFERENCE_VALUE)) {
threadCount = model.getAttribute(LAUNCH_NUMBER_OF_WORKERS,
TLCConsumptionProfile.LOCAL_NORMAL.getWorkerThreads());
final int defaultMaxHeapSize = TLCUIActivator.getDefault().getPreferenceStore()
.getInt(ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT);
memoryPercentage = model.getAttribute(LAUNCH_MAX_HEAP_SIZE, defaultMaxHeapSize);
setTLCProfileComboSelection(CUSTOM_TLC_PROFILE_DISPLAY_NAME);
} else {
final TLCConsumptionProfile profile = TLCConsumptionProfile.getProfileWithPreferenceValue(tlcProfile);
setTLCProfileComboSelection(profile.getDisplayName());
if (profile.profileIsForRemoteWorkers()) {
final String configuration = profile.getConfigurationKey(); // currentProfileIsAdHoc
final boolean isAdHoc = configuration
.equals(TLCConsumptionProfile.REMOTE_AD_HOC.getConfigurationKey());
currentProfileIsAdHoc.set(isAdHoc);
moveToTopOfDistributedOptionsStack(configuration, false, isAdHoc);
if (configuration.equals(CLOUD_CONFIGURATION_KEY)) {
final String email = model.getAttribute(LAUNCH_DISTRIBUTED_RESULT_MAIL_ADDRESS,
LAUNCH_DISTRIBUTED_RESULT_MAIL_ADDRESS_DEFAULT);
resultMailAddressText.setText(email);
}
} else {
moveToTopOfDistributedOptionsStack(LAUNCH_DISTRIBUTED_NO, true, true);
}
threadCount = profile.getWorkerThreads();
memoryPercentage = currentProfileIsAdHoc.get()
? model.getAttribute(LAUNCH_MAX_HEAP_SIZE, profile.getMemoryPercentage())
: profile.getMemoryPercentage();
}
} else { // for pre-1.5.8 models...
String remoteWorkers = LAUNCH_DISTRIBUTED_NO;
try {
remoteWorkers = model.getAttribute(LAUNCH_DISTRIBUTED, LAUNCH_DISTRIBUTED_DEFAULT);
} catch(CoreException e) { // for very old models
if (model.getAttribute(LAUNCH_DISTRIBUTED, false)) {
remoteWorkers = TLCConsumptionProfile.REMOTE_AD_HOC.getConfigurationKey();
currentProfileIsAdHoc.set(true);
}
}
if (remoteWorkers.equals(LAUNCH_DISTRIBUTED_NO)) {
moveToTopOfDistributedOptionsStack(LAUNCH_DISTRIBUTED_NO, true, true);
threadCount = model.getAttribute(LAUNCH_NUMBER_OF_WORKERS,
TLCConsumptionProfile.LOCAL_NORMAL.getWorkerThreads());
final int defaultMaxHeapSize = TLCUIActivator.getDefault().getPreferenceStore()
.getInt(ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT);
memoryPercentage = model.getAttribute(LAUNCH_MAX_HEAP_SIZE, defaultMaxHeapSize);
setTLCProfileComboSelection(CUSTOM_TLC_PROFILE_DISPLAY_NAME);
} else {
final TLCConsumptionProfile profile = TLCConsumptionProfile
.getProfileWithPreferenceValue(remoteWorkers);
final String configuration = profile.getConfigurationKey();
final boolean isAdHoc = configuration
.equals(TLCConsumptionProfile.REMOTE_AD_HOC.getConfigurationKey());
currentProfileIsAdHoc.set(isAdHoc);
moveToTopOfDistributedOptionsStack(configuration, false, isAdHoc);
if (configuration.equals(CLOUD_CONFIGURATION_KEY)) {
final String email = model.getAttribute(LAUNCH_DISTRIBUTED_RESULT_MAIL_ADDRESS,
LAUNCH_DISTRIBUTED_RESULT_MAIL_ADDRESS_DEFAULT);
resultMailAddressText.setText(email);
}
threadCount = 0;
if (isAdHoc) {
final int defaultMaxHeapSize = TLCUIActivator.getDefault().getPreferenceStore()
.getInt(ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT);
memoryPercentage = model.getAttribute(LAUNCH_MAX_HEAP_SIZE, defaultMaxHeapSize);
} else {
memoryPercentage = 0;
}
setTLCProfileComboSelection(profile.getDisplayName());
}
}
programmaticallySettingWorkerParameters.set(true);
workers.setSelection(threadCount);
maxHeapSize.setSelection(memoryPercentage);
programmaticallySettingWorkerParameters.set(false);
// distribute FPSet count
distributedFPSetCountSpinner.setSelection(model.getAttribute(LAUNCH_DISTRIBUTED_FPSET_COUNT, LAUNCH_DISTRIBUTED_FPSET_COUNT_DEFAULT));
// distribute FPSet count
distributedNodesCountSpinner.setSelection(model.getAttribute(LAUNCH_DISTRIBUTED_NODES_COUNT, LAUNCH_DISTRIBUTED_NODES_COUNT_DEFAULT));
// comments/description/notes
String commentsStr = model.getAttribute(MODEL_COMMENTS, EMPTY_STRING);
commentsSource.setDocument(new Document(commentsStr));
if (!EMPTY_STRING.equals(commentsStr)) {
expandSection(SEC_COMMENTS);
}
}
public void validatePage(boolean switchToErrorPage)
{
if (getManagedForm() == null)
{
return;
}
DataBindingManager dm = getDataBindingManager();
IMessageManager mm = getManagedForm().getMessageManager();
ModelEditor modelEditor = (ModelEditor) getEditor();
// The following comment was apparently written by Simon:
// delete the messages
// this is now done in validateRunnable
// in ModelEditor
// resetAllMessages(false);
// validateRunnable is in ModelEditor. I believe it is executed only when
// the user executes the Run or Validate Model command.
// Errors that the validatePage method checks for should be cleared
// whenever the method is called. However, calling resetAllMessages
// seems to be the wrong way to do it because error messages from all
// pages are reported on each page. Hence, that would require validating
// all pages whenever any one is validated. See the ModelEditor.removeErrorMessage
// method for a further discussion of this problem.
// Comments added by LL on 21 Mar 2013.
// getting the root module node of the spec
// this can be null!
ModuleNode rootModuleNode = SemanticHelper.getRootModuleNode();
// setup the names from the current page
getLookupHelper().resetModelNames(this);
// constants in the table
List<Assignment> constants = getConstants();
// merge constants with currently defined in the specobj, if any
if (rootModuleNode != null)
{
List<Assignment> toDelete = ModelHelper.mergeConstantLists(constants, ModelHelper.createConstantsList(rootModuleNode));
if (!toDelete.isEmpty())
{
// if constants have been removed, these should be deleted from
// the model too
SectionPart constantSection = dm.getSection(dm.getSectionForAttribute(MODEL_PARAMETER_CONSTANTS));
if (constantSection != null)
{
// mark the constants dirty
constantSection.markDirty();
}
}
constantTable.setInput(constants);
}
// The following string is used to test whether two differently-typed model
// values appear in symmetry sets (sets of model values declared to be symmetric).
// It is set to the type of the first typed model value found in a symmetry set.
String symmetryType = null;
// boolean symmetryUsed = false;
// iterate over the constants
for (int i = 0; i < constants.size(); i++)
{
Assignment constant = (Assignment) constants.get(i);
List<String> values = Arrays.asList(constant.getParams());
// check parameters
validateId(MODEL_PARAMETER_CONSTANTS, values, "param1_", "A parameter name");
// the constant is still in the list
if (constant.getRight() == null || EMPTY_STRING.equals(constant.getRight()))
{
// right side of assignment undefined
modelEditor.addErrorMessage(constant.getLabel(), "Provide a value for constant " + constant.getLabel(),
this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm
.getAttributeControl(MODEL_PARAMETER_CONSTANTS)));
setComplete(false);
expandSection(dm.getSectionForAttribute(MODEL_PARAMETER_CONSTANTS));
} else
{ // Following added by LL on 21 Mar 2013
modelEditor.removeErrorMessage(constant.getLabel(), UIHelper.getWidget(dm
.getAttributeControl(MODEL_PARAMETER_CONSTANTS)));
if (constant.isSetOfModelValues())
{
TypedSet modelValuesSet = TypedSet.parseSet(constant.getRight());
if (constant.isSymmetricalSet())
{
if (((CheckboxTableViewer) propertiesTable).getCheckedElements().length > 0) {
modelEditor.addErrorMessage(constant.getLabel(), String.format(
"%s declared to be symmetric while one or more temporal formulas are set to be checked.\n"
+ "If the temporal formula is a liveness property, liveness checking might fail to find\n"
+ "violations. The Model Checking Result page will show a warning during TLC startup if\n"
+ "any one of the temporal formulas is a liveness property.",
constant.getLabel()), this.getId(), IMessageProvider.INFORMATION,
UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_CONSTANTS)));
expandSection(dm.getSectionForAttribute(MODEL_PARAMETER_CONSTANTS));
expandSection(dm.getSectionForAttribute(MODEL_CORRECTNESS_PROPERTIES));
}
boolean hasTwoTypes = false; // set true if this symmetry set has two differently-typed model
// values.
String typeString = null; // set to the type of the first typed model value in this symmetry
// set.
if (modelValuesSet.hasType())
{
typeString = modelValuesSet.getType();
} else
{
for (int j = 0; j < modelValuesSet.getValues().length; j++)
{
String thisTypeString = TypedSet.getTypeOfId(modelValuesSet.getValues()[j]);
if (thisTypeString != null)
{
if (typeString != null && !typeString.equals(thisTypeString))
{
hasTwoTypes = true;
} else
{
typeString = thisTypeString;
}
}
}
}
if (hasTwoTypes
|| (symmetryType != null && typeString != null && !typeString.equals(symmetryType)))
{
modelEditor.addErrorMessage(constant.getLabel(),
"Two differently typed model values used in symmetry sets.",
this.getId()/*constant*/, IMessageProvider.ERROR, UIHelper.getWidget(dm
.getAttributeControl(MODEL_PARAMETER_CONSTANTS)));
setComplete(false);
expandSection(dm.getSectionForAttribute(MODEL_PARAMETER_CONSTANTS));
} else
{
if (typeString != null)
{
symmetryType = typeString;
}
}
// symmetry can be used for only one set of model values
}
if (modelValuesSet.getValueCount() > 0)
{
// there were values defined
// check if those are numbers?
/*
* if (modelValuesSet.hasANumberOnlyValue()) {
* mm.addMessage("modelValues1",
* "A model value can not be an number", modelValuesSet,
* IMessageProvider.ERROR, constantTable.getTable());
* setComplete(false); }
*/
List<String> mvList = modelValuesSet.getValuesAsList();
// check list of model values
validateUsage(MODEL_PARAMETER_CONSTANTS, mvList, "modelValues2_", "A model value",
"Constant Assignment", true);
// check if the values are correct ids
validateId(MODEL_PARAMETER_CONSTANTS, mvList, "modelValues2_", "A model value");
// get widget for model values assigned to constant
Control widget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_CONSTANTS));
// check if model values are config file keywords
for (int j = 0; j < mvList.size(); j++)
{
String value = (String) mvList.get(j);
if (SemanticHelper.isConfigFileKeyword(value))
{
modelEditor.addErrorMessage(value, "The toolbox cannot handle the model value " + value
+ ".", this.getId(), IMessageProvider.ERROR, widget);
setComplete(false);
}
}
} else
{
// This made an error by LL on 15 Nov 2009
modelEditor.addErrorMessage(constant.getLabel(),
"The set of model values should not be empty.", this.getId(), IMessageProvider.ERROR,
UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_CONSTANTS)));
setComplete(false);
}
}
}
// the constant identifier is a config file keyword
if (SemanticHelper.isConfigFileKeyword(constant.getLabel()))
{
modelEditor.addErrorMessage(constant.getLabel(), "The toolbox cannot handle the constant identifier "
+ constant.getLabel() + ".", this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm
.getAttributeControl(MODEL_PARAMETER_CONSTANTS)));
setComplete(false);
}
}
// iterate over the constants again, and check if the parameters are used as Model Values
for (int i = 0; i < constants.size(); i++)
{
Assignment constant = (Assignment) constants.get(i);
List<String> values = Arrays.asList(constant.getParams());
// check list of parameters
validateUsage(MODEL_PARAMETER_CONSTANTS, values, "param1_", "A parameter name", "Constant Assignment",
false);
}
// number of workers
int number = workers.getSelection();
if (number > Runtime.getRuntime().availableProcessors())
{
modelEditor.addErrorMessage("strangeNumber1", "Specified number of workers is " + number
+ ". The number of processors available on the system is "
+ Runtime.getRuntime().availableProcessors()
+ ".\n The number of workers should not exceed the number of processors.",
this.getId(), IMessageProvider.WARNING, UIHelper.getWidget(dm
.getAttributeControl(LAUNCH_NUMBER_OF_WORKERS)));
expandSection(SEC_HOW_TO_RUN);
} else {
modelEditor.removeErrorMessage("strangeNumber1", UIHelper.getWidget(dm
.getAttributeControl(LAUNCH_NUMBER_OF_WORKERS)));
}
// legacy value?
// better handle legacy models
try {
final int defaultMaxHeapSize = TLCUIActivator
.getDefault()
.getPreferenceStore()
.getInt(ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT);
final int legacyValue = getModel().getAttribute(
LAUNCH_MAX_HEAP_SIZE, defaultMaxHeapSize);
// old default, silently convert to new default
if (legacyValue == 500) {
getModel().setAttribute(
LAUNCH_MAX_HEAP_SIZE, TLCPreferenceInitializer.MAX_HEAP_SIZE_DEFAULT);
maxHeapSize.setSelection(TLCPreferenceInitializer.MAX_HEAP_SIZE_DEFAULT);
} else if (legacyValue >= 100) {
modelEditor
.addErrorMessage(
"strangeNumber1",
"Found legacy value for physically memory of ("
+ legacyValue
+ "mb) that needs manual conversion. 25% is a safe setting on most computers.",
this.getId(), IMessageProvider.WARNING,
maxHeapSize);
setComplete(false);
expandSection(SEC_HOW_TO_RUN);
}
} catch (CoreException e) {
TLCUIActivator.getDefault().logWarning("Faild to read heap value", e);
}
// max heap size
// color the scale according to OS and TLC requirements
int maxHeapSizeValue = maxHeapSize.getSelection();
double x = maxHeapSizeValue / 100d;
float y = (float) linearInterpolator.interpolate(x);
maxHeapSize.setBackground(new Color(Display.getDefault(), new RGB(120 * y, 1 - y, 1f)));
// IP/network address correct?
final int networkAddressIndex = this.networkInterfaceCombo.getSelectionIndex();
if (networkAddressIndex < 0) {
// Bogus input
modelEditor.addErrorMessage("strangeAddress1",
String.format(
"Found the manually inserted master's network address %s. "
+ "This is usually unnecessary and hints at a misconfiguration. "
+ "Make sure your computer running the TLC master is reachable at address %s.",
this.networkInterfaceCombo.getText(), this.networkInterfaceCombo.getText()),
this.getId(), IMessageProvider.WARNING, networkInterfaceCombo);
expandSection(SEC_HOW_TO_RUN);
}
// The following code added by LL and DR on 10 Sep 2009.
// Reset the enabling and selection of spec type depending on the number number
// of variables in the spec.
// This code needs to be modified when we modify the model launcher
// to allow the No Spec option to be selected when there are variables.
if (rootModuleNode != null)
{
final Control errorMsgControl = UIHelper.getWidget(getDataBindingManager().getAttributeControl(MODEL_BEHAVIOR_NO_SPEC));
final String errorMsgKey = MODEL_BEHAVIOR_NO_SPEC + "ErrorMsgKey";
if (rootModuleNode.getVariableDecls().length == 0)
{
setHasVariables(false);
modelEditor.addErrorMessage(errorMsgKey,
"\"What is the behavior spec?\" automatically set to \"No Behavior Spec\" because spec has no declared variables.", this.getId(),
IMessageProvider.INFORMATION, errorMsgControl);
// set selection to the NO SPEC field
if (!NO_SPEC_COMBO_LABEL.equals(behaviorCombo.getText())) {
// mark dirty so that changes must be written to config file
setSpecSelection(MODEL_BEHAVIOR_TYPE_NO_SPEC);
dm.getSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_NO_SPEC)).markDirty();
}
} else
{
setHasVariables(true);
modelEditor.removeErrorMessage(errorMsgKey, errorMsgControl);
// if there are variables, the user
// may still want to choose no spec
// so the selection is not changed
// if (noSpecRadio.getSelection())
// // mark dirty so that changes must be written to config file
// dm.getSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION)).markDirty();
// // set selection to the default
// setSpecSelection(MODEL_BEHAVIOR_TYPE_DEFAULT);
}
}
// This code disables or enables sections
// depending on whether whether no spec is selected
// or not.
// This must occur after the preceeding code in case
// that code changes the selection.
final Section whatToCheckSection = dm.getSection(SEC_WHAT_TO_CHECK).getSection();
final Set<Section> resultPageSections = ((ResultPage) modelEditor.findPage(ResultPage.ID))
.getSections(SEC_GENERAL, SEC_STATISTICS);
final String hint = " (\"What is the behavior spec?\" above has no behavior spec)";
final String hintResults = " (\"What is the behavior spec?\" on \"Model Overview\" page has no behavior spec)";
if (NO_SPEC_COMBO_LABEL.equals(behaviorCombo.getText())) {
whatToCheckSection
.setText(!whatToCheckSection.getText().endsWith(hint) ? whatToCheckSection.getText() + hint
: whatToCheckSection.getText());
whatToCheckSection.setExpanded(false);
whatToCheckSection.setEnabled(false);
resultPageSections.forEach(new Consumer<Section>() {
@Override
public void accept(Section sec) {
sec.setText(!sec.getText().endsWith(hintResults) ? sec.getText() + hintResults : sec.getText());
sec.setEnabled(false);
sec.setExpanded(false);
}
});
} else {
whatToCheckSection.setText(whatToCheckSection.getText().replace(hint, ""));
whatToCheckSection.setExpanded(true);
whatToCheckSection.setEnabled(true);
resultPageSections.forEach(new Consumer<Section>() {
@Override
public void accept(Section sec) {
sec.setText(sec.getText().replace(hintResults, ""));
sec.setEnabled(true);
sec.setExpanded(true);
}
});
}
// The following code is not needed now because we automatically change
// the selection to No Spec if there are no variables.
// if (selectedAttribute != null) {
// // the user selected to use a spec
// // check if there are variables declared
// if (rootModuleNode != null
// && rootModuleNode.getVariableDecls().length == 0) {
// // no variables => install an error
// mm.addMessage("noVariables",
// "There were no variables declared in the root module",
// null, IMessageProvider.ERROR, UIHelper.getWidget(dm
// .getAttributeControl(selectedAttribute)));
// setComplete(false);
// expandSection(dm.getSectionForAttribute(selectedAttribute));
// check if the selected fields are filled
final Control initTA = UIHelper.getWidget(dm.getAttributeControl(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT));
final Control nextTA = UIHelper.getWidget(dm.getAttributeControl(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT));
final Control specTA = UIHelper.getWidget(dm.getAttributeControl(MODEL_BEHAVIOR_CLOSED_SPECIFICATION));
modelEditor.removeErrorMessage("noInit", initTA);
modelEditor.removeErrorMessage("noNext", nextTA);
modelEditor.removeErrorMessage("noSpec", specTA);
if (TEMPORAL_FORMULA_COMBO_LABEL.equals(behaviorCombo.getText())
&& (specSource.getDocument().get().trim().length() == 0)) {
modelEditor.addErrorMessage("noSpec", "The formula must be provided", this.getId(), IMessageProvider.ERROR,
specTA);
setComplete(false);
expandSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION));
} else if (INIT_NEXT_COMBO_LABEL.equals(behaviorCombo.getText())) {
final String init = initFormulaSource.getDocument().get().trim();
final String next = nextFormulaSource.getDocument().get().trim();
if (init.length() == 0) {
modelEditor.addErrorMessage("noInit", "The Init formula must be provided", this.getId(),
IMessageProvider.ERROR, initTA);
setComplete(false);
expandSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT));
}
if (next.length() == 0) {
modelEditor.addErrorMessage("noNext", "The Next formula must be provided", this.getId(),
IMessageProvider.ERROR, nextTA);
setComplete(false);
expandSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT));
}
}
final Control emails = UIHelper.getWidget(dm.getAttributeControl(LAUNCH_DISTRIBUTED_RESULT_MAIL_ADDRESS));
modelEditor.removeErrorMessage("email address invalid", emails);
modelEditor.removeErrorMessage("email address missing", emails);
// Verify that the user provided email address is valid and can be used to send
// the model checking result to.
final TLCConsumptionProfile profile = getSelectedTLCProfile();
if ((profile != null) && CLOUD_CONFIGURATION_KEY.equals(profile.getConfigurationKey())) {
final String text = resultMailAddressText.getText();
try {
InternetAddress.parse(text, true);
} catch (AddressException exp) {
modelEditor.addErrorMessage("email address invalid",
"For Cloud TLC to work please enter a valid email address.", this.getId(),
IMessageProvider.ERROR, emails);
setComplete(false);
expandSection(SEC_HOW_TO_RUN);
}
if ("".equals(text.trim())) {
modelEditor.addErrorMessage("email address missing",
"For Cloud TLC to work please enter an email address.", this.getId(), IMessageProvider.ERROR,
emails);
setComplete(false);
expandSection(SEC_HOW_TO_RUN);
}
}
mm.setAutoUpdate(true);
super.validatePage(switchToErrorPage);
}
/**
* This method is used to enable and disable UI widgets depending on the fact if the specification
* has variables.
* @param hasVariables true if the spec contains variables
*/
private void setHasVariables(final boolean hasVariables) {
String[] newItems = null;
if (hasVariables) {
if (behaviorCombo.indexOf(INIT_NEXT_COMBO_LABEL) == -1) {
newItems = VARIABLE_BEHAVIOR_COMBO_ITEMS;
}
} else {
if (behaviorCombo.indexOf(INIT_NEXT_COMBO_LABEL) != -1) {
newItems = NO_VARIABLE_BEHAVIOR_COMBO_ITEMS;
}
}
if (newItems != null) {
final String currentSelection = behaviorCombo.getText();
behaviorCombo.removeAll();
behaviorCombo.setItems(newItems);
final int index = behaviorCombo.indexOf(currentSelection);
if (index != -1) {
behaviorCombo.select(index);
}
}
}
/**
* This method sets the selection on the
* @param selectedFormula
*/
private void setSpecSelection(int specType)
{
int index = -1;
switch (specType) {
case MODEL_BEHAVIOR_TYPE_NO_SPEC:
index = behaviorCombo.indexOf(NO_SPEC_COMBO_LABEL);
break;
case MODEL_BEHAVIOR_TYPE_SPEC_CLOSED:
index = behaviorCombo.indexOf(TEMPORAL_FORMULA_COMBO_LABEL);
break;
case MODEL_BEHAVIOR_TYPE_SPEC_INIT_NEXT:
index = behaviorCombo.indexOf(INIT_NEXT_COMBO_LABEL);
break;
default:
throw new IllegalArgumentException("Wrong spec type, this is a bug");
}
if (index != -1) {
behaviorCombo.select(index);
moveToTopOfBehaviorOptionsStack(behaviorCombo.getText());
}
}
/**
* Save data back to model
*/
public void commit(boolean onSave)
{
final Model model = getModel();
final String comments = FormHelper.trimTrailingSpaces(commentsSource.getDocument().get());
model.setAttribute(MODEL_COMMENTS, comments);
// TLCUIActivator.getDefault().logDebug("Main page commit");
// closed formula
String closedFormula = FormHelper.trimTrailingSpaces(this.specSource.getDocument().get());
model.setAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION, closedFormula);
// init formula
String initFormula = FormHelper.trimTrailingSpaces(this.initFormulaSource.getDocument().get());
model.setAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT, initFormula);
// next formula
String nextFormula = FormHelper.trimTrailingSpaces(this.nextFormulaSource.getDocument().get());
model.setAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT, nextFormula);
// fairness formula
// String fairnessFormula =
// FormHelper.trimTrailingSpaces(this.fairnessFormulaSource.getDocument().get());
// model.setAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_FAIRNESS,
// fairnessFormula);
// mode
final String selectedBehavior = behaviorCombo.getText();
int specType;
if (TEMPORAL_FORMULA_COMBO_LABEL.equals(selectedBehavior)) {
specType = MODEL_BEHAVIOR_TYPE_SPEC_CLOSED;
} else if (INIT_NEXT_COMBO_LABEL.equals(selectedBehavior)) {
specType = MODEL_BEHAVIOR_TYPE_SPEC_INIT_NEXT;
} else if (NO_SPEC_COMBO_LABEL.equals(selectedBehavior)) {
specType = MODEL_BEHAVIOR_TYPE_NO_SPEC;
} else {
specType = MODEL_BEHAVIOR_TYPE_DEFAULT;
}
model.setAttribute(MODEL_BEHAVIOR_SPEC_TYPE, specType);
// check deadlock
boolean checkDeadlock = this.checkDeadlockButton.getSelection();
model.setAttribute(MODEL_CORRECTNESS_CHECK_DEADLOCK, checkDeadlock);
final TLCConsumptionProfile profile = getSelectedTLCProfile();
final String profileValue = (profile != null) ? profile.getPreferenceValue()
: CUSTOM_TLC_PROFILE_PREFERENCE_VALUE;
model.setAttribute(TLC_RESOURCES_PROFILE, profileValue);
// number of workers & memory guidance
model.setAttribute(LAUNCH_NUMBER_OF_WORKERS, workers.getSelection());
model.setAttribute(LAUNCH_MAX_HEAP_SIZE, maxHeapSize.getSelection());
// run in distributed mode
if ((profile != null) && profile.profileIsForRemoteWorkers()) {
model.setAttribute(LAUNCH_DISTRIBUTED, profile.getPreferenceValue());
} else {
model.setAttribute(LAUNCH_DISTRIBUTED, LAUNCH_DISTRIBUTED_NO);
}
String resultMailAddress = this.resultMailAddressText.getText();
model.setAttribute(LAUNCH_DISTRIBUTED_RESULT_MAIL_ADDRESS, resultMailAddress);
// distributed FPSet count
model.setAttribute(LAUNCH_DISTRIBUTED_FPSET_COUNT, distributedFPSetCountSpinner.getSelection());
// distributed FPSet count
model.setAttribute(LAUNCH_DISTRIBUTED_NODES_COUNT, distributedNodesCountSpinner.getSelection());
// network interface
String iface = "";
final int index = this.networkInterfaceCombo.getSelectionIndex();
if (index == -1) {
// Normally, the user selects an address from the provided list.
// This branch handles the case where the user manually entered an
// address. We don't verify it though.
iface = this.networkInterfaceCombo.getText();
} else {
iface = this.networkInterfaceCombo.getItem(index);
}
model.setAttribute(LAUNCH_DISTRIBUTED_INTERFACE, iface);
// invariants
List<String> serializedList = FormHelper.getSerializedInput(invariantsTable);
model.setAttribute(MODEL_CORRECTNESS_INVARIANTS, serializedList);
// properties
serializedList = FormHelper.getSerializedInput(propertiesTable);
model.setAttribute(MODEL_CORRECTNESS_PROPERTIES, serializedList);
// constants
List<String> constants = FormHelper.getSerializedInput(constantTable);
model.setAttribute(MODEL_PARAMETER_CONSTANTS, constants);
// variables
String variables = ModelHelper.createVariableList(SemanticHelper.getRootModuleNode());
model.setAttribute(MODEL_BEHAVIOR_VARS, variables);
super.commit(onSave);
}
@SuppressWarnings("unchecked")
public List<Assignment> getConstants() {
return (List<Assignment>) constantTable.getInput();
}
protected void createBodyContent(IManagedForm managedForm)
{
DataBindingManager dm = getDataBindingManager();
int sectionFlags = Section.TITLE_BAR | Section.DESCRIPTION | Section.TREE_NODE;
FormToolkit toolkit = managedForm.getToolkit();
Composite body = managedForm.getForm().getBody();
GridLayout gl;
GridData gd;
TableWrapData twd;
Section section;
installTopMargin(body);
TableWrapLayout twl = new TableWrapLayout();
twl.leftMargin = 0;
twl.rightMargin = 0;
twl.numColumns = 2;
body.setLayout(twl);
/*
* Comments/notes section spanning two columns
*/
section = FormHelper.createSectionComposite(body, "Model description", "", toolkit, sectionFlags,
getExpansionListener());
twd = new TableWrapData();
twd.colspan = 2;
twd.grabHorizontal = true;
twd.align = TableWrapData.FILL;
section.setLayoutData(twd);
final ValidateableSectionPart commentsPart = new ValidateableSectionPart(section, this, SEC_COMMENTS);
managedForm.addPart(commentsPart);
final DirtyMarkingListener commentsListener = new DirtyMarkingListener(commentsPart, true);
final Composite commentsArea = (Composite) section.getClient();
commentsArea.setLayout(new TableWrapLayout());
commentsSource = FormHelper.createFormsSourceViewer(toolkit, commentsArea, SWT.V_SCROLL | SWT.WRAP);
// layout of the source viewer
twd = new TableWrapData(TableWrapData.FILL_GRAB);
twd.heightHint = 60;
commentsSource.addTextListener(commentsListener);
commentsSource.getTextWidget().setLayoutData(twd);
commentsSource.getTextWidget().addFocusListener(focusListener);
toolkit.paintBordersFor(commentsArea);
dm.bindAttribute(MODEL_COMMENTS, commentsSource, commentsPart);
/*
* Because the two Composite objects `left' and `right' are added to the
* object `body' in this order, `left' is displayed to the left of `right'.
*/
// left
final Composite left = toolkit.createComposite(body);
gl = new GridLayout(1, false);
gl.marginHeight = 0;
gl.marginWidth = 0;
left.setLayout(gl);
twd = new TableWrapData(TableWrapData.FILL_GRAB);
twd.grabHorizontal = true;
left.setLayoutData(twd);
// right
final Composite right = toolkit.createComposite(body);
gl = new GridLayout(1, false);
gl.marginHeight = 0;
gl.marginWidth = 0;
right.setLayout(gl);
twd = new TableWrapData(TableWrapData.FILL_GRAB);
twd.grabHorizontal = true;
right.setLayoutData(twd);
// what is the spec
section = FormHelper.createSectionComposite(left, "What is the behavior spec?", "", toolkit, sectionFlags
| Section.EXPANDED, getExpansionListener());
// only grab horizontal space
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.horizontalIndent = 0;
gd.verticalIndent = 0;
section.setLayoutData(gd);
Composite behaviorArea = (Composite)section.getClient();
behaviorArea.setLayout(new GridLayout(1, false));
ValidateableSectionPart behaviorPart = new ValidateableSectionPart(section, this, SEC_WHAT_IS_THE_SPEC);
managedForm.addPart(behaviorPart);
DirtyMarkingListener whatIsTheSpecListener = new DirtyMarkingListener(behaviorPart, true);
behaviorCombo = new Combo(behaviorArea, SWT.READ_ONLY);
behaviorCombo.setItems(VARIABLE_BEHAVIOR_COMBO_ITEMS);
behaviorCombo.addFocusListener(focusListener);
behaviorCombo.addSelectionListener(whatIsTheSpecListener);
behaviorCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(final SelectionEvent se) {
moveToTopOfBehaviorOptionsStack(behaviorCombo.getText());
}
public void widgetDefaultSelected(final SelectionEvent se) { }
});
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
behaviorCombo.setLayoutData(gd);
dm.bindAttribute(MODEL_BEHAVIOR_NO_SPEC, behaviorCombo, behaviorPart);
behaviorOptions = new Composite(behaviorArea, SWT.NONE);
StackLayout stackLayout = new StackLayout();
behaviorOptions.setLayout(stackLayout);
final Composite noSpecComposite = new Composite(behaviorOptions, SWT.NONE);
behaviorOptions.setData(NO_SPEC_COMBO_LABEL, noSpecComposite);
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.minimumHeight = 1;
behaviorOptions.setLayoutData(gd);
stackLayout.topControl = noSpecComposite;
// split formula option
final Composite initNextComposite = new Composite(behaviorOptions, SWT.NONE);
behaviorOptions.setData(INIT_NEXT_COMBO_LABEL, initNextComposite);
initNextComposite.setLayout(new GridLayout(2, false));
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
initNextComposite.setLayoutData(gd);
// init
toolkit.createLabel(initNextComposite, "Init:");
initFormulaSource = FormHelper.createFormsSourceViewer(toolkit, initNextComposite,
SWT.NONE | SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.heightHint = 48;
initFormulaSource.getTextWidget().setLayoutData(gd);
initFormulaSource.getTextWidget().addModifyListener(whatIsTheSpecListener);
initFormulaSource.getTextWidget().addFocusListener(focusListener);
dm.bindAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT, initFormulaSource, behaviorPart);
// next
toolkit.createLabel(initNextComposite, "Next:");
nextFormulaSource = FormHelper.createFormsSourceViewer(toolkit, initNextComposite,
SWT.NONE | SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.heightHint = 48;
nextFormulaSource.getTextWidget().setLayoutData(gd);
nextFormulaSource.getTextWidget().addModifyListener(whatIsTheSpecListener);
nextFormulaSource.getTextWidget().addFocusListener(focusListener);
dm.bindAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT, nextFormulaSource, behaviorPart);
// fairness
// toolkit.createLabel(behaviorArea, "Fairness:");
// fairnessFormulaSource = FormHelper.createSourceViewer(toolkit,
// behaviorArea, SWT.NONE | SWT.SINGLE);
// gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.heightHint = 18;
// fairnessFormulaSource.getTextWidget().setLayoutData(gd);
// fairnessFormulaSource.getTextWidget().addModifyListener(whatIsTheSpecListener);
// fairnessFormulaSource.getTextWidget().addModifyListener(widgetActivatingListener);
// dm.bindAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_FAIRNESS,
// fairnessFormulaSource, behaviorPart);
// closed formula option
final Composite temporalFormulaComposite = new Composite(behaviorOptions, SWT.NONE);
behaviorOptions.setData(TEMPORAL_FORMULA_COMBO_LABEL, temporalFormulaComposite);
temporalFormulaComposite.setLayout(new GridLayout(1, true));
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
temporalFormulaComposite.setLayoutData(gd);
specSource = FormHelper.createFormsSourceViewer(toolkit, temporalFormulaComposite, SWT.V_SCROLL | SWT.BORDER);
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.verticalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.minimumHeight = 55;
specSource.getTextWidget().setLayoutData(gd);
specSource.getTextWidget().addModifyListener(whatIsTheSpecListener);
dm.bindAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION, specSource, behaviorPart);
// what to check
section = FormHelper.createSectionComposite(body, "What to check?", "", toolkit,
(sectionFlags & ~Section.DESCRIPTION | Section.EXPANDED), getExpansionListener());
// only grab horizontal space
twd = new TableWrapData();
twd.colspan = 2;
twd.grabHorizontal = true;
twd.align = TableWrapData.FILL;
section.setLayoutData(twd);
Composite toBeCheckedArea = (Composite) section.getClient();
gl = new GridLayout(1, false);
gl.verticalSpacing = 0;
toBeCheckedArea.setLayout(gl);
checkDeadlockButton = toolkit.createButton(toBeCheckedArea, "Deadlock", SWT.CHECK);
ValidateableSectionPart toBeCheckedPart = new ValidateableSectionPart(section, this, SEC_WHAT_TO_CHECK);
managedForm.addPart(toBeCheckedPart);
DirtyMarkingListener whatToCheckListener = new DirtyMarkingListener(toBeCheckedPart, true);
checkDeadlockButton.addSelectionListener(whatToCheckListener);
// Invariants
ValidateableTableSectionPart invariantsPart = new ValidateableTableSectionPart(toBeCheckedArea, "Invariants",
"Formulas true in every reachable state.", toolkit, sectionFlags, this, SEC_WHAT_TO_CHECK_INVARIANTS);
managedForm.addPart(invariantsPart);
invariantsTable = invariantsPart.getTableViewer();
dm.bindAttribute(MODEL_CORRECTNESS_INVARIANTS, invariantsTable, invariantsPart);
// Properties
ValidateableTableSectionPart propertiesPart = new ValidateableTableSectionPart(toBeCheckedArea, "Properties",
"Temporal formulas true for every possible behavior.", toolkit, sectionFlags, this,
SEC_WHAT_TO_CHECK_PROPERTIES);
managedForm.addPart(propertiesPart);
propertiesTable = propertiesPart.getTableViewer();
dm.bindAttribute(MODEL_CORRECTNESS_PROPERTIES, propertiesTable, propertiesPart);
// what is the model
// Constants
ValidateableConstantSectionPart constantsPart = new ValidateableConstantSectionPart(right,
"What is the model?", "Specify the values of declared constants.", toolkit, sectionFlags, this,
SEC_WHAT_IS_THE_MODEL);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent = 0;
gd.verticalIndent = 0;
constantsPart.getSection().setLayoutData(gd);
managedForm.addPart(constantsPart);
constantTable = constantsPart.getTableViewer();
dm.bindAttribute(MODEL_PARAMETER_CONSTANTS, constantTable, constantsPart);
Composite parametersArea = (Composite) constantsPart.getSection().getClient();
// create a composite to put the text into
Composite linksPanelToAdvancedPage = toolkit.createComposite(parametersArea);
gd = new GridData();
gd.horizontalSpan = 2;
linksPanelToAdvancedPage.setLayoutData(gd);
linksPanelToAdvancedPage.setLayout(new FillLayout(SWT.VERTICAL));
// first line with hyperlinks
Composite elementLine = toolkit.createComposite(linksPanelToAdvancedPage);
elementLine.setLayout(new FillLayout(SWT.HORIZONTAL));
// the text
toolkit.createLabel(elementLine, "Advanced parts of the model:");
// the hyperlinks
Hyperlink hyper;
hyper = toolkit.createHyperlink(elementLine, "Additional definitions,", SWT.NONE);
hyper.setHref(SEC_NEW_DEFINITION);
hyper.addHyperlinkListener(sectionExpandingAdapter);
hyper = toolkit.createHyperlink(elementLine, "Definition override,", SWT.NONE);
hyper.setHref(SEC_DEFINITION_OVERRIDE);
hyper.addHyperlinkListener(sectionExpandingAdapter);
// second line with hyperlinks
Composite elementLine2 = toolkit.createComposite(linksPanelToAdvancedPage);
elementLine2.setLayout(new FillLayout(SWT.HORIZONTAL));
hyper = toolkit.createHyperlink(elementLine2, "State constraints,", SWT.NONE);
hyper.setHref(SEC_STATE_CONSTRAINT);
hyper.addHyperlinkListener(sectionExpandingAdapter);
hyper = toolkit.createHyperlink(elementLine2, "Action constraints,", SWT.NONE);
hyper.setHref(SEC_ACTION_CONSTRAINT);
hyper.addHyperlinkListener(sectionExpandingAdapter);
hyper = toolkit.createHyperlink(elementLine2, "Additional model values.", SWT.NONE);
hyper.setHref(SEC_MODEL_VALUES);
hyper.addHyperlinkListener(sectionExpandingAdapter);
// run tab
section = FormHelper.createSectionComposite(body, "How to run?", "TLC Parameters", toolkit, sectionFlags,
getExpansionListener());
twd = new TableWrapData();
twd.colspan = 2;
twd.grabHorizontal = true;
twd.align = TableWrapData.FILL;
section.setLayoutData(twd);
final Composite howToRunArea = (Composite) section.getClient();
gl = new GridLayout(2, false);
gl.marginWidth = 0;
howToRunArea.setLayout(gl);
final ValidateableSectionPart howToRunPart = new ValidateableSectionPart(section, this, SEC_HOW_TO_RUN);
managedForm.addPart(howToRunPart);
final DirtyMarkingListener howToRunListener = new DirtyMarkingListener(howToRunPart, true);
toolkit.createLabel(howToRunArea, "System resources dedicated to TLC:");
tlcProfileCombo = new Combo(howToRunArea, SWT.READ_ONLY);
tlcProfileCombo.setItems(TLC_PROFILE_DISPLAY_NAMES);
tlcProfileCombo.addSelectionListener(howToRunListener);
tlcProfileCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(final SelectionEvent se) {
final String selectedText = tlcProfileCombo.getText();
final boolean needReset = TLC_PROFILE_LOCAL_SEPARATOR.equals(selectedText)
|| TLC_PROFILE_REMOTE_SEPARATOR.equals(selectedText);
if (needReset) {
tlcProfileCombo.select(lastSelectedTLCProfileIndex.get());
} else {
final TLCConsumptionProfile profile = TLCConsumptionProfile.getProfileWithDisplayName(selectedText);
lastSelectedTLCProfileIndex.set(tlcProfileCombo.getSelectionIndex());
programmaticallySettingWorkerParameters.set(true);
currentProfileIsAdHoc.set(false);
try {
if (profile != null) {
workers.setSelection(profile.getWorkerThreads());
maxHeapSize.setSelection(profile.getMemoryPercentage());
removeCustomTLCProfileComboItemIfPresent();
if (profile.profileIsForRemoteWorkers()) {
final String configuration = profile.getConfigurationKey();
final boolean isAdHoc = configuration
.equals(TLCConsumptionProfile.REMOTE_AD_HOC.getConfigurationKey());
moveToTopOfDistributedOptionsStack(configuration, false, isAdHoc);
if (isAdHoc) {
currentProfileIsAdHoc.set(true);
clearEmailErrors();
}
} else {
moveToTopOfDistributedOptionsStack(LAUNCH_DISTRIBUTED_NO, true, true);
clearEmailErrors();
}
} else {
moveToTopOfDistributedOptionsStack(LAUNCH_DISTRIBUTED_NO, true, true);
clearEmailErrors();
}
} finally {
programmaticallySettingWorkerParameters.set(false);
}
}
}
public void widgetDefaultSelected(final SelectionEvent se) { }
});
gd = new GridData();
gd.horizontalIndent = 30;
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
tlcProfileCombo.setLayoutData(gd);
lastSelectedTLCProfileIndex = new AtomicInteger(tlcProfileCombo.getSelectionIndex());
/*
* Workers Spinner
*/
// label workers
toolkit.createLabel(howToRunArea, "Number of worker threads:");
// field workers
workers = new Spinner(howToRunArea, SWT.NONE);
workers.addSelectionListener(howToRunListener);
workers.addFocusListener(focusListener);
workers.addListener(SWT.Verify, (e) -> {
if (!programmaticallySettingWorkerParameters.get()) {
setTLCProfileComboSelection(CUSTOM_TLC_PROFILE_DISPLAY_NAME);
}
});
gd = new GridData();
gd.horizontalIndent = 40;
gd.widthHint = 40;
workers.setLayoutData(gd);
workers.setMinimum(1);
workers.setPageIncrement(1);
workers.setToolTipText("Determines how many threads will be spawned working on the next state relation.");
workers.setSelection(TLCConsumptionProfile.LOCAL_NORMAL.getWorkerThreads());
dm.bindAttribute(LAUNCH_NUMBER_OF_WORKERS, workers, howToRunPart);
/*
* MapHeap Scale
*/
// max heap size label
toolkit.createLabel(howToRunArea, "Fraction of physical memory allocated to TLC:");
// Create a composite inside the right "cell" of the "how to run"
// section grid layout to fit the scale and the maxHeapSizeFraction
// label into a single row.
final Composite maxHeapScale = new Composite(howToRunArea, SWT.NONE);
gl = new GridLayout(2, false);
maxHeapScale.setLayout(gl);
gd = new GridData();
gd.horizontalIndent = 30;
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
maxHeapScale.setLayoutData(gd);
// field max heap size
int defaultMaxHeapSize = TLCUIActivator.getDefault().getPreferenceStore().getInt(
ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT);
maxHeapSize = new Scale(maxHeapScale, SWT.NONE);
maxHeapSize.addSelectionListener(howToRunListener);
maxHeapSize.addFocusListener(focusListener);
maxHeapSize.addListener(SWT.Selection, (e) -> {
if (!programmaticallySettingWorkerParameters.get() && !currentProfileIsAdHoc.get()) {
setTLCProfileComboSelection(CUSTOM_TLC_PROFILE_DISPLAY_NAME);
}
});
gd = new GridData();
gd.minimumWidth = 250;
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
maxHeapSize.setLayoutData(gd);
maxHeapSize.setMaximum(99);
maxHeapSize.setMinimum(1);
maxHeapSize.setPageIncrement(5);
maxHeapSize.setSelection(defaultMaxHeapSize);
maxHeapSize.setToolTipText("Specifies the heap size of the Java VM that runs TLC.");
dm.bindAttribute(LAUNCH_MAX_HEAP_SIZE, maxHeapSize, howToRunPart);
// label next to the scale showing the current fraction selected
final TLCRuntime instance = TLCRuntime.getInstance();
long memory = instance.getAbsolutePhysicalSystemMemory(defaultMaxHeapSize / 100d);
final Label maxHeapSizeFraction = toolkit.createLabel(maxHeapScale,
generateMemoryDisplayText(defaultMaxHeapSize, memory));
maxHeapSize.addPaintListener((pe) -> {
int percentage = ((Scale) pe.getSource()).getSelection();
long megabytes = TLCRuntime.getInstance().getAbsolutePhysicalSystemMemory(percentage / 100d);
maxHeapSizeFraction.setText(generateMemoryDisplayText(percentage, megabytes));
});
/*
* Distribution. Help button added by LL on 17 Jan 2013
*/
distributedOptions = new Composite(howToRunArea, SWT.NONE);
stackLayout = new StackLayout();
distributedOptions.setLayout(stackLayout);
gd = new GridData();
gd.horizontalSpan = 2;
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
distributedOptions.setLayoutData(gd);
// No distribution has no options
final Composite offComposite = new Composite(distributedOptions, SWT.NONE);
distributedOptions.setData(LAUNCH_DISTRIBUTED_NO, offComposite);
stackLayout.topControl = offComposite;
/*
* Composite wrapping number of distributed FPSet and iface when ad hoc selected
*/
final Composite adHocOptions = new Composite(distributedOptions, SWT.NONE);
gl = new GridLayout(2, false);
gl.marginWidth = 0;
adHocOptions.setLayout(gl);
distributedOptions.setData(TLCConsumptionProfile.REMOTE_AD_HOC.getConfigurationKey(), adHocOptions);
Button helpButton = HelpButton.helpButton(adHocOptions, "model/distributed-mode.html") ;
gd = new GridData();
gd.horizontalSpan = 2;
gd.horizontalAlignment = SWT.END;
helpButton.setLayoutData(gd);
/*
* Server interface/hostname (This text shows the hostname detected by the Toolbox under which TLCServer
* will listen)
*/
// label
toolkit.createLabel(adHocOptions, "Master's network address:");
// field
networkInterfaceCombo = new Combo(adHocOptions, SWT.NONE);
networkInterfaceCombo.addSelectionListener(howToRunListener);
networkInterfaceCombo.addFocusListener(focusListener);
gd = new GridData();
gd.horizontalIndent = 10;
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
networkInterfaceCombo.setLayoutData(gd);
networkInterfaceCombo.setToolTipText("IP address to which workers (and distributed fingerprint sets) will connect.");
networkInterfaceCombo.addSelectionListener(howToRunListener);
networkInterfaceCombo.addFocusListener(focusListener);
try {
final Comparator<InetAddress> comparator = new Comparator<InetAddress>() {
// Try to "guess" the best possible match.
public int compare(InetAddress o1, InetAddress o2) {
// IPv4 < IPv6 (v6 is less common even today)
if (o1 instanceof Inet4Address && o2 instanceof Inet6Address) {
return -1;
} else if (o1 instanceof Inet6Address && o2 instanceof Inet4Address) {
return 1;
}
// anything < LoopBack (loopback only useful if master and worker are on the same host)
if (!o1.isLoopbackAddress() && o2.isLoopbackAddress()) {
return -1;
} else if (o1.isLoopbackAddress() && !o2.isLoopbackAddress()) {
return 1;
}
// Public Addresses < Non-private RFC 1918 (I guess this is questionable)
if (!o1.isSiteLocalAddress() && o2.isSiteLocalAddress()) {
return -1;
} else if (o1.isSiteLocalAddress() && !o2.isSiteLocalAddress()) {
return 1;
}
return 0;
}
};
// Get all IP addresses of the host and sort them according to the Comparator.
final List<InetAddress> addresses = new ArrayList<InetAddress>();
final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
while (nets.hasMoreElements()) {
final NetworkInterface iface = (NetworkInterface) nets.nextElement();
final Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
final InetAddress addr = inetAddresses.nextElement();
// Cannot connect to a multicast address
if (addr.isMulticastAddress()) {
continue;
}
addresses.add(addr);
}
}
// Add the sorted IP addresses and select the first one which -
// according to the comparator - is assumed to be the best match.
Collections.sort(addresses, comparator);
for (InetAddress inetAddress : addresses) {
networkInterfaceCombo.add(inetAddress.getHostAddress());
}
networkInterfaceCombo.select(0);
} catch (SocketException e1) {
e1.printStackTrace();
}
dm.bindAttribute(LAUNCH_DISTRIBUTED_INTERFACE, networkInterfaceCombo, howToRunPart);
/*
* Distributed FPSet count
*/
// label
toolkit.createLabel(adHocOptions, "Number of distributed fingerprint sets (zero for single built-in set):");
// field
distributedFPSetCountSpinner = new Spinner(adHocOptions, SWT.NONE);
distributedFPSetCountSpinner.addSelectionListener(howToRunListener);
distributedFPSetCountSpinner.addFocusListener(focusListener);
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalIndent = 10;
gd.widthHint = 40;
distributedFPSetCountSpinner.setLayoutData(gd);
distributedFPSetCountSpinner.setMinimum(0);
distributedFPSetCountSpinner.setMaximum(64); // Haven't really tested this many distributed fpsets
distributedFPSetCountSpinner.setPageIncrement(1);
distributedFPSetCountSpinner.setToolTipText("Determines how many distributed FPSets will be expected by the TLCServer process");
distributedFPSetCountSpinner.setSelection(IConfigurationDefaults.LAUNCH_DISTRIBUTED_FPSET_COUNT_DEFAULT);
dm.bindAttribute(LAUNCH_DISTRIBUTED_FPSET_COUNT, distributedFPSetCountSpinner, howToRunPart);
/*
* Composite wrapping all widgets related to jclouds
*/
final Composite jcloudsOptions = new Composite(distributedOptions, SWT.NONE);
gl = new GridLayout(2, false);
gl.marginWidth = 0;
jcloudsOptions.setLayout(gl);
/*
* Distributed nodes count
*/
helpButton = HelpButton.helpButton(jcloudsOptions, "cloudtlc/index.html") ;
gd = new GridData();
gd.horizontalSpan = 2;
gd.horizontalAlignment = SWT.END;
helpButton.setLayoutData(gd);
// label
toolkit.createLabel(jcloudsOptions, "Number of compute nodes to use:");
// field
distributedNodesCountSpinner = new Spinner(jcloudsOptions, SWT.NONE);
distributedNodesCountSpinner.addSelectionListener(howToRunListener);
distributedNodesCountSpinner.addFocusListener(focusListener);
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalIndent = 10;
gd.widthHint = 40;
distributedNodesCountSpinner.setLayoutData(gd);
distributedNodesCountSpinner.setMinimum(1);
distributedNodesCountSpinner.setMaximum(64); // Haven't really tested this many distributed fpsets
distributedNodesCountSpinner.setPageIncrement(1);
distributedNodesCountSpinner.setToolTipText(
"Determines how many compute nodes/VMs will be launched. More VMs means faster results and higher costs.");
distributedNodesCountSpinner.setSelection(IConfigurationDefaults.LAUNCH_DISTRIBUTED_NODES_COUNT_DEFAULT);
dm.bindAttribute(LAUNCH_DISTRIBUTED_NODES_COUNT, distributedNodesCountSpinner, howToRunPart);
/*
* Result mail address input
*/
toolkit.createLabel(jcloudsOptions, "Result mailto addresses:");
resultMailAddressText = toolkit.createText(jcloudsOptions, "", SWT.BORDER);
resultMailAddressText.setMessage("[email protected],[email protected]");
final String resultAddressTooltip = "A list (comma-separated) of one to N email addresses to send the model checking result to.";
resultMailAddressText.setToolTipText(resultAddressTooltip);
resultMailAddressText.addKeyListener(new KeyAdapter() {
private final ModelEditor modelEditor = (ModelEditor) getEditor();
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
try {
final String text = resultMailAddressText.getText();
InternetAddress.parse(text, true);
} catch (AddressException exp) {
modelEditor.addErrorMessage("emailAddressInvalid",
"Invalid email address", getId(),
IMessageProvider.ERROR, resultMailAddressText);
return;
}
clearEmailErrors();
}
});
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.horizontalIndent = 10;
gd.minimumWidth = 330;
resultMailAddressText.setLayoutData(gd);
resultMailAddressText.addModifyListener(howToRunListener);
dm.bindAttribute(LAUNCH_DISTRIBUTED_RESULT_MAIL_ADDRESS, resultMailAddressText, howToRunPart);
distributedOptions.setData(CLOUD_CONFIGURATION_KEY, jcloudsOptions);
// add listeners propagating the changes of the elements to the changes
// of the parts to the list to be activated after the values has been loaded
dirtyPartListeners.add(commentsListener);
dirtyPartListeners.add(whatIsTheSpecListener);
dirtyPartListeners.add(whatToCheckListener);
dirtyPartListeners.add(howToRunListener);
}
private void moveToTopOfDistributedOptionsStack(final String id, final boolean enableWorker,
final boolean enableMaxHeap) {
workers.getDisplay().asyncExec(() -> {
workers.setEnabled(enableWorker);
maxHeapSize.setEnabled(enableMaxHeap);
});
moveCompositeWithIdToTopOfStack(id, distributedOptions);
distributedOptions.getParent().getParent().layout();
}
private void moveToTopOfBehaviorOptionsStack(final String id) {
moveCompositeWithIdToTopOfStack(id, behaviorOptions);
}
private void moveCompositeWithIdToTopOfStack(final String id, final Composite parent) {
final Composite composite = (Composite)parent.getData(id);
final StackLayout stackLayout = (StackLayout)parent.getLayout();
stackLayout.topControl = composite;
parent.layout();
}
private TLCConsumptionProfile getSelectedTLCProfile() {
return TLCConsumptionProfile.getProfileWithDisplayName(tlcProfileCombo.getText());
}
private void clearEmailErrors() {
((ModelEditor)getEditor()).removeErrorMessage("emailAddressInvalid", resultMailAddressText);
}
private void setTLCProfileComboSelection(final String displayName) {
final int index = tlcProfileCombo.indexOf(displayName);
if (index != -1) {
tlcProfileCombo.select(index);
if (!CUSTOM_TLC_PROFILE_DISPLAY_NAME.equals(displayName)) {
removeCustomTLCProfileComboItemIfPresent();
}
} else if (CUSTOM_TLC_PROFILE_DISPLAY_NAME.equals(displayName)) {
tlcProfileCombo.add(displayName, 1);
tlcProfileCombo.select(1);
}
lastSelectedTLCProfileIndex.set(tlcProfileCombo.getSelectionIndex());
}
private void removeCustomTLCProfileComboItemIfPresent() {
if (tlcProfileCombo.getItem(1).equals(CUSTOM_TLC_PROFILE_DISPLAY_NAME)) {
tlcProfileCombo.remove(1);
}
}
private String generateMemoryDisplayText(final int percentage, final long megabytes) {
return percentage + "%" + " (" + megabytes + " mb) ";
}
private void installTopMargin(final Composite body) {
Composite c = body;
CTabFolder tabFolder = (c instanceof CTabFolder) ? (CTabFolder)c : null;
while ((tabFolder == null) && (c.getParent() != null)) {
c = c.getParent();
tabFolder = (c instanceof CTabFolder) ? (CTabFolder)c : null;
}
if (tabFolder != null) {
final Layout l = tabFolder.getParent().getLayout();
if (l instanceof FillLayout) {
final FillLayout fl = (FillLayout)l;
fl.marginHeight = 6;
}
}
}
/**
* Interpolates based on LinearInterpolation
*/
private class Interpolator {
private final double[] yCoords, xCoords;
public Interpolator(double[] x, double[] y) {
this.xCoords = x;
this.yCoords = y;
}
public double interpolate(double x) {
for (int i = 1; i < xCoords.length; i++) {
if (x < xCoords[i]) {
return yCoords[i] - (yCoords[i] - yCoords[i - 1])
* (xCoords[i] - x) / (xCoords[i] - xCoords[i - 1]);
}
}
return 0d;
}
}
}
|
package sibtra.gps;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.TooManyListenersException;
import sibtra.imu.UtilMensajesIMU;
import sibtra.util.EligeSerial;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
public class GPSConnectionTriumph extends GPSConnection {
private static final int MAXMENSAJE = 5000;
// private static final double NULLANG = -5 * Math.PI;
/** Buffer en la que se van almacenando los trozos de mensajes que se van recibiendo */
private byte buff[] = new byte[MAXMENSAJE];
/** Indice inicial de un mensaje correcto */
private int indIni=0;
/** Indice final de un mensaje correcto */
private int indFin=-1;
/** largo del mensaje binario */
private int largoMen;
private boolean esEstandar=false;
private boolean esTexto=false;
/** Calidad del enlace con la base. NaN si no se ha recibdo paquete DL */
double calidadLink=Double.NaN;
/** Indica estado de la depuracion */
protected int nivelLog=0;
public static int ERR=0;
public static int WAR=0;
public static int INFO=15;
protected void log(int nivel,String msg) {
if(nivel==0) {
System.err.println(msg);
}
if(nivel<=nivelLog) {
System.out.println(msg);
}
}
/**
* Constructor por defecto no hace nada.
* Para usar el puerto hay que invocar a {@link #setParameters(SerialParameters)}
* y luego {@link #openConnection()}
*/
public GPSConnectionTriumph() {
super();
}
public GPSConnectionTriumph(String portName) throws SerialConnectionException {
this(portName,115200);
}
public GPSConnectionTriumph(String portName, int baudios) throws SerialConnectionException {
this(portName,baudios,ERR);
}
public GPSConnectionTriumph(String portName, int baudios, int nivelLog) throws SerialConnectionException {
super(portName,baudios);
this.nivelLog=nivelLog;
comandoGPS("%dM%dm\n");
// comandoGPS("em,,{jps/RT,nmea/GGA,jps/PO,jps/BL,nmea/GST,jps/DL,jps/ET}:0.2\n");
//GGA cada segundo, GSA,GST,VTG y DL cada segundo
// comandoGPS("%em%em,,{nmea/{GGA:0.2,GSA,GST,VTG},jps/DL}:1\n");
// comandoGPS("%em%em,,{nmea/GGA:0.2,nmea/GSA,nmea/GST,nmea/VTG}:1\n");
// comandoGPS("%em%em,,{nmea/GGA:0.2,nmea/GSA,nmea/GST,nmea/VTG,jps/DL}:1\n");
comandoGPS("%em%em,,{jps/RT,nmea/GGA,jps/PG,jps/ET}:5\n");
}
/**
* Maneja los eventos seriales {@link SerialPortEvent#DATA_AVAILABLE}.
* Si se recibe un mensaje completo del GPS {@link #nuevaCadenaNMEA(String)}
*/
public synchronized void serialEvent(SerialPortEvent e) {
if (e.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
while (is.available() != 0) {
int val = is.read();
if(indFin==(buff.length-1)) {
log(ERR,"Buffer se llenó. Resetamos");
indIni=0; indFin=-1; esEstandar=false; esTexto=false;
}
indFin++;
buff[indFin]= (byte) val;
if(esTexto) {
if ( buff[indFin] == 10 || buff[indFin]==13)
{
//mensaje de texto completo
indFin--; //quitamos caracter del salto
if(indFin<=indIni) {
indIni=0; indFin=-1; esEstandar=false; esTexto=false;
continue;
}
String menTexto=new String(buff,indIni,(indFin-indIni+1));
if(menTexto.charAt(0)=='$') {
log(INFO,"Recibida NMEA:"+menTexto);
cuentaPaquetesRecibidos++;
nuevaCadenaNMEA(menTexto);
}
else {
log(INFO,"Recibida Texto:"+menTexto);
cuentaPaquetesRecibidos++;
nuevaCadenaTexto(menTexto);
}
indIni=0; indFin=-1; esEstandar=false; esTexto=false;
}
} else if (esEstandar) {
if ( (indFin-indIni+1)==(largoMen+5) ) {
//tenemos el mensaje estandar completo
// System.out.print('e');
cuentaPaquetesRecibidos++;
nuevaCadenaEstandar();
indIni=0; indFin=-1; esEstandar=false; esTexto=false;
}
} else {
boolean sincronizado=false;
while(!sincronizado && (indFin>=indIni)) {
int larAct=indFin-indIni+1;
larAct=indFin-indIni+1;
if (larAct==1) {
if (isCabTex(indIni)) {
esTexto=true;
sincronizado=true;
}
else
if (!isCabBin(indIni)) {
//no es cabecera permitida, nos resincronizamos
indIni=0; indFin=-1; //reiniciamos el buffer
} else //por ahora puede ser binaria
sincronizado=true;
continue;
}
if (larAct==2) {
if (!isCabBin(indIni) || !isCabBin(indIni+1)) {
//no es cabecera permitida, nos resincronizamos
indIni++;
} else //por ahora puede ser binaria
sincronizado=true;
continue;
}
if (larAct==3) {
if (!isCabBin(indIni) || !isCabBin(indIni+1) || !isHexa(indIni+2)) {
//no es caracter hexa, nos resincronizamos
indIni++;
} else //por ahora puede ser binaria
sincronizado=true;
continue;
}
if (larAct==4) {
if (!isCabBin(indIni) || !isCabBin(indIni+1)
|| !isHexa(indIni+2) || !isHexa(indIni+3)) {
//no es caracter hexa, nos resincronizamos
indIni++;
} else //por ahora puede ser binaria
sincronizado=true;
continue;
}
//caso de largo 5
if (!isCabBin(indIni) || !isCabBin(indIni+1)
|| !isHexa(indIni+2) || !isHexa(indIni+3) || !isHexa(indIni+4)) {
//no es caracter hexa, nos resincronizamos
indIni++;
} else { //estamos seguros que es binaria
sincronizado=true;
esEstandar=true;
largoMen=largo();
}
}
}
}
} catch (IOException ioe) {
log(ERR,"\nError al recibir los datos");
} catch (Exception ex) {
log(ERR,"\nGPSConnection Error al procesar >"+buff+"< : " + ex.getMessage());
ex.printStackTrace();
indIni=-1;
}
}
}
private int largo() {
int lar=0;
int indAct=indIni+2;
if(buff[indAct]<=(byte)'9') lar+=32*(buff[indAct]-(byte)'0');
else lar+=32*(buff[indAct]-(byte)'A'+10);
indAct++;
if(buff[indAct]<=(byte)'9') lar+=16*(buff[indAct]-(byte)'0');
else lar+=16*(buff[indAct]-(byte)'A'+10);
indAct++;
if(buff[indAct]<=(byte)'9') lar+=(buff[indAct]-(byte)'0');
else lar+=(buff[indAct]-(byte)'A'+10);
return lar;
}
private boolean isHexa(int ind) {
return ((buff[ind]>=(byte)'0') && (buff[ind]<=(byte)'9')) || ((buff[ind]>=(byte)'A' && buff[ind]<=(byte)'F')) ;
}
private boolean isCabBin(int ind) {
return ((buff[ind]>=48) && (buff[ind]<=126)) ;
}
private boolean isCabTex(int ind) {
return ((buff[ind]>=33) && (buff[ind]<=47)) ;
}
/** Se invoca cuando se recibe una cadena de texto que no es NMEA */
void nuevaCadenaTexto(String mensaje) {
//TODO considerar mensajes de texto propietarios GREIS
}
/** Se invoca cuando se recibe una cadena binaria propietaria GREIS */
void nuevaCadenaEstandar() {
int larMen=indFin-indIni+1;
//iterpretamos los mensajes
/* RT [~~]=126
* struct RcvTime {5} {
u4 tod; // Tr modulo 1 day (86400000 ms) [ms]
u1 cs; // Checksum
};
*/
if(buff[indIni]==(byte)'~' && buff[indIni+1]==(byte)'~') {
if(larMen!=(5+5)) {
log(WAR,"El mensaje RT no tienen el tamaño correcto "+larMen+" Ignoramos mensaje");
return;
}
//comprobamos checksum
byte csc=(byte)checksum8(buff, indIni, larMen-1);
if(csc!=buff[indFin]) {
log(WAR,"Error checksum "+csc+"!="+buff[indFin]+" Ignoramos mensaje");
return;
}
//el checksum es correcto
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(buff, indIni+5, 4);
bb.rewind();
int tod=bb.getInt();
log(INFO,"\n\n\nMensaje RT: tod="+tod);
return;
}
/* [::](ET) Epoch Time5
struct EpochTime {5} {
u4 tod; // Tr modulo 1 day (86400000 ms) [ms]
u1 cs; // Checksum
};
*/
if(buff[indIni]==(byte)':' && buff[indIni+1]==(byte)':') {
if(larMen!=(5+5)) {
log(WAR,"El mensaje ET no tienen el tamaño correcto "+larMen+" Ignoramos mensaje");
return;
}
//comprobamos checksum
byte csc=(byte)checksum8(buff, indIni, larMen-1);
if(csc!=buff[indFin]) {
log(WAR,"Error checksum "+csc+"!="+buff[indFin]+" Ignoramos mensaje");
return;
}
//el checksum es correcto
ByteBuffer bb = ByteBuffer.allocate(4);
bb.put(buff, indIni+5, 4);
bb.order(ByteOrder.LITTLE_ENDIAN);
int tod=bb.getInt(0);
log(INFO,"Mensaje ET: tod="+tod);
return;
}
/* [PO] Cartesian Position
struct Pos {30} {
f8 x, y, z; // Cartesian coordinates [m]
Position SEP6 [m]
f4 sigma; //
u1 solType; // Solution type
u1 cs; // Checksum
};
*/
if(buff[indIni]==(byte)'P' && buff[indIni+1]==(byte)'O') {
if(larMen!=(5+30)) {
log(WAR,"El mensaje PO no tienen el tamaño correcto "+larMen+" Ignoramos mensaje");
return;
}
//comprobamos checksum
byte csc=(byte)checksum8(buff, indIni, larMen-1);
if(csc!=buff[indFin]) {
log(WAR,"Error checksum "+csc+"!="+buff[indFin]+" Ignoramos mensaje");
return;
}
//el checksum es correcto
ByteBuffer bb = ByteBuffer.allocate(30);
bb.put(buff, indIni+5, 30);
bb.rewind();
bb.order(ByteOrder.LITTLE_ENDIAN);
double x=bb.getDouble();
double y=bb.getDouble();
double z=bb.getDouble();
float sigma=bb.getFloat();
byte solType=bb.get();
log(INFO,"Mensaje PO: ("+x+","+y+","+z+") sigma="+sigma+" solType="+solType);
return;
}
/*
* [PG] Geodetic Position
struct GeoPos {30} {
f8 lat; // Latitude [rad]
f8 lon; // Longitude [rad]
f8 alt; // Ellipsoidal height [m]
f4 pSigma; // Position SEP [m]
u1 solType; // Solution type
u1 cs; // Checksum
};
*/
if(buff[indIni]==(byte)'P' && buff[indIni+1]==(byte)'G') {
if(larMen!=(5+30)) {
log(WAR,"El mensaje PG no tienen el tamaño correcto "+larMen+" Ignoramos mensaje");
return;
}
//comprobamos checksum
byte csc=(byte)checksum8(buff, indIni, larMen-1);
if(csc!=buff[indFin]) {
log(WAR,"Error checksum PG "+csc+"!="+buff[indFin]+" Ignoramos mensaje");
return;
}
//el checksum es correcto
ByteBuffer bb = ByteBuffer.allocate(30);
bb.put(buff, indIni+5, 30);
bb.rewind();
bb.order(ByteOrder.LITTLE_ENDIAN);
double lat=bb.getDouble();
double lon=bb.getDouble();
double alt=bb.getDouble();
float sigma=bb.getFloat();
byte solType=bb.get();
log(INFO,"Mensaje PG: ("+lat+","+lon+","+alt+") sigma="+sigma+" solType="+solType);
return;
}
/* [BL] Base Line
struct BaseLine {34} {
f8 x, y, z; // Calculated baseline vector coordinates [m]
f4 sigma; // Baseline Spherical Error Probable (SEP) [m]
u1 solType; // Solution type
i4 time; // receiver time of the baseline estimate [s]
u1 cs; // Checksum
};
*/
if(buff[indIni]==(byte)'B' && buff[indIni+1]==(byte)'L') {
if(larMen!=(5+34)) {
log(WAR,"El mensaje BL no tienen el tamaño correcto "+larMen+" Ignoramos mensaje");
return;
}
//comprobamos checksum
byte csc=(byte)checksum8(buff, indIni, larMen-1);
if(csc!=buff[indFin]) {
log(WAR,"Error checksum "+csc+"!="+buff[indFin]+" Ignoramos mensaje");
return;
}
//el checksum es correcto
ByteBuffer bb = ByteBuffer.allocate(34);
bb.put(buff, indIni+5, 34);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.rewind();
double x=bb.getDouble();
double y=bb.getDouble();
double z=bb.getDouble();
float sigma=bb.getFloat();
byte solType=bb.get();
int time=bb.getInt();
log(INFO,"Mensaje BL: ("+x+","+y+","+z+") sigma="+sigma+" solType="+solType
+" time="+time);
return;
}
//Mensaje de texto DL
// [DL] Data Link Status
// This message displays the status of the data links associated with the corresponding
// serial ports/modem.
// # Format Description
// 1 DLINK Title of the message
// able only if this number is non-zero. Otherwise the total number of
// data links value is immediately followed by the checksum.
// 3 ({%C,%C,%S, Group of fields associated with the given data link (note that the
// %3D,%4D,%4 total number of such groups is determined by the previous field).
// D,%.2F}) These fields are
// - Data link identifier (refer to Table 4-8 below).
// - Reference station identifier.
// - Time [in seconds] elapsed since receiving last message (maxi-
// - Number of received messages (between 0001 and 9999). If no
// message has been received, this data field contains zero.
// - Number of corrupt messages (between 0001 and 9999). If no cor-
// rupt messages have been detected, this data field is set to zero.
// - Data link quality in percent (0-100);
// 4 @%2X Checksum
// Table 4-8. Data Link Identifiers
// Id Corresponding Stream
// EJemplo:DL02B,DLINK,1,{D,C,0000,999,0000,0000,100.00}@62
// VEMOS QUE FALTA LA COMA ANTES DE LA ARROBA^
if(buff[indIni]==(byte)'D' && buff[indIni+1]==(byte)'L') {
if(larMen<(5+9)) {
log(WAR,"El mensaje DL no tienen el tamaño necesario "+larMen+". Ignoramos mensaje");
return;
}
//convertimos a string
try {
String cadena=new String(buff,indIni,larMen);
int posArroba=cadena.indexOf('@');
String CS=cadena.substring(posArroba+1);
//TODO comprobamos checksum
// int csc=checksum8(buff, indIni, larMen-2);
// if( csc!=Byte.valueOf(CS,16) ) {
// log(WAR,"Error checksum "+csc+"!="+CS+". Ignoramos mensaje");
// return;
String[] campos=cadena.substring(0, posArroba).split(",");
//el checksum es correcto
if(campos.length<4) {
log(WAR,"DL no tiene los campos mínimos necesarios. Ignoramos");
return;
}
if(!campos[1].equals("DLINK")) {
log(WAR,"DL no tiene título DLINK. Ignoramos");
return;
}
int la=Integer.valueOf(campos[2]);
int ca=3;
while(la>0) {
while(campos[ca].charAt(0)!='{') ca++;
char tipo=campos[ca++].charAt(1);
char decoId=campos[ca++].charAt(0);
String stationID=campos[ca++];
int timeLast=Integer.valueOf(campos[ca++]);
int numOK=Integer.valueOf(campos[ca++]);
int numCorrup=Integer.valueOf(campos[ca++]);
//TODO posible problema con }
double quality=Double.valueOf(campos[ca].substring(0,campos[ca].lastIndexOf('}')));
ca++;
log(INFO,String.format("DL: %c %c %s %d %d %d %f"
,decoId, tipo, stationID, timeLast, numOK, numCorrup,quality ));
if(tipo=='D' && numOK>0)
calidadLink=quality;
la
}
} catch (Exception e) {
log(WAR,"Error parseando campo DL:"+e.getMessage()+" Ignoramos");
}
return;
}
//contenido del mensaje en crudo
System.out.print("Binaria ("+larMen+"):"+new String(buff,indIni,5)+" >");
for(int i=indIni+5; i<=indFin; i++)
if (buff[i]<32 || buff[i]>126)
//no imprimible
System.out.print('.');
else
System.out.print((char)buff[i]);
log(INFO,"< >"+UtilMensajesIMU.hexaString(buff, indIni+5, larMen-5)+"<");
}
public static int checksum8(byte[] buff, int ini, int largo) {
int res=0;
for(int i=ini; i<ini+largo; i++)
res= (((res<<2)|(res>>>6)) ^ buff[i]) & 0xff; //nos aseguramos parte alta de int a 0
return ((res<<2)|(res>>>6))& 0xff;
}
/**
* @param comando comando de texto a enviar al GPS
*/
public void comandoGPS(String comando) {
try {
os.write(comando.getBytes());
log(INFO,"Enviado Comando:>"+comando+"<");
} catch (Exception e) {
log(WAR,"Problema al enviar comando Triumph:"+e.getMessage());
}
}
/** Calidad del enlace con la base */
public double getCalidadLink() {
return calidadLink;
}
/**
* @param args
*/
public static void main(String[] args) {
GPSConnectionTriumph gpsC;
try {
gpsC=new GPSConnectionTriumph("/dev/ttyUSB0",115200,INFO);
// gpsC.comandoGPS("%DL%out,,jps/DL\n");
// try { Thread.sleep(5000); } catch (Exception e) {}
// gpsC.comandoGPS("em,,{jps/RT,nmea/GGA,jps/PO,jps/BL,nmea/GST,jps/ET}:10\n");
try { Thread.sleep(10000000); } catch (Exception e) {}
// gpsC.comandoGPS("dm\n");
} catch (Exception e) {
System.err.println("Problema al usar el GPS:"+e.getMessage());
}
System.exit(0);
}
}
|
package at.bitandart.zoubek.mervin.util.vis;
import java.text.DecimalFormat;
import org.eclipse.jface.viewers.ColumnLabelProvider;
public abstract class NumericColumnLabelProvider extends ColumnLabelProvider {
private DecimalFormat decimalFormat;
public NumericColumnLabelProvider() {
super();
decimalFormat = new DecimalFormat("
}
/**
* @param decimalFormat
* the format to use for converting the value to a {@link String}
* .
*/
public NumericColumnLabelProvider(DecimalFormat decimalFormat) {
super();
this.decimalFormat = decimalFormat;
}
@Override
public String getText(Object element) {
if (hasValue(element)) {
return decimalFormat.format(getValue(element));
}
return null;
}
public abstract float getValue(Object element);
public abstract boolean hasValue(Object element);
}
|
package com.redhat.ceylon.eclipse.code.search;
import static com.redhat.ceylon.eclipse.code.editor.Navigation.gotoLocation;
import static com.redhat.ceylon.eclipse.code.preferences.CeylonPreferenceInitializer.FULL_LOC_SEARCH_RESULTS;
import static com.redhat.ceylon.eclipse.code.search.CeylonSearchResultTreeContentProvider.LEVEL_FILE;
import static com.redhat.ceylon.eclipse.code.search.CeylonSearchResultTreeContentProvider.LEVEL_FOLDER;
import static com.redhat.ceylon.eclipse.code.search.CeylonSearchResultTreeContentProvider.LEVEL_MODULE;
import static com.redhat.ceylon.eclipse.code.search.CeylonSearchResultTreeContentProvider.LEVEL_PACKAGE;
import static com.redhat.ceylon.eclipse.code.search.CeylonSearchResultTreeContentProvider.LEVEL_PROJECT;
import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CONFIG_LABELS;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.FLAT_MODE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.FOLDER_MODE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.MODULE_MODE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.PACKAGE_MODE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.PROJECT_MODE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.TREE_MODE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.UNIT_MODE;
import static com.redhat.ceylon.eclipse.util.EditorUtil.getPreferences;
import static org.eclipse.jface.action.IAction.AS_CHECK_BOX;
import static org.eclipse.search.ui.IContextMenuConstants.GROUP_VIEWER_SETUP;
import static org.eclipse.ui.dialogs.PreferencesUtil.createPreferenceDialogOn;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.search.JavaSearchEditorOpener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
import org.eclipse.search.ui.text.Match;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.texteditor.ITextEditor;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.preferences.CeylonPreferencePage;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
public class CeylonSearchResultPage extends AbstractTextSearchViewPage {
private CeylonStructuredContentProvider contentProvider;
private IPropertyChangeListener propertyChangeListener;
@Override
public void init(IPageSite site) {
super.init(site);
propertyChangeListener =
new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
getViewer().refresh();
}
};
getPreferences().addPropertyChangeListener(propertyChangeListener);
}
@Override
public void dispose() {
super.dispose();
if (propertyChangeListener!=null) {
getPreferences().removePropertyChangeListener(propertyChangeListener);
propertyChangeListener = null;
}
}
public CeylonSearchResultPage() {
super(FLAG_LAYOUT_FLAT|FLAG_LAYOUT_TREE);
setElementLimit(50);
initGroupingActions();
}
@Override
protected void clear() {
if (contentProvider!=null) {
contentProvider.clear();
}
//getViewer().refresh();
}
private void configureViewer(StructuredViewer viewer) {
viewer.setContentProvider(contentProvider);
viewer.setLabelProvider(new MatchCountingLabelProvider(this));
viewer.setComparator(new CeylonViewerComparator());
}
@Override
protected void configureTableViewer(final TableViewer viewer) {
contentProvider =
new CeylonSearchResultContentProvider(viewer, this);
configureViewer(viewer);
}
@Override
protected void configureTreeViewer(TreeViewer viewer) {
contentProvider =
new CeylonSearchResultTreeContentProvider(viewer, this);
configureViewer(viewer);
}
@Override
protected void elementsChanged(Object[] elements) {
if (contentProvider!=null) {
contentProvider.elementsChanged(elements);
}
getViewer().refresh();
}
@Override
protected void showMatch(Match match,
int offset, int length,
boolean activate)
throws PartInitException {
Object elem = match.getElement();
if (elem instanceof CeylonElement) {
open((CeylonElement) elem,
offset, length, activate);
}
else if (elem instanceof IJavaElement) {
open((IJavaElement) elem, match,
offset, length, activate);
}
}
private void open(IJavaElement element, Match match,
int offset, int length,
boolean activate)
throws PartInitException {
IFile file = (IFile) element.getResource();
if (file==null) {
//a binary archive
IEditorPart editor =
new JavaSearchEditorOpener().openMatch(match);
if (editor instanceof ITextEditor) {
((ITextEditor) editor).selectAndReveal(offset, length);
}
}
else {
//a source file in the workspace
IWorkbenchPage page = getSite().getPage();
if (offset >= 0 && length != 0) {
openAndSelect(page, file,
offset, length, activate);
}
else {
open(page, file, activate);
}
}
}
private void open(CeylonElement element,
int offset, int length,
boolean activate)
throws PartInitException {
IFile file = element.getFile();
if (file==null) {
String path = element.getVirtualFile().getPath();
gotoLocation(new Path(path), offset, length);
}
else {
IWorkbenchPage page = getSite().getPage();
if (offset>=0 && length!=0) {
openAndSelect(page, file,
offset, length, activate);
}
else {
open(page, file, activate);
}
}
}
private static final String GROUP_LAYOUT =
PLUGIN_ID + ".search.CeylonSearchResultPage.layout";
private static final String GROUP_GROUPING =
PLUGIN_ID + ".search.CeylonSearchResultPage.grouping";
private static final String KEY_GROUPING =
PLUGIN_ID + ".search.CeylonSearchResultPage.grouping";
private GroupAction fGroupFileAction;
private GroupAction fGroupPackageAction;
private GroupAction fGroupModuleAction;
private GroupAction fGroupFolderAction;
private GroupAction fGroupProjectAction;
private LayoutAction fLayoutFlatAction;
private LayoutAction fLayoutTreeAction;
private int fCurrentGrouping;
private void initGroupingActions() {
fGroupProjectAction =
new GroupAction("Project",
"Group by Project",
PROJECT_MODE, LEVEL_PROJECT);
fGroupFolderAction =
new GroupAction("Source Folder",
"Group by Source Folder",
FOLDER_MODE, LEVEL_FOLDER);
fGroupModuleAction =
new GroupAction("Module",
"Group by Module",
MODULE_MODE, LEVEL_MODULE);
fGroupPackageAction =
new GroupAction("Package",
"Group by Package",
PACKAGE_MODE, LEVEL_PACKAGE);
fGroupFileAction =
new GroupAction("Source File",
"Group by Source File",
UNIT_MODE, LEVEL_FILE);
fLayoutTreeAction =
new LayoutAction("Tree",
"Show as Tree",
TREE_MODE, FLAG_LAYOUT_TREE);
fLayoutFlatAction =
new LayoutAction("Flat",
"Show as List",
FLAT_MODE, FLAG_LAYOUT_FLAT);
}
private void updateGroupingActions() {
fGroupProjectAction.setChecked(fCurrentGrouping == LEVEL_PROJECT);
fGroupFolderAction.setChecked(fCurrentGrouping == LEVEL_FOLDER);
fGroupModuleAction.setChecked(fCurrentGrouping == LEVEL_MODULE);
fGroupPackageAction.setChecked(fCurrentGrouping == LEVEL_PACKAGE);
fGroupFileAction.setChecked(fCurrentGrouping == LEVEL_FILE);
}
private void updateLayoutActions() {
int layout = getLayout();
fLayoutFlatAction.setChecked(layout==FLAG_LAYOUT_FLAT);
fLayoutTreeAction.setChecked(layout==FLAG_LAYOUT_TREE);
}
@Override
protected void fillToolbar(IToolBarManager tbm) {
super.fillToolbar(tbm);
tbm.appendToGroup(GROUP_VIEWER_SETUP,
new Separator(GROUP_LAYOUT));
tbm.appendToGroup(GROUP_LAYOUT, fLayoutFlatAction);
tbm.appendToGroup(GROUP_LAYOUT, fLayoutTreeAction);
updateLayoutActions();
if (getLayout() != FLAG_LAYOUT_FLAT) {
tbm.appendToGroup(GROUP_VIEWER_SETUP,
new Separator(GROUP_GROUPING));
tbm.appendToGroup(GROUP_GROUPING, fGroupProjectAction);
tbm.appendToGroup(GROUP_GROUPING, fGroupFolderAction);
tbm.appendToGroup(GROUP_GROUPING, fGroupModuleAction);
tbm.appendToGroup(GROUP_GROUPING, fGroupPackageAction);
tbm.appendToGroup(GROUP_GROUPING, fGroupFileAction);
try {
fCurrentGrouping =
getSettings().getInt(KEY_GROUPING);
}
catch (NumberFormatException nfe) {
//missing key
fCurrentGrouping = LEVEL_PROJECT;
}
contentProvider.setLevel(fCurrentGrouping);
updateGroupingActions();
}
getSite().getActionBars().updateActionBars();
}
@Override
protected void fillContextMenu(IMenuManager mgr) {
super.fillContextMenu(mgr);
MenuManager submenu = new MenuManager("Find");
submenu.setActionDefinitionId(CeylonEditor.FIND_MENU_ID);
ISelection selection = getViewer().getSelection();
submenu.add(new FindReferencesAction(this, selection));
submenu.add(new FindAssignmentsAction(this, selection));
submenu.add(new FindSubtypesAction(this, selection));
submenu.add(new FindRefinementsAction(this, selection));
mgr.add(submenu);
}
@Override
public void makeContributions(IMenuManager menuManager,
IToolBarManager toolBarManager,
IStatusLineManager statusLineManager) {
final IPreferenceStore prefs = getPreferences();
Action showLocAction =
new Action("Show Full Paths", AS_CHECK_BOX) {
@Override
public void run() {
prefs.setValue(FULL_LOC_SEARCH_RESULTS, isChecked());
getViewer().refresh();
}
};
showLocAction.setChecked(prefs.getBoolean(FULL_LOC_SEARCH_RESULTS));
menuManager.add(showLocAction);
super.makeContributions(menuManager,
toolBarManager,
statusLineManager);
Action configureAction =
new Action("Configure Labels...",
CeylonPlugin.getInstance().getImageRegistry()
.getDescriptor(CONFIG_LABELS)) {
@Override
public void run() {
createPreferenceDialogOn(getSite().getShell(),
CeylonPreferencePage.ID,
new String[] { CeylonPreferencePage.ID },
null).open();
}
};
menuManager.add(configureAction);
}
private class GroupAction extends Action {
private int fGrouping;
public GroupAction(String label, String tooltip,
String imageKey, int grouping) {
super(label);
setToolTipText(tooltip);
setImageDescriptor(CeylonPlugin.getInstance()
.getImageRegistry()
.getDescriptor(imageKey));
fGrouping = grouping;
}
@Override
public boolean isEnabled() {
return getLayout()!= FLAG_LAYOUT_FLAT;
}
@Override
public void run() {
setGrouping(fGrouping);
}
}
private class LayoutAction extends Action {
private int layout;
public LayoutAction(String label, String tooltip,
String imageKey, int layout) {
super(label);
setToolTipText(tooltip);
setImageDescriptor(CeylonPlugin.getInstance()
.getImageRegistry()
.getDescriptor(imageKey));
this.layout = layout;
}
@Override
public void run() {
setLayout(layout);
setChecked(getLayout()==layout);
}
}
void setGrouping(int grouping) {
fCurrentGrouping= grouping;
contentProvider.setLevel(grouping);
updateGroupingActions();
getSettings().put(KEY_GROUPING, fCurrentGrouping);
getViewPart().updateLabel();
}
}
|
package eu.cloudscaleproject.env.spotter;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Platform;
import eu.cloudscaleproject.env.common.Unzip;
public class BuiltinServerController
{
private static HashMap<String, BuiltinServerController> mapControllers = new HashMap<>();
public static BuiltinServerController getInstance(IProject project)
{
if (project == null) return null;
if (!mapControllers.containsKey(project.getName()))
{
BuiltinServerController controller = new BuiltinServerController(project);
mapControllers.put(project.getName(), controller);
}
return mapControllers.get(project.getName());
}
private IProject project;
private static String SERVER_ZIP_PACK = "resources/server/ds-server.zip";
private static String SERVER_FOLDER = "ds-server";
private static String SERVER_JAR = "ds-server.jar";
private Logger logger = Logger.getLogger(BuiltinServerController.class.getName());
private File serverJar;
private Process serverProcess;
private LinkedList<String> outputBuffer = new LinkedList<String>();
private StreamRedirectThread streamRedirectThread;
private Document logDocument = new PlainDocument();
private int serverPort = 8080;
private BuiltinServerController(IProject project)
{
this.project = project;
logger.addHandler(new Handler()
{
@Override
public void publish(LogRecord record)
{
serverLog(record.getLevel(), record.getMessage());
}
@Override public void flush() { }
@Override public void close() throws SecurityException { }
});
}
public IProject getProject()
{
return project;
}
public List<String> getServerOutput()
{
return Collections.unmodifiableList(this.outputBuffer);
}
public void initialize() throws IOException
{
if (serverJar != null)
{
return;
}
serverJar = getServerJar();
if (serverJar == null)
{
logger.warning("Server initialization failed.");
return;
}
logger.info("Builtin server persisted in :: "+serverJar.getPath());
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
if (isServerRunning())
stopServer();
}
});
}
private File getServerJar()
{
File workspaceFolder = Platform.getLocation().toFile();
File serverFolder = new File(workspaceFolder, SERVER_FOLDER);
File serverJar = new File(serverFolder, SERVER_JAR);
if (!serverJar.exists())
{
try
{
logger.info("Unpacking DynamicSpotter server to > " + serverFolder.getPath());
// Unpack server
InputStream is = getClass().getClassLoader().getResourceAsStream(SERVER_ZIP_PACK);
Unzip.unZip(is, serverFolder.getPath());
}
catch (IOException e)
{
logger.severe("Failed to unpack DynamicSpotter server : " + e.getMessage());
e.printStackTrace();
return null;
}
}
return serverJar;
}
public int getServerPort()
{
return serverPort;
}
public void setServerPort(int serverPort)
{
if (isServerRunning())
{
throw new IllegalStateException("Can't set server port - server is aalready running");
}
this.serverPort = serverPort;
}
public void stopServer()
{
logger.info("Stopping DynamicSpotter server...");
if (this.serverProcess == null)
return;
if (isServerRunning())
{
this.serverProcess.destroy();
this.serverProcess = null;
}
}
public boolean isServerRunning()
{
if (serverProcess == null)
return false;
try
{
serverProcess.exitValue();
return false;
}
catch (Exception e)
{
return true;
}
}
public void startServer() throws IOException
{
startServer (8080);
}
public void startServer(int port) throws IOException
{
logger.info("Starting DynamicSpotter server (port="+port+")...");
if (isServerRunning())
{
logger.info("DynamicSpotter Server is already running.");
throw new IllegalStateException("Server is already running.");
}
if (serverJar == null)
{
initialize();
}
String command = String.format("java -jar %s start port=%s", this.serverJar.getName(), port);
this.serverProcess = Runtime.getRuntime().exec(command, null, this.serverJar.getParentFile());
this.serverPort = port;
streamRedirectThread = new StreamRedirectThread(serverProcess.getInputStream(), logger);
streamRedirectThread.start();
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run()
{
if (serverProcess != null) serverProcess.destroy();
}
});
}
public Process getServerProcess()
{
return serverProcess;
}
public Document getDocument()
{
return logDocument;
}
private void serverLog (Level level, String log)
{
try
{
logDocument.insertString(logDocument.getLength(), log + "\n", null);
}
catch (BadLocationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static class StreamRedirectThread extends Thread
{
private InputStream inputStream;
private Logger logger;
public StreamRedirectThread(InputStream is, Logger logger)
{
this.logger = logger;
this.inputStream = is;
}
@Override
public void run()
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try
{
String line;
while ((line = reader.readLine()) != null)
{
Level level = Level.INFO;
if (line.contains(" WARN "))
level = Level.WARNING;
else if (line.contains(" SEVERE "))
level = Level.SEVERE;
logger.log(level, "[SERVER OUTPUT] " + line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
|
package eu.hyvar.feature.validation.adapter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EObjectValidator;
import org.eclipse.emf.validation.model.EvaluationMode;
import org.eclipse.emf.validation.model.IConstraintStatus;
import org.eclipse.emf.validation.service.IBatchValidator;
import org.eclipse.emf.validation.service.ModelValidationService;
import eu.hyvar.evolution.HyEvolutionUtil;
import eu.hyvar.evolution.HyLinearTemporalElement;
import eu.hyvar.evolution.HyName;
import eu.hyvar.evolution.HyNamedElement;
import eu.hyvar.evolution.HyTemporalElement;
import eu.hyvar.feature.HyFeature;
import eu.hyvar.feature.HyFeatureAttribute;
import eu.hyvar.feature.HyFeatureChild;
import eu.hyvar.feature.HyGroup;
import eu.hyvar.feature.HyGroupComposition;
import eu.hyvar.feature.HyRootFeature;
import eu.hyvar.feature.HyVersion;
import eu.hyvar.feature.impl.HyFeatureImpl;
import eu.hyvar.feature.impl.HyFeatureModelImpl;
import eu.hyvar.feature.impl.HyGroupImpl;
/**
* An adapter that plugs the EMF Model Validation Service API into the
* {@link org.eclipse.emf.ecore.EValidator} API.
*/
public class EValidatorAdapter extends EObjectValidator {
private List<Date> dates = null;
/**
* Model Validation Service interface for batch validation of EMF elements.
*/
private final IBatchValidator batchValidator;
/**
* Initializes me.
*/
public EValidatorAdapter() {
super();
batchValidator = ModelValidationService.getInstance().newValidator(EvaluationMode.BATCH);
batchValidator.setIncludeLiveConstraints(true);
batchValidator.setReportSuccesses(false);
}
@Override
public boolean validate(EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate(eObject.eClass(), eObject, diagnostics, context);
}
/**
* Implements validation by delegation to the EMF validation framework.
*/
@Override
public boolean validate(EClass eClass, EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context) {
// first, do whatever the basic EcoreValidator does
super.validate(eClass, eObject, diagnostics, context);
IStatus status = Status.OK_STATUS;
checkConstraints(eClass, eObject, diagnostics, context);
// no point in validating if we can't report results
if (diagnostics != null) {
// if EMF Mode Validation Service already covered the sub-tree,
// which it does for efficient computation and error reporting,
// then don't repeat (the Diagnostician does the recursion
// externally). If there is no context map, then we can't
// help it
if (!hasProcessed(eObject, context)) {
status = batchValidator.validate(eObject, new NullProgressMonitor());
processed(eObject, context, status);
appendDiagnostics(status, diagnostics);
}
}
return status.isOK();
}
private void addErrorMessage(EClass eClass, EObject eObject, DiagnosticChain diagnostics, String message) {
diagnostics.add(new BasicDiagnostic(Diagnostic.ERROR, eClass.getName(), 0, message, new Object[] { eObject }));
}
/**
* Checks if valid since and valid until are equal at a given timestamp.
* Is a date is null, the date will be treated like no restriction
* @param date
* @param validSince
* @param validUntil
* @return true if since < until or else false
*/
private boolean validSinceUntilCombinationAtTimestamp(Date date, Date validSince, Date validUntil) {
return count(date, validSince, validUntil) == 1 ? true : false;
}
/**
* Checks if validSince and/or validUntil is/are null and returns
* corresponding to that situation 1 or 0 depending whether date is valid
* between validSince and validUntil or not
*
* @param Use
* this variable for the date from model
* @param validSince
* @param validUntil
* @return Returns 1 if model is valid at date or 0 if not
*/
private int count(Date date, Date validSince, Date validUntil) {
if (validSince == null && validUntil == null) {
return 1;
}
if (validSince == null && validUntil != null) {
if (date.before(validUntil))
return 1;
}
if (validSince != null && validUntil == null) {
if (date.after(validSince) || date.equals(validSince))
return 1;
}
if (validSince != null && validUntil != null) {
if ((date.after(validSince) || date.equals(validSince)) && date.before(validUntil))
return 1;
}
return 0;
}
/**
* Checks constraints for each HyFeature defined in the model.
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkHyFeatureConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
HyFeatureImpl feature = (HyFeatureImpl) eObject;
EList<HyGroupComposition> compositions = feature.getGroupMembership();
EList<HyVersion> versions = feature.getVersions();
EList<HyName> names = feature.getNames();
EList<HyFeatureAttribute> attributes = feature.getAttributes();
// Version Constraint(s)
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
int count = 0;
for (int j = 0; j < versions.size(); j++) {
HyVersion version = versions.get(j);
Date validSince = version.getValidSince();
Date validUntil = version.getValidUntil();
count += count(date, validSince, validUntil);
}
if (count > 1)
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has more than one version at timestamp " + date.toString());
// if feature has no valid versions, feature cannot be valid either
if (count == 0 && versions.size() > 0 && validSinceUntilCombinationAtTimestamp(date, feature.getValidSince(), feature.getValidUntil())) {
addErrorMessage(eClass, eObject, diagnostics, eClass.getName() + " has no valid versions but is valid at timestamp " + date.toString()
+ ". This is not possible");
}
}
// Group Constraint
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
int count = 0;
for (int j = 0; j < compositions.size(); j++) {
HyGroupComposition composition = compositions.get(j);
Date validSince = composition.getValidSince();
Date validUntil = composition.getValidUntil();
count += count(date, validSince, validUntil);
}
if (count > 1)
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has more than group membership at timestamp " + date.toString());
}
// Name Constraint
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
int count = 0;
for (int j = 0; j < names.size(); j++) {
HyName name = names.get(j);
Date validSince = name.getValidSince();
Date validUntil = name.getValidUntil();
count += count(date, validSince, validUntil);
}
if (count > 1) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has more than one name at timestamp " + date.toString());
}
}
// Attribute Constraint
for(int i = 0; i < dates.size(); i++){
Date date = dates.get(i);
int count = 0;
for(int j = 0; j < attributes.size(); j++){
HyFeatureAttribute attribute = attributes.get(j);
Date validSince = attribute.getValidSince();
Date validUntil = attribute.getValidUntil();
count += count(date, validSince, validUntil);
}
}
}
/**
* Checks constraints for each HyGroup defined in the model.
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkHyGroupConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
HyGroupImpl group = (HyGroupImpl) eObject;
EList<HyGroupComposition> compositions = group.getParentOf();
// special case if no date exist in model
if(compositions.size() > 1 && dates.isEmpty())
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has more than one GroupComposition at any time. Please define valid since and valid until for each composition");
// Check group compositions
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
int count = 0;
for (int j = 0; j < compositions.size(); j++) {
HyGroupComposition composition = compositions.get(j);
Date validSince = composition.getValidSince();
Date validUntil = composition.getValidUntil();
count += count(date, validSince, validUntil);
}
if (count > 1) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has more than one GroupComposition at timestamp " + date.toString());
}
if(count >= 1){
boolean validAtTimeStamp = validSinceUntilCombinationAtTimestamp(date, group.getValidSince(),
group.getValidUntil());
if (!validAtTimeStamp) {
addErrorMessage(eClass, eObject, diagnostics, eClass.getName() + " is invalid at timestamp "
+ date.toString() + " but one composition is valid.");
}
}
if(count == 0){
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has no GroupComposition at timestamp " + date.toString());
}
}
// Constraint Group can only be in one FeatureChild at one timestamp
EList<HyFeatureChild> childrenOf = group.getChildOf();
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
if (group.getValidSince() != null) {
int count = 0;
for (int j = 0; j < childrenOf.size(); j++) {
if (childrenOf.get(j).getValidSince() != null) {
if (date.equals(childrenOf.get(j).getValidSince())) {
count++;
}
}
}
if (count > 1)
addErrorMessage(eClass, eObject, diagnostics, eClass.getName()
+ " is children in more than one HyFeatureChild at timestamp " + date.toString());
if (count == 0)
addErrorMessage(eClass, eObject, diagnostics, eClass.getName()
+ " is not a children in any HyFeatureChild at timestamp " + date.toString());
}
}
}
private void checkHyFeatureChildConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
}
private void checkHyVersionConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
}
private void checkHyNamedElementConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
}
/**
* Checks if the model has more than one root feature at a timestamp
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkHyFeatureModelConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
HyFeatureModelImpl model = (HyFeatureModelImpl) eObject;
EList<HyRootFeature> rootFeatures = model.getRootFeature();
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
int count = 0;
for (int j = 0; j < rootFeatures.size(); j++) {
Date validSince = rootFeatures.get(j).getValidSince();
Date validUntil = rootFeatures.get(j).getValidUntil();
count += count(date, validSince, validUntil);
}
if (count > 1) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has more than one root feature at timestamp " + date.toString());
}
if (count == 0){
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has no root feature at timestamp " + date.toString());
}
}
}
/**
* Checks if the composition has features or not.
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkHyGroupCompositionConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
//FIXME date = null?!
HyGroupComposition composition = (HyGroupComposition) eObject;
EList<HyFeature> features = composition.getFeatures();
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
int count = 0;
for (int j = 0; j < features.size(); j++) {
Date validSince = features.get(j).getValidSince();
Date validUntil = features.get(j).getValidUntil();
count += count(date, validSince, validUntil);
}
if (count == 0){
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has no feature(s) at timestamp " + date.toString());
}
}
}
private void checkHyCardinalityBasedElementConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
// HyCardinalityImpl cardinalityElement = (HyCardinalityBasedElement)
// eObject;
}
private void checkHyLinearTemporalElementConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
}
private void checkHyTemporalElementConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
}
private void checkHyCardinilityConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
}
private void checkHyCardinalityConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
/*
HyCardinalityImpl cardinality = (HyCardinalityImpl) eObject;
if (cardinality.getMaxCardinality() > 1 || cardinality.getMaxCardinality() < 0) {
addErrorMessage(eClass, eObject, diagnostics, eClass.getName() + " has invalid max cardinality with value"
+ cardinality.getMaxCardinality() + ". Valid values are 0 and 1.");
}
if (cardinality.getMinCardinality() > 1 || cardinality.getMinCardinality() < 0) {
addErrorMessage(eClass, eObject, diagnostics, eClass.getName() + " has invalid min cardinality with value"
+ cardinality.getMinCardinality() + ". Valid values are 0 and 1.");
}
*/
}
/**
* Checks if an object has more than one type at a timestamp
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkTypes(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
List<HyTemporalElement> types = null;
if (eObject instanceof HyFeature) {
HyFeature e = (HyFeature) eObject;
types = new ArrayList<HyTemporalElement>();
types.addAll(e.getTypes());
}
else if(eObject instanceof HyGroup) {
HyGroup e = (HyGroup) eObject;
types = new ArrayList<HyTemporalElement>();
types.addAll(e.getTypes());
}
if(types != null) {
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
int count = 0;
for (int j = 0; j < types.size(); j++) {
Date validSince = types.get(j).getValidSince();
Date validUntil = types.get(j).getValidUntil();
count += count(date, validSince, validUntil);
}
if (count > 1) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has more than one type at timestamp " + date.toString());
}
}
}
}
/**
* Checks if a object is instance of a HyLinearTemporalElement and checks if more than
* superseding and superseded objects are valid. Also checks for circle of superseding
* objects.
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkSuperseeding(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
if (eObject instanceof HyLinearTemporalElement) {
HyLinearTemporalElement element = (HyLinearTemporalElement) eObject;
// check if a circle exist
HyLinearTemporalElement whileElement = (HyLinearTemporalElement) eObject;
Vector<HyLinearTemporalElement> list = new Vector<HyLinearTemporalElement>();
boolean endWhile = false;
while(whileElement != null && !endWhile){
for(int i=0; i<list.size(); i++){
if(list.get(i).equals(whileElement)){
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has a circle of superseding elements");
endWhile = true;
}
}
list.add(whileElement);
whileElement = (HyLinearTemporalElement)whileElement.getSupersedingElement();
}
if (element.getSupersedingElement() != null || element.getSupersededElement() != null)
if (element.getSupersedingElement() == element.getSupersededElement()) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName() + " has equal superseded and superseding element");
}
if (element.getSupersededElement() != null && element.getSupersedingElement() != null) {
Date supersedingValidSince = element.getSupersedingElement().getValidSince();
Date supersededValidUntil = element.getSupersededElement().getValidUntil();
if (supersedingValidSince == null && supersededValidUntil == null) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName()
+ ": the superseding and superseded elements are valid both valid at all timestamps." +
". Define valid since of superseding element and valid until of superseded element to avoid this error");
}
if (supersedingValidSince == null && supersededValidUntil != null) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName()
+ ": the superseding and superseded elements are valid both valid before timestamp " + supersededValidUntil +
". Define valid since of superseding element to avoid this error");
}
if (supersedingValidSince != null && supersededValidUntil == null) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName()
+ ": the superseding and superseded elements are valid both valid from timestamp " + supersedingValidSince +
". Define valid until of superseded element to avoid this error");
}
if (supersedingValidSince != null && supersededValidUntil != null) {
if (supersedingValidSince.equals(supersededValidUntil)) {
addErrorMessage(eClass, eObject, diagnostics,
eClass.getName()
+ ": the superseding and superseded elements are valid at one time stamp. Superseded element until timestamp"
+ "has to be smaller than until timestamp from superseded element");
}
}
}
}
}
/**
* Checks if valid since and valid until are not equal and valid until is before valid since
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkTemporalConstraint(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
if (eObject instanceof HyTemporalElement) {
HyTemporalElement element = (HyTemporalElement) eObject;
if (element.getValidSince() != null && element.getValidUntil() != null) {
if (element.getValidSince().equals(element.getValidUntil())) {
addErrorMessage(eClass, eObject, diagnostics, eClass.getName()
+ " valid since and valid until are equal. Valid until must be greater than valid since");
}
if (element.getValidSince().after(element.getValidUntil())) {
addErrorMessage(eClass, eObject, diagnostics, eClass.getName()
+ " valid since is after valid until. Valid since must be before valid until");
}
}
}
}
/**
* This function calls, depending on object type, the corresponding function to check
* all defined constraints for an object.
* @param eClass
* @param eObject
* @param diagnostics
* @param context
*/
private void checkConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
// initialize list with all used dates by the model
if (eClass.getName() == "HyFeatureModel") {
dates = HyEvolutionUtil.collectDates(eObject);
}
checkTypes(eClass, eObject, diagnostics, context);
checkSuperseeding(eClass, eObject, diagnostics, context);
checkTemporalConstraint(eClass, eObject, diagnostics, context);
if(eObject instanceof HyNamedElement){
}
switch (eClass.getName()) {
case "HyGroup":
checkHyGroupConstraints(eClass, eObject, diagnostics, context);
break;
case "HyFeatureChild":
checkHyFeatureChildConstraints(eClass, eObject, diagnostics, context);
break;
case "HyVersion":
checkHyVersionConstraints(eClass, eObject, diagnostics, context);
break;
case "HyName":
checkHyNamedElementConstraints(eClass, eObject, diagnostics, context);
break;
case "HyFeatureModel":
checkHyFeatureModelConstraints(eClass, eObject, diagnostics, context);
break;
case "HyGroupComposition":
checkHyGroupCompositionConstraints(eClass, eObject, diagnostics, context);
break;
case "HyCardinalityBasedElement":
checkHyCardinalityBasedElementConstraints(eClass, eObject, diagnostics, context);
break;
case "HyLinearTemporalElement":
checkHyLinearTemporalElementConstraints(eClass, eObject, diagnostics, context);
break;
case "HyTemporalElement":
checkHyTemporalElementConstraints(eClass, eObject, diagnostics, context);
break;
case "HyCardinility":
checkHyCardinilityConstraints(eClass, eObject, diagnostics, context);
break;
case "HyRootFeature":
checkHyRootFeatureConstraints(eClass, eObject, diagnostics, context);
break;
case "HyFeature":
checkHyFeatureConstraints(eClass, eObject, diagnostics, context);
break;
case "HyCardinality":
checkHyCardinalityConstraints(eClass, eObject, diagnostics, context);
case "":
break;
default:
break;
}
}
private void checkHyRootFeatureConstraints(EClass eClass, EObject eObject, DiagnosticChain diagnostics,
Map<Object, Object> context) {
HyRootFeature rootFeature = (HyRootFeature) eObject;
/*
for (int i = 0; i < dates.size(); i++) {
Date date = dates.get(i);
if(!validSinceUntilCombinationAtTimestamp(date, rootFeature.getValidSince(), rootFeature.getValidUntil())){
}
if(rootFeature.getValidSince().equals(rootFeature.getValidUntil())){
}
if(rootFeature.getValidSince().after(rootFeature.getValidUntil())){
}
}*/
}
/**
* Direct validation of {@link EDataType}s is not supported by the EMF
* validation framework; they are validated indirectly via the
* {@link EObject}s that hold their values.
*/
@Override
public boolean validate(EDataType eDataType, Object value, DiagnosticChain diagnostics,
Map<Object, Object> context) {
return super.validate(eDataType, value, diagnostics, context);
}
/**
* If we have a context map, record this object's <code>status</code> in it
* so that we will know later that we have processed it and its sub-tree.
*
* @param eObject
* an element that we have validated
* @param context
* the context (may be <code>null</code>)
* @param status
* the element's validation status
*/
private void processed(EObject eObject, Map<Object, Object> context, IStatus status) {
if (context != null) {
context.put(eObject, status);
}
}
/**
* Determines whether we have processed this <code>eObject</code> before, by
* automatic recursion of the EMF Model Validation Service. This is only
* possible if we do, indeed, have a context.
*
* @param eObject
* an element to be validated (we hope not)
* @param context
* the context (may be <code>null</code>)
* @return <code>true</code> if the context is not <code>null</code> and the
* <code>eObject</code> or one of its containers has already been
* validated; <code>false</code>, otherwise
*/
private boolean hasProcessed(EObject eObject, Map<Object, Object> context) {
boolean result = false;
if (context != null) {
// this is O(NlogN) but there's no helping it
while (eObject != null) {
if (context.containsKey(eObject)) {
result = true;
eObject = null;
} else {
eObject = eObject.eContainer();
}
}
}
return result;
}
/**
* Converts a status result from the EMF validation service to diagnostics.
*
* @param status
* the EMF validation service's status result
* @param diagnostics
* a diagnostic chain to accumulate results on
*/
private void appendDiagnostics(IStatus status, DiagnosticChain diagnostics) {
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (IStatus element : children) {
appendDiagnostics(element, diagnostics);
}
} else if (status instanceof IConstraintStatus) {
diagnostics.add(new BasicDiagnostic(status.getSeverity(), status.getPlugin(), status.getCode(),
status.getMessage(), ((IConstraintStatus) status).getResultLocus().toArray()));
}
}
}
|
package moppydesk;
import gnu.io.SerialPort;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.Receiver;
/**
*
* @author Sammy1Am
*/
public class MoppyPlayer implements Receiver {
/**
* The periods for each MIDI note in an array. The floppy drives
* don't really do well outside of the defined range, so skip those notes.
* Periods are in microseconds because that's what the Arduino uses for its
* clock-cycles in the micro() function, and because milliseconds aren't
* precise enough for musical notes.
*/
public static int[] microPeriods = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30578, 28861, 27242, 25713, 24270, 22909, 21622, 20409, 19263, 18182, 17161, 16198, //C1 - B1
15289, 14436, 13621, 12856, 12135, 11454, 10811, 10205, 9632, 9091, 8581, 8099, //C2 - B2
7645, 7218, 6811, 6428, 6068, 5727, 5406, 5103, 4816, 4546, 4291, 4050, //C3 - B3
3823, 3609, 3406, 3214, 3034, 2864, 2703, 2552, 2408, 2273, 2146, 2025, //C4 - B4
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/**
* Resolution of the Arduino code in microSeconds.
*/
public static int ARDUINO_RESOLUTION = 40;
/**
* Current period of each MIDI channel (zero is off) as set
* by the NOTE ON message; for pitch-bending.
*/
private int[] currentPeriod = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
MoppyBridge mb;
SerialPort com;
public MoppyPlayer(MoppyBridge newMb) {
mb = newMb;
}
public void close() {
mb.close();
}
//Is called by Java MIDI libraries for each MIDI message encountered.
public void send(MidiMessage message, long timeStamp) {
if (message.getStatus() > 127 && message.getStatus() < 144) { // Note OFF
//Convert the MIDI channel being used to the controller pin on the
//Arduino by multipying by 2.
byte pin = (byte) (2 * (message.getStatus() - 127));
//System.out.println("Got note OFF on pin: " + (pin & 0xFF));
mb.sendEvent(pin, 0);
currentPeriod[message.getStatus() - 128] = 0;
} else if (message.getStatus() > 143 && message.getStatus() < 160) { // Note ON
//Convert the MIDI channel being used to the controller pin on the
//Arduino by multipying by 2.
byte pin = (byte) (2 * (message.getStatus() - 143));
//Get note number from MIDI message, and look up the period.
//NOTE: Java bytes range from -128 to 127, but we need to make them
//0-255 to use for lookups. & 0xFF does the trick.
// After looking up the period, devide by (the Arduino resolution * 2).
// The Arduino's timer will only tick once per X microseconds based on the
// resolution. And each tick will only turn the pin on or off. So a full
// on-off cycle (one step on the floppy) is two periods.
int period = microPeriods[(message.getMessage()[1] & 0xff)] / (ARDUINO_RESOLUTION * 2);
//System.out.println("Got note ON on pin: " + (pin & 0xFF) + " with period " + period);
//System.out.println(message.getLength() + " " + message.getMessage()[message.getLength()-1]);
//Zero velocity events turn off the pin.
if (message.getMessage()[2] == 0) {
mb.sendEvent(pin, 0);
currentPeriod[message.getStatus() - 144] = 0;
} else {
mb.sendEvent(pin, period);
currentPeriod[message.getStatus() - 144] = period;
}
} else if (message.getStatus() > 223 && message.getStatus() < 240) { //Pitch bends
//Only proceed if the note is on (otherwise, no pitch bending)
if (currentPeriod[message.getStatus() - 224] != 0) {
//Convert the MIDI channel being used to the controller pin on the
//Arduino by multipying by 2.
byte pin = (byte) (2 * (message.getStatus() - 223));
double pitchBend = ((message.getMessage()[2] & 0xff) << 8) + (message.getMessage()[1] & 0xff);
int period = (int) (currentPeriod[message.getStatus() - 224] / Math.pow(2.0, (pitchBend - 8192) / 8192));
//System.out.println(currentPeriod[message.getStatus() - 224] + "-" + period);
mb.sendEvent(pin, period);
}
}
}
}
|
package org.intermine.web;
import org.intermine.metadata.Model;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.AttributeDescriptor;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.util.TypeUtil;
/**
* Superclass of left and right nodes
* @author Mark Woodbridge
*/
public class Node
{
String fieldName, path, prefix, type, parentType;
boolean attribute = false, reference = false, collection = false;
int indentation;
/**
* Constructor for a root node
* @param type the root type of this tree
*/
public Node(String type) {
this.type = type;
path = type;
prefix = "";
indentation = 0;
}
/**
* Constructor for a non-root node
* @param parent the parent node of this node
* @param fieldName the name of the field that this node represents
* @param model the model used to resolve paths
*/
public Node(Node parent, String fieldName, Model model) {
this.fieldName = fieldName;
prefix = parent.getPath();
path = prefix + "." + fieldName;
parentType = parent.getType();
ClassDescriptor cld = MainHelper.getClassDescriptor(parent.getType(), model);
FieldDescriptor fd = cld.getFieldDescriptorByName(fieldName);
type = TypeUtil.unqualifiedName(fd.isAttribute()
? ((AttributeDescriptor) fd).getType()
: ((ReferenceDescriptor) fd)
.getReferencedClassDescriptor().getType().getName());
attribute = fd.isAttribute();
reference = fd.isReference();
collection = fd.isCollection();
indentation = path.split("[.]").length - 1;
}
/**
* Type of parent node. Required for MainController to find field value
* enumerations with fieldName and parentType.
*
* @return type of parent node
*/
public String getParentType() {
return parentType;
}
/**
* Gets the value of path
*
* @return the value of path
*/
public String getPath() {
return path;
}
/**
* Gets the value of type
*
* @return the value of type
*/
public String getType() {
return type;
}
/**
* Set the value of type
*
* @param type the value of type
*/
public void setType(String type) {
this.type = type;
}
/**
* Gets the value of prefix
*
* @return the value of prefix
*/
public String getPrefix() {
return prefix;
}
/**
* Gets the value of fieldName
*
* @return the value of fieldName
*/
public String getFieldName() {
return fieldName;
}
/**
* Gets the value of attribute
*
* @return the value of attribute
*/
public boolean isAttribute() {
return attribute;
}
/**
* Gets the value of reference
*
* @return the value of reference
*/
public boolean isReference() {
return reference;
}
/**
* Gets the value of collection
*
* @return the value of collection
*/
public boolean isCollection() {
return collection;
}
/**
* Gets the value of indentation
*
* @return the value of indentation
*/
public int getIndentation() {
return indentation;
}
/**
* @see Object#toString
*/
public String toString() {
return path + ":" + type;
}
/**
* @see Object#equals
*/
public boolean equals(Object o) {
return (o instanceof Node)
&& path.equals(((Node) o).path)
&& type.equals(((Node) o).type);
}
/**
* @see Object#hashCode
*/
public int hashCode() {
return 2 * path.hashCode()
+ 3 * type.hashCode();
}
}
|
package gov.nih.nci.cabig.caaers.tools;
import gov.nih.nci.cabig.ctms.tools.DataSourceSelfDiscoveringPropertiesFactoryBean;
/**
* This class searches through the following directories, looking for a file named
* ${databaseConfigurationName}.properties:
* <ul>
* <li><kbd>${catalina.home}/conf/caaers</kbd></li>
* <li><kbd>${user.home}/.caaers</kbd></li>
* <li><kbd>/etc/caaers</kbd></li>
* </ul>
*
* It loads this file and returns it when {@link #getObject} is called.
*
* @author Rhett Sutphin
*/
public class CaaersDataSourcePropertiesFactoryBean extends DataSourceSelfDiscoveringPropertiesFactoryBean {
public static final String QUARTZ_DELEGATE_PROPERTY_NAME= "jdbc.quartz.delegateClassName";
public static final String SCHEMA_PROPERTY_NAME = "datasource.schema";
public static final String AUTH_MODE_PROPERTY_NAME = "authenticationMode";
public static final String WEBSSO_BASE_URL = "webSSO.server.baseUrl";
public static final String WEBSSO_SERVER_TRUST_CERTIFICATE = "webSSO.server.trustCert";
public static final String WEBSSO_HOST_CERTIFICATE = "hostCertificate";
public static final String WEBSSO_HOST_KEY = "hostKey";
public static final String WEBSSO_CAS_ACEGI_SECURITY_URL = "webSSO.cas.acegi.security.url" ;
public CaaersDataSourcePropertiesFactoryBean() {
setApplicationDirectoryName("caaers");
}
/**
* Sets reasonable defaults for caAERS-specific properties
*/
@Override
protected void computeProperties() {
String quartzDelegateClass = selectQuartzDelegateClass();
if(quartzDelegateClass != null) properties.setProperty(QUARTZ_DELEGATE_PROPERTY_NAME, quartzDelegateClass);
String schema = selectSchema();
if(schema != null) properties.setProperty(SCHEMA_PROPERTY_NAME, schema);
if(properties.getProperty(AUTH_MODE_PROPERTY_NAME) == null) properties.setProperty(AUTH_MODE_PROPERTY_NAME, "local");
if(properties.getProperty(WEBSSO_BASE_URL) == null) properties.setProperty(WEBSSO_BASE_URL, "http://dummyurl.com/url");
if(properties.getProperty(WEBSSO_SERVER_TRUST_CERTIFICATE) == null) properties.setProperty(WEBSSO_SERVER_TRUST_CERTIFICATE, "dummyTrustCerts");
if(properties.getProperty(WEBSSO_HOST_CERTIFICATE) == null) properties.setProperty(WEBSSO_HOST_CERTIFICATE, "dummyHostCert");
if(properties.getProperty(WEBSSO_HOST_KEY) == null) properties.setProperty(WEBSSO_HOST_KEY, "dummykey");
if(properties.getProperty(WEBSSO_CAS_ACEGI_SECURITY_URL) == null) properties.setProperty(WEBSSO_CAS_ACEGI_SECURITY_URL, "http://dummy.com/casurl/");
}
/**
* To determin the quartz delegate class to use
* @return
*/
private String selectQuartzDelegateClass(){
String defaultClass = "org.quartz.impl.jdbcjobstore.StdJDBCDelegate";
String postgresClass = "org.quartz.impl.jdbcjobstore.PostgreSQLDelegate";
String oracleClass = "org.quartz.impl.jdbcjobstore.oracle.OracleDelegate";
String rdbms = properties.getProperty(RDBMS_PROPERTY_NAME);
String driver = properties.getProperty(DRIVER_PROPERTY_NAME);
String db = (rdbms != null) ? rdbms : driver;
if(db != null){
if(db.toLowerCase().contains("postgres")) return postgresClass;
if(db.toLowerCase().contains("oracle")) return oracleClass;
}
return defaultClass;
}
/**
* Jackrabbit calls database vendor as schema , jackrabbit needs this variable
* @return
*/
private String selectSchema() {
String rdbms = properties.getProperty(RDBMS_PROPERTY_NAME);
String driver = properties.getProperty(DRIVER_PROPERTY_NAME);
String db = (rdbms != null) ? rdbms : driver;
if(db != null){
if(db.toLowerCase().contains("postgres")) return "postgresql";
if(db.toLowerCase().contains("oracle")) return "oracle";
}
return db;
}
}
|
package org.ow2.proactive.scheduler.gui.composite;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Map.Entry;
import javax.swing.JPanel;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.objectweb.proactive.api.PAFuture;
import org.ow2.proactive.scheduler.Activator;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.task.TaskId;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskState;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.util.ResultPreviewTool.SimpleTextPanel;
import org.ow2.proactive.scheduler.gui.Colors;
import org.ow2.proactive.scheduler.gui.Internal;
import org.ow2.proactive.scheduler.gui.data.JobsController;
import org.ow2.proactive.scheduler.gui.data.JobsOutputController;
import org.ow2.proactive.scheduler.gui.data.SchedulerProxy;
import org.ow2.proactive.scheduler.gui.preferences.PreferenceInitializer;
import org.ow2.proactive.scheduler.gui.views.JobOutput;
import org.ow2.proactive.scheduler.gui.views.JobOutput.RemoteHint;
import org.ow2.proactive.scheduler.gui.views.ResultPreview;
import org.ow2.proactive.scheduler.gui.views.TaskView;
import org.ow2.proactive.utils.Tools;
/**
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
public class TaskComposite extends Composite implements Comparator<TaskState> {
/** the unique id and the title for the column "Id" */
public static final String COLUMN_ID_TITLE = "Id";
/** the unique id and the title for the column "State" */
public static final String COLUMN_STATUS_TITLE = "State";
/** the unique id and the title for the column "Name" */
public static final String COLUMN_NAME_TITLE = "Name";
/** the unique id and the title for the column "Description" */
public static final String COLUMN_DESCRIPTION_TITLE = "Description";
/** the unique id and the title for the column "Node failures" */
public static final String COLUMN_NODEFAILURE_TITLE = "Node failures";
/** the unique id and the title for the column "Start time" */
public static final String COLUMN_START_TIME_TITLE = "Start time";
/** the unique id and the title for the column "Finished time" */
public static final String COLUMN_FINISHED_TIME_TITLE = "Finished time";
/** the unique id and the title for the column "Total Duration" */
public static final String COLUMN_DURATION_TITLE = "Tot Duration";
/** the unique id and the title for the column "Exec Duration" */
public static final String COLUMN_EXEC_DURATION_TITLE = "Exec Duration";
/** the unique id and the title for the column "host name" */
public static final String COLUMN_HOST_NAME_TITLE = "Host name";
/** the canceled tasks background color */
public static final Color TASKS_FAULTY_BACKGROUND_COLOR = Colors.ORANGE;
/** the failed tasks background color */
public static final Color TASKS_FAILED_BACKGROUND_COLOR = Colors.RED;
/** the aborted tasks background color */
public static final Color TASKS_ABORTED_BACKGROUND_COLOR = Colors.BROWN;
/** Add this sort as it is an additional one : 1000 has been chosen in order to have no interaction with provided sorting */
protected static final int SORT_BY_DURATION = 1000;
/** The background color of tasks that couldn't be started due to dependencies failure */
public static final Color TASKS_NOT_STARTED_BACKGROUND_COLOR = Colors.DEEP_SKY_BLUE;
private List<TaskState> tasks = null;
private final Label label;
private final Table table;
private int order = TaskState.ASC_ORDER;
private int lastSorting = TaskState.SORT_BY_ID;
private Action remoteAction;
private TaskId selectedId = null;
/**
* This is the default constructor.
*
* @param parent
*/
public TaskComposite(final Composite parent, final TaskView view) {
super(parent, SWT.NONE);
this.setLayout(new GridLayout());
this.label = createLabel(parent);
createTaskBar(parent, view);
this.table = createTable(parent);
}
private Label createLabel(final Composite parent) {
final Label label = new Label(this, SWT.CENTER);
label.setText("No job selected");
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
label.setForeground(Colors.RED);
return label;
}
private void createTaskBar(final Composite parent, final TaskView view) {
ImageDescriptor imgDesc = Activator.getDefault().getImageRegistry().getDescriptor(
Internal.IMG_REMOTE_CONNECTION);
remoteAction = new Action("Remote connection", imgDesc) {
@Override
public void run() {
if (selectedId == null) {
return;
}
// fetch the job output if we did not have it
JobOutput out = JobsOutputController.getInstance().getJobOutput(selectedId.getJobId());
if (out == null) {
JobsOutputController.getInstance().createJobOutput(selectedId.getJobId(), false);
// wait a little to for the async log fetching to be done
new Thread() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
fireRemoteButton(selectedId);
}
}.start();
} else {
// log was already fetched, do not wait
fireRemoteButton(selectedId);
}
}
};
remoteAction.setEnabled(false);
view.getViewSite().getActionBars().getToolBarManager().add(remoteAction);
}
private Table createTable(final Composite parent) {
//The table must be create with the SWT.SINGLE option !
final Table table = new Table(this, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
table.setLayoutData(new GridData(GridData.FILL_BOTH));
table.setHeaderVisible(true);
table.setLinesVisible(true);
// creating TableColumn
TableColumn tc1 = new TableColumn(table, SWT.LEFT);
TableColumn tc2 = new TableColumn(table, SWT.LEFT);
TableColumn tc3 = new TableColumn(table, SWT.LEFT);
TableColumn tc4 = new TableColumn(table, SWT.LEFT);
TableColumn tc5 = new TableColumn(table, SWT.LEFT);
TableColumn tc6 = new TableColumn(table, SWT.LEFT);
TableColumn tc7 = new TableColumn(table, SWT.LEFT);
TableColumn tc8 = new TableColumn(table, SWT.LEFT);
TableColumn tc9 = new TableColumn(table, SWT.LEFT);
TableColumn tc10 = new TableColumn(table, SWT.LEFT);
// addSelectionListener
tc1.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_ID);
}
});
tc2.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_STATUS);
}
});
tc3.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_NAME);
}
});
tc4.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_HOST_NAME);
}
});
tc5.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_STARTED_TIME);
}
});
tc6.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_FINISHED_TIME);
}
});
tc7.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_EXEC_DURATION);
}
});
tc8.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, SORT_BY_DURATION);
}
});
tc9.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_EXECUTIONONFAILURELEFT);
}
});
tc10.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
sort(event, TaskState.SORT_BY_DESCRIPTION);
}
});
// setText
tc1.setText(COLUMN_ID_TITLE);
tc2.setText(COLUMN_STATUS_TITLE);
tc3.setText(COLUMN_NAME_TITLE);
tc4.setText(COLUMN_HOST_NAME_TITLE);
tc5.setText(COLUMN_START_TIME_TITLE);
tc6.setText(COLUMN_FINISHED_TIME_TITLE);
tc7.setText(COLUMN_EXEC_DURATION_TITLE);
tc8.setText(COLUMN_DURATION_TITLE);
tc9.setText(COLUMN_NODEFAILURE_TITLE);
tc10.setText(COLUMN_DESCRIPTION_TITLE);
// setWidth
tc1.setWidth(68);
tc2.setWidth(110);
tc3.setWidth(100);
tc4.setWidth(150);
tc5.setWidth(130);
tc6.setWidth(130);
tc7.setWidth(110);
tc8.setWidth(110);
tc9.setWidth(100);
tc10.setWidth(200);
// setMoveable
tc1.setMoveable(true);
tc2.setMoveable(true);
tc3.setMoveable(true);
tc4.setMoveable(true);
tc5.setMoveable(true);
tc6.setMoveable(true);
tc7.setMoveable(true);
tc8.setMoveable(true);
tc9.setMoveable(true);
tc10.setMoveable(true);
table.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
Widget widget = event.item;
if ((widget != null) && (!widget.isDisposed())) {
TaskId id = (TaskId) widget.getData();
updateResultPreview(id, false);
selectedId = id;
remoteAction.setEnabled(true);
}
}
});
table.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
TableItem[] items = ((Table) e.getSource()).getSelection();
if (items.length > 0)
updateResultPreview((TaskId) items[0].getData(), true);
}
public void mouseDown(MouseEvent e) {
}
public void mouseUp(MouseEvent e) {
}
});
MenuManager menuMgr = new MenuManager();
menuMgr.add(remoteAction);
table.setMenu(menuMgr.createContextMenu(this));
return table;
}
/**
* Called when the remote connection button is clicked
* <p>
* try to find a remote connection hint for the selected task,
* try to find an application associated to the protocol,
* try to launch it
*
* @param id currently selected id
*/
private void fireRemoteButton(final TaskId id) {
JobOutput out = JobsOutputController.getInstance().getJobOutput(id.getJobId());
if (out == null) {
Activator.log(IStatus.ERROR, "Unable to retrieve Output for Job " + id.getJobId(), null);
return;
}
RemoteHint remote = null;
for (Entry<String, RemoteHint> remoteHint : out.getRemoteConnHints().entrySet()) {
if (id.value().equals(remoteHint.getKey())) {
remote = remoteHint.getValue();
break;
}
}
if (remote == null) {
final String msg = "Task " + id.getReadableName() + "(" + id.value() + ")" +
" does not provide remote connection information.";
Activator.log(IStatus.INFO, msg, null);
getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(), "Remote Connection", msg + "\n");
}
});
return;
}
String app = PreferenceInitializer.getRemoteConnectionProperties().getProperty(
remote.protocol.toLowerCase());
if (app == null || "".equals(app)) {
final String msg = "No Remote Connection application association is defined for protocol '" +
remote.protocol + "'";
Activator.log(IStatus.ERROR, msg, null);
getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(), "Remote Connection", msg + "\n");
}
});
return;
}
try {
Activator
.log(IStatus.INFO, "Launching Remote Connection for task " + id.getReadableName() + "(" +
id.value() + ") [proto=" + remote.protocol + " app=" + app + " url=" + remote.url +
"]", null);
Runtime.getRuntime().exec(app + " " + remote.url);
} catch (IOException e) {
final String msg = "Failed to launch application Remote Connection command '" + app + " " +
remote.url + "'";
Activator.log(IStatus.ERROR, msg, e);
getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(), "Remote Connection", msg + "\n");
}
});
}
}
private void initResultPreviewDisplay() {
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ResultPreview.ID);
} catch (PartInitException e) {
Activator.log(IStatus.ERROR, "Error when showing the result preview ", e);
e.printStackTrace();
}
}
/**
* Update Result Preview Panel by displaying a description of a task's result
* Create resultPreview SWT view if needed.
* @param taskId Task identifier for which a result preview is asked
* @param grapchicalPreview try to display a Graphical description of the result if available (otherwise display textual description),
* otherwise display a textual description of task's result.
*/
private void updateResultPreview(TaskId taskId, boolean grapchicalPreview) {
ResultPreview resultPreview = ResultPreview.getInstance();
if (resultPreview == null) {
//force view creation
initResultPreviewDisplay();
resultPreview = ResultPreview.getInstance();
}
//check nevertheless whether creation of view has succeed
if (resultPreview != null) {
JobState job = JobsController.getLocalView().getJobById(taskId.getJobId());
TaskState task = job.getHMTasks().get(taskId);
// update its tasks informations if task is finished
if (task.getStatus() == TaskStatus.FINISHED || task.getStatus() == TaskStatus.FAULTY ||
task.getStatus() == TaskStatus.WAITING_ON_ERROR) {
TaskResult tr = getTaskResult(job.getId(), taskId);
if (tr != null) {
if (grapchicalPreview) {
displayGraphicalPreview(resultPreview, tr);
resultPreview.putOnTop();
} else {
displayTextualPreview(resultPreview, tr);
resultPreview.putOnTop();
}
} else {
throw new RuntimeException("Cannot get the result of Task " + taskId + ".");
}
} else { //Not available
resultPreview.update(new SimpleTextPanel("No preview is available because the task is " +
task.getStatus() + "..."));
}
}
}
/**
* Display in Result Preview view graphical description of a task result if
* any graphical description is available for this task
* @param resultPreview Result preview SWT view object
* @param result TaskResult that has eventually a graphical description
*/
private void displayGraphicalPreview(ResultPreview resultPreview, TaskResult result) {
JPanel previewPanel;
try {
previewPanel = result.getGraphicalDescription();
resultPreview.update(previewPanel);
} catch (Throwable t) {
// root exception can be wrapped into ProActive level exception
// try to display also cause exception.
// TODO cdelbe : recursive display ?
String cause = t.getCause() != null ? System.getProperty("line.separator") + "caused by " +
t.getCause() : "";
resultPreview.update(new SimpleTextPanel("[ERROR] Cannot create graphical previewer: " +
System.getProperty("line.separator") + t + cause));
}
}
/**
* Display in Result Preview view textual description of a task result.
* @param resultPreview Result preview SWT view object
* @param result TaskResult for which a textual description is to display
*/
private void displayTextualPreview(ResultPreview resultPreview, TaskResult result) {
JPanel previewPanel;
try {
previewPanel = new SimpleTextPanel(result.getTextualDescription());
resultPreview.update(previewPanel);
} catch (Throwable t) {
// root exception can be wrapped into ProActive level exception
// try to display also cause exception.
String cause = t.getCause() != null ? System.getProperty("line.separator") + "caused by " +
t.getCause() : "";
resultPreview.update(new SimpleTextPanel("[ERROR] Cannot create textual previewer: " +
System.getProperty("line.separator") + t + cause));
}
}
// TODO TMP MKRIS
private static final Hashtable<TaskId, TaskResult> cachedTaskResult = new Hashtable<TaskId, TaskResult>();
public static TaskResult getTaskResult(JobId jid, TaskId tid) {
// TODO : NO ACCESS TO SCHED HERE ...
// get result from scheduler
// I just did a copy/past of that code form jobsController
TaskResult tr = cachedTaskResult.get(tid);
if (tr == null) {
tr = SchedulerProxy.getInstance().getTaskResult(jid, tid.getReadableName());
tr = PAFuture.getFutureValue(tr);
if (tr != null) {
cachedTaskResult.put(tid, tr);
}
}
return tr;
}
public static void deleteTaskResultCache() {
cachedTaskResult.clear();
}
// END TMP MKRIS
private void sort(final SelectionEvent event, final int field) {
if (this.tasks != null) {
if (this.lastSorting == field) {
// if the new sort is the same as the last sort, invert order.
this.order = (this.order == TaskState.DESC_ORDER) ? TaskState.ASC_ORDER
: TaskState.DESC_ORDER;
TaskState.setSortingOrder(this.order);
}
TaskState.setSortingBy(field);
this.lastSorting = field;
if (field == SORT_BY_DURATION) {
Collections.sort(this.tasks, this);
} else {
Collections.sort(this.tasks);
}
refreshTable();
this.table.setSortColumn((TableColumn) event.widget);
this.table.setSortDirection((this.order == TaskState.DESC_ORDER) ? SWT.DOWN : SWT.UP);
}
}
private void refreshTable() {
if (this.isDisposed()) {
return;
}
// Turn off drawing to avoid flicker
this.table.setRedraw(false);
// Dispose old bold fonts (see SCHEDULING-535)
for (final TableItem item : this.table.getItems()) {
final Font font = item.getFont();
if ((font.getFontData()[0].getStyle() & SWT.BOLD) != 0) {
font.dispose();
}
}
// We remove all the table entries
this.table.removeAll();
this.remoteAction.setEnabled(false);
// then add the entries
for (final TaskState taskState : this.tasks) {
final TableItem item = new TableItem(this.table, SWT.BOLD);
// To have a unique identifier for this TableItem
item.setData(taskState.getId());
this.internalFillItem(item, taskState);
}
// Turn drawing back on
this.table.setRedraw(true);
}
// Called by following methods:
// - changeLine()
// - refreshTable()
private void internalFillItem(final TableItem item, final TaskState taskState) {
// The table CAN'T be disposed no need to check !
boolean setFont = false;
switch (taskState.getStatus()) {
case ABORTED:
setFont = true;
item.setForeground(TASKS_ABORTED_BACKGROUND_COLOR);
break;
case FAULTY:
setFont = true;
item.setForeground(TASKS_FAULTY_BACKGROUND_COLOR);
break;
case FAILED:
setFont = true;
item.setForeground(TASKS_FAILED_BACKGROUND_COLOR);
break;
case NOT_STARTED:
case NOT_RESTARTED:
setFont = true;
item.setForeground(TASKS_NOT_STARTED_BACKGROUND_COLOR);
break;
case FINISHED:
case PAUSED:
case PENDING:
case RUNNING:
case SUBMITTED:
}
if (!setFont && ((taskState.getMaxNumberOfExecution() - taskState.getNumberOfExecutionLeft()) > 0)) {
setFont = true;
}
if (setFont) {
final Font font = item.getFont();
final FontData fontData = font.getFontData()[0];
fontData.setStyle(fontData.getStyle() | SWT.BOLD);
// A new font is created see refreshTable() for disposing
item.setFont(new Font(font.getDevice(), fontData));
}
final TableColumn[] cols = table.getColumns();
// I must fill item by this way, because all columns are movable
// So i don't know if the column "Id" is at the first or the "nth"
// position
for (int i = 0; i < cols.length; i++) {
String title = cols[i].getText();
if (title.equals(COLUMN_ID_TITLE)) {
item.setText(i, "" + taskState.getId().hashCode());
} else if (title.equals(COLUMN_STATUS_TITLE)) {
String tmp = taskState.getStatus().toString();
switch (taskState.getStatus()) {
case RUNNING:
case FINISHED:
case FAULTY:
int nb = (taskState.getMaxNumberOfExecution() - taskState.getNumberOfExecutionLeft() + 1);
if (nb > taskState.getMaxNumberOfExecution()) {
nb = taskState.getMaxNumberOfExecution();
}
tmp = tmp + " (" + nb + "/" + taskState.getMaxNumberOfExecution() + ")";
break;
case WAITING_ON_ERROR:
tmp = tmp + " (" +
(taskState.getMaxNumberOfExecution() - taskState.getNumberOfExecutionLeft()) +
"/" + taskState.getMaxNumberOfExecution() + ")";
break;
}
item.setText(i, tmp);
} else if (title.equals(COLUMN_NAME_TITLE)) {
item.setText(i, taskState.getName());
} else if (title.equals(COLUMN_DESCRIPTION_TITLE)) {
item.setText(i, (taskState.getDescription() == null) ? "no description available" : taskState
.getDescription());
} else if (title.equals(COLUMN_START_TIME_TITLE)) {
item.setText(i, Tools.getFormattedDate(taskState.getStartTime()));
} else if (title.equals(COLUMN_FINISHED_TIME_TITLE)) {
item.setText(i, Tools.getFormattedDate(taskState.getFinishedTime()));
} else if (title.equals(COLUMN_DURATION_TITLE)) {
item.setText(i, Tools.getFormattedDuration(taskState.getFinishedTime(), taskState
.getStartTime()));
} else if (title.equals(COLUMN_EXEC_DURATION_TITLE)) {
item.setText(i, Tools.getFormattedDuration(0, taskState.getExecutionDuration()));
} else if (title.equals(COLUMN_NODEFAILURE_TITLE)) {
if (taskState.getStatus() == TaskStatus.FAILED) {
item.setText(i, taskState.getMaxNumberOfExecutionOnFailure() + "/" +
taskState.getMaxNumberOfExecutionOnFailure());
} else {
item.setText(i, (taskState.getMaxNumberOfExecutionOnFailure() - taskState
.getNumberOfExecutionOnFailureLeft()) +
"/" + taskState.getMaxNumberOfExecutionOnFailure());
}
} else if (title.equals(COLUMN_HOST_NAME_TITLE)) {
String hostName = taskState.getExecutionHostName();
if (hostName == null) {
item.setText(i, "n/a");
} else {
item.setText(i, hostName);
}
}
}
}
/**
* This method "clear" the view by removing all item in the table and set the label to
* "No job selected"
*/
public void clear() {
this.table.removeAll();
this.label.setText("No selected job");
}
/**
* This method remove all item of the table and fill it with the tasks vector. The label is also
* updated.
*
* @param jobId the jobId, just for the label.
*
* @param tasks
*/
public void setTasks(JobId jobId, ArrayList<TaskState> tasks) {
this.tasks = tasks;
int tmp = tasks.size();
if (!this.label.isDisposed()) {
this.label.setText("Job " + jobId + " has " + tmp + ((tmp == 1) ? " task" : " tasks"));
}
refreshTable();
}
/**
* This method remove all item of the table and fill it with the tasks vector. The label is also
* updated.
*
* @param numberOfJobs
*
* @param tasks
*/
public void setTasks(final int numberOfJobs, final ArrayList<TaskState> tasks) {
this.tasks = tasks;
if (!this.label.isDisposed()) {
this.label.setText(numberOfJobs + " jobs selected / " + tasks.size() + " tasks selected");
}
refreshTable();
}
/**
* This method allow to replace only one line on the task table. This method identify the "good"
* item with the taskId. The TaskState is use to fill item.
*
* @param taskState all informations for fill item
*/
public void changeLine(TaskState taskState) {
if (this.table.isDisposed()) {
return;
}
for (final TableItem item : this.table.getItems()) {
if (((TaskId) item.getData()).equals(taskState.getId())) {
this.internalFillItem(item, taskState);
break;
}
}
}
/**
* @see org.eclipse.swt.widgets.Widget#isDisposed()
*/
@Override
public boolean isDisposed() {
return super.isDisposed() || ((table != null) && (table.isDisposed())) ||
((label != null) && (label.isDisposed()));
}
/**
* @see org.eclipse.swt.widgets.Control#setMenu(org.eclipse.swt.widgets.Menu)
*/
@Override
public void setMenu(Menu menu) {
super.setMenu(menu);
table.setMenu(menu);
label.setMenu(menu);
}
/**
* @see org.eclipse.swt.widgets.Control#setVisible(boolean)
*/
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (label != null) {
label.setVisible(visible);
}
if (table != null) {
table.setVisible(visible);
}
}
public TaskId getIdOfSelectedTask() {
TableItem[] items = table.getSelection();
if (items.length == 0) {
return null;
}
return (TaskId) items[0].getData();
}
/**
* Implementation of the {@see Comparable<TaskSate>} interface.
*/
public int compare(final TaskState t1, final TaskState t2) {
try {
final long t1Duration = t1.getFinishedTime() - t1.getStartTime();
final long t2Duration = t2.getFinishedTime() - t2.getStartTime();
if (this.order == TaskState.ASC_ORDER) {
return (int) (t1Duration - t2Duration);
} else {
return (int) (t2Duration - t1Duration);
}
} catch (Exception e) {
return 0;
}
}
}
|
package gov.nih.nci.system.dao.orm.translator;
import gov.nih.nci.iso21090.Ad;
import gov.nih.nci.iso21090.AddressPartType;
import gov.nih.nci.iso21090.Adxp;
import gov.nih.nci.iso21090.EntityNamePartQualifier;
import gov.nih.nci.iso21090.EntityNamePartType;
import gov.nih.nci.iso21090.Enxp;
import gov.nih.nci.iso21090.hibernate.node.ComplexNode;
import gov.nih.nci.iso21090.hibernate.node.ConstantNode;
import gov.nih.nci.iso21090.hibernate.node.Node;
import gov.nih.nci.iso21090.hibernate.tuple.IsoConstantTuplizerHelper;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import gov.nih.nci.system.query.nestedcriteria.NestedCriteria;
import gov.nih.nci.system.util.SystemConstant;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.hibernate.MappingException;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.ManyToOne;
import org.hibernate.mapping.OneToMany;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.Value;
public class NestedCriteria2HQL {
private NestedCriteria criteria;
private Configuration cfg;
private boolean caseSensitive;
private HQLCriteria hqlCriteria;
private static Logger log = Logger.getLogger(NestedCriteria2HQL.class);
private List<Object> paramList = new ArrayList<Object>();
private String isoprefix = "gov.nih.nci.iso21090.";
private Integer aliasCount = 0;
private String srcAlias;
private final Map<String, String> partTypes = new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put("gov.nih.nci.iso21090.EntityNamePartType",
"gov.nih.nci.iso21090.Enxp");
put("gov.nih.nci.iso21090.AddressPartType",
"gov.nih.nci.iso21090.Adxp");
}
};
public NestedCriteria2HQL(NestedCriteria crit, Configuration cfg,
boolean caseSensitive) {
this.criteria = crit;
this.cfg = cfg;
this.caseSensitive = caseSensitive;
}
public NestedCriteria2HQL(NestedCriteria crit, Configuration cfg,
boolean caseSensitive, String srcAlias) {
this.criteria = crit;
this.cfg = cfg;
this.caseSensitive = caseSensitive;
this.srcAlias = srcAlias;
}
public HQLCriteria translate() throws Exception {
StringBuffer hql = new StringBuffer();
processNestedCriteria(hql, criteria);
hqlCriteria = prepareQuery(hql);
log.debug("HQL Query :" + hqlCriteria.getHqlString());
System.out.println("HQL query: " + hql.toString());
return hqlCriteria;
}
private void processNestedCriteria(StringBuffer hql, NestedCriteria criteria)
throws Exception {
if (condition1(criteria)) {
log.debug("Processing Scenario1: src=dest and internal nested criteria=null");
solveScenario1(hql, criteria);
} else if (condition2(criteria)) {
log.debug("Processing Scenario2: src!=dest and internal nested criteria=null");
solveScenario2(hql, criteria);
} else if (condition3(criteria)) {
log.debug("Processing Scenario3: nested criteria!=null");
solveScenario3(hql, criteria);
} else {
// should never happen
log.error("Unexpected NestedCriteria condition found for criteria: "
+ criteria);
throw new Exception(
"Unexpected NestedCriteria condition found for criteria: "
+ criteria);
}
}
private boolean condition1(NestedCriteria criteria) {
if (criteria.getSourceName().equals(criteria.getTargetObjectName())
&& criteria.getInternalNestedCriteria() == null)
return true;
return false;
}
private boolean condition2(NestedCriteria criteria) {
if (!criteria.getSourceName().equals(criteria.getTargetObjectName())
&& criteria.getInternalNestedCriteria() == null)
return true;
return false;
}
private boolean condition3(NestedCriteria criteria) {
if (criteria.getInternalNestedCriteria() != null)
return true;
return false;
}
// Single Object with query by example
@SuppressWarnings("rawtypes")
private void solveScenario1(StringBuffer hql, NestedCriteria criteria)
throws Exception {
Collection sourceObjectList = criteria.getSourceObjectList();
if (sourceObjectList == null) {
log.error("Scenario1: Source object list is unexpectedly null");
throw new Exception("Source Object List is unexpectedly null");
}
String targetObjectName = criteria.getTargetObjectName();
String destAlias = getAlias(targetObjectName, 1);
if (sourceObjectList.size() == 1) {
log.debug("Scenario1: Processing single object in source object list");
Object sourceObject = sourceObjectList.iterator().next();
String select = getHQLQueryFromSourceObjectWithCriterion(
sourceObject, cfg, false);
hql.append(select);
log.debug("Scenario1: Single object HQL sub-select: " + select);
} else {
log.debug("Scenario1: Processing multiple objects in source object list");
hql.append("select " + destAlias + " from " + targetObjectName
+ " " + destAlias + " where ");
for (Iterator i = sourceObjectList.iterator(); i.hasNext();) {
Object obj = i.next();
hql.append(destAlias
+ " in ("
+ getHQLQueryFromSourceObjectWithCriterion(obj, cfg,
false) + " )");
if (i.hasNext())
hql.append(" or ");
}
}
}
// Getting association for the query by example
@SuppressWarnings("rawtypes")
private void solveScenario2(StringBuffer hql, NestedCriteria criteria)
throws Exception {
Collection sourceObjectList = criteria.getSourceObjectList();
if (sourceObjectList == null) {
log.error("Scenario2: Source object list is unexpectedly null");
throw new Exception(
"Scenario2: Source Object List is unexpectedly null");
}
String targetObjectName = criteria.getTargetObjectName();
String sourceObjectName = criteria.getSourceName();
String srcAlias = getAlias(criteria.getSourceName(), 1);
String destAlias = getAlias(targetObjectName, 1);
log.debug("Scenario2: targetObjectName: " + targetObjectName);
log.debug("Scenario2: sourceObjectName: " + sourceObjectName);
log.debug("Scenario2: srcAlias: " + srcAlias);
log.debug("Scenario2: destAlias: " + destAlias);
if (sourceObjectList.size() == 1) {
log.debug("Scenario2: Processing single object in source object list");
StringBuffer selectBuffer = new StringBuffer();
String roleName = criteria.getRoleName();
if (roleName == null) {
selectBuffer.append("select ").append(destAlias)
.append(" from ").append(targetObjectName).append(" ")
.append(destAlias).append(", ")
.append(sourceObjectName).append(" ").append(srcAlias)
.append(" where ");
log.debug("Scenario2: roleName: " + roleName);
selectBuffer.append(destAlias).append("=").append(srcAlias);
if (isObjectEmpty(sourceObjectList.iterator().next())) {
selectBuffer.append(" and ").append(srcAlias)
.append(".id is not null ");
} else if (isObjectAssociationEmpty(sourceObjectList.iterator()
.next())) {
selectBuffer.append(" and ").append(
getHQLQueryFromSourceObjectWithCriterion(
sourceObjectList.iterator().next(), cfg,
true));
} else {
selectBuffer
.append(" and ")
.append(srcAlias)
.append(" in (")
.append(getHQLQueryFromSourceObjectWithCriterion(
sourceObjectList.iterator().next(), cfg,
false)).append(")");
}
} else {
if (criteria.isTargetCollection()) {
// No attributes or associations populated
if (isObjectEmpty(sourceObjectList.iterator().next())) {
if (criteria.getSourceRoleName() != null
&& !criteria.isSourceCollection()) {
selectBuffer.append("select ").append(destAlias)
.append(" from ").append(targetObjectName)
.append(" ").append(destAlias)
.append(" where ");
selectBuffer.append(destAlias).append(".")
.append(criteria.getSourceRoleName())
.append(".id is not null ");
} else {
selectBuffer.append("select ").append(destAlias)
.append(" from ").append(sourceObjectName)
.append(" ").append(srcAlias)
.append(" inner join ").append(srcAlias)
.append(".").append(roleName).append(" ")
.append(destAlias).append(" where ")
.append(srcAlias)
.append(".id is not null ");
}
}
// Only some of the attributes populated
else if (isObjectAssociationEmpty(sourceObjectList
.iterator().next())) {
if (criteria.getSourceRoleName() != null
&& !criteria.isSourceCollection()) {
selectBuffer
.append("select ")
.append(destAlias)
.append(" from ")
.append(targetObjectName)
.append(" ")
.append(destAlias)
.append(", ")
.append(sourceObjectName)
.append(" ")
.append(srcAlias)
.append(" where ")
.append(destAlias)
.append(".")
.append(criteria.getSourceRoleName())
.append(".id")
.append("=")
.append(srcAlias)
.append(".id")
.append(" and ")
.append(getHQLQueryFromSourceObjectWithCriterion(
sourceObjectList.iterator().next(),
cfg, true));
} else {
selectBuffer
.append("select ")
.append(destAlias)
.append(" from ")
.append(sourceObjectName)
.append(" ")
.append(srcAlias)
.append(" inner join ")
.append(srcAlias)
.append(".")
.append(roleName)
.append(" ")
.append(destAlias)
.append(" where ")
.append(getHQLQueryFromSourceObjectWithCriterion(
sourceObjectList.iterator().next(),
cfg, true));
}
}
// Attributes and associtions populated
else {
selectBuffer
.append("select ")
.append(destAlias)
.append(" from ")
.append(sourceObjectName)
.append(" ")
.append(srcAlias)
.append(" inner join ")
.append(srcAlias)
.append(".")
.append(roleName)
.append(" ")
.append(destAlias)
.append(" where ")
.append(srcAlias)
.append(" in (")
.append(getHQLQueryFromSourceObjectWithCriterion(
sourceObjectList.iterator().next(),
cfg, false)).append(")");
}
} else // Target is not collection
{
// No attributes or associations populated
if (isObjectEmpty(sourceObjectList.iterator().next())) {
selectBuffer.append("select ").append(destAlias)
.append(" from ").append(sourceObjectName)
.append(" ").append(srcAlias)
.append(" inner join ").append(srcAlias)
.append(".").append(roleName).append(" ")
.append(destAlias).append(" where ")
.append(srcAlias).append(".id is not null ");
}
// Only some of the attributes populated
else if (isObjectAssociationEmpty(sourceObjectList
.iterator().next())) {
selectBuffer
.append("select ")
.append(destAlias)
.append(" from ")
.append(targetObjectName)
.append(" ")
.append(destAlias)
.append(", ")
.append(sourceObjectName)
.append(" ")
.append(srcAlias)
.append(" where ")
.append(srcAlias)
.append(".")
.append(roleName)
.append(".id")
.append("=")
.append(destAlias)
.append(".id")
.append(" and ")
.append(getHQLQueryFromSourceObjectWithCriterion(
sourceObjectList.iterator().next(),
cfg, true));
}
// Attributes and associtions populated
else {
selectBuffer
.append("select ")
.append(destAlias)
.append(" from ")
.append(targetObjectName)
.append(" ")
.append(destAlias)
.append(", ")
.append(sourceObjectName)
.append(" ")
.append(srcAlias)
.append(" where ")
.append(destAlias)
.append(".id")
.append("=")
.append(srcAlias)
.append(".")
.append(roleName)
.append(".id")
.append(" and ")
.append(srcAlias)
.append(" in (")
.append(getHQLQueryFromSourceObjectWithCriterion(
sourceObjectList.iterator().next(),
cfg, false)).append(")");
}
}
}
log.debug("Scenario2: single object HQL sub-select: "
+ selectBuffer.toString());
hql.append(selectBuffer.toString());
} else // More than one example objects present
{
log.debug("Scenario2: Processing multiple objects in source object list");
String roleName = criteria.getRoleName();
if (roleName == null) {
hql.append("select ").append(destAlias).append(" from ")
.append(targetObjectName).append(" ").append(destAlias)
.append(", ").append(sourceObjectName).append(" ")
.append(srcAlias).append(" where ");
hql.append(destAlias).append(".id").append("=")
.append(srcAlias).append(".id");
hql.append(" and ");
} else {
if (criteria.isTargetCollection()) {
if (criteria.getSourceRoleName() != null
&& !criteria.isSourceCollection()) {
hql.append("select ").append(destAlias)
.append(" from ").append(targetObjectName)
.append(" ").append(destAlias).append(", ")
.append(sourceObjectName).append(" ")
.append(srcAlias).append(" where ");
hql.append(destAlias).append(".")
.append(criteria.getSourceRoleName())
.append(".id").append("=").append(srcAlias)
.append(".id");
hql.append(" and ");
} else {
hql.append("select ").append(destAlias)
.append(" from ").append(sourceObjectName)
.append(" ").append(srcAlias)
.append(" inner join ").append(srcAlias)
.append(".").append(roleName).append(" ")
.append(destAlias).append(" where ")
.append("1=1 and ");
}
} else {
hql.append("select ").append(destAlias).append(" from ")
.append(targetObjectName).append(" ")
.append(destAlias).append(", ")
.append(sourceObjectName).append(" ")
.append(srcAlias).append(" where ");
hql.append(destAlias).append(".id").append("=")
.append(srcAlias).append(".").append(roleName)
.append(".id");
hql.append(" and ");
}
}
for (Iterator i = sourceObjectList.iterator(); i.hasNext();) {
Object obj = i.next();
hql.append(
srcAlias
+ " in ("
+ getHQLQueryFromSourceObjectWithCriterion(obj,
cfg, false)).append(")");
if (i.hasNext())
hql.append(" or ");
}
}
}
// Traversing the path of the nested search criteria
private void solveScenario3(StringBuffer hql, NestedCriteria criteria)
throws Exception {
String targetObjectName = criteria.getTargetObjectName();
String sourceObjectName = criteria.getSourceName();
String srcAlias = getAlias(criteria.getSourceName(), 2);
String destAlias = getAlias(targetObjectName, 1);
log.debug("Scenario3: targetObjectName: " + targetObjectName);
log.debug("Scenario3: sourceObjectName: " + sourceObjectName);
log.debug("Scenario3: srcAlias: " + srcAlias);
log.debug("Scenario3: destAlias: " + destAlias);
String roleName = criteria.getRoleName();
log.debug("Scenario2: roleName: " + roleName);
if (roleName == null) {
hql.append("select ").append(destAlias).append(" from ")
.append(targetObjectName).append(" ").append(destAlias)
.append(", ").append(sourceObjectName).append(" ")
.append(srcAlias).append(" where ");
hql.append(destAlias).append(".id").append("=").append(srcAlias)
.append(".id");
StringBuffer internalNestedCriteriaBuffer = new StringBuffer();
processNestedCriteria(internalNestedCriteriaBuffer,
criteria.getInternalNestedCriteria());
hql.append(" and ").append(srcAlias).append(" in (")
.append(internalNestedCriteriaBuffer).append(")");
} else {
if (criteria.isTargetCollection()) {
if (criteria.getSourceRoleName() != null
&& !criteria.isSourceCollection()) {
hql.append("select ").append(destAlias).append(" from ")
.append(targetObjectName).append(" ")
.append(destAlias).append(", ")
.append(sourceObjectName).append(" ")
.append(srcAlias).append(" where ");
hql.append(destAlias).append(".")
.append(criteria.getSourceRoleName()).append(".id")
.append("=").append(srcAlias).append(".id");
hql.append(" and ");
} else {
hql.append("select ").append(destAlias).append(" from ")
.append(targetObjectName).append(" ")
.append(destAlias).append(", ")
.append(sourceObjectName).append(" ")
.append(srcAlias).append(" where ");
hql.append(destAlias).append(" in elements(")
.append(srcAlias).append(".")
.append(criteria.getRoleName()).append(")");
hql.append(" and ");
}
} else {
hql.append("select ").append(destAlias).append(" from ")
.append(targetObjectName).append(" ").append(destAlias)
.append(", ").append(sourceObjectName).append(" ")
.append(srcAlias).append(" where ");
hql.append(destAlias).append(".id").append("=")
.append(srcAlias).append(".").append(roleName)
.append(".id");
hql.append(" and ");
}
StringBuffer internalNestedCriteriaBuffer = new StringBuffer();
processNestedCriteria(internalNestedCriteriaBuffer,
criteria.getInternalNestedCriteria());
hql.append(srcAlias).append(" in (")
.append(internalNestedCriteriaBuffer).append(")");
}
log.debug("Scenario3: HQL select: " + hql.toString());
}
public static String getCountQuery(String hql) {
String upperHQL = hql.toUpperCase();
String modifiedHQL = "";
int firstSelectIndex = upperHQL.indexOf("SELECT");
int firstFromIndex = upperHQL.indexOf("FROM");
if ((firstSelectIndex >= 0) && (firstSelectIndex < firstFromIndex)) {
String projections = hql.substring(
firstSelectIndex + "SELECT".length(), firstFromIndex);
String[] tokens = projections.split(",");
modifiedHQL = hql
.substring(0, firstSelectIndex + "SELECT".length())
+ " count("
+ tokens[0].trim()
+ ") "
+ hql.substring(firstFromIndex);
} else {
modifiedHQL = hql.substring(0, firstFromIndex)
+ " select count(*) " + hql.substring(firstFromIndex);
}
return modifiedHQL;
}
@SuppressWarnings("rawtypes")
private boolean checkClobAttribute(String objClassName) {
PersistentClass pclass = cfg.getClassMapping(objClassName);
Iterator properties = pclass.getPropertyIterator();
while (properties.hasNext()) {
Property prop = (Property) properties.next();
if (!prop.getType().isAssociationType())
if (prop.getType().getName().equals("text"))
return true;
}
return false;
}
@SuppressWarnings("unused")
private boolean distinctRequired() {
boolean distinct = true;
boolean containsCLOB = checkClobAttribute(criteria
.getTargetObjectName());
boolean condition1 = condition1(criteria);
if (condition1 || containsCLOB)
distinct = false;
return distinct;
}
@SuppressWarnings("rawtypes")
private boolean inRequired() {
boolean condition2 = condition2(criteria);
boolean condition3 = condition3(criteria);
boolean condition1 = false;
// Verify if it is condition1() and it contains one object in the list
// with no associations
if (condition1(criteria)) {
condition1 = true;
List objects = criteria.getSourceObjectList();
if (objects == null) {
condition1 = false;
} else if (objects.size() == 1) {
try {
Object object = objects.get(0);
Map<String, Object> map = getAssociatedObjectCriterion(
object, cfg, null, null);
if (map == null || map.size() == 0) {
condition1 = false;
}
if (!condition1) {
condition1 = isComponentSetCriterion(object);
}
} catch (Exception e) {
log.error(" Ignore this error ", e);
}
}
}
if (condition2) {
try {
if (criteria.isTargetCollection()
&& !criteria.isSourceCollection()
&& criteria.getSourceRoleName() != null
&& criteria.getSourceObjectList().size() == 1
&& isObjectAssociationEmpty(criteria
.getSourceObjectList().iterator().next()))
condition2 = false;
} catch (Exception e) {
log.error(" Ignore this error ", e);
}
}
return condition1 || condition2 || condition3;
}
private HQLCriteria prepareQuery(StringBuffer hql) {
// Check if the target contains any CLOB. If yes then do a subselect
// with distinct else do plain distinct
String destAlias = getAlias(criteria.getTargetObjectName(), 1);
String countQ = "";
String normalQ = "";
String originalQ = hql.toString();
boolean distinctRequired = false; // indistinctRequired();
// never comes to else code, as a part of legacy code,not removed.
if (!distinctRequired) {
if (inRequired()) {
String modifiedQ = originalQ.replaceFirst(destAlias, destAlias
+ ".id");
String suffix = "from " + criteria.getTargetObjectName()
+ " as " + destAlias + " where " + destAlias
+ ".id in (" + modifiedQ + ")";
normalQ = "select " + destAlias + " " + suffix;
countQ = "select count(*) " + suffix;
} else {
normalQ = originalQ;
countQ = getCountQuery(originalQ);
}
} else {
normalQ = originalQ.replaceFirst("select " + destAlias,
"select distinct (" + destAlias + ") ");
countQ = originalQ.replaceFirst("select " + destAlias,
"select count(distinct " + destAlias + ".id) ");
}
log.debug("****** NormalQ: " + normalQ);
log.debug("****** CountQ: " + countQ);
HQLCriteria hCriteria = new HQLCriteria(normalQ, countQ, paramList);
return hCriteria;
}
private String getObjectAttributeCriterion(String sourceAlias, Object obj,
Configuration cfg, String parentClassName, String parentRoleName,
StringBuffer aliasSetBuffer) throws Exception {
StringBuffer whereClause = new StringBuffer();
Map<String, Object> criterionMap = getObjAttrCriterion(obj, cfg,
parentClassName, parentRoleName);
String rootKlass = obj.getClass().getName();
List<PersistentClass> pclasses = getPersistentClasses(rootKlass, parentClassName,
parentRoleName);
PersistentClass pclass=pclasses.iterator().next();
if (criterionMap != null) {
Iterator<String> keys = criterionMap.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
Object value = criterionMap.get(key);
boolean isStringObject = !key.equals("id")
&& (value instanceof String);
if (isStringObject) {
if (isCaseSensitive()) {
whereClause.append(sourceAlias + SystemConstant.DOT
+ key + getOperator(value) + "? ");
paramList
.add(((String) value).replaceAll("\\*", "\\%"));
} else {
whereClause.append("lower(" + sourceAlias
+ SystemConstant.DOT + key + ") "
+ getOperator(value) + "? ");
paramList.add(((String) value).toLowerCase()
.replaceAll("\\*", "\\%"));
}
} else {
boolean isIsoObject = !key.equals("id")
&& (value.getClass().getName()
.startsWith(isoprefix));
if (isIsoObject) {
StringBuffer tempBuffer = new StringBuffer();
Value componentValue = locateComponent(pclass, key);
String queryAppender = sourceAlias + SystemConstant.DOT
+ key;
String rootKlassWithAtt = rootKlass + "." + key;
generateISOWhereQuery(value, tempBuffer, whereClause,
componentValue, "", queryAppender, 0,
aliasSetBuffer, rootKlassWithAtt);
} else {
whereClause.append(sourceAlias)
.append(SystemConstant.DOT).append(key)
.append(getOperator(value)).append("? ");
paramList.add(value);
}
}
if (keys.hasNext())
whereClause.append(" and ");
}
}
return whereClause.toString();
}
private Value locateComponent(Object pV, String key) {
Value value;
try {
Property property = null;
if (pV instanceof Component) {
property = ((Component) pV).getProperty(key);
} else if (pV instanceof PersistentClass) {
property = ((PersistentClass) pV).getProperty(key);
}
if (property == null) {
return null;
}
value = property.getValue();
} catch (MappingException e) {
log.warn("Skipping processing of Hibernate mapping property " + key, e);
value = null;
}
return value;
}
/**
*
* @param obj
* sourceObject
* @param query
* tempStringBuffer to hold the state of HQL object
* (i.e)value1.item in recursion
* @param whereQueryClause
* Final Result to be appended to the HQL
* @param componentValue
* recursively parse PersistentClass to find required Component
* @param parentheses
* temporary value for adding ( braces and ) braces in case of
* Set ISO Object
* @param queryAppender
* temporary value to hold sourceAlias + key value
* @param andCount
* temporary value to maintain state whether to add "and"
* condition or not
* @param aliasSetBuffer
* @throws Exception
*/
@SuppressWarnings({"rawtypes"})
private void generateISOWhereQuery(Object obj, StringBuffer query,
StringBuffer whereQueryClause, Value componentValue,
String parentheses, String queryAppender, Integer andCount,
StringBuffer aliasSetBuffer, String rootKlassAttr) throws Exception {
Class klass = obj.getClass();
while (!klass.getName().equals("java.lang.Object")) {
for (Field field : klass.getDeclaredFields()) {
int modifier = field.getModifiers();
if (!Modifier.isStatic(modifier)) {
field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {
String fieldName = field.getName();
if (fieldName.equals("precision")
&& value instanceof Integer
&& ((Integer) value) == 0) {
continue;
} else if ((value instanceof AddressPartType || value instanceof EntityNamePartType)
&& fieldName.equals("type")) {
continue;
}
String objectClassName = value.getClass().getName();
StringBuffer newQuery = new StringBuffer(
query.toString());
newQuery.append(SystemConstant.DOT).append(fieldName);
boolean isoObject = objectClassName
.startsWith(isoprefix);
// parse the set and create an hql Set<CD>
boolean isSetObject = objectClassName
.startsWith("java.util.HashSet") && !fieldName.equalsIgnoreCase("qualifier");
boolean isEnumObject = value.getClass().isEnum();
boolean isListObject = objectClassName
.startsWith("java.util.ArrayList");
if (isListObject) {
if (fieldName.equals("partsInternal"))
continue;
processISOWhereQueryIfListObject(whereQueryClause,
componentValue, queryAppender, andCount,
aliasSetBuffer, rootKlassAttr, value,
newQuery);
} else {
if (fieldName.equals("partRestriction"))
continue;
Value persistChildvalue = locateComponent(componentValue, fieldName);
if (persistChildvalue == null) //Hibernate Mapping component was not found - skip processing of field
continue;
if (isoObject & !isEnumObject) {
parentheses = "";
generateISOWhereQuery(value, newQuery,
whereQueryClause, persistChildvalue,
parentheses, queryAppender, andCount++,
aliasSetBuffer, rootKlassAttr);
} else if (isSetObject) {
Set set = (Set) value;
int count = 0;
for (Object object : set) {
String setItemAlias = getAlias(object
.getClass().getName(), aliasCount++);
aliasSetBuffer.append(" inner join "
+ queryAppender
+ newQuery.toString() + " as "
+ setItemAlias);
parentheses = (count == 0)
? " (( "
: ") or ( ";
if (object.getClass()
.isAssignableFrom(Ad.class))
whereQueryClause.append(parentheses);
generateISOWhereQuery(object,
new StringBuffer(),
whereQueryClause,
persistChildvalue, parentheses,
setItemAlias, andCount,
aliasSetBuffer, rootKlassAttr);
count++;
}
whereQueryClause.append(" )) ");
} else {
String tempQuery = null;
if (isCaseSensitive()) {
tempQuery = parentheses + "lower("
+ queryAppender
+ newQuery.toString() + " )";
} else {
tempQuery = parentheses + queryAppender
+ newQuery.toString();
}
parentheses = "";
if (andCount > 0)
whereQueryClause.append(" and ");
whereQueryClause.append(tempQuery
+ getOperator(value) + "? ");
if (value instanceof String) {
paramList.add(((String) value).replaceAll(
"\\*", "\\%"));
} else {
if (fieldName.equalsIgnoreCase("qualifier")){
Set<EntityNamePartQualifier> qualifierSet = new HashSet<EntityNamePartQualifier>();
String qualifierValue = null;
Iterator itr = ((HashSet)value).iterator();
while(itr.hasNext()){
qualifierValue = (String)itr.next();
if (EntityNamePartQualifier.valueOf(qualifierValue) != null){
qualifierSet.add(EntityNamePartQualifier.valueOf(qualifierValue));
}
}
paramList.add(qualifierSet);
} else {
paramList.add(value);
}
}
andCount++;
}
}
}
}
}
klass = klass.getSuperclass();
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void processISOWhereQueryIfListObject(
StringBuffer whereQueryClause, Value componentValue,
String queryAppender, Integer andCount,
StringBuffer aliasSetBuffer, String rootKlassAttr, Object value,
StringBuffer newQuery) throws Exception {
List list = (List) value;
boolean isEnDataType = list.size() > 0
&& list.iterator().next().getClass()
.isAssignableFrom(Enxp.class);
if (isEnDataType) {
resolveISOWhereQueryForEN((List) value, newQuery,
(Component) componentValue, whereQueryClause,
queryAppender, andCount, aliasSetBuffer, rootKlassAttr);
} else if (componentValue.getClass().isAssignableFrom(
org.hibernate.mapping.Set.class)) {
org.hibernate.mapping.Set set = (org.hibernate.mapping.Set) componentValue;
Object element = set.getElement();
Object component = null;
if (element instanceof Component) {
component = element;
} else if (element instanceof ManyToOne){
ManyToOne manyToOne = (ManyToOne)element;
String many2OnePClassName = manyToOne.getReferencedEntityName();
if (!many2OnePClassName.startsWith("_xxEntityxx_gov_nih_nci_cacoresdk_domain_other_datatype")) {
throw new Exception("Unsupported Entity type detected. Expected: '_xxEntityxx_gov_nih_nci_cacoresdk_domain_other_datatype*', found: " + many2OnePClassName);
}
component = cfg.getClassMapping(many2OnePClassName);
} else if (element instanceof OneToMany){
OneToMany oneToMany = (OneToMany) element;
String oneToManyPClassName = oneToMany.getReferencedEntityName();
if (!oneToManyPClassName.startsWith("_xxEntityxx_gov_nih_nci_cacoresdk_domain_other_datatype")) {
throw new Exception("Unsupported Entity type detected. Expected: '_xxEntityxx_gov_nih_nci_cacoresdk_domain_other_datatype*', found: " + oneToManyPClassName);
}
component = cfg.getClassMapping(oneToManyPClassName);
} else {
throw new Exception("Unsupported ISO Data Type AD component detected: " + element.getClass().getName());
}
resolveISOWhereQueryForAd((List) value, newQuery, component,
whereQueryClause, queryAppender, andCount, aliasSetBuffer,
rootKlassAttr);
} else {
resolveISOWhereQueryForAd((List) value, newQuery,
(Component) componentValue, whereQueryClause,
queryAppender, andCount, aliasSetBuffer, rootKlassAttr);
}
}
private void resolveISOWhereQueryForEN(List<Enxp> valueList,
StringBuffer newQuery, Component componentValue,
StringBuffer whereQueryClause, String queryAppender,
Integer andCount, StringBuffer aliasSetBuffer, String rootKlassAttr)
throws Exception {
IsoConstantTuplizerHelper tuplizerHelper = new IsoConstantTuplizerHelper();
ComplexNode complexNode = tuplizerHelper
.getComplexNodeBean(rootKlassAttr);
List<Node> nodes = complexNode.getInnerNodes();
Map<String, String> map = new HashMap<String, String>();
String value=null;
for (Node node : nodes) {
if(node instanceof ConstantNode){
continue;
}
ComplexNode innerComplexNode = (ComplexNode) node;
value = innerComplexNode.getName();
String key = null;
List<Node> innerNodes = innerComplexNode.getInnerNodes();
for (Node innerNode : innerNodes) {
if (innerNode instanceof ConstantNode
&& innerNode.getName().equals("type")) {
ConstantNode constantNode = (ConstantNode) innerNode;
key = constantNode.getConstantValue();
map.put(key, value);
break;
}
}
}
if (value == null) {
String exceptionMessage = "Tag value 'mapped-constant' missing for entity name part 'type' for attribute "
+ rootKlassAttr + " in the domain model.";
log.error(exceptionMessage);
throw new Exception(exceptionMessage);
}
Set<String> keySet = map.keySet();
for (Enxp enxp : valueList) {
if (enxp.getType() != null && (enxp.getCode() == null && enxp.getCodeSystem() == null && enxp.getCodeSystemVersion() == null && enxp.getQualifier() == null && enxp.getValue() == null))
throw new Exception("If Entity Name Part type is specified, Entity Name Part code, code system, code system version, qualifier, and / or value must also be specified");
if (enxp.getType() == null && (enxp.getCode() != null || enxp.getCodeSystem() != null || enxp.getCodeSystemVersion() == null || enxp.getQualifier() == null || enxp.getValue() != null))
throw new Exception("If Entity Name Part code, code system, code system version, qualifier, or value is specified, Entity Name Part type must also be specified");
StringBuffer tempNewQuery = new StringBuffer(newQuery.toString());
EntityNamePartType entityNamePartType = enxp.getType();
String partNameMatch = entityNamePartType.toString();
if (keySet.contains(partNameMatch)) {
String partName = map.get(partNameMatch);
int index = partName.indexOf('_');
String componentPartName = partName.substring(index,
partName.length());
tempNewQuery.append(componentPartName);
String parentheses = "";
Value persistChildvalue = locateComponent(componentValue,partName);
generateISOWhereQuery(enxp, tempNewQuery, whereQueryClause,
persistChildvalue, parentheses, queryAppender,
andCount++, aliasSetBuffer, rootKlassAttr);
} else {
String message = "No En ISO Data Type Entity Name part type 'mapped-constant' tag value found for specified type " + enxp.getType() + " and attribute " + rootKlassAttr + " in domain model.";
log.error(message);
throw new Exception(message);
}
}
}
private void resolveISOWhereQueryForAd(List<? extends Object> valueList,
StringBuffer newQuery, Object componentValue,
StringBuffer whereQueryClause, String queryAppender,
Integer andCount, StringBuffer aliasSetBuffer, String rootKlassAttr)
throws Exception {
Map<String, Set<String>> addressPartTypeMap = new HashMap<String, Set<String>>();
for (Object object : valueList) {
Adxp adxp = (Adxp)object;
if (adxp.getType() != null && (adxp.getCode() == null && adxp.getCodeSystem() == null && adxp.getValue() == null))
throw new Exception("If Address Part type is specified, the Address Part code, code system, and / or value must also be specified");
if (adxp.getType() == null && (adxp.getCode() != null || adxp.getCodeSystem() != null || adxp.getValue() != null))
throw new Exception("If Address Part code, code system, or value is specified, Address Part type must also be specified");
Field partInstanceObjectField = null;
StringBuffer tempNewQuery = new StringBuffer(newQuery.toString());
partInstanceObjectField = getDeclaredField(object.getClass(),
"type");
partInstanceObjectField.setAccessible(true);
Object partType = partInstanceObjectField.get(object);
Iterator<Property> propertyItr = null;
if (componentValue instanceof Component){
propertyItr = ((Component)componentValue).getPropertyIterator();
} else if (componentValue instanceof PersistentClass){
propertyItr = ((PersistentClass)componentValue).getPropertyIterator();
}
@SuppressWarnings("unchecked")
boolean isValidPartType = false;
while (propertyItr.hasNext()) {
Property property = propertyItr.next();
String partName = property.getName();
Component psComp = (Component) property.getValue();
String psCompClassName = psComp.getComponentClassName();
String partTypeClassName = partType.getClass().getName();
String partTypeName = partTypes.get(partTypeClassName)
+ partType;
if (psCompClassName.equalsIgnoreCase(partTypeName)) {
// search for matching part name (part_0,part_1,part_2 etc)
if (addressPartTypeMap.keySet().contains(partTypeName)) {
Set<String> parts = addressPartTypeMap
.get(partTypeName);
if (parts.contains(partName)) {
continue;
} else {
parts.add(partName);
}
} else {
Set<String> parts = new HashSet<String>();
parts.add(partName);
addressPartTypeMap.put(partTypeName, parts);
}
Value persistChildvalue = locateComponent(componentValue,partName);
int index = partName.indexOf('_');
String componentPartName = partName.substring(index,
partName.length());
tempNewQuery.append(componentPartName);
String parentheses = "";
generateISOWhereQuery(object, tempNewQuery,
whereQueryClause, persistChildvalue, parentheses,
queryAppender, andCount++, aliasSetBuffer,
rootKlassAttr);
isValidPartType = true;
break;
}
}
if (!isValidPartType) {
throw new Exception(" Invalid Address PartType " + partType
+ " specified in RESTfulQuery");
}
}
}
private void resolveISOWhereQueryForDsetAdMany2One(List<? extends Object> valueList,
StringBuffer newQuery, PersistentClass componentValue,
StringBuffer whereQueryClause, String queryAppender,
Integer andCount, StringBuffer aliasSetBuffer, String rootKlassAttr)
throws Exception {
Map<String, Set<String>> addressPartTypeMap = new HashMap<String, Set<String>>();
for (Object object : valueList) {
Adxp adxp = (Adxp)object;
if (adxp.getType() != null && (adxp.getCode() == null && adxp.getCodeSystem() == null && adxp.getValue() == null))
throw new Exception("If Address Part type is specified, the Address Part code, code system, and / or value must also be specified");
if (adxp.getType() == null && (adxp.getCode() != null || adxp.getCodeSystem() != null || adxp.getValue() != null))
throw new Exception("If Address Part code, code system, or value is specified, Address Part type must also be specified");
Field partInstanceObjectField = null;
StringBuffer tempNewQuery = new StringBuffer(newQuery.toString());
partInstanceObjectField = getDeclaredField(object.getClass(),"type");
partInstanceObjectField.setAccessible(true);
Object partType = partInstanceObjectField.get(object);
//Component partComponent = (Component) componentValue;
@SuppressWarnings("unchecked")
Iterator<Property> propertyItr = componentValue.getPropertyIterator();
boolean isValidPartType = false;
while (propertyItr.hasNext()) {
Property property = propertyItr.next();
String partName = property.getName();
Component psComp = (Component) property.getValue();
String psCompClassName = psComp.getComponentClassName();
String partTypeClassName = partType.getClass().getName();
String partTypeName = partTypes.get(partTypeClassName)
+ partType;
if (psCompClassName.equalsIgnoreCase(partTypeName)) {
// search for matching part name (part_0,part_1,part_2 etc)
if (addressPartTypeMap.keySet().contains(partTypeName)) {
Set<String> parts = addressPartTypeMap
.get(partTypeName);
if (parts.contains(partName)) {
continue;
} else {
parts.add(partName);
}
} else {
Set<String> parts = new HashSet<String>();
parts.add(partName);
addressPartTypeMap.put(partTypeName, parts);
}
Value persistChildvalue = locateComponent(componentValue,partName);
int index = partName.indexOf('_');
String componentPartName = partName.substring(index,
partName.length());
tempNewQuery.append(componentPartName);
String parentheses = "";
generateISOWhereQuery(object, tempNewQuery,
whereQueryClause, persistChildvalue, parentheses,
queryAppender, andCount++, aliasSetBuffer,
rootKlassAttr);
isValidPartType = true;
break;
}
}
if (!isValidPartType) {
throw new Exception(" Invalid Address PartType " + partType
+ " specified in RESTfulQuery");
}
}
}
@SuppressWarnings("rawtypes")
private boolean isObjectPrimitive(Object value) {
if (value instanceof Collection && ((Collection) value).size() > 0) {
return false;
}
if (!(value instanceof Integer || value instanceof Float
|| value instanceof Double || value instanceof Character
|| value instanceof Long || value instanceof Boolean
|| value instanceof Byte || value instanceof Short
|| value instanceof String || value instanceof Date)) {
return false;
}
return true;
}
private Map<String, Object> getObjAttrCriterion(Object obj,
Configuration cfg, String parentClassName, String parentRoleName)
throws Exception {
Map<String, Object> criterions = new HashMap<String, Object>();
String objClassName = obj.getClass().getName();
List<PersistentClass> pclasses = getPersistentClasses(objClassName,
parentClassName, parentRoleName);
PersistentClass pclass = null;
if (pclasses != null && pclasses.size() > 0) {
pclass = pclasses.iterator().next();
}
if (pclass != null) {
Map<String, Object> tempObjectCriterion = getCriterionForComponentAndAttribute(
obj, pclass);
if (tempObjectCriterion != null) {
criterions.putAll(tempObjectCriterion);
}
while (pclass.getSuperclass() != null) {
pclass = pclass.getSuperclass();
if (pclass != null) {
Map<String, Object> tempObjectCriterion2 = getCriterionForComponentAndAttribute(
obj, pclass);
if (tempObjectCriterion2 != null) {
criterions.putAll(tempObjectCriterion2);
}
}
}
Property identifierProperty = pclass.getIdentifierProperty();
// in case of iso-datatypes identifier property is hidden.
if (identifierProperty == null) {
return criterions;
}
String identifier = identifierProperty.getName();
Field idField = getDeclaredField(pclass.getMappedClass(),
identifier);
idField.setAccessible(true);
try {
if (idField.get(obj) != null)
criterions.put(identifier, idField.get(obj));
} catch (Exception e) {
// Do nothing - when dealing with implicit queries, pclass would
// be the concrete subclass of obj,
// and the identifier field might be in a subclass of obj
}
}
return criterions;
}
@SuppressWarnings({"rawtypes"})
private Map<String, Object> getCriterionForComponentAndAttribute(
Object obj, PersistentClass pclass) throws Exception {
Map<String, Object> criterions = new HashMap<String, Object>();
Iterator properties = pclass.getPropertyIterator();
if (!properties.hasNext()) {
return null;
}
Property tempProperty = (Property) pclass.getPropertyIterator().next();
String propertyAccessorName = tempProperty.getPropertyAccessorName();
boolean isPropertyCollectionAccessor = propertyAccessorName
.equals("gov.nih.nci.iso21090.hibernate.property.CollectionPropertyAccessor");
if ((tempProperty.getType().isComponentType() && isPropertyCollectionAccessor)) {
String tempFieldName = tempProperty.getName();
Field field = null;
int truncatedFieldLength = tempFieldName.length() - 2;
String tempComFieldName = tempFieldName.substring(0,
truncatedFieldLength);
field = getDeclaredField(pclass.getMappedClass(), tempComFieldName);
field.setAccessible(true);
List parts = (List) field.get(obj);
boolean hasFoundComponent = false;
while (properties.hasNext()) {
Property prop = (Property) properties.next();
String fieldName = prop.getName();
Component psComp = (Component) prop.getValue();
String psCompClassName = psComp.getComponentClassName();
Adxp adxpPart = null;
for (Object part : parts) {
adxpPart = (Adxp) part;
String addressPartTypeName = "gov.nih.nci.iso21090.Adxp"
+ adxpPart.getType().name();
if (psCompClassName.equalsIgnoreCase(addressPartTypeName)) {
String comFieldName = fieldName;
criterions.put(comFieldName, adxpPart);
hasFoundComponent = true;
break;
}
}
if (hasFoundComponent)
parts.remove(adxpPart);
}
} else {
while (properties.hasNext()) {
Property prop = (Property) properties.next();
if (!prop.getType().isAssociationType()) {
String fieldName = prop.getName();
Field field = getDeclaredField(pclass.getMappedClass(),
fieldName);
field.setAccessible(true);
try {
if (field.get(obj) != null) {
if (prop.getType().getName().equals("text"))
criterions.put(fieldName, field.get(obj) + "*");
else
criterions.put(fieldName, field.get(obj));
}
} catch (Exception e) {
// Do nothing - when dealing with implicit queries,
// pclass
// would be the concrete subclass of obj, and thus
// contain
// fields that are not in obj
}
}
}
}
return criterions;
}
private String getHQLQueryFromSourceObjectWithCriterion(Object obj,
Configuration cfg, boolean skipAssociations) throws Exception {
return getHQLQueryFromSourceObjectWithCriterion(obj, cfg,
skipAssociations, null, null);
}
// get the result HQL String from the Object obj
private String getHQLQueryFromSourceObjectWithCriterion(Object obj,
Configuration cfg, boolean skipAssociations, String parentClass,
String parentRoleName) throws Exception {
String srcAlias=this.srcAlias;
if (this.srcAlias == null)
srcAlias = getAlias(obj.getClass().getName(), 1);
StringBuffer hql = new StringBuffer();
Map<String, Object> associationCritMap = null;
if (!skipAssociations) {
associationCritMap = getAssociatedObjectCriterion(obj, cfg,
parentClass, parentRoleName);
List<PersistentClass> tempPclasses = getPersistentClasses(obj
.getClass().getName(), parentClass, parentRoleName);
PersistentClass tempPclass = tempPclasses.iterator().next();
hql.append("select ");
hql.append(srcAlias);
hql.append(" from ").append(tempPclass.getEntityName()).append(" ")
.append(srcAlias);
if (associationCritMap != null && associationCritMap.size() > 0) {
StringBuffer associationHQL = generateAssociationHQLCriteria(
cfg, srcAlias, associationCritMap, tempPclass);
hql.append(associationHQL);
}
}
StringBuffer aliasSetBuffer = new StringBuffer();
String attributeCriteria = getObjectAttributeCriterion(srcAlias, obj,
cfg, parentClass, parentRoleName, aliasSetBuffer);
hql.append(aliasSetBuffer.toString());
if ((associationCritMap == null || associationCritMap.size() == 0
&& attributeCriteria != null
&& attributeCriteria.trim().length() > 0)
&& !skipAssociations)
hql.append(" where ");
if (associationCritMap != null && associationCritMap.size() > 0
&& attributeCriteria != null
&& attributeCriteria.trim().length() > 0)
hql.append(" ").append(" and ");
hql.append(attributeCriteria);
log.info("HQL query: " + hql.toString());
return hql.toString();
}
@SuppressWarnings("rawtypes")
private StringBuffer generateAssociationHQLCriteria(Configuration cfg,
String srcAlias, Map<String, Object> associationCritMap,
PersistentClass tempPclass) throws Exception {
Iterator<String> associationKeys = associationCritMap.keySet()
.iterator();
StringBuffer hql = new StringBuffer();
int counter = 0;
while (associationKeys.hasNext()) {
String roleName = associationKeys.next();
Object roleValue = associationCritMap.get(roleName);
if (roleValue instanceof Collection) {
Object[] objs = ((Collection) roleValue).toArray();
for (int i = 0; i < objs.length; i++) {
List<PersistentClass> tempRolePclasses = getPersistentClasses(
objs[i].getClass().getName(),
tempPclass.getEntityName(), roleName);
String alias = getAlias(objs[i].getClass().getName(),
counter++);
String objectClassName = null;
if (tempRolePclasses.size() > 1) {
objectClassName = objs[i].getClass().getName();
} else {
PersistentClass tempRolePClass = tempRolePclasses
.iterator().next();
objectClassName = tempRolePClass.getEntityName();
}
hql.append(",").append(objectClassName).append(" ")
.append(alias);
}
} else {
List<PersistentClass> tempRolePclasses = getPersistentClasses(
roleValue.getClass().getName(),
tempPclass.getEntityName(), roleName);
String alias = getAlias(roleValue.getClass().getName(),
counter++);
String roleEntityName = null;
if (tempRolePclasses.size() > 1) {
roleEntityName = roleValue.getClass().getName();
} else {
PersistentClass tempRolePClass = tempRolePclasses
.iterator().next();
roleEntityName = tempRolePClass.getEntityName();
}
hql.append(",").append(roleEntityName).append(" ")
.append(alias);
}
}
hql.append(" where ");
associationKeys = associationCritMap.keySet().iterator();
counter = 0;
while (associationKeys.hasNext()) {
String roleName = associationKeys.next();
Object roleValue = associationCritMap.get(roleName);
if (roleValue instanceof Collection) {
Object[] objs = ((Collection) roleValue).toArray();
for (int i = 0; i < objs.length; i++) {
String alias = getAlias(objs[i].getClass().getName(),
counter++);
hql.append(alias).append(" in elements(").append(srcAlias)
.append(".").append(roleName).append(")");
hql.append(" and ");
String objectCriterion = getHQLQueryFromSourceObjectWithCriterion(
objs[i], cfg, false, tempPclass.getEntityName(),
roleName);
hql.append(alias).append(" in (").append(objectCriterion)
.append(") ");
if (i < objs.length - 1)
hql.append(" and ");
}
} else {
String alias = getAlias(roleValue.getClass().getName(),
counter++);
hql.append(alias).append(".id").append("=").append(srcAlias)
.append(".").append(roleName).append(".id");
hql.append(" and ");
String objectCriterion = getHQLQueryFromSourceObjectWithCriterion(
roleValue, cfg, false, tempPclass.getEntityName(),
roleName);
hql.append(alias).append(" in (").append(objectCriterion)
.append(") ");
}
hql.append(" ");
if (associationKeys.hasNext())
hql.append(" and ");
}
return hql;
}
@SuppressWarnings({"rawtypes"})
private Map<String, Object> getAssociatedObjectWithFieldCriterion(
Object obj, PersistentClass pclass) throws Exception {
Map<String, Object> criterions = new HashMap<String, Object>();
Iterator properties = pclass.getPropertyIterator();
while (properties.hasNext()) {
Property prop = (Property) properties.next();
if (prop.getType().isAssociationType()) {
String fieldName = prop.getName();
Field field = getDeclaredField(pclass.getMappedClass(),
fieldName);
field.setAccessible(true);
try {
Object value = field.get(obj);
if (value != null)
if ((value instanceof Collection && ((Collection) value)
.size() > 0) || !(value instanceof Collection))
criterions.put(fieldName, field.get(obj));
} catch (Exception e) {
// Do nothing - when dealing with implicit queries, pclass
// would be the concrete subclass of obj, and thus contain
// fields that are not in obj
}
}
}
return criterions;
}
// component set don't have primary key
// avoid duplication of result set.
@SuppressWarnings("rawtypes")
private boolean isComponentSetCriterion(Object obj) throws Exception {
List<PersistentClass> pclasses = getPersistentClasses(obj.getClass()
.getName(), null, null);
PersistentClass pclass = pclasses.iterator().next();
Iterator properties = pclass.getPropertyIterator();
while (properties.hasNext()) {
Property prop = (Property) properties.next();
// is component
if (prop.getType().isComponentType()) {
String fieldName = prop.getName();
Field field = getDeclaredField(pclass.getMappedClass(),
fieldName);
field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {
Field[] fields = value.getClass().getDeclaredFields();
for (Field componentField : fields) {
componentField.setAccessible(true);
Object comFieldObject = componentField.get(value);
// is of Type Set
if (comFieldObject != null
&& (comFieldObject instanceof Collection && ((Collection) comFieldObject)
.size() > 0)) {
return true;
}
}
}
}
}
return false;
}
private Map<String, Object> getAssociatedObjectCriterion(Object obj,
Configuration cfg, String parentClassName, String parentRoleName)
throws Exception {
Map<String, Object> criterions = null;
Map<String, Object> superClassCriterions = null;
String objClassName = obj.getClass().getName();
List<PersistentClass> pclasses = getPersistentClasses(objClassName,
parentClassName, parentRoleName);
PersistentClass pclass = null;
if (pclasses != null) {
pclass = pclasses.iterator().next();
}
if (pclass != null) {
criterions = getAssociatedObjectWithFieldCriterion(obj, pclass);
pclass = pclass.getSuperclass();
while (pclass != null) {
superClassCriterions = getAssociatedObjectWithFieldCriterion(
obj, pclass);
pclass = pclass.getSuperclass();
}
}
if (superClassCriterions != null)
criterions.putAll(superClassCriterions);
return criterions;
}
private String getAlias(String sourceName, int count) {
String alias = sourceName.substring(sourceName
.lastIndexOf(SystemConstant.DOT) + 1);
alias = alias.substring(0, 1).toLowerCase() + alias.substring(1);
return alias + "_" + count;
}
private String getOperator(Object valueObj) {
if (valueObj instanceof java.lang.String) {
String value = (String) valueObj;
if (value.indexOf('*') >= 0) {
return " like ";
}
}
return "=";
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
@SuppressWarnings("rawtypes")
private Field getDeclaredField(Class klass, String fieldName)
throws NoSuchFieldException {
Field field = null;
do {
try {
field = klass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
field = null;
klass = klass.getSuperclass();
}
} while (!klass.getName().equals("java.lang.Object") && field == null);
if (field == null)
throw new NoSuchFieldException("fieldName: " + fieldName);
return field;
}
private List<PersistentClass> getPersistentClasses(String objClassName,
String parentObjectClassName, String parentRoleName)
throws Exception {
List<PersistentClass> pClasses = getPersistentClassList(objClassName);
if (pClasses.size() == 1) {
return pClasses;
}
if (parentObjectClassName == null || parentRoleName == null
&& pClasses.size() > 1) {
return pClasses; }
for (PersistentClass persistentClass : pClasses) {
parentObjectClassName = parentObjectClassName.replace('.', '_');
String tempSubString = parentObjectClassName + "_" + parentRoleName;
String childPClassName = persistentClass.getEntityName();
if (childPClassName.contains(tempSubString)) {
List<PersistentClass> tempPClasses=new ArrayList<PersistentClass>();
tempPClasses.add(persistentClass);
return tempPClasses;
}
}
return null;
}
@SuppressWarnings({"rawtypes", "unchecked"})
private List<PersistentClass> getPersistentClassList(String objClassName) {
List<PersistentClass> pClasses = new ArrayList<PersistentClass>();
PersistentClass pclass = cfg.getClassMapping(objClassName);
if (pclass == null) {// might be dealing with an implicit class. Check
// to see if we have a persistent subclass
// mapping we can use instead
Iterator iter = cfg.getClassMappings();
Class objClass = null;
try {
objClass = Class.forName(objClassName);
} catch (ClassNotFoundException e1) {
log.error("Class not found for " + objClassName);
return null;
}
while (iter.hasNext()) {
pclass = (PersistentClass) iter.next();
try {
(pclass.getMappedClass()).asSubclass(objClass);
log.debug("Searching for persistent subclass of "
+ objClassName + "; found " + pclass.getClassName());
pClasses.add(pclass);
} catch (Exception e) {
// do nothing
}
}// while
} else {
pClasses.add(pclass);
}
return pClasses;
}
@SuppressWarnings("rawtypes")
private boolean isObjectEmpty(Object obj) {
Class klass = obj.getClass();
while (!klass.getName().equals("java.lang.Object")) {
for (Field field : klass.getDeclaredFields()) {
int modifier = field.getModifiers();
if (!Modifier.isStatic(modifier)) {
try {
field.setAccessible(true);
Object value = field.get(obj);
if (value != null && value instanceof Collection
&& ((Collection) value).size() > 0)
return false;
if (value != null)
return false;
} catch (IllegalArgumentException e) {
// No action
} catch (IllegalAccessException e) {
// No action
}
}
}
klass = klass.getSuperclass();
}
return true;
}
@SuppressWarnings("rawtypes")
private boolean isObjectAssociationEmpty(Object obj) throws Exception {
Class klass = obj.getClass();
while (!klass.getName().equals("java.lang.Object")) {
for (Field field : klass.getDeclaredFields()) {
int modifier = field.getModifiers();
if (!Modifier.isStatic(modifier)) {
try {
field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {
isObjectPrimitive(value);
}
} catch (IllegalArgumentException e) {
// No action
} catch (IllegalAccessException e) {
// No action
}
}
}
klass = klass.getSuperclass();
}
return true;
}
}
|
package net.sf.farrago.test;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.regex.Pattern;
import junit.framework.Assert;
import junit.framework.Test;
import java.sql.Date;
* API. See also unitsql/jdbc/*.sql.
*
* todo: test:
* 1. string too long for char/varchar field
* 2. value which converted to char/varchar is too long
* 3. various numeric values out of range, e.g. put 65537 in a tinyint
* 4. assign boolean to integer columns (becomes 0/1)
* 5. assign numerics to boolean
* 5a. small enough
* 5b out of range (not 0 or 1)
*
* @author Tim Leung
* @author John V. Sichi
* @version $Id$
*/
public class FarragoJdbcTest extends FarragoTestCase
{
// Constants used by testDataTypes
private static final byte minByte = Byte.MIN_VALUE;
private static final byte maxByte = Byte.MAX_VALUE;
private static final short minShort = Short.MIN_VALUE;
private static final short maxShort = Short.MAX_VALUE;
private static final int minInt = Integer.MIN_VALUE;
private static final int maxInt = Integer.MAX_VALUE;
private static final long minLong = Long.MIN_VALUE;
private static final long maxLong = Long.MAX_VALUE;
private static final float minFloat = Float.MIN_VALUE;
private static final float maxFloat = Float.MAX_VALUE;
private static final double minDouble = Double.MIN_VALUE;
private static final double maxDouble = Double.MAX_VALUE;
private static final boolean boolValue = true;
private static final BigDecimal bigDecimalValue =
new BigDecimal(maxDouble);
private static final String stringValue = "0";
private static final byte [] bytes = { 127, -34, 56, 29, 56, 49 };
/**
* A point of time in Sydney, Australia. (The timezone is deliberately not
* PST, where the test is likely to be run, or GMT, and should be in
* daylight-savings time in December.)
*
* 4:22:33.456 PM on 21st December 2004 Japan (GMT+9)
* is 9 hours earlier in GMT, namely
* 7:22:33.456 AM on 21st December 2004 GMT
* and is another 8 hours earlier in PST:
* 11:22:33.456 PM on 20th December 2004 PST (GMT-8)
*/
private static final Calendar sydneyCal =
makeCalendar("JST", 2004, 11, 21, 16, 22, 33, 456);
private static final Time time = new Time(sydneyCal.getTime().getTime());
private static final Date date = new Date(sydneyCal.getTime().getTime());
static {
// Sanity check, assuming local time is PST
String tzID = TimeZone.getDefault().getID();
if (tzID.equals("America/Tijuana")) {
String t = time.toString();
assert t.equals("23:22:33") : t;
String d = date.toString();
assert d.equals("2004-12-20") : d;
}
}
private static final Timestamp timestamp =
new Timestamp(sydneyCal.getTime().getTime());
private static final Byte tinyIntObj = new Byte(minByte);
private static final Short smallIntObj = new Short(maxShort);
private static final Integer integerObj = new Integer(minInt);
private static final Long bigIntObj = new Long(maxLong);
private static final Float floatObj = new Float(maxFloat);
private static final Double doubleObj = new Double(maxDouble);
private static final Boolean boolObj = Boolean.FALSE;
private static final BigDecimal decimalObj =
new BigDecimal(13412342124143241D);
private static final String charObj = "CHAR test string";
private static final String varcharObj = "VARCHAR test string";
private static final int TINYINT = 2;
private static final int SMALLINT = 3;
private static final int INTEGER = 4;
private static final int BIGINT = 5;
private static final int REAL = 6;
private static final int FLOAT = 7;
private static final int DOUBLE = 8;
private static final int BOOLEAN = 9;
private static final int CHAR = 10;
private static final int VARCHAR = 11;
private static final int BINARY = 12;
private static final int VARBINARY = 13;
private static final int TIME = 14;
private static final int DATE = 15;
private static final int TIMESTAMP = 16;
private static boolean schemaExists = false;
private static final String [] columnNames =
new String[TestSqlType.all.length];
private static String columnTypeStr = "";
private static String columnStr = "";
private static String paramStr = "";
static {
for (int i = 0; i < TestSqlType.all.length; i++) {
final TestSqlType sqlType = TestSqlType.all[i];
assert sqlType.ordinal == (i + 2);
columnNames[i] =
"\"Column " + (i + 1) + ": " + sqlType.string + "\"";
if (i > 0) {
columnTypeStr += ", ";
columnStr += ", ";
paramStr += ", ";
}
columnTypeStr += (columnNames[i] + " " + sqlType.string);
columnStr += columnNames[i];
paramStr += "?";
}
columnTypeStr = "id integer primary key, " + columnTypeStr;
columnStr = "id, " + columnStr;
paramStr = "( ?, " + paramStr + ")";
}
// Flags indicating whether bugs have been fixed. (It's better to 'if'
// out than to comment out code, because commented out code doesn't get
// refactored.)
private static final boolean dtbug119_fixed = false;
private static final boolean todo = false;
private Object [] values;
/**
* Creates a new FarragoJdbcTest object.
*/
public FarragoJdbcTest(String testName)
throws Exception
{
super(testName);
}
// implement TestCase
public static Test suite()
{
return wrappedSuite(FarragoJdbcTest.class);
}
/**
* Creates a calendar.
*/
private static Calendar makeCalendar(
String tz,
int year,
int month,
int date,
int hour,
int minute,
int second,
int millis)
{
final Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, month, date, hour, minute, second);
cal.set(Calendar.MILLISECOND, millis);
TimeZone timeZone = TimeZone.getTimeZone(tz);
cal.setTimeZone(timeZone);
return cal;
}
public void testSynchronousCancel()
throws Exception
{
testCancel(true);
}
public void testAsynchronousCancel()
throws Exception
{
testCancel(false);
}
private void testCancel(boolean synchronous)
throws Exception
{
// cleanup
String sql = "drop schema cancel_test cascade";
try {
stmt.execute(sql);
} catch (SQLException ex) {
// ignore
}
sql = "create schema cancel_test";
stmt.execute(sql);
sql = "create foreign table cancel_test.m(id int not null) "
+ "server sys_mock_foreign_data_server "
+ "options(executor_impl 'FENNEL', row_count '1000000000')";
stmt.execute(sql);
sql = "select * from cancel_test.m";
resultSet = stmt.executeQuery(sql);
boolean found;
found = resultSet.next();
assertTrue(found);
found = resultSet.next();
assertTrue(found);
if (synchronous) {
// cancel immediately
stmt.cancel();
} else {
Timer timer = new Timer(true);
// cancel after 2 seconds
TimerTask task = new TimerTask()
{
public void run()
{
try {
stmt.cancel();
} catch (SQLException ex) {
Assert.fail(
"Cancel request failed: "
+ ex.getMessage());
}
}
};
timer.schedule(task, 2000);
}
try {
while (resultSet.next()) {
}
} catch (SQLException ex) {
// expected
Assert.assertTrue(ex.getMessage().indexOf("abort") > -1);
return;
}
Assert.fail("Expected failure due to cancel request");
}
// NOTE jvs 26-July-2004: some of the tests in this class modify fixture
// tables such as SALES.EMPS, but that's OK, because transactions are
// implicitly rolled back by FarragoTestCase.tearDown.
public void testPreparedStmtDataTypes()
throws Exception
{
String query =
"insert into datatypes_schema.dataTypes_table values " + paramStr;
preparedStmt = connection.prepareStatement(query);
values = new Object[2 + TestSqlType.all.length];
preparedStmt.setInt(1, 100);
checkSetString();
checkSetByteMin();
checkSetByteMax();
checkSetShortMin();
checkSetShortMax();
checkSetIntMin();
checkSetIntMax();
checkSetLongMin();
checkSetLongMax();
checkSetFloatMin();
checkSetFloatMax();
checkSetDoubleMin();
checkSetDoubleMax();
checkSetBooleanFalse();
if (todo) {
// BigDecimal values seem to go in but don't come out!
checkSetBigDecimal();
}
checkSetBytes();
checkSetDate();
checkSetTime();
checkSetTimestamp();
checkSetObject();
}
protected void setUp()
throws Exception
{
super.setUp();
synchronized (getClass()) {
if (!schemaExists) {
stmt.executeUpdate("create schema datatypes_schema");
stmt.executeUpdate(
"create table datatypes_schema.dataTypes_table ("
+ columnTypeStr + ")");
}
schemaExists = true;
}
}
private void checkSetObject()
throws SQLException
{
// Test PreparedStatement.setObject(int,Object) for each kind
// of object.
preparedStmt.setObject(TINYINT, tinyIntObj);
values[TINYINT] = tinyIntObj;
preparedStmt.setObject(SMALLINT, smallIntObj);
values[SMALLINT] = smallIntObj;
preparedStmt.setObject(INTEGER, integerObj);
values[INTEGER] = integerObj;
preparedStmt.setObject(BIGINT, bigIntObj);
values[BIGINT] = bigIntObj;
preparedStmt.setObject(REAL, floatObj);
values[REAL] = floatObj;
preparedStmt.setObject(FLOAT, doubleObj);
values[FLOAT] = doubleObj;
preparedStmt.setObject(DOUBLE, doubleObj);
values[DOUBLE] = doubleObj;
preparedStmt.setObject(BOOLEAN, boolObj);
values[BOOLEAN] = boolObj;
preparedStmt.setObject(CHAR, charObj);
values[CHAR] = charObj;
preparedStmt.setObject(VARCHAR, varcharObj);
values[VARCHAR] = varcharObj;
preparedStmt.setObject(BINARY, bytes);
values[BINARY] = bytes;
preparedStmt.setObject(VARBINARY, bytes);
values[VARBINARY] = bytes;
preparedStmt.setObject(DATE, date);
values[DATE] = date;
preparedStmt.setObject(TIME, time);
values[TIME] = time;
preparedStmt.setObject(TIMESTAMP, timestamp);
values[TIMESTAMP] = timestamp;
checkResults(TestJavaType.Object);
}
private void checkSetTimestamp()
throws Exception
{
checkSet(TestJavaType.Timestamp, TestSqlType.Char, timestamp);
checkSet(TestJavaType.Timestamp, TestSqlType.Varchar, timestamp);
checkSet(TestJavaType.Timestamp, TestSqlType.Date, timestamp);
checkSet(TestJavaType.Timestamp, TestSqlType.Time, timestamp);
checkSet(TestJavaType.Timestamp, TestSqlType.Timestamp, timestamp);
checkResults(TestJavaType.Timestamp);
}
private void checkSetTime()
throws Exception
{
checkSet(TestJavaType.Time, TestSqlType.Char, time);
checkSet(TestJavaType.Time, TestSqlType.Varchar, time);
checkSet(TestJavaType.Time, TestSqlType.Time, time);
checkSet(TestJavaType.Time, TestSqlType.Timestamp, time);
checkResults(TestJavaType.Time);
}
private void checkSetDate()
throws Exception
{
checkSet(TestJavaType.Date, TestSqlType.Char, date);
checkSet(TestJavaType.Date, TestSqlType.Varchar, date);
checkSet(TestJavaType.Date, TestSqlType.Date, date);
checkSet(TestJavaType.Date, TestSqlType.Timestamp, date);
checkResults(TestJavaType.Date);
}
private void checkSetBytes()
throws Exception
{
checkSet(TestJavaType.Bytes, TestSqlType.typesBinary, bytes);
checkResults(TestJavaType.Bytes);
}
private void checkSetBigDecimal()
throws Exception
{
checkSet(TestJavaType.BigDecimal, TestSqlType.typesNumericAndChars,
bigDecimalValue);
checkResults(TestJavaType.BigDecimal);
}
private void checkSetBooleanFalse()
throws Exception
{
checkSet(
TestJavaType.Boolean, TestSqlType.typesNumericAndChars, boolObj);
checkResults(TestJavaType.Boolean);
}
private void checkSetDoubleMax()
throws Exception
{
checkSet(
TestJavaType.Double,
TestSqlType.typesNumericAndChars,
new Double(maxDouble));
checkResults(TestJavaType.Double);
}
private void checkSetDoubleMin()
throws Exception
{
checkSet(
TestJavaType.Double,
TestSqlType.typesNumericAndChars,
new Double(minDouble));
checkResults(TestJavaType.Double);
}
private void checkSetFloatMax()
throws Exception
{
checkSet(
TestJavaType.Float,
TestSqlType.typesNumericAndChars,
new Float(maxFloat));
checkResults(TestJavaType.Float);
}
private void checkSetFloatMin()
throws Exception
{
checkSet(
TestJavaType.Float,
TestSqlType.typesNumericAndChars,
new Float(minFloat));
checkResults(TestJavaType.Float);
}
private void checkSetLongMax()
throws Exception
{
checkSet(
TestJavaType.Long,
TestSqlType.typesNumericAndChars,
new Long(maxLong));
checkResults(TestJavaType.Long);
}
private void checkSetLongMin()
throws Exception
{
checkSet(
TestJavaType.Long,
TestSqlType.typesNumericAndChars,
new Long(minLong));
checkResults(TestJavaType.Long);
}
private void checkSetIntMax()
throws Exception
{
checkSet(
TestJavaType.Int,
TestSqlType.typesNumericAndChars,
new Integer(maxInt));
checkResults(TestJavaType.Int);
}
private void checkSetIntMin()
throws Exception
{
checkSet(
TestJavaType.Int,
TestSqlType.typesNumericAndChars,
new Integer(minInt));
checkResults(TestJavaType.Int);
}
private void checkSetShortMax()
throws Exception
{
checkSet(
TestJavaType.Short,
TestSqlType.typesNumericAndChars,
new Short(maxShort));
checkResults(TestJavaType.Short);
}
private void checkSetShortMin()
throws Exception
{
checkSet(
TestJavaType.Short,
TestSqlType.typesNumericAndChars,
new Short(minShort));
checkResults(TestJavaType.Short);
}
private void checkSetByteMax()
throws Exception
{
checkSet(
TestJavaType.Byte,
TestSqlType.typesNumericAndChars,
new Byte(maxByte));
checkResults(TestJavaType.Byte);
}
private void checkSetByteMin()
throws Exception
{
checkSet(
TestJavaType.Byte,
TestSqlType.typesNumericAndChars,
new Byte(minByte));
checkResults(TestJavaType.Byte);
}
private void checkSetString()
throws Exception
{
// Skipped: dtbug220
// for (int j=2; j<=TestSqlType.length; j++)
checkSet(TestJavaType.String, TestSqlType.Char, stringValue);
checkSet(TestJavaType.String, TestSqlType.Varchar, stringValue);
if (true) {
//todo: setString on VARBINARY column should fail
checkSet(TestJavaType.String, TestSqlType.Binary, stringValue);
checkSet(TestJavaType.String, TestSqlType.Varbinary, stringValue);
}
checkResults(TestJavaType.String);
}
private void checkResults(TestJavaType javaType)
throws SQLException
{
int res = preparedStmt.executeUpdate();
assertEquals(1, res);
// Select the results back, to make sure the values we expected got
// written.
final Statement stmt = connection.createStatement();
final ResultSet resultSet =
stmt.executeQuery("select * from datatypes_schema.dataTypes_table");
final int columnCount = resultSet.getMetaData().getColumnCount();
assert columnCount == (TestSqlType.all.length + 1);
while (resultSet.next()) {
for (int k = 0; k < TestSqlType.all.length; k++) {
// TestSqlType#2 (Tinyint) is held in column #2 (1-based).
final TestSqlType sqlType = TestSqlType.all[k];
final Object actual = resultSet.getObject(sqlType.ordinal);
Object value = values[sqlType.ordinal];
if (value == null) {
// value was not valid for this column -- so we don't
// expect a result
continue;
}
final Object expected = sqlType.getExpected(value);
String message =
"sqltype [" + sqlType.string + "], javatype ["
+ ((javaType == null) ? "?" : javaType.name)
+ "], expected [" + toString(expected)
+ ((expected == null) ? "" : (" :" + expected.getClass()))
+ "], actual [" + toString(actual)
+ ((actual == null) ? "" : (" :" + actual.getClass()))
+ "]";
assertEquals(message, expected, actual);
}
}
stmt.close();
connection.rollback();
// wipe out the array for the next test
Arrays.fill(values, null);
}
/**
* Override {@link Assert#assertEquals(String,Object,Object)} to handle
* byte arrays correctly.
*/
public static void assertEquals(
String message,
Object expected,
Object actual)
{
if (expected instanceof byte [] && actual instanceof byte []
&& Arrays.equals((byte []) expected, (byte []) actual)) {
return;
}
Assert.assertEquals(message, expected, actual);
}
private String toString(Object o)
{
if (o instanceof byte []) {
StringBuffer buf = new StringBuffer("{");
byte [] bytes = (byte []) o;
for (int i = 0; i < bytes.length; i++) {
if (i > 0) {
buf.append(", ");
}
byte b = bytes[i];
buf.append(Integer.toHexString(b));
}
buf.append("}");
return buf.toString();
}
return String.valueOf(o);
}
private void checkSet(
TestJavaType javaType,
TestSqlType [] types,
Object value)
throws Exception
{
for (int i = 0; i < types.length; i++) {
TestSqlType type = types[i];
checkSet(javaType, type, value);
}
}
private void checkSet(
TestJavaType javaType,
TestSqlType sqlType,
Object value)
throws Exception
{
int column = sqlType.ordinal;
int validity = sqlType.checkIsValid(value);
Throwable throwable;
tracer.fine("Call PreparedStmt.set" + javaType.name + "(" + column
+ ", " + value + "), value is " + TestSqlType.validityName[validity]);
try {
javaType.setMethod.invoke(
preparedStmt,
new Object [] { new Integer(column), value });
throwable = null;
} catch (IllegalAccessException e) {
throwable = e;
} catch (IllegalArgumentException e) {
throwable = e;
} catch (InvocationTargetException e) {
throwable = e.getCause();
}
switch (validity) {
case TestSqlType.VALID:
if (throwable != null) {
fail("Error received when none expected, javaType="
+ javaType.name + ", sqlType=" + sqlType.string
+ ", value=" + value + ", throwable=" + throwable);
}
this.values[column] = value;
break;
case TestSqlType.INVALID:
if (throwable instanceof SQLException) {
String errorString = throwable.toString();
if (errorString.matches(
".*Cannot assign a value of Java class .* to .*")) {
break;
}
}
fail("Was expecting error, javaType=" + javaType.name
+ ", sqlType=" + sqlType.string + ", value=" + value);
break;
case TestSqlType.OUTOFRANGE:
Pattern outOfRangePattern = Pattern.compile("out of range");
if (throwable instanceof SQLException) {
String errorString = throwable.toString();
if (outOfRangePattern.matcher(errorString).matches()) {
break;
}
}
fail("Was expecting out-of-range error, javaType=" + javaType.name
+ ", sqlType=" + sqlType.string + ", value=" + value);
break;
}
}
public void testDataTypes()
throws Exception
{
final String ins_query =
"insert into datatypes_schema.dataTypes_table values ";
String query = ins_query + paramStr;
query =
"select " + columnStr + " from datatypes_schema.datatypes_table";
preparedStmt = connection.prepareStatement(query);
resultSet = preparedStmt.executeQuery();
int id;
while (resultSet.next()) {
id = resultSet.getInt(1);
switch (id) {
case 100:
/* Numerics and timestamps skipped due to dtbug220 */
assertEquals(
stringValue,
resultSet.getString(TINYINT));
assertEquals(
stringValue,
resultSet.getString(SMALLINT));
assertEquals(
stringValue,
resultSet.getString(INTEGER));
assertEquals(
stringValue,
resultSet.getString(BIGINT));
assertEquals(
stringValue,
resultSet.getString(REAL));
assertEquals(
stringValue,
resultSet.getString(FLOAT));
assertEquals(
stringValue,
resultSet.getString(DOUBLE));
assertEquals(
stringValue,
resultSet.getString(BOOLEAN));
// Check CHAR - result String can be longer than the input string
// Just check the first part
assertEquals(
stringValue,
resultSet.getString(CHAR).substring(
0,
stringValue.length()));
assertEquals(
stringValue,
resultSet.getString(VARCHAR));
// What should BINARY/VARBINARY be?
//assertEquals(stringValue, resultSet.getString(BINARY));
//assertEquals(stringValue, resultSet.getString(VARBINARY));
// dtbug110, 199
assertEquals(
stringValue,
resultSet.getString(DATE));
assertEquals(
stringValue,
resultSet.getString(TIME));
assertEquals(
stringValue,
resultSet.getString(TIMESTAMP));
break;
case 101:
assertEquals(
minByte,
resultSet.getByte(TINYINT));
assertEquals(
minByte,
resultSet.getByte(SMALLINT));
assertEquals(
minByte,
resultSet.getByte(INTEGER));
assertEquals(
minByte,
resultSet.getByte(BIGINT));
assertEquals(
minByte,
resultSet.getByte(REAL));
assertEquals(
minByte,
resultSet.getByte(FLOAT));
assertEquals(
minByte,
resultSet.getByte(DOUBLE));
assertEquals(
1,
resultSet.getByte(BOOLEAN));
assertEquals(
minByte,
resultSet.getByte(CHAR));
assertEquals(
minByte,
resultSet.getByte(VARCHAR));
break;
case 102:
assertEquals(
maxByte,
resultSet.getByte(TINYINT));
assertEquals(
maxByte,
resultSet.getByte(SMALLINT));
assertEquals(
maxByte,
resultSet.getByte(INTEGER));
assertEquals(
maxByte,
resultSet.getByte(BIGINT));
assertEquals(
maxByte,
resultSet.getByte(REAL));
assertEquals(
maxByte,
resultSet.getByte(FLOAT));
assertEquals(
maxByte,
resultSet.getByte(DOUBLE));
assertEquals(
1,
resultSet.getByte(BOOLEAN));
assertEquals(
maxByte,
resultSet.getByte(CHAR));
assertEquals(
maxByte,
resultSet.getByte(VARCHAR));
break;
case 103:
assertEquals(
0,
resultSet.getShort(TINYINT));
assertEquals(
minShort,
resultSet.getShort(SMALLINT));
assertEquals(
minShort,
resultSet.getShort(INTEGER));
assertEquals(
minShort,
resultSet.getShort(BIGINT));
assertEquals(
minShort,
resultSet.getShort(REAL));
assertEquals(
minShort,
resultSet.getShort(FLOAT));
assertEquals(
minShort,
resultSet.getShort(DOUBLE));
assertEquals(
1,
resultSet.getShort(BOOLEAN));
assertEquals(
minShort,
resultSet.getShort(CHAR));
assertEquals(
minShort,
resultSet.getShort(VARCHAR));
break;
case 104:
assertEquals(
-1,
resultSet.getShort(TINYINT));
assertEquals(
maxShort,
resultSet.getShort(SMALLINT));
assertEquals(
maxShort,
resultSet.getShort(INTEGER));
assertEquals(
maxShort,
resultSet.getShort(BIGINT));
assertEquals(
maxShort,
resultSet.getShort(REAL));
assertEquals(
maxShort,
resultSet.getShort(FLOAT));
assertEquals(
maxShort,
resultSet.getShort(DOUBLE));
assertEquals(
1,
resultSet.getShort(BOOLEAN));
assertEquals(
maxShort,
resultSet.getShort(CHAR));
assertEquals(
maxShort,
resultSet.getShort(VARCHAR));
break;
case 105:
assertEquals(
0,
resultSet.getInt(TINYINT));
assertEquals(
0,
resultSet.getInt(SMALLINT));
assertEquals(
minInt,
resultSet.getInt(INTEGER));
assertEquals(
minInt,
resultSet.getInt(BIGINT));
assertEquals(
minInt,
resultSet.getInt(REAL));
assertEquals(
minInt,
resultSet.getInt(FLOAT));
assertEquals(
minInt,
resultSet.getInt(DOUBLE));
assertEquals(
1,
resultSet.getInt(BOOLEAN));
assertEquals(
minInt,
resultSet.getInt(CHAR));
assertEquals(
minInt,
resultSet.getInt(VARCHAR));
break;
case 106:
assertEquals(
-1,
resultSet.getInt(TINYINT));
assertEquals(
-1,
resultSet.getInt(SMALLINT));
assertEquals(
maxInt,
resultSet.getInt(INTEGER));
assertEquals(
maxInt,
resultSet.getInt(BIGINT));
assertEquals(
-2147483648,
resultSet.getInt(REAL));
assertEquals(
maxInt,
resultSet.getInt(FLOAT));
assertEquals(
maxInt,
resultSet.getInt(DOUBLE));
assertEquals(
1,
resultSet.getInt(BOOLEAN));
assertEquals(
maxInt,
resultSet.getInt(CHAR));
assertEquals(
maxInt,
resultSet.getInt(VARCHAR));
break;
case 107:
assertEquals(
0,
resultSet.getLong(TINYINT));
assertEquals(
0,
resultSet.getLong(SMALLINT));
assertEquals(
0,
resultSet.getLong(INTEGER));
assertEquals(
minLong,
resultSet.getLong(BIGINT));
assertEquals(
minLong,
resultSet.getLong(REAL));
assertEquals(
minLong,
resultSet.getLong(FLOAT));
assertEquals(
minLong,
resultSet.getLong(DOUBLE));
assertEquals(
1,
resultSet.getLong(BOOLEAN));
assertEquals(
minLong,
resultSet.getLong(CHAR));
assertEquals(
minLong,
resultSet.getLong(VARCHAR));
break;
case 108:
assertEquals(
-1,
resultSet.getLong(TINYINT));
assertEquals(
-1,
resultSet.getLong(SMALLINT));
assertEquals(
-1,
resultSet.getLong(INTEGER));
assertEquals(
maxLong,
resultSet.getLong(BIGINT));
assertEquals(
maxLong,
resultSet.getLong(REAL));
assertEquals(
maxLong,
resultSet.getLong(FLOAT));
assertEquals(
maxLong,
resultSet.getLong(DOUBLE));
assertEquals(
1,
resultSet.getLong(BOOLEAN));
assertEquals(
maxLong,
resultSet.getLong(CHAR));
assertEquals(
maxLong,
resultSet.getLong(VARCHAR));
break;
case 109:
assertEquals(
0,
resultSet.getFloat(TINYINT),
0);
assertEquals(
0,
resultSet.getFloat(SMALLINT),
0);
assertEquals(
0,
resultSet.getFloat(INTEGER),
0);
assertEquals(
0,
resultSet.getFloat(BIGINT),
0);
assertEquals(
minFloat,
resultSet.getFloat(REAL),
0);
assertEquals(
minFloat,
resultSet.getFloat(FLOAT),
0);
assertEquals(
minFloat,
resultSet.getFloat(DOUBLE),
0);
assertEquals(
1,
resultSet.getFloat(BOOLEAN),
1);
assertEquals(
minFloat,
resultSet.getFloat(CHAR),
0);
assertEquals(
minFloat,
resultSet.getFloat(VARCHAR),
0);
break;
case 110:
assertEquals(
-1,
resultSet.getFloat(TINYINT),
0);
assertEquals(
-1,
resultSet.getFloat(SMALLINT),
0);
assertEquals(
maxInt,
resultSet.getFloat(INTEGER),
0);
assertEquals(
maxLong,
resultSet.getFloat(BIGINT),
0);
assertEquals(
maxFloat,
resultSet.getFloat(REAL),
0);
assertEquals(
maxFloat,
resultSet.getFloat(FLOAT),
0);
assertEquals(
maxFloat,
resultSet.getFloat(DOUBLE),
0);
assertEquals(
1,
resultSet.getFloat(BOOLEAN),
1);
assertEquals(
maxFloat,
resultSet.getFloat(CHAR),
0);
assertEquals(
maxFloat,
resultSet.getFloat(VARCHAR),
0);
break;
case 111:
assertEquals(
0,
resultSet.getDouble(TINYINT),
0);
assertEquals(
0,
resultSet.getDouble(SMALLINT),
0);
assertEquals(
0,
resultSet.getDouble(INTEGER),
0);
assertEquals(
0,
resultSet.getDouble(BIGINT),
0);
assertEquals(
0,
resultSet.getDouble(REAL),
0);
assertEquals(
minDouble,
resultSet.getDouble(FLOAT),
0);
assertEquals(
minDouble,
resultSet.getDouble(DOUBLE),
0);
assertEquals(
1,
resultSet.getDouble(BOOLEAN),
1);
assertEquals(
minDouble,
resultSet.getDouble(CHAR),
0);
assertEquals(
minDouble,
resultSet.getDouble(VARCHAR),
0);
break;
case 112:
assertEquals(
-1,
resultSet.getDouble(TINYINT),
0);
assertEquals(
-1,
resultSet.getDouble(SMALLINT),
0);
assertEquals(
maxInt,
resultSet.getDouble(INTEGER),
0);
assertEquals(
maxLong,
resultSet.getDouble(BIGINT),
0);
assertEquals(
Float.POSITIVE_INFINITY,
resultSet.getDouble(REAL),
0);
assertEquals(
maxDouble,
resultSet.getDouble(FLOAT),
0);
assertEquals(
maxDouble,
resultSet.getDouble(DOUBLE),
0);
assertEquals(
1,
resultSet.getDouble(BOOLEAN),
1);
assertEquals(
maxDouble,
resultSet.getDouble(CHAR),
0);
assertEquals(
maxDouble,
resultSet.getDouble(VARCHAR),
0);
break;
case 113:
assertEquals(
boolValue,
resultSet.getBoolean(TINYINT));
assertEquals(
boolValue,
resultSet.getBoolean(SMALLINT));
assertEquals(
boolValue,
resultSet.getBoolean(INTEGER));
assertEquals(
boolValue,
resultSet.getBoolean(BIGINT));
assertEquals(
boolValue,
resultSet.getBoolean(REAL));
assertEquals(
boolValue,
resultSet.getBoolean(FLOAT));
assertEquals(
boolValue,
resultSet.getBoolean(DOUBLE));
assertEquals(
boolValue,
resultSet.getBoolean(BOOLEAN));
//assertEquals(boolValue, resultSet.getBoolean(CHAR));
//can not convert String (true) to long exception
//assertEquals(boolValue, resultSet.getBoolean(VARCHAR));
break;
case 114:
// dtbug119
if (dtbug119_fixed) {
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(TINYINT));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(SMALLINT));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(INTEGER));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(BIGINT));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(REAL));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(FLOAT));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(DOUBLE));
//todo:
//assertEquals(bigDecimalValue, resultSet.getBigDecimal(BigDecimal));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(CHAR));
assertEquals(
bigDecimalValue,
resultSet.getBigDecimal(VARCHAR));
}
break;
case 115:
// Check BINARY - resBytes can be longer than the input bytes
byte [] resBytes = resultSet.getBytes(BINARY);
assertNotNull(resBytes);
for (int i = 0; i < bytes.length; i++) {
assertEquals(bytes[i], resBytes[i]);
}
// Check VARBINARY - should be same length
resBytes = resultSet.getBytes(VARBINARY);
// resBytes null for some reason
/*assertNotNull(resBytes);
assertEquals(bytes.length, resBytes.length);
for (int i=0; i<bytes.length; i++)
assertEquals(bytes[i], resBytes[i]); */
break;
case 116:
assertEquals(
date,
resultSet.getDate(CHAR));
assertEquals(
date,
resultSet.getDate(VARCHAR));
assertEquals(
date,
resultSet.getDate(DATE));
assertEquals(
date,
resultSet.getDate(TIMESTAMP));
break;
case 117:
assertEquals(
time,
resultSet.getTime(CHAR));
assertEquals(
time,
resultSet.getTime(VARCHAR));
assertEquals(
time,
resultSet.getTime(TIME));
assertEquals(
time,
resultSet.getTime(TIMESTAMP));
break;
case 118:
assertEquals(
timestamp,
resultSet.getTimestamp(CHAR));
assertEquals(
timestamp,
resultSet.getTimestamp(VARCHAR));
assertEquals(
timestamp,
resultSet.getTimestamp(DATE));
assertEquals(
timestamp,
resultSet.getTimestamp(TIME));
assertEquals(
timestamp,
resultSet.getTimestamp(TIMESTAMP));
break;
case 119:
assertEquals(
tinyIntObj,
resultSet.getObject(TINYINT));
assertEquals(
smallIntObj,
resultSet.getObject(SMALLINT));
assertEquals(
integerObj,
resultSet.getObject(INTEGER));
assertEquals(
bigIntObj,
resultSet.getObject(BIGINT));
assertEquals(
floatObj,
resultSet.getObject(REAL));
assertEquals(
doubleObj,
resultSet.getObject(FLOAT));
assertEquals(
doubleObj,
resultSet.getObject(DOUBLE));
assertEquals(
boolObj,
resultSet.getObject(BOOLEAN));
// Check CHAR - result String can be longer than the input string
// Just check the first part
assertEquals(
charObj,
resultSet.getString(CHAR).substring(
0,
charObj.length()));
assertEquals(
varcharObj,
resultSet.getObject(VARCHAR));
// Check BINARY - resBytes can be longer than the input bytes
resBytes = (byte []) resultSet.getObject(BINARY);
assertNotNull(resBytes);
for (int i = 0; i < bytes.length; i++) {
assertEquals(bytes[i], resBytes[i]);
}
// Check VARBINARY - should be same length
resBytes = (byte []) resultSet.getObject(VARBINARY);
assertNotNull(resBytes);
assertEquals(bytes.length, resBytes.length);
for (int i = 0; i < bytes.length; i++) {
assertEquals(bytes[i], resBytes[i]);
}
// dtbug199
//assertEquals(date, resultSet.getObject(DATE));
//assertEquals(time, resultSet.getObject(TIME));
//assertEquals(timestamp, resultSet.getObject(TIMESTAMP));
break;
default:
// Unexpected id
assert false;
break;
}
}
resultSet.close();
resultSet = null;
}
/**
* Test sql Date/Time to java.sql Date/Time translations.
*/
public void testDateTimeSql()
throws Exception
{
String dateSql =
"select DATE '2004-12-21', TIME '12:22:33'," + ""
+ " TIMESTAMP '2004-12-21 12:22:33' from values('true')";
preparedStmt = connection.prepareStatement(dateSql);
resultSet = preparedStmt.executeQuery();
if (resultSet.next()) {
Date date = resultSet.getDate(1);
Timestamp tstamp = resultSet.getTimestamp(3);
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getDefault());
cal.clear();
cal.set(2004, 11, 21); //month is zero based. idiots ...
assertEquals(cal.getTime().getTime(), date.getTime());
cal.set(2004, 11, 21, 12, 22, 33);
assertEquals(cal.getTime().getTime(), tstamp.getTime());
} else {
assert false : "Static query returned no rows?";
}
resultSet.close();
if (false) {
resultSet = stmt.executeQuery(dateSql);
while (resultSet.next()) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT-6"));
// not supported by IteratorResultSet yet.
Date date = resultSet.getDate(1, sydneyCal);
Timestamp tstamp = resultSet.getTimestamp(3, sydneyCal);
cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));
cal.clear();
cal.set(2004, 11, 21); //month is zero based. idiots ...
assertEquals(cal.getTime().getTime(), date.getTime());
cal.set(2004, 11, 21, 12, 22, 33);
assertEquals(cal.getTime().getTime(), tstamp.getTime());
}
}
}
/**
* Test setQueryTimeout
*
* @throws Exception .
*/
public void testTimeout()
throws Exception
{
String sql = "select * from sales.emps";
preparedStmt = connection.prepareStatement(sql);
for (int i = 10; i >= -2; i
preparedStmt.setQueryTimeout(i);
resultSet = preparedStmt.executeQuery();
assertEquals(
4,
getResultSetCount());
resultSet.close();
}
sql = "select empid from sales.emps where name=?";
preparedStmt = connection.prepareStatement(sql);
ParameterMetaData pmd = preparedStmt.getParameterMetaData();
assertEquals(
1,
pmd.getParameterCount());
assertEquals(
128,
pmd.getPrecision(1));
assertEquals(
Types.VARCHAR,
pmd.getParameterType(1));
assertEquals(
"VARCHAR",
pmd.getParameterTypeName(1));
preparedStmt.setString(1, "Wilma");
preparedStmt.setQueryTimeout(5);
resultSet = preparedStmt.executeQuery();
compareResultSet(Collections.singleton("1"));
preparedStmt.setString(1, "Eric");
preparedStmt.setQueryTimeout(3);
resultSet = preparedStmt.executeQuery();
compareResultSet(Collections.singleton("3"));
}
/**
* Test char and varchar Data Type in JDBC
*
* @throws Exception .
*/
public void testChar()
throws Exception
{
preparedStmt =
connection.prepareStatement(
"insert into \"SALES\".\"EMPS\" values "
+ "(?, ?, 10, ?, ?, ?, 28, NULL, NULL, false)");
preparedStmt.setByte(3, (byte) 1);
preparedStmt.setByte(4, (byte) -128);
doEmpInsert(1);
preparedStmt.setShort(3, (short) 2);
preparedStmt.setShort(4, (short) 32767);
doEmpInsert(2);
preparedStmt.setInt(3, 3);
preparedStmt.setInt(4, -234234);
doEmpInsert(3);
preparedStmt.setLong(3, 4L);
preparedStmt.setLong(4, 123432432432545455L);
doEmpInsert(4);
Throwable throwable;
try {
preparedStmt.setFloat(3, 5.0F);
preparedStmt.setFloat(4, 6.02e+23F);
doEmpInsert(5);
throwable = null;
fail("Expected an error");
} catch (SQLException e) {
throwable = e;
}
assertExceptionMatches(throwable,
".*Value '5.0' is too long for parameter of type CHAR.1.");
try {
preparedStmt.setDouble(3, 6.2);
preparedStmt.setDouble(4, 3.14);
doEmpInsert(6);
} catch (SQLException e) {
throwable = e;
}
assertExceptionMatches(throwable,
".*Value '6.2' is too long for parameter of type CHAR.1.");
preparedStmt.setBigDecimal(
3,
new BigDecimal(2));
preparedStmt.setBigDecimal(
4,
new BigDecimal(88.23432432));
doEmpInsert(7);
try {
preparedStmt.setBoolean(3, false);
preparedStmt.setBoolean(4, true);
doEmpInsert(8);
} catch (SQLException e) {
throwable = e;
}
assertExceptionMatches(throwable,
".*Value 'false' is too long for parameter of type CHAR.1.");
preparedStmt.setString(3, "x");
preparedStmt.setBoolean(4, true);
doEmpInsert(8);
preparedStmt.setString(3, "F");
preparedStmt.setString(4, "San Jose");
doEmpInsert(9);
preparedStmt.setObject(
3,
new Character('M'));
preparedStmt.setObject(
4,
new StringBuffer("New York"));
doEmpInsert(10);
// this query won't find everything we insert above because of bugs in
// executeUpdate when there's a setFloat/setDouble called on a varchar
// column. See comments in bug#117
//query = "select gender, city, empid from sales.emps where name like '";
//query += name + "%'";
// for now, use this query instead
String query =
"select gender, city, empid from sales.emps where empno>1000";
preparedStmt = connection.prepareStatement(query);
resultSet = preparedStmt.executeQuery();
int empid;
while (resultSet.next()) {
empid = resultSet.getInt(3);
switch (empid) {
case 101:
// ERROR - bug #117 logged for errors given in the following commented lines
// assertEquals(gender, resultSet.getByte(1));
// assertEquals(city, resultSet.getByte(2));
break;
case 102:
// assertEquals(gender2, resultSet.getShort(1));
// assertEquals(city2, resultSet.getShort(2));
break;
case 103:
// assertEquals(gender3, resultSet.getInt(1));
// assertEquals(city3, resultSet.getInt(2));
break;
case 104:
// assertEquals(gender4, resultSet.getLong(1));
// assertEquals(city4, resultSet.getLong(2));
break;
case 105:
// assertEquals(gender5, resultSet.getFloat(1), 0.0001);
// assertEquals(city5, resultSet.getFloat(2), 0.0001);
break;
case 106:
// assertEquals(gender6, resultSet.getDouble(1), 0.0001);
// assertEquals(city6, resultSet.getDouble(2), 0.0001);
break;
case 107:
// ERROR
// assertEquals(gender7, resultSet.getBigDecimal(1));
// assertEquals(city7, resultSet.getBigDecimal(2));
break;
case 108:
assertEquals(
"x",
resultSet.getString(1));
// ERROR: same as bug #117
// assertEquals(city8, resultSet.getBoolean(2));
break;
case 109:
assertEquals(
"F",
resultSet.getString(1));
assertEquals(
"San Jose",
resultSet.getString(2));
break;
case 110:
// ERROR - the actual result looks correct, probably merely object type not matching
// assertEquals(genderx, resultSet.getObject(1));
// assertEquals(cityx, resultSet.getObject(2));
break;
default:
// uncomment this when I can do a like sql query
assertEquals(1, 2);
break;
}
}
resultSet.close();
resultSet = null;
}
static void assertExceptionMatches(
Throwable e,
String expectedPattern)
{
if (e == null) {
fail("Expected an error which matches pattern '" + expectedPattern
+ "'");
}
String msg = e.toString();
if (!msg.matches(expectedPattern)) {
fail("Got a different error '" + msg + "' than expected '"
+ expectedPattern + "'");
}
}
private void doEmpInsert(int i)
throws SQLException
{
String name = "JDBC Test Char";
preparedStmt.setInt(1, i + 1000);
preparedStmt.setString(2, name + i);
preparedStmt.setInt(5, i + 100);
int res = preparedStmt.executeUpdate();
assertEquals(1, res);
}
/**
* Test integer Data Type in JDBC
*
* @throws Exception .
*/
public void testInteger()
throws Exception
{
short empno = 555;
byte deptno = 10;
int empid = -99;
long age = 28L;
float empno2 = 666.6F;
double deptno2 = 10.0;
BigDecimal empid2 = new BigDecimal(88.20334342);
boolean age2 = true;
String empno3 = "777";
Object deptno3 = new Integer(10);
String name = "JDBC Test Int";
String name2 = "JDBC Test Int2";
String name3 = "JDBC Test Int3";
int res;
String query = "insert into \"SALES\".\"EMPS\" values ";
query += "(?, ?, ?, 'M', 'Oakland', ?, ?, NULL, NULL, false)";
preparedStmt = connection.prepareStatement(query);
preparedStmt.setShort(1, empno);
preparedStmt.setString(2, name);
preparedStmt.setByte(3, deptno);
preparedStmt.setInt(4, empid);
preparedStmt.setLong(5, age);
res = preparedStmt.executeUpdate();
assertEquals(1, res);
preparedStmt.setFloat(1, empno2);
preparedStmt.setString(2, name2);
preparedStmt.setDouble(3, deptno2);
preparedStmt.setBigDecimal(4, empid2);
preparedStmt.setBoolean(5, age2);
res = preparedStmt.executeUpdate();
assertEquals(1, res);
preparedStmt.setString(1, empno3);
preparedStmt.setString(2, name3);
preparedStmt.setObject(3, deptno3);
preparedStmt.setInt(4, 28);
preparedStmt.setLong(5, 28);
res = preparedStmt.executeUpdate();
assertEquals(1, res);
query =
"select empno, deptno, empid, age from sales.emps where name = ?";
preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, name);
resultSet = preparedStmt.executeQuery();
while (resultSet.next()) {
assertEquals(
empno,
resultSet.getShort(1));
assertEquals(
deptno,
resultSet.getByte(2));
assertEquals(
empid,
resultSet.getInt(3));
assertEquals(
age,
resultSet.getLong(4));
}
resultSet.close();
preparedStmt.setString(1, name2);
resultSet = preparedStmt.executeQuery();
while (resultSet.next()) {
assertEquals(
666,
resultSet.getFloat(1),
0.0001);
assertEquals(
deptno2,
resultSet.getDouble(2),
0.0001);
// ERROR: Bug#119: getBigDecimal not supported
// assertEquals(empid2, resultSet.getBigDecimal(3));
// ERROR: Bug#117: getBoolean returns SQLException like getXXX on char data types (where XXX is numeric type)
// assertEquals(age2, resultSet.getBoolean(4));
}
resultSet.close();
preparedStmt.setString(1, name3);
resultSet = preparedStmt.executeQuery();
while (resultSet.next()) {
assertEquals(
empno3,
resultSet.getString(1));
assertEquals(
deptno3,
resultSet.getObject(2));
}
resultSet.close();
resultSet = null;
}
/**
* Test re-execution of a prepared query.
*
* @throws Exception .
*/
public void testPreparedQuery()
throws Exception
{
String sql = "select * from sales.emps";
preparedStmt = connection.prepareStatement(sql);
for (int i = 0; i < 5; ++i) {
resultSet = preparedStmt.executeQuery();
assertEquals(
4,
getResultSetCount());
resultSet.close();
resultSet = null;
}
}
/**
* Test re-execution of an unprepared query. There's no black-box way to
* verify that caching is working, but if it is, this will at least
* exercise it.
*
* @throws Exception .
*/
public void testCachedQuery()
throws Exception
{
repeatQuery();
}
/**
* Test re-execution of an unprepared query with statement caching
* disabled.
*
* @throws Exception .
*/
public void testUncachedQuery()
throws Exception
{
// disable caching
stmt.execute("alter system set \"codeCacheMaxBytes\" = min");
repeatQuery();
// re-enable caching
stmt.execute("alter system set \"codeCacheMaxBytes\" = max");
}
private void repeatQuery()
throws Exception
{
String sql = "select * from sales.emps";
for (int i = 0; i < 3; ++i) {
resultSet = stmt.executeQuery(sql);
assertEquals(
4,
getResultSetCount());
resultSet.close();
resultSet = null;
}
}
/**
* Test retrieval of ResultSetMetaData without actually executing query.
*/
public void testPreparedMetaData()
throws Exception
{
String sql = "select name from sales.emps";
preparedStmt = connection.prepareStatement(sql);
ResultSetMetaData metaData = preparedStmt.getMetaData();
assertEquals(
1,
metaData.getColumnCount());
assertTrue(metaData.isSearchable(1));
assertEquals(
ResultSetMetaData.columnNoNulls,
metaData.isNullable(1));
assertEquals(
"NAME",
metaData.getColumnName(1));
assertEquals(
128,
metaData.getPrecision(1));
assertEquals(
Types.VARCHAR,
metaData.getColumnType(1));
assertEquals(
"VARCHAR",
metaData.getColumnTypeName(1));
}
// TODO: re-execute DDL, DML
/**
* Test valid usage of a dynamic parameter and retrieval of associated
* metadata.
*/
public void testDynamicParameter()
throws Exception
{
String sql = "select empid from sales.emps where name=?";
preparedStmt = connection.prepareStatement(sql);
ParameterMetaData pmd = preparedStmt.getParameterMetaData();
assertEquals(
1,
pmd.getParameterCount());
assertEquals(
128,
pmd.getPrecision(1));
assertEquals(
Types.VARCHAR,
pmd.getParameterType(1));
assertEquals(
"VARCHAR",
pmd.getParameterTypeName(1));
preparedStmt.setString(1, "Wilma");
resultSet = preparedStmt.executeQuery();
compareResultSet(Collections.singleton("1"));
preparedStmt.setString(1, "Eric");
resultSet = preparedStmt.executeQuery();
compareResultSet(Collections.singleton("3"));
preparedStmt.setString(1, "George");
resultSet = preparedStmt.executeQuery();
assertEquals(
0,
getResultSetCount());
preparedStmt.setString(1, null);
resultSet = preparedStmt.executeQuery();
assertEquals(
0,
getResultSetCount());
}
/**
* Test metadata for dynamic parameter in an UPDATE statement.
*/
public void testDynamicParameterInUpdate()
throws Exception
{
String sql = "update sales.emps set age = ?";
preparedStmt = connection.prepareStatement(sql);
ParameterMetaData pmd = preparedStmt.getParameterMetaData();
assertEquals(
1,
pmd.getParameterCount());
assertEquals(
Types.INTEGER,
pmd.getParameterType(1));
assertEquals(
"INTEGER",
pmd.getParameterTypeName(1));
}
/**
* Test invalid usage of a dynamic parameter.
*/
public void testInvalidDynamicParameter()
throws Exception
{
String sql = "select ? from sales.emps";
try {
preparedStmt = connection.prepareStatement(sql);
} catch (SQLException ex) {
// expected
return;
}
Assert.fail("Expected failure due to invalid dynamic param");
}
/**
* Test invalid attempt to execute a statement with a dynamic parameter
* without preparation.
*/
public void testDynamicParameterExecuteImmediate()
throws Exception
{
String sql = "select empid from sales.emps where name=?";
try {
resultSet = stmt.executeQuery(sql);
} catch (SQLException ex) {
// expected
return;
}
Assert.fail(
"Expected failure due to immediate execution with dynamic param");
}
/**
* Defines a SQL type, and a corresponding column in the datatypes table,
* and some operations particular to each type.
*/
private static class TestSqlType
{
/** Definition of the <code>TINYINT</code> SQL type. */
private static final TestSqlType Tinyint =
new TestSqlType(TINYINT, "tinyint") {
public Object getExpected(Object value)
{
if (value instanceof Number) {
return new Byte(((Number) value).byteValue());
}
if (value instanceof Boolean) {
return new Byte(((Boolean) value).booleanValue()
? (byte) 1 : (byte) 0);
}
return super.getExpected(value);
}
};
/** Definition of the <code>SMALLINT</code> SQL type. */
private static final TestSqlType Smallint =
new TestSqlType(SMALLINT, "smallint") {
public Object getExpected(Object value)
{
if (value instanceof Number) {
return new Short(((Number) value).shortValue());
}
if (value instanceof Boolean) {
return new Short(((Boolean) value).booleanValue()
? (short) 1 : (short) 0);
}
return super.getExpected(value);
}
};
/** Definition of the <code>INTEGER</code> SQL type. */
private static final TestSqlType Integer =
new TestSqlType(INTEGER, "integer") {
public Object getExpected(Object value)
{
if (value instanceof Number) {
return new Integer(((Number) value).intValue());
}
if (value instanceof Boolean) {
return new Integer(((Boolean) value).booleanValue()
? 1 : 0);
}
return super.getExpected(value);
}
};
/** Definition of the <code>BIGINT</code> SQL type. */
private static final TestSqlType Bigint =
new TestSqlType(BIGINT, "bigint") {
public Object getExpected(Object value)
{
if (value instanceof Number) {
return new Long(((Number) value).longValue());
}
if (value instanceof Boolean) {
return new Long(((Boolean) value).booleanValue() ? 1 : 0);
}
return super.getExpected(value);
}
};
/** Definition of the <code>REAL</code> SQL type. */
private static final TestSqlType Real =
new TestSqlType(REAL, "real") {
public Object getExpected(Object value)
{
if (value instanceof Number) {
// SQL real yields Java float
return new Float(((Number) value).floatValue());
}
if (value instanceof Boolean) {
return new Float(((Boolean) value).booleanValue() ? 1 : 0);
}
return super.getExpected(value);
}
};
/** Definition of the <code>FLOAT</code> SQL type. */
private static final TestSqlType Float =
new TestSqlType(FLOAT, "float") {
public Object getExpected(Object value)
{
if (value instanceof Number) {
// SQL float yields Java double
return new Double(((Number) value).doubleValue());
}
if (value instanceof Boolean) {
return new Double(((Boolean) value).booleanValue() ? 1
: 0);
}
return super.getExpected(value);
}
};
/** Definition of the <code>DOUBLE</code> SQL type. */
private static final TestSqlType Double =
new TestSqlType(DOUBLE, "double") {
public Object getExpected(Object value)
{
if (value instanceof Number) {
// SQL double yields Java double
return new Double(((Number) value).doubleValue());
}
if (value instanceof Boolean) {
return new Double(((Boolean) value).booleanValue() ? 1
: 0);
}
return super.getExpected(value);
}
};
/** Definition of the <code>BOOLEAN</code> SQL type. */
private static final TestSqlType Boolean =
new TestSqlType(BOOLEAN, "boolean") {
public int checkIsValid(Object value)
{
if ((value == null) || value instanceof Boolean) {
return VALID;
}
if (value instanceof Number) {
return isBetween((Number) value, 0, 1) ? VALID
: OUTOFRANGE;
}
return INVALID;
}
public Object getExpected(Object value)
{
if (value instanceof Number) {
// SQL double yields Java double
return new Boolean(((Number) value).intValue() != 0);
}
return super.getExpected(value);
}
};
/* Are we supporting bit/decimal/numeric? see dtbug175 */
/*"bit", */
/*"decimal(12,2)", */
/* If strings too small - will get:
java: TupleAccessor.cpp:416: void fennel::TupleAccessor::unmarshal(fennel::TupleData&, unsigned int) const: Assertion `value.cbData <= accessor.cbStorage' failed.
*/
/** Definition of the <code>CHAR(100)</code> SQL type. */
private static final TestSqlType Char =
new TestSqlType(CHAR, "char(100)") {
public Object getExpected(Object value)
{
String s = String.valueOf(value);
if (s.length() < 100) {
// Pad to 100 characters.
StringBuffer buf = new StringBuffer(s);
while (buf.length() < 100) {
buf.append(' ');
}
s = buf.toString();
}
return s;
}
};
/** Definition of the <code>VARCHAR(200)</code> SQL type. */
private static final TestSqlType Varchar =
new TestSqlType(VARCHAR, "varchar(200)") {
public Object getExpected(Object value)
{
return String.valueOf(value);
}
};
/** Definition of the <code>BINARY(10)</code> SQL type. */
private static final TestSqlType Binary =
new TestSqlType(BINARY, "binary(10)") {
public int checkIsValid(Object value)
{
if (value == null) {
return VALID;
} else if (value instanceof byte []) {
byte [] bytes = (byte []) value;
if (bytes.length < 10) {
return VALID;
} else {
return OUTOFRANGE;
}
} else {
return INVALID;
}
}
public Object getExpected(Object value)
{
if (value instanceof byte []) {
byte [] b = (byte []) value;
if (b.length == 10) {
return b;
}
// Pad to 10 bytes.
byte [] b2 = new byte[10];
System.arraycopy(
b,
0,
b2,
0,
Math.min(b.length, 10));
return b2;
}
return super.getExpected(value);
}
};
/** Definition of the <code>VARBINARY(20)</code> SQL type. */
private static final TestSqlType Varbinary =
new TestSqlType(VARBINARY, "varbinary(20)") {
public int checkIsValid(Object value)
{
if (value == null) {
return VALID;
} else if (value instanceof byte []) {
byte [] bytes = (byte []) value;
if (bytes.length < 20) {
return VALID;
} else {
return OUTOFRANGE;
}
} else {
return INVALID;
}
}
};
/** Definition of the <code>TIME(0)</code> SQL type. */
private static final TestSqlType Time =
new TestSqlType(TIME, "Time(0)") {
public Object getExpected(Object value)
{
if (value instanceof java.util.Date) {
// Lop off the date, leaving only the time of day.
java.util.Date d = (java.util.Date) value;
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
return new Time(cal.getTimeInMillis());
}
return super.getExpected(value);
}
};
/** Definition of the <code>DATE</code> SQL type. */
private static final TestSqlType Date =
new TestSqlType(DATE, "Date") {
public Object getExpected(Object value)
{
if (value instanceof java.util.Date) {
// Truncate the date to 12:00AM
java.util.Date d = (java.util.Date) value;
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new Date(cal.getTimeInMillis());
}
return super.getExpected(value);
}
};
/** Definition of the <code>TIMESTAMP</code> SQL type. */
private static final TestSqlType Timestamp =
new TestSqlType(TIMESTAMP, "timestamp(0)") {
public Object getExpected(Object value)
{
if (value instanceof Timestamp) {
return value;
} else if (value instanceof java.util.Date) {
return new Timestamp(
((java.util.Date) value).getTime());
}
return super.getExpected(value);
}
};
private static final TestSqlType [] all =
{
Tinyint, Smallint, Integer, Bigint, Real, Float, Double, Boolean,
Char, Varchar, Binary, Varbinary, Time, Date, Timestamp,
};
private static final TestSqlType [] typesNumericAndChars =
{
Tinyint, Smallint, Integer, Bigint, Real, Float, Double, Char,
Varchar,
};
private static final TestSqlType [] typesBinary = { Binary, Varbinary, };
public static final int VALID = 0;
public static final int INVALID = 1;
public static final int OUTOFRANGE = 2;
public static String [] validityName =
{ "valid", "invalid", "outofrange" };
private final int ordinal;
private final String string;
TestSqlType(
int ordinal,
String example)
{
this.ordinal = ordinal;
this.string = example;
}
private static boolean isBetween(
Number number,
long min,
long max)
{
long x = number.longValue();
return (min <= x) && (x <= max);
}
public Object getExpected(Object value)
{
return value;
}
public int checkIsValid(Object value)
{
return VALID;
}
}
/**
* Defines a Java type.
*
* <p>Each type has a correponding set of get/set methods, for example
* "Boolean" has {@link ResultSet#getBoolean(int)} and
* {@link PreparedStatement#setBoolean(int,boolean)}.
*/
private static class TestJavaType
{
private static final TestJavaType Boolean =
new TestJavaType("Boolean", boolean.class, true);
private static final TestJavaType Byte =
new TestJavaType("Byte", byte.class, true);
private static final TestJavaType Short =
new TestJavaType("Short", short.class, true);
private static final TestJavaType Int =
new TestJavaType("Int", int.class, true);
private static final TestJavaType Long =
new TestJavaType("Long", long.class, true);
private static final TestJavaType Float =
new TestJavaType("Float", float.class, true);
private static final TestJavaType Double =
new TestJavaType("Double", double.class, true);
private static final TestJavaType BigDecimal =
new TestJavaType("BigDecimal", BigDecimal.class, true);
private static final TestJavaType String =
new TestJavaType("String", String.class, true);
private static final TestJavaType Bytes =
new TestJavaType("Bytes", byte [].class, true);
// Date, Time, Timestamp each have an additional set method, e.g.
// setXxx(int,Date,Calendar)
// TODO: test this
private static final TestJavaType Date =
new TestJavaType("Date", Date.class, true);
private static final TestJavaType Time =
new TestJavaType("Time", Time.class, true);
private static final TestJavaType Timestamp =
new TestJavaType("Timestamp", Timestamp.class, true);
// Object has 2 extra 'setObject' methods:
// setObject(int,Object,int targetTestSqlType)
// setObject(int,Object,int targetTestSqlType,int scale)
// TODO: test this
private static final TestJavaType Object =
new TestJavaType("Object", Object.class, true);
// next 4 are not regular, because their 'set' method has an extra
// parmaeter, e.g. setAsciiStream(int,InputStream,int length)
private static final TestJavaType AsciiStream =
new TestJavaType("AsciiStream", InputStream.class, false);
private static final TestJavaType UnicodeStream =
new TestJavaType("UnicodeStream", InputStream.class, false);
private static final TestJavaType BinaryStream =
new TestJavaType("BinaryStream", InputStream.class, false);
private static final TestJavaType CharacterStream =
new TestJavaType("CharacterStream", Reader.class, false);
private static final TestJavaType Ref =
new TestJavaType("Ref", Ref.class, true);
private static final TestJavaType Blob =
new TestJavaType("Blob", Blob.class, true);
private static final TestJavaType Clob =
new TestJavaType("Clob", Clob.class, true);
private static final TestJavaType Array =
new TestJavaType("Array", Array.class, true);
private final String name;
private final Class clazz;
/** whether it has a setXxxx(int,xxx) method */
private final boolean regular;
private final Method setMethod;
TestJavaType [] all =
{
Boolean, Byte, Short, Int, Long, Float, Double, BigDecimal, String,
Bytes, Date, Time, Timestamp, Object, AsciiStream, UnicodeStream,
BinaryStream, CharacterStream, Ref, Blob, Clob, Array,
};
private TestJavaType(
String name,
Class clazz,
boolean regular)
{
this.name = name;
this.clazz = clazz;
this.regular = regular;
// e.g. PreparedStatement.setBoolean(int,boolean)
Method method = null;
try {
method =
PreparedStatement.class.getMethod(
"set" + name,
new Class [] { int.class, clazz });
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
}
this.setMethod = method;
}
}
}
// End FarragoJdbcTest.java
|
package nl.mpi.kinnate.entityindexer;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import nl.mpi.arbil.ui.ArbilWindowManager;
import nl.mpi.arbil.util.ApplicationVersionManager;
import nl.mpi.arbil.util.BugCatcherManager;
import nl.mpi.kinnate.KinOathVersion;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityArray;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kintypestrings.KinTypeElement;
import nl.mpi.kinnate.projects.ProjectManager;
import nl.mpi.kinnate.projects.ProjectRecord;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifierArray;
import nl.mpi.kinnate.userstorage.KinSessionStorage;
import org.basex.core.BaseXException;
import org.basex.core.Context;
import org.basex.core.cmd.Add;
import org.basex.core.cmd.Close;
import org.basex.core.cmd.CreateDB;
import org.basex.core.cmd.DropDB;
import org.basex.core.cmd.List;
import org.basex.core.cmd.Open;
import org.basex.core.cmd.Optimize;
import org.basex.core.cmd.Set;
import org.basex.core.cmd.XQuery;
import org.basex.query.QueryException;
import org.basex.query.QueryProcessor;
import org.basex.query.iter.Iter;
import org.basex.query.value.item.Item;
public class EntityCollection extends DatabaseUpdateHandler {
final private String databaseName; // = "nl-mpi-kinnate";
final private ProjectRecord projectRecord;
final static Context context = new Context();
final static Object databaseLock = new Object();
final private String dbErrorMessage = "Could not perform the required query, not all data might be shown at this point.\nSee the log file via the help menu for more details.";
public class SearchResults {
public String[] resultsPathArray;
public String statusMessage;
public int resultCount = 0;
}
public EntityCollection(ProjectRecord projectRecord) throws EntityServiceException {
this.projectRecord = projectRecord;
databaseName = projectRecord.getProjectUUID();
// make sure the database exists
try {
synchronized (databaseLock) {
new Set("dbpath", projectRecord.getProjectDataBaseDirectory()).execute(context);
new Open(databaseName).execute(context);
//context.close();
new Close().execute(context);
}
} catch (BaseXException baseXException) {
try {
synchronized (databaseLock) {
new CreateDB(databaseName).execute(context);
// new Open(databaseName).execute(context);
}
} catch (BaseXException exception2) {
BugCatcherManager.getBugCatcher().logError(exception2);
throw new EntityServiceException("Could not create database:" + exception2.getMessage());
}
}
// todo: should we explicitly close the DB? putting it in the distructor would not be reliable
// todo: however now that we close via the Close() method it seems fine and the DB is not explicitly opened
}
public ProjectRecord getProjectRecord() {
return projectRecord;
}
// public void closeDataBase() {
// try {
// new Close().execute(context);
// } catch (BaseXException baseXException2) {
// new ArbilBugCatcher().logError(baseXException2);
// see comments below
public void recreateDatabase() throws EntityServiceException {
/*
* this was depricated due to inserted data being non updateable without creating duplicates,
* however we can use it again now that paths are not used to delete records but instead the identifier is used.
* */
try {
// System.out.println("List: " + new List().execute(context));
synchronized (databaseLock) {
new DropDB(databaseName).execute(context);
new Set("CREATEFILTER", "*.kmdi").execute(context);
new CreateDB(databaseName, projectRecord.getProjectDataFilesDirectory().toString()).execute(context);
// System.out.println("List: " + new List().execute(context));
// System.out.println("Find: " + new Find(databaseName).title());
// System.out.println("Info: " + new Info().execute(context));
// new Open(databaseName).execute(context);
// new CreateIndex("text").execute(context); // TEXT|ATTRIBUTE|FULLTEXT|PATH
// new CreateIndex("fulltext").execute(context);
// new CreateIndex("attribute").execute(context);
// new CreateIndex("path").execute(context);
// new Close().execute(context);
// context.close();
}
} catch (BaseXException exception) {
BugCatcherManager.getBugCatcher().logError(exception);
throw new EntityServiceException("Could not recreate database:" + exception.getMessage());
}
updateOccured();
}
/////////////////// Export Queries ///////////////////
public Context openExistingExportDatabase(String exportDatabaseName) throws BaseXException {
Context tempDbContext = new Context();
synchronized (databaseLock) {
new Open(exportDatabaseName).execute(tempDbContext);
}
return tempDbContext;
}
public void dropExportDatabase(Context tempDbContext, String exportDatabaseName) throws BaseXException {
synchronized (databaseLock) {
new DropDB(exportDatabaseName).execute(tempDbContext);
}
}
public Context createExportDatabase(File directoryOfInputFiles, String suffixFilter, String exportDatabaseName) throws BaseXException {
if (suffixFilter == null) {
suffixFilter = "*.kmdi";
}
Context tempDbContext = new Context();
synchronized (databaseLock) {
new DropDB(exportDatabaseName).execute(tempDbContext);
new Set("CREATEFILTER", suffixFilter).execute(tempDbContext);
new CreateDB(exportDatabaseName, directoryOfInputFiles.toString()).execute(tempDbContext);
}
return tempDbContext;
}
public String performExportQuery(Context tempDbContext, String exportDatabaseName, String exportQueryString) throws BaseXException {
if (tempDbContext == null) {
tempDbContext = context;
}
String returnString = null;
synchronized (databaseLock) {
if (exportDatabaseName != null) {
new Close().execute(context);
// todo: verify that opeing two database at the same time will not cause issues
new Open(exportDatabaseName).execute(tempDbContext);
}
returnString = new XQuery(exportQueryString).execute(tempDbContext);
if (exportDatabaseName != null) {
new Close().execute(tempDbContext);
new Open(databaseName).execute(context);
}
}
return returnString;
}
/////////////////// End Export Queries ///////////////////
public void dropDatabase() {
try {
synchronized (databaseLock) {
new DropDB(databaseName).execute(context);
System.out.println("List: " + new List().execute(context));
}
} catch (BaseXException baseXException) {
BugCatcherManager.getBugCatcher().logError(baseXException);
}
}
private void addFileToDB(URI updatedDataUrl, UniqueIdentifier updatedFileIdentifier) throws EntityServiceException {
// the document might be in any location, so the url must be used to add to the DB, but the ID must be used to remove the old DB entries, so that old records will removed including duplicates
String urlString = updatedDataUrl.toASCIIString();
try {
synchronized (databaseLock) {
// delete appears to be fine with a uri string, providing that the document was added as individually and not added as a collection
// the use of DELETE has been replaced by deleting via the ID in a query
// new Delete(urlString).execute(context);
runDeleteQuery(updatedFileIdentifier);
// add requires a url other wise it appends the working path when using base-uri in a query
// add requires the parent directory otherwise it adds the file name to the root and appends the working path when using base-uri in a query
// todo: has the database been opened at this point???
// add appears not to have been tested by anybody, I am not sure if I like basex now, but the following works
new Add(projectRecord.getProjectDataFilesDirectory().toURI().relativize(updatedDataUrl).toASCIIString(), urlString).execute(context);
}
} catch (BaseXException baseXException) {
// todo: if this throws here then the db might be corrupt and the user needs a way to drop and repopulate the db
BugCatcherManager.getBugCatcher().logError(baseXException);
throw new EntityServiceException(dbErrorMessage + "\n Add file to database:" + baseXException.getMessage());
}
}
public void deleteFromDatabase(UniqueIdentifier updatedFileIdentifier) throws EntityServiceException {
try {
synchronized (databaseLock) {
new Open(databaseName).execute(context);
// the use of DELETE has been replaced by deleting via the ID in a query
// new Delete(urlString).execute(context);
runDeleteQuery(updatedFileIdentifier);
new Optimize().execute(context);
new Close().execute(context);
}
updateOccured();
} catch (BaseXException baseXException) {
// todo: if this throws here then the db might be corrupt and the user needs a way to drop and repopulate the db
BugCatcherManager.getBugCatcher().logError(baseXException);
throw new EntityServiceException(dbErrorMessage + "\n Delete file from database:" + baseXException.getMessage());
}
}
public void updateDatabase(final UniqueIdentifier[] updatedFileArray, final JProgressBar progressBar) throws EntityServiceException {
try {
if (progressBar != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setMinimum(0);
progressBar.setMaximum(updatedFileArray.length);
progressBar.setIndeterminate(false);
progressBar.setValue(0);
}
});
}
synchronized (databaseLock) {
new Open(databaseName).execute(context);
for (UniqueIdentifier updatedUniqueIdentifier : updatedFileArray) {
addFileToDB(updatedUniqueIdentifier.getFileInProject(projectRecord).toURI(), updatedUniqueIdentifier);
if (progressBar != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setValue(progressBar.getValue() + 1);
}
});
}
}
if (progressBar != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(true);
}
});
}
new Optimize().execute(context);
if (progressBar != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(false);
}
});
}
new Close().execute(context);
}
updateOccured();
} catch (BaseXException baseXException) {
BugCatcherManager.getBugCatcher().logError(baseXException);
throw new EntityServiceException(dbErrorMessage + "\n Update database:" + baseXException.getMessage());
}
}
public void updateDatabase(URI updatedFile, UniqueIdentifier updatedFileIdentifier) throws EntityServiceException {
// it would appear that a re adding a file does not remove the old entries so for now we will dump and recreate the entire database
// update, this has been updated and adding directories as a collection breaks the update and delete methods in basex so we now do each document individualy
// createDatabase();
try {
synchronized (databaseLock) {
new Open(databaseName).execute(context);
addFileToDB(updatedFile, updatedFileIdentifier);
new Optimize().execute(context);
new Close().execute(context);
}
updateOccured();
} catch (BaseXException baseXException) {
BugCatcherManager.getBugCatcher().logError(baseXException);
throw new EntityServiceException(dbErrorMessage + "\n Update database:" + baseXException.getMessage());
}
}
// public SearchResults listGedcomFamIds() {
// // todo: probably needs to be updated.
// throw new EntityServiceException(dbErrorMessage /* exception.getMessage() */);
|
package org.eclipse.persistence.sdo.helper.delegates;
import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.XMLDocument;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.WeakHashMap;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.sdo.SDOType;
import org.eclipse.persistence.sdo.SDOXMLDocument;
import org.eclipse.persistence.sdo.helper.SDOUnmappedContentHandler;
import org.eclipse.persistence.sdo.helper.SDOClassLoader;
import org.eclipse.persistence.sdo.helper.SDOMarshalListener;
import org.eclipse.persistence.sdo.helper.SDOTypeHelper;
import org.eclipse.persistence.sdo.helper.SDOUnmarshalListener;
import org.eclipse.persistence.sdo.helper.SDOXMLHelper;
import org.eclipse.persistence.sdo.types.SDOPropertyType;
import org.eclipse.persistence.sdo.types.SDOTypeType;
import org.eclipse.persistence.exceptions.SDOException;
import org.eclipse.persistence.exceptions.XMLMarshalException;
import org.eclipse.persistence.internal.oxm.XMLConversionManager;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.XMLLogin;
import org.eclipse.persistence.oxm.XMLMarshaller;
import org.eclipse.persistence.oxm.XMLRoot;
import org.eclipse.persistence.oxm.XMLUnmarshaller;
import org.eclipse.persistence.oxm.record.ContentHandlerRecord;
import org.eclipse.persistence.oxm.record.FormattedWriterRecord;
import org.eclipse.persistence.oxm.record.NodeRecord;
import org.eclipse.persistence.oxm.record.WriterRecord;
import org.eclipse.persistence.sessions.Project;
import org.xml.sax.InputSource;
/**
* <p><b>Purpose</b>: Helper to XML documents into DataObects and DataObjects into XML documents.
* <p><b>Responsibilities</b>:<ul>
* <li> Load methods create commonj.sdo.XMLDocument objects from XML (unmarshal)
* <li> Save methods create XML from commonj.sdo.XMLDocument and commonj.sdo.DataObject objects (marshal)
* </ul>
*/
public class SDOXMLHelperDelegate implements SDOXMLHelper {
private SDOClassLoader loader;
private XMLContext xmlContext;
private Map<Thread, XMLMarshaller> xmlMarshallerMap;
private Map<Thread, XMLUnmarshaller> xmlUnmarshallerMap;
private Project topLinkProject;
// hold the context containing all helpers so that we can preserve inter-helper relationships
private HelperContext aHelperContext;
public SDOXMLHelperDelegate(HelperContext aContext) {
this(aContext, Thread.currentThread().getContextClassLoader());
}
public SDOXMLHelperDelegate(HelperContext aContext, ClassLoader aClassLoader) {
aHelperContext = aContext;
// This ClassLoader is internal to SDO so no inter servlet-ejb container context issues should arise
loader = new SDOClassLoader(aClassLoader, aContext);
xmlMarshallerMap = new WeakHashMap<Thread, XMLMarshaller>();
xmlUnmarshallerMap = new WeakHashMap<Thread, XMLUnmarshaller>();
}
/**
* The specified TimeZone will be used for all String to date object
* conversions. By default the TimeZone from the JVM is used.
*/
public void setTimeZone(TimeZone timeZone) {
getXmlConversionManager().setTimeZone(timeZone);
}
/**
* By setting this flag to true the marshalled date objects marshalled to
* the XML schema types time and dateTime will be qualified by a time zone.
* By default time information is not time zone qualified.
*/
public void setTimeZoneQualified(boolean timeZoneQualified) {
getXmlConversionManager().setTimeZoneQualified(timeZoneQualified);
}
/**
* Creates and returns an XMLDocument from the input String.
* By default does not perform XSD validation.
* Same as
* load(new StringReader(inputString), null, null);
*
* @param inputString specifies the String to read from
* @return the new XMLDocument loaded
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(String inputString) {
StringReader reader = new StringReader(inputString);
try {
return load(reader, null, null);
} catch (IOException ioException) {
ioException.printStackTrace();
return null;
}
}
/**
* Creates and returns an XMLDocument from the inputStream.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* Same as
* load(inputStream, null, null);
*
* @param inputStream specifies the InputStream to read from
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputStream inputStream) throws IOException {
return load(inputStream, null, null);
}
/**
* Creates and returns an XMLDocument from the inputStream.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* @param inputStream specifies the InputStream to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputStream inputStream, String locationURI, Object options) throws IOException {
InputSource inputSource = new InputSource(inputStream);
return load(inputSource, locationURI, options);
}
/**
* Creates and returns an XMLDocument from the inputSource.
* The InputSource will be closed after reading.
* By default does not perform XSD validation.
* @param inputSource specifies the InputSource to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputSource inputSource, String locationURI, Object options) throws IOException {
// get XMLUnmarshaller once - as we may create a new instance if this helper isDirty=true
XMLUnmarshaller anXMLUnmarshaller = getXmlUnmarshaller();
Object unmarshalledObject = null;
if (options == null) {
try {
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource);
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} else {
try {
DataObject optionsDataObject = (DataObject)options;
try {
SDOType theType = (SDOType)optionsDataObject.get(SDOConstants.TYPE_LOAD_OPTION);
try{
if (theType != null) {
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource, theType.getImplClass());
}else{
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource);
}
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} catch (ClassCastException ccException) {
throw SDOException.typePropertyMustBeAType(ccException);
}
} catch (ClassCastException ccException) {
throw SDOException.optionsMustBeADataObject(ccException, SDOConstants.ORACLE_SDO_URL ,SDOConstants.XMLHELPER_LOAD_OPTIONS);
}
}
if (unmarshalledObject instanceof XMLRoot) {
XMLRoot xmlRoot = (XMLRoot)unmarshalledObject;
XMLDocument xmlDocument = createDocument((DataObject)((XMLRoot)unmarshalledObject).getObject(), ((XMLRoot)unmarshalledObject).getNamespaceURI(), ((XMLRoot)unmarshalledObject).getLocalName());
if(xmlRoot.getEncoding() != null) {
xmlDocument.setEncoding(xmlRoot.getEncoding());
}
if(xmlRoot.getXMLVersion() != null) {
xmlDocument.setXMLVersion(xmlRoot.getXMLVersion());
}
xmlDocument.setSchemaLocation(xmlRoot.getSchemaLocation());
xmlDocument.setNoNamespaceSchemaLocation(xmlRoot.getNoNamespaceSchemaLocation());
return xmlDocument;
} else if (unmarshalledObject instanceof DataObject) {
String localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXmlDescriptor().getDefaultRootElement();
if (localName == null) {
localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXsdLocalName();
}
return createDocument((DataObject)unmarshalledObject, ((DataObject)unmarshalledObject).getType().getURI(), localName);
} else if (unmarshalledObject instanceof XMLDocument) {
return (XMLDocument)unmarshalledObject;
}
return null;
}
/**
* Creates and returns an XMLDocument from the inputReader.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* @param inputReader specifies the Reader to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(Reader inputReader, String locationURI, Object options) throws IOException {
InputSource inputSource = new InputSource(inputReader);
return load(inputSource, locationURI, options);
}
public XMLDocument load(Source source, String locationURI, Object options) throws IOException {
// get XMLUnmarshaller once - as we may create a new instance if this helper isDirty=true
XMLUnmarshaller anXMLUnmarshaller = getXmlUnmarshaller();
Object unmarshalledObject = null;
if (options == null) {
try {
unmarshalledObject = anXMLUnmarshaller.unmarshal(source);
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} else {
try {
DataObject optionsDataObject = (DataObject)options;
try {
SDOType theType = (SDOType)optionsDataObject.get(SDOConstants.TYPE_LOAD_OPTION);
try{
if (theType != null) {
unmarshalledObject = anXMLUnmarshaller.unmarshal(source, theType.getImplClass());
}else{
unmarshalledObject = anXMLUnmarshaller.unmarshal(source);
}
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} catch (ClassCastException ccException) {
throw SDOException.typePropertyMustBeAType(ccException);
}
} catch (ClassCastException ccException) {
throw SDOException.optionsMustBeADataObject(ccException, SDOConstants.ORACLE_SDO_URL ,SDOConstants.XMLHELPER_LOAD_OPTIONS);
}
}
if (unmarshalledObject instanceof XMLRoot) {
XMLRoot xmlRoot = (XMLRoot)unmarshalledObject;
XMLDocument xmlDocument = createDocument((DataObject)((XMLRoot)unmarshalledObject).getObject(), ((XMLRoot)unmarshalledObject).getNamespaceURI(), ((XMLRoot)unmarshalledObject).getLocalName());
if(xmlRoot.getEncoding() != null) {
xmlDocument.setEncoding(xmlRoot.getEncoding());
}
if(xmlRoot.getXMLVersion() != null) {
xmlDocument.setXMLVersion(xmlRoot.getXMLVersion());
}
xmlDocument.setSchemaLocation(xmlRoot.getSchemaLocation());
xmlDocument.setNoNamespaceSchemaLocation(xmlRoot.getNoNamespaceSchemaLocation());
return xmlDocument;
} else if (unmarshalledObject instanceof DataObject) {
DataObject unmarshalledDataObject = (DataObject)unmarshalledObject;
String localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXmlDescriptor().getDefaultRootElement();
if (localName == null) {
localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXsdLocalName();
}
return createDocument(unmarshalledDataObject, unmarshalledDataObject.getType().getURI(), localName);
} else if (unmarshalledObject instanceof XMLDocument) {
return (XMLDocument)unmarshalledObject;
}
return null;
}
public String save(DataObject dataObject, String rootElementURI, String rootElementName) {
try {
StringWriter writer = new StringWriter();
save(dataObject, rootElementURI, rootElementName, writer);
return writer.toString();
} catch (XMLMarshalException e) {
throw SDOException.xmlMarshalExceptionOccurred(e, rootElementURI, rootElementName);
}
}
public void save(DataObject dataObject, String rootElementURI, String rootElementName, OutputStream outputStream) throws XMLMarshalException, IOException {
OutputStreamWriter writer = new OutputStreamWriter(outputStream, getXmlMarshaller().getEncoding());
save(dataObject, rootElementURI, rootElementName, writer);
}
public void save(XMLDocument xmlDocument, OutputStream outputStream, Object options) throws IOException {
String encoding = this.getXmlMarshaller().getEncoding();
if(xmlDocument.getEncoding() != null) {
encoding = xmlDocument.getEncoding();
}
OutputStreamWriter writer = new OutputStreamWriter(outputStream, encoding);
save(xmlDocument, writer, options);
}
public void save(XMLDocument xmlDocument, Writer outputWriter, Object options) throws IOException {
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
anXMLMarshaller.setEncoding(xmlDocument.getEncoding());
anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation());
anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation());
WriterRecord writerRecord;
if(anXMLMarshaller.isFormattedOutput()) {
writerRecord = new FormattedWriterRecord();
} else {
writerRecord = new WriterRecord();
}
writerRecord.setWriter(outputWriter);
writerRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(xmlDocument.getRootObject());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName()));
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(writerRecord);
anXMLMarshaller.marshal(xmlDocument, writerRecord);
outputWriter.flush();
}
public void save(XMLDocument xmlDocument, Result result, Object options) throws IOException {
if(result instanceof StreamResult) {
StreamResult streamResult = (StreamResult)result;
Writer writer = streamResult.getWriter();
if (null == writer) {
save(xmlDocument, streamResult.getOutputStream(), options);
} else {
save(xmlDocument, writer, options);
}
} else {
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
anXMLMarshaller.setEncoding(xmlDocument.getEncoding());
anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation());
anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(xmlDocument.getRootObject());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName()));
if(result instanceof SAXResult) {
ContentHandlerRecord marshalRecord = new ContentHandlerRecord();
marshalRecord.setContentHandler(((SAXResult)result).getHandler());
marshalRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(marshalRecord);
anXMLMarshaller.marshal(xmlDocument, marshalRecord);
} else if(result instanceof DOMResult) {
NodeRecord marshalRecord = new NodeRecord();
marshalRecord.setDOM(((DOMResult)result).getNode());
marshalRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(marshalRecord);
anXMLMarshaller.marshal(xmlDocument, marshalRecord);
} else {
StringWriter writer = new StringWriter();
this.save(xmlDocument, writer, options);
String xml = writer.toString();
StreamSource source = new StreamSource(new java.io.StringReader(xml));
anXMLMarshaller.getTransformer().transform(source, result);
}
}
}
/**
* Creates an XMLDocument with the specified XML rootElement for the DataObject.
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @return XMLDocument a new XMLDocument set with the specified parameters.
*/
public XMLDocument createDocument(DataObject dataObject, String rootElementURI, String rootElementName) {
SDOXMLDocument document = new SDOXMLDocument();
document.setRootObject(dataObject);
document.setRootElementURI(rootElementURI);
if (rootElementName != null) {
document.setRootElementName(rootElementName);
}
Property globalProp = getHelperContext().getXSDHelper().getGlobalProperty(rootElementURI, rootElementName, true);
if (null != globalProp) {
document.setSchemaType(((SDOType) globalProp.getType()).getXsdType());
}
document.setEncoding(SDOXMLDocument.DEFAULT_XML_ENCODING);
document.setXMLVersion(SDOXMLDocument.DEFAULT_XML_VERSION);
return document;
}
private void save(DataObject rootObject, String rootElementURI, String rootElementName, Writer writer) throws XMLMarshalException {
// TODO: Change IOException here and in the public String save() caller to propagate XMLMarshalException instead of IOException
SDOXMLDocument xmlDocument = (SDOXMLDocument)createDocument(rootObject, rootElementURI, rootElementName);
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
WriterRecord writerRecord;
if(anXMLMarshaller.isFormattedOutput()) {
writerRecord = new FormattedWriterRecord();
} else {
writerRecord = new WriterRecord();
}
writerRecord.setWriter(writer);
writerRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(rootObject);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(rootElementURI, rootElementName));
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(writerRecord);
anXMLMarshaller.marshal(xmlDocument, writerRecord);
try {
writer.flush();
} catch(IOException ex) {
throw XMLMarshalException.marshalException(ex);
}
}
public void setLoader(SDOClassLoader loader) {
this.loader = loader;
getXmlConversionManager().setLoader(this.loader);
}
public SDOClassLoader getLoader() {
return loader;
}
public void setXmlContext(XMLContext xmlContext) {
this.xmlContext = xmlContext;
}
public synchronized XMLContext getXmlContext() {
if (xmlContext == null) {
xmlContext = new XMLContext(getTopLinkProject());
XMLConversionManager xmlConversionManager = getXmlConversionManager();
xmlConversionManager.setLoader(this.loader);
xmlConversionManager.setTimeZone(TimeZone.getTimeZone("GMT"));
xmlConversionManager.setTimeZoneQualified(true);
}
return xmlContext;
}
public void initializeDescriptor(XMLDescriptor descriptor){
AbstractSession theSession = (AbstractSession)getXmlContext().getSession(0);
//do initialization for new descriptor;
descriptor.preInitialize(theSession);
descriptor.initialize(theSession);
descriptor.postInitialize(theSession);
descriptor.getObjectBuilder().initializePrimaryKey(theSession);
getXmlContext().storeXMLDescriptorByQName(descriptor);
}
public void addDescriptors(List types) {
for (int i = 0; i < types.size(); i++) {
SDOType nextType = (SDOType)types.get(i);
if (!nextType.isDataType() && nextType.isFinalized()){
XMLDescriptor nextDescriptor = nextType.getXmlDescriptor();
getTopLinkProject().addDescriptor(nextDescriptor);
}
}
for (int i = 0; i < types.size(); i++) {
SDOType nextType = (SDOType)types.get(i);
if (!nextType.isDataType() && nextType.isFinalized()){
XMLDescriptor nextDescriptor = nextType.getXmlDescriptor();
initializeDescriptor(nextDescriptor);
}
}
}
public void setTopLinkProject(Project toplinkProject) {
this.topLinkProject = toplinkProject;
//TODO: temporarily nulling things out but should eventually have sessionbroker or list of sessions
this.xmlContext = null;
this.xmlMarshallerMap.clear();
this.xmlUnmarshallerMap.clear();
}
public Project getTopLinkProject() {
if (topLinkProject == null) {
topLinkProject = new Project();
XMLLogin xmlLogin = new XMLLogin();
xmlLogin.setEqualNamespaceResolvers(false);
topLinkProject.setDatasourceLogin(xmlLogin);
// 200606_changeSummary
NamespaceResolver nr = new NamespaceResolver();
SDOTypeHelper sdoTypeHelper = (SDOTypeHelper) aHelperContext.getTypeHelper();
String sdoPrefix = sdoTypeHelper.getPrefix(SDOConstants.SDO_URL);
nr.put(sdoPrefix, SDOConstants.SDO_URL);
SDOType changeSummaryType = (SDOType) sdoTypeHelper.getType(SDOConstants.SDO_URL, SDOConstants.CHANGESUMMARY);
changeSummaryType.getXmlDescriptor().setNamespaceResolver(nr);
topLinkProject.addDescriptor(changeSummaryType.getXmlDescriptor());
SDOType openSequencedType = (SDOType) aHelperContext.getTypeHelper().getType(SDOConstants.ORACLE_SDO_URL, "OpenSequencedType");
topLinkProject.addDescriptor(openSequencedType.getXmlDescriptor());
SDOTypeType typeType = (SDOTypeType)aHelperContext.getTypeHelper().getType(SDOConstants.SDO_URL, SDOConstants.TYPE);
if(!typeType.isInitialized()) {
typeType.initializeMappings();
}
topLinkProject.addDescriptor(typeType.getXmlDescriptor());
SDOPropertyType propertyType = (SDOPropertyType)aHelperContext.getTypeHelper().getType(SDOConstants.SDO_URL, SDOConstants.PROPERTY);
if(!propertyType.isInitialized()) {
propertyType.initializeMappings();
}
topLinkProject.addDescriptor(propertyType.getXmlDescriptor());
((SDOTypeHelper)aHelperContext.getTypeHelper()).addWrappersToProject(topLinkProject);
}
return topLinkProject;
}
public void setXmlMarshaller(XMLMarshaller xmlMarshaller) {
this.xmlMarshallerMap.put(Thread.currentThread(), xmlMarshaller);
}
public XMLMarshaller getXmlMarshaller() {
XMLMarshaller marshaller = xmlMarshallerMap.get(Thread.currentThread());
if (marshaller == null) {
marshaller = getXmlContext().createMarshaller();
marshaller.setMarshalListener(new SDOMarshalListener(marshaller, (SDOTypeHelper) aHelperContext.getTypeHelper()));
xmlMarshallerMap.put(Thread.currentThread(), marshaller);
}
XMLContext context = getXmlContext();
if (marshaller.getXMLContext() != context) {
marshaller.setXMLContext(context);
}
return marshaller;
}
public void setXmlUnmarshaller(XMLUnmarshaller xmlUnmarshaller) {
this.xmlUnmarshallerMap.put(Thread.currentThread(), xmlUnmarshaller);
}
public XMLUnmarshaller getXmlUnmarshaller() {
XMLUnmarshaller unmarshaller = xmlUnmarshallerMap.get(Thread.currentThread());
if (unmarshaller == null) {
unmarshaller = getXmlContext().createUnmarshaller();
unmarshaller.getProperties().put(SDOConstants.SDO_HELPER_CONTEXT, aHelperContext);
unmarshaller.setUnmappedContentHandlerClass(SDOUnmappedContentHandler.class);
unmarshaller.setUnmarshalListener(new SDOUnmarshalListener(aHelperContext));
unmarshaller.setResultAlwaysXMLRoot(true);
xmlUnmarshallerMap.put(Thread.currentThread(), unmarshaller);
}
XMLContext context = getXmlContext();
if (unmarshaller.getXMLContext() != context) {
unmarshaller.setXMLContext(context);
}
return unmarshaller;
}
public void reset() {
setTopLinkProject(null);
setXmlContext(null);
this.xmlMarshallerMap.clear();
this.xmlUnmarshallerMap.clear();
setLoader(new SDOClassLoader(getClass().getClassLoader(), (HelperContext)aHelperContext));
}
public HelperContext getHelperContext() {
return aHelperContext;
}
public void setHelperContext(HelperContext helperContext) {
aHelperContext = helperContext;
}
private void handleXMLMarshalException(XMLMarshalException xmlException) {
if(xmlException.getErrorCode() == XMLMarshalException.NO_DESCRIPTOR_WITH_MATCHING_ROOT_ELEMENT || xmlException.getErrorCode() == XMLMarshalException.DESCRIPTOR_NOT_FOUND_IN_PROJECT){
throw SDOException.globalPropertyNotFound();
}else{
throw xmlException;
}
}
public XMLConversionManager getXmlConversionManager() {
return (XMLConversionManager)getXmlContext().getSession(0).getDatasourceLogin().getDatasourcePlatform().getConversionManager();
}
}
|
package com.galois.qrstream.qrpipe;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.galois.qrstream.image.BitmapImage;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.decoder.Version;
/**
* Class provides API for interfacing with Android application. It
* facilitates transmission of QR codes in streaming QR code protocol.
*
* We may find it necessary to add context to the transmission. For example,
* - resulting image dimension (px)
* - density of QR code (QR version 1-40, not currently exposed in API)
* - others?
*/
public class Transmit {
/* Dimension of transmitted QR code images */
private final int imgHeight;
private final int imgWidth;
public Transmit(int height, int width) {
imgHeight = height;
imgWidth = width;
}
/**
* Encodes array of bytes into a collection of QR codes. It is designed to
* interface with QRStream Android application. It will break input data into
* chunks small enough for encoding into QR codes.
*
* @param data The array of bytes to encode
* @return The sequence of QR codes generated from input data.
* @throws TransmitException if input {@code data} cannot be encoded as QR code.
*/
public Iterable<BitmapImage> encodeQRCodes(final byte[] data) throws TransmitException {
// The collection of qr codes containing encoded data
ArrayList<BitmapImage> qrCodes = new ArrayList<BitmapImage>();
if (data != null && data.length > 0) {
// Assume particular QR density and error correction level so that
// we can calculate the appropriate chunk size for the input data.
Version qrVersion = Version.getVersionForNumber(40);
ErrorCorrectionLevel ecLevel = ErrorCorrectionLevel.L;
int maxChunkSize = getPayloadMaxBytes(ecLevel, qrVersion);
int totalChunks = getTotalChunks(data.length, maxChunkSize);
int chunkId = 0;
ByteArrayInputStream input = null;
try {
input = new ByteArrayInputStream(data);
int bytesRemaining;
while ((bytesRemaining = input.available()) > 0) {
byte[] dataChunk = null;
if (bytesRemaining <= maxChunkSize) {
dataChunk = new byte[bytesRemaining];
} else {
dataChunk = new byte[maxChunkSize];
}
int bytesRead = input.read(dataChunk, 0, dataChunk.length);
if (bytesRead < 0) {
throw new AssertionError(
"Data reportedly available to read but read returned end of input.");
} else if (bytesRead != dataChunk.length) {
throw new AssertionError("Should be possible to read "
+ dataChunk.length + " bytes when there are " + bytesRemaining
+ " bytes available.");
}
chunkId += 1;
qrCodes.add(encodeQRCode(dataChunk, chunkId, totalChunks,
qrVersion, ecLevel));
}
if (chunkId != totalChunks) {
throw new TransmitException("Failed to encode as many chunks as we "
+ "expected. Expected " + totalChunks + " but got " + chunkId);
}
} finally {
// The close method for ByteArrayInputStream does
// nothing but we have this here for completeness.
// If using any other stream, remove try-catch around close.
if (input != null) {
try {
input.close();
} catch (IOException e) {
throw new AssertionError(
"ByteArrayInputStream never throws IOException in close()");
}
}
}
}
return qrCodes;
}
protected BitmapImage encodeQRCode(byte[] chunkedData, int chunkId, int totalChunks,
Version v, ErrorCorrectionLevel ecLevel) throws TransmitException {
if (chunkedData == null) {
throw new NullPointerException("Cannot encode 'null' value as QR code.");
}
if (chunkedData.length >= getPayloadMaxBytes(ecLevel, v)) {
throw new IllegalArgumentException(
"Input data too large for QR version: " + v.getVersionNumber()
+ " and error correction level: " + ecLevel
+ " chunkedData.length = " + chunkedData.length + " maxPayload= "
+ getPayloadMaxBytes(ecLevel, v));
}
BitMatrix bMat = bytesToQRCode(chunkedData);
//prependChunkId(chunkedData, chunkId, totalChunks));
if (bMat.getWidth() != imgWidth || bMat.getHeight() != imgHeight) {
throw new AssertionError("Expected image dimensions to be equal");
}
return BitmapImage.createBitmapImage(bMat);
}
/**
* Returns the maximum number of bytes that can be encoded in QR code with
* version {@code v} and error correction level, {@code ecLevel}.
*
* @param ecLevel
* The error correction level, can be one of these values
* {@code L, M, Q, H}.
* @param v
* The version corresponding to the density of the QR code, 1-40.
* @return
*/
protected int getPayloadMaxBytes(ErrorCorrectionLevel ecLevel, Version v) {
// Max payload for (version,ecLevel) = number data bytes - header bytes
Version.ECBlocks ecBlocks = v.getECBlocksForLevel(ecLevel);
int numReservedBytes = Utils.getNumberQRHeaderBytes(v);
int numDataBytes = v.getTotalCodewords() - ecBlocks.getTotalECCodewords();
return numDataBytes - numReservedBytes;
}
/**
* Injects chunk# and totalChunks into byte[] for encoding into QR code.
* The first {@code NUM_BYTES_PER_INT} bytes are the chunk# followed by
* {@code NUM_BYTES_PER_INT} bytes for the total # chunks.
*
* Note:
* Four bytes may be too much space to reserve, but it was convenient
* to think about. We could probably just use 3 bytes for each int
* and let MAX_INTEGER=2^24-1 = 16,777,215.
*
* If 4 bytes, then max bytes transferred in indices alone would
* equal 2,147,483,647 * 8 bytes = ~16GB.
* If QR code could transfer ~1200 bytes, then largest transfer we could handle
* is 2,147,483,647 * (1200 - 8 bytes) = ~2,384 GB.
* Number realistic max chunks likely to be = 16 GB file / (1200 - 8) bytes
* ~= 14,412,642
* Number realistic bits we'd need = log2(14,412,642) ~= 24
*/
protected byte[] prependChunkId(byte[] rawData, int chunk, int totalChunks) {
// Unable to prepend chunk number to rawData if receive invalid inputs
if (totalChunks < 0 || chunk < 0) {
throw new IllegalArgumentException("Number of chunks must be positive");
}
byte[] inputData = rawData == null ? new byte[0] : rawData.clone();
// Reserve first NUM_BYTES_PER_INT bytes of data for chunk id and
// another NUM_BYTES_PER_INT bytes of data for the totalChunks.
byte[] chunkId = Utils.intToBytes(chunk);
byte[] nChunks = Utils.intToBytes(totalChunks);
byte[] combined = new byte[inputData.length + chunkId.length + nChunks.length];
System.arraycopy(chunkId, 0, combined, 0, chunkId.length);
System.arraycopy(nChunks, 0, combined, chunkId.length, nChunks.length);
System.arraycopy(inputData, 0, combined, chunkId.length + nChunks.length, inputData.length);
return combined;
}
/**
* Generates a QR code given a set of input bytes. This function
* assumes that any injection of a sequence number has already occurred.
*
* ZXing library only encodes String and does not accept byte[], therefore we
* 1. Convert input byte[] to ISO-8859-1 encoded String
* 2. Pass it to ZXing with the ISO-8859-1 character-set hint
* 3. When ZXing sees ISO-8859-1 character-set they set the QR
* encoding mode to 'Byte encoding' and turn the String back to turn to byte[].
* @param rawData the binary data to encode into a single QR code image.
*/
protected BitMatrix bytesToQRCode(byte[] rawData) throws TransmitException {
/*
* Max QR code density is function of error correction level and version of
* QR code. Max bytes for QR in binary/byte mode = 2,953 bytes using, QR
* code version 40 and error-correction level L.
*/
String data;
try {
/* NOTE: There is no significant advantage to using Alphanumeric mode rather than
* Binary mode, in terms of the number of bits we can pack into a single QR code.
* Assuming QR version 40 and error correction level L.
* A. Alphanumeric, max bits = 4296 max chars * 5.5 bits/char = 23,628.
* B. Binary/byte, max bits = 2953 max chars * 8 bits/char = 23,624.
*/
data = new String(rawData, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new AssertionError("ISO-8859-1 character set encoding not supported");
}
/*
* ZXing will determine the necessary QR code density given the number
* of input bytes. If number of bytes is greater than max QR code version,
* ZXing will throw WriterException("Data too big").
*/
QRCodeWriter writer = new QRCodeWriter();
try {
return writer.encode(data, BarcodeFormat.QR_CODE, imgWidth, imgHeight,
getEncodeHints());
} catch (WriterException e) {
throw new TransmitException(e.getMessage());
}
}
/**
* Returns properties for the ZXing QR code writer indicating use of
* ISO-8859-1 character set and the desired error correction level.
*
* There are four error acceptable error correction levels:
* Level L (Low) 7% of codewords can be restored.
* Level M (Medium) 15% of codewords can be restored.
* Level Q (Quartile) 25% of codewords can be restored.
* Level H (High) 30% of codewords can be restored.
*/
private Map<EncodeHintType, Object> getEncodeHints(ErrorCorrectionLevel errorLevel) {
/* Hints */
HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1");
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
return hints;
}
/**
* Returns the ZXing QR code writer properties indicating use of
* ISO-8859-1 character set and a low level of error correction.
*/
private Map<EncodeHintType, Object> getEncodeHints() {
return getEncodeHints(ErrorCorrectionLevel.L);
}
/**
* Returns the number of {@code desiredChunkSize} servings we can fit
* into {@code length}. If {@code desiredChunksSize} does not fit
* evenly, it rounds up to the nearest integer.
*
* @param length the input size that we want to split into chunks.
* @param desiredChunkSize the size of split that we want to break {@source length} into.
*/
private int getTotalChunks(int length, int desiredChunkSize) {
if (length < 0 || desiredChunkSize < 0) {
throw new IllegalArgumentException("Input must be non-negative.");
}
return (length + desiredChunkSize) / desiredChunkSize;
}
}//public class Transmit
|
package data_objects.drivers;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Map;
import java.util.Properties;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.jruby.Ruby;
import org.jruby.RubyBigDecimal;
import org.jruby.RubyBignum;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyNumeric;
import org.jruby.RubyObjectAdapter;
import org.jruby.RubyProc;
import org.jruby.RubyRegexp;
import org.jruby.RubyString;
import org.jruby.RubyTime;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import data_objects.RubyType;
/**
*
* @author alexbcoles
* @author mkristian
*/
public abstract class AbstractDriverDefinition implements DriverDefinition {
// assuming that API is thread safe
protected static final RubyObjectAdapter API = JavaEmbedUtils
.newObjectAdapter();
protected final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
private final static BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);
private final static BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);
private final static long MRI_FIXNUM_MAX = (1L<<32) - 1;
private final static long MRI_FIXNUM_MIN = -1 * MRI_FIXNUM_MAX - 1;
private final String scheme;
private final String jdbcScheme;
private final String moduleName;
private final Driver driver;
/**
*
* @param scheme
* @param moduleName
* @param jdbcDriver
*/
protected AbstractDriverDefinition(String scheme, String moduleName, String jdbcDriver) {
this(scheme, scheme, moduleName, jdbcDriver);
}
/**
*
* @param scheme
* @param jdbcScheme
* @param moduleName
* @param jdbcDriver
*/
protected AbstractDriverDefinition(String scheme, String jdbcScheme,
String moduleName, String jdbcDriver) {
this.scheme = scheme;
this.jdbcScheme = jdbcScheme;
this.moduleName = moduleName;
try {
this.driver = (Driver)loadClass(jdbcDriver).newInstance();
}
catch (InstantiationException e) {
throw new RuntimeException("should not happen", e);
}
catch (IllegalAccessException e) {
throw new RuntimeException("should not happen", e);
}
catch (ClassNotFoundException e) {
throw new RuntimeException("should not happen", e);
}
}
private Class<?> loadClass(String className)
throws ClassNotFoundException {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Class<?> result = null;
try {
if (ccl != null) {
result = ccl.loadClass(className);
}
} catch (ClassNotFoundException e) {
// ignore
}
if (result == null) {
result = getClass().getClassLoader().loadClass(className);
}
return result;
}
/**
*
* @return
*/
public String getModuleName() {
return this.moduleName;
}
/**
*
* @param uri jdbc uri for which a connection is created
* @param properties further properties needed to create a cconnection, i.e. username + password
* @return
* @throws SQLException
*/
public Connection getConnection(String uri, Properties properties) throws SQLException{
return driver.connect(uri, properties);
}
/**
*
* @param connection_uri
* @return
* @throws URISyntaxException
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unchecked")
public URI parseConnectionURI(IRubyObject connection_uri)
throws URISyntaxException, UnsupportedEncodingException {
URI uri;
if ("DataObjects::URI".equals(connection_uri.getType().getName())) {
String query;
StringBuilder userInfo = new StringBuilder();
verifyScheme(stringOrNull(API.callMethod(connection_uri, "scheme")));
String user = stringOrNull(API.callMethod(connection_uri, "user"));
String password = stringOrNull(API.callMethod(connection_uri,
"password"));
String host = stringOrNull(API.callMethod(connection_uri, "host"));
int port = intOrMinusOne(API.callMethod(connection_uri, "port"));
String path = stringOrNull(API.callMethod(connection_uri, "path"));
IRubyObject query_values = API.callMethod(connection_uri, "query");
String fragment = stringOrNull(API.callMethod(connection_uri,
"fragment"));
if (user != null && !"".equals(user)) {
userInfo.append(user);
if (password != null) {
userInfo.append(":").append(password);
}
}
if (query_values.isNil()) {
query = null;
} else if (query_values instanceof RubyHash) {
query = mapToQueryString(query_values.convertToHash());
} else {
query = API.callMethod(query_values, "to_s").asJavaString();
}
if (host != null && !"".equals(host)) {
// a client/server database (e.g. MySQL, PostgreSQL, MS
// SQLServer)
String normalizedPath;
if (path != null && path.length() > 0 && path.charAt(0) != '/') {
normalizedPath = '/' + path;
} else {
normalizedPath = path;
}
uri = new URI(this.jdbcScheme,
(userInfo.length() > 0 ? userInfo.toString() : null),
host, port, normalizedPath, query, fragment);
} else {
// an embedded / file-based database (e.g. SQLite3, Derby
// (embedded mode), HSQLDB - use opaque uri
uri = new URI(this.jdbcScheme, path, fragment);
}
} else {
// If connection_uri comes in as a string, we just pass it
// through
uri = new URI(connection_uri.asJavaString());
}
return uri;
}
/**
*
* @param scheme
*/
protected void verifyScheme(String scheme) {
if (!this.scheme.equals(scheme)) {
throw new RuntimeException("scheme mismatch, expected: "
+ this.scheme + " but got: " + scheme);
}
}
/**
* Convert a map of key/values to a URI query string
*
* @param map
* @return
* @throws java.io.UnsupportedEncodingException
*/
private String mapToQueryString(Map<Object, Object> map)
throws UnsupportedEncodingException {
StringBuilder querySb = new StringBuilder();
for (Map.Entry<Object, Object> pairs: map.entrySet()){
String key = (pairs.getKey() != null) ? pairs.getKey().toString()
: "";
String value = (pairs.getValue() != null) ? pairs.getValue()
.toString() : "";
querySb.append(java.net.URLEncoder.encode(key, "UTF-8"))
.append("=");
querySb.append(java.net.URLEncoder.encode(value, "UTF-8"));
}
return querySb.toString();
}
/**
*
* @return
*/
public RubyObjectAdapter getObjectAdapter() {
return API;
}
/**
*
* @param type
* @param precision
* @param scale
* @return
*/
public RubyType jdbcTypeToRubyType(int type, int precision, int scale) {
return RubyType.jdbcTypeToRubyType(type, scale);
}
/**
*
* @param runtime
* @param rs
* @param col
* @param type
* @return
* @throws SQLException
* @throws IOException
*/
public IRubyObject getTypecastResultSetValue(Ruby runtime,
ResultSet rs, int col, RubyType type) throws SQLException,
IOException {
//System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString());
switch (type) {
case FIXNUM:
case INTEGER:
case BIGNUM:
try {
// in most cases integers will fit into long type
// and therefore should be faster to use getLong
long lng = rs.getLong(col);
if (rs.wasNull()) {
return runtime.getNil();
}
// return RubyNumeric.int2fix(runtime, lng);
// Currently problematic as JRUBY has different boundaries for
if (lng >= MRI_FIXNUM_MAX || lng < MRI_FIXNUM_MIN) {
return RubyBignum.newBignum(runtime, lng);
}
return RubyFixnum.newFixnum(runtime, lng);
} catch (SQLException sqle) {
// if getLong failed then use getBigDecimal
BigDecimal bdi = rs.getBigDecimal(col);
if (bdi == null) {
return runtime.getNil();
}
// will return either Fixnum or Bignum
return RubyBignum.bignorm(runtime, bdi.toBigInteger());
}
case FLOAT:
// TODO: why getDouble is not used here?
BigDecimal bdf = rs.getBigDecimal(col);
if (bdf == null) {
return runtime.getNil();
}
return new RubyFloat(runtime, bdf.doubleValue());
case BIG_DECIMAL:
BigDecimal bd = rs.getBigDecimal(col);
if (bd == null) {
return runtime.getNil();
}
return new RubyBigDecimal(runtime, bd);
case DATE:
java.sql.Date date = rs.getDate(col);
if (date == null) {
return runtime.getNil();
}
return prepareRubyDateFromSqlDate(runtime, sqlDateToDateTime(date));
case DATE_TIME:
java.sql.Timestamp dt = null;
// DateTimes with all-zero components throw a SQLException with
// SQLState S1009 in MySQL Connector/J 3.1+
// See
try {
dt = rs.getTimestamp(col);
} catch (SQLException ignored) {
}
if (dt == null) {
return runtime.getNil();
}
return prepareRubyDateTimeFromSqlTimestamp(runtime, sqlTimestampToDateTime(dt));
case TIME:
switch (rs.getMetaData().getColumnType(col)) {
case Types.TIME:
java.sql.Time tm = rs.getTime(col);
if (tm == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm));
case Types.TIMESTAMP:
java.sql.Timestamp ts = rs.getTimestamp(col);
if (ts == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, sqlTimestampToDateTime(ts));
case Types.DATE:
java.sql.Date da = rs.getDate(col);
if (da == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlDate(runtime, da);
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime,
str);
return_str.setTaint(true);
return return_str;
}
case TRUE_CLASS:
// getBoolean delivers False in case the underlying data is null
if (rs.getString(col) == null){
return runtime.getNil();
}
return runtime.newBoolean(rs.getBoolean(col));
case BYTE_ARRAY:
InputStream binaryStream = rs.getBinaryStream(col);
ByteList bytes = new ByteList(2048);
try {
byte[] buf = new byte[2048];
for (int n = binaryStream.read(buf); n != -1; n = binaryStream
.read(buf)) {
bytes.append(buf, 0, n);
}
} finally {
binaryStream.close();
}
return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass(
"ByteArray"), "new", runtime.newString(bytes));
case CLASS:
String classNameStr = rs.getString(col);
if (classNameStr == null) {
return runtime.getNil();
}
RubyString class_name_str = RubyString.newUnicodeString(runtime, rs
.getString(col));
class_name_str.setTaint(true);
return API.callMethod(runtime.fastGetModule("DataObjects"), "full_const_get",
class_name_str);
case OBJECT:
InputStream asciiStream = rs.getAsciiStream(col);
IRubyObject obj = runtime.getNil();
UnmarshalStream ums = null;
try {
ums = new UnmarshalStream(runtime, asciiStream,
RubyProc.NEVER);
obj = ums.unmarshalObject();
} catch (IOException ioe) {
// TODO: log this
}finally {
if(ums != null){
try{
ums.close();
}catch (Exception ex){
//TODO log this
}
}
}
return obj;
case NIL:
return runtime.getNil();
case STRING:
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime, str);
return_str.setTaint(true);
return return_str;
}
}
/**
*
* @param ps
* @param arg
* @param idx
* @throws SQLException
*/
public void setPreparedStatementParam(PreparedStatement ps,
IRubyObject arg, int idx) throws SQLException {
switch (RubyType.inferRubyType(arg)) {
case FIXNUM:
ps.setLong(idx, Long.parseLong(arg.toString()));
break;
case BIGNUM:
BigInteger big = ((RubyBignum) arg).getValue();
if (big.compareTo(LONG_MIN) < 0 || big.compareTo(LONG_MAX) > 0) {
// set as big decimal
ps.setBigDecimal(idx, new BigDecimal(((RubyBignum) arg).getValue()));
} else {
// set as long
ps.setLong(idx, ((RubyBignum) arg).getLongValue());
}
break;
case FLOAT:
ps.setDouble(idx, RubyNumeric.num2dbl(arg));
break;
case BIG_DECIMAL:
ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue());
break;
case NIL:
ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx));
break;
case TRUE_CLASS:
case FALSE_CLASS:
ps.setBoolean(idx, arg.toString().equals("true"));
break;
case STRING:
ps.setString(idx, arg.asString().getUnicodeValue());
break;
case CLASS:
ps.setString(idx, arg.toString());
break;
case BYTE_ARRAY:
ps.setBytes(idx, ((RubyString) arg).getBytes());
break;
// TODO: add support for ps.setBlob();
case DATE:
ps.setDate(idx, java.sql.Date.valueOf(arg.toString()));
break;
case TIME:
DateTime dateTime = ((RubyTime) arg).getDateTime();
Timestamp ts = new Timestamp(dateTime.getMillis());
ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar());
break;
case DATE_TIME:
String datetime = arg.toString().replace('T', ' ');
ps.setTimestamp(idx, Timestamp.valueOf(datetime
.replaceFirst("[-+]..:..$", "")));
break;
case REGEXP:
ps.setString(idx, ((RubyRegexp) arg).source().toString());
break;
case OTHER:
default:
int jdbcType = ps.getParameterMetaData().getParameterType(idx);
ps.setObject(idx, arg.asJavaString(), jdbcType);
}
}
/**
*
* @param sqlText
* @param ps
* @param idx
* @return
* @throws SQLException
*/
public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException {
return false;
}
/**
*
* @param ps
* @return
* @throws SQLException
*/
public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException {
return 0;
}
/**
*
* @param sqlText
* @param args
* @return
*/
public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) {
return sqlText;
}
/**
*
* @return
*/
public abstract boolean supportsJdbcGeneratedKeys();
/**
*
* @return
*/
public abstract boolean supportsJdbcScrollableResultSets();
/**
*
* @return
*/
public boolean supportsConnectionEncodings() {
return false;
}
/**
*
* @return
*/
public boolean supportsConnectionPrepareStatementMethodWithGKFlag() {
return true;
}
/**
*
* @param connection
* @return
*/
public ResultSet getGeneratedKeys(Connection connection) {
return null;
}
/**
*
* @return
*/
public Properties getDefaultConnectionProperties() {
return new Properties();
}
/**
*
* @param connectionUri
* @return
*/
public String getJdbcUri(URI connectionUri) {
String jdbcUri = connectionUri.toString();
if (jdbcUri.contains("@")) {
jdbcUri = connectionUri.toString().replaceFirst(":
}
// Replace . with : in scheme name - necessary for Oracle scheme oracle:thin
// : cannot be used in JDBC_URI_SCHEME as then it is identified as opaque URI
// jdbcUri = jdbcUri.replaceFirst("^([a-z]+)(\\.)", "$1:");
if (!jdbcUri.startsWith("jdbc:")) {
jdbcUri = "jdbc:" + jdbcUri;
}
return jdbcUri;
}
/**
*
* @param doConn
* @param conn
* @param query
* @throws SQLException
*/
public void afterConnectionCallback(IRubyObject doConn, Connection conn,
Map<String, String> query) throws SQLException {
// do nothing
}
/**
*
* @param props
* @param encodingName
*/
public void setEncodingProperty(Properties props, String encodingName) {
// do nothing
}
/**
*
* @param runtime
* @param connection
* @param url
* @param props
* @return
* @throws SQLException
*/
public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection,
String url, Properties props) throws SQLException {
throw new UnsupportedOperationException("This method only returns a method"
+ " for drivers that support specifiying an encoding.");
}
/**
*
* @param str
* @return
*/
public String quoteString(String str) {
StringBuilder quotedValue = new StringBuilder(str.length() + 2);
quotedValue.append("\'");
quotedValue.append(str.replaceAll("'", "''"));
quotedValue.append("\'");
return quotedValue.toString();
}
/**
*
* @param connection
* @param value
* @return
*/
public String quoteByteArray(IRubyObject connection, IRubyObject value) {
return quoteString(value.asJavaString());
}
/**
*
* @param s
* @return
*/
public String statementToString(Statement s) {
return s.toString();
}
/**
*
* @param date
* @return
*/
protected static DateTime sqlDateToDateTime(Date date) {
if (date == null)
return null;
else
return new DateTime(date);
}
/**
*
* @param ts
* @return
*/
protected static DateTime sqlTimestampToDateTime(Timestamp ts) {
if (ts == null)
return null;
else
return new DateTime(ts);
}
/**
*
* @param runtime
* @param stamp
* @return
*/
protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp(
Ruby runtime, DateTime stamp) {
if (stamp.getMillis() == 0) {
return runtime.getNil();
}
int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 1000;
RubyClass klazz = runtime.fastGetClass("DateTime");
IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod(
runtime.getCurrentContext(),
"new",
new IRubyObject[] { runtime.newFixnum(zoneOffset),
runtime.newFixnum(86400) });
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(stamp.getYear()),
runtime.newFixnum(stamp.getMonthOfYear()),
runtime.newFixnum(stamp.getDayOfMonth()),
runtime.newFixnum(stamp.getHourOfDay()),
runtime.newFixnum(stamp.getMinuteOfHour()),
runtime.newFixnum(stamp.getSecondOfMinute()),
rbOffset });
}
/**
*
* @param runtime
* @param time
* @return
*/
protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime,
DateTime time) {
// TODO: why in this case nil is returned?
if (time.getMillis() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, time);
return rbTime;
}
/**
*
* @param runtime
* @param date
* @return
*/
protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime,
Date date) {
if (date.getTime() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, date.getTime());
return rbTime;
}
/**
*
* @param runtime
* @param date
* @return
*/
public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime,
DateTime date) {
if (date.getMillis() == 0) {
return runtime.getNil();
}
RubyClass klazz = runtime.fastGetClass("Date");
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(date.getYear()),
runtime.newFixnum(date.getMonthOfYear()),
runtime.newFixnum(date.getDayOfMonth()) });
}
/**
*
* @param obj
* @return
*/
private static String stringOrNull(IRubyObject obj) {
return (!obj.isNil()) ? obj.asJavaString() : null;
}
/**
*
* @param obj
* @return
*/
private static int intOrMinusOne(IRubyObject obj) {
return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1;
}
// private static Integer integerOrNull(IRubyObject obj) {
// return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null;
}
|
package org.dspace.curate;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.dspace.handle.HandleManager;
import org.dspace.app.util.DCInput;
import org.dspace.app.util.DCInputSet;
import org.dspace.app.util.DCInputsReader;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.Bundle;
import org.dspace.content.Bitstream;
import org.dspace.content.crosswalk.MetadataValidationException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.identifier.IdentifierService;
import org.dspace.identifier.IdentifierNotFoundException;
import org.dspace.identifier.IdentifierNotResolvableException;
import org.dspace.utils.DSpace;
import org.apache.log4j.Logger;
/**
* DataPackageStats retrieves detailed statistics about a data package.
*
* Some statistics are calculated based on the files that are contained in the
* data package. Extra processing time is required to load and process the data
* file metadata, so this report takes some time to run. For simpler information
* about data packages, see DataPackageInfo.
*
* The task succeeds if it was able to locate all required stats, otherwise it fails.
* Originally based on the RequiredMetadata task by Richard Rodgers.
*
* Input: a single data package OR a collection that contains data packages
* Output: CSV file with appropriate stats
* @author Ryan Scherle
*/
@Suspendable
public class DataPackageStats extends AbstractCurationTask {
private static Logger log = Logger.getLogger(DataPackageStats.class);
private IdentifierService identifierService = null;
DocumentBuilderFactory dbf = null;
DocumentBuilder docb = null;
static long total = 0;
private Context context;
private static List<String> journalsThatAllowReview = new ArrayList<String>();
private static List<String> integratedJournals = new ArrayList<String>();
private static List<String> integratedJournalsThatAllowEmbargo = new ArrayList<String>();
@Override
public void init(Curator curator, String taskId) throws IOException {
super.init(curator, taskId);
identifierService = new DSpace().getSingletonService(IdentifierService.class);
// init xml processing
try {
dbf = DocumentBuilderFactory.newInstance();
docb = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new IOException("unable to initiate xml processor", e);
}
// init list of journals that support embargo and review
String journalPropFile = ConfigurationManager.getProperty("submit.journal.config");
log.info("initializing journal settings from property file " + journalPropFile);
Properties properties = new Properties();
try {
properties.load(new FileInputStream(journalPropFile));
String journalTypes = properties.getProperty("journal.order");
for (int i = 0; i < journalTypes.split(",").length; i++) {
String journalType = journalTypes.split(",")[i].trim();
String journalDisplay = properties.getProperty("journal." + journalType + ".fullname");
String integrated = properties.getProperty("journal." + journalType + ".integrated");
String embargo = properties.getProperty("journal." + journalType + ".embargoAllowed", "true");
String allowReviewWorkflow = properties.getProperty("journal." + journalType + ".allowReviewWorkflow", "false");
if(integrated != null && Boolean.valueOf(integrated)) {
integratedJournals.add(journalDisplay);
}
if(allowReviewWorkflow != null && Boolean.valueOf(allowReviewWorkflow)) {
journalsThatAllowReview.add(journalDisplay);
}
if(embargo != null && Boolean.valueOf(embargo)) {
integratedJournalsThatAllowEmbargo.add(journalDisplay);
}
}
} catch(Exception e) {
log.error("Unable to initialize the journal settings");
}
}
/**
* Perform the curation task upon passed DSO
*
* @param dso the DSpace object
* @throws IOException
*/
@Override
public int perform(DSpaceObject dso) throws IOException {
log.info("performing DataPackageStats task " + total++ );
String handle = "\"[no handle found]\"";
String packageDOI = "\"[no package DOI found]\"";
String articleDOI = "\"[no article DOI found]\"";
String journal = "[no journal found]"; // don't add quotes here, because journal is always quoted when output below
boolean journalAllowsEmbargo = false;
boolean journalAllowsReview = false;
String numKeywords = "\"[no numKeywords found]\"";
String numKeywordsJournal = "\"[unknown]\"";
String numberOfFiles = "\"[no numberOfFiles found]\"";
long packageSize = 0;
String embargoType = "none";
String embargoDate = "";
int maxDownloads = 0;
String numberOfDownloads = "\"[unknown]\"";
String manuscriptNum = null;
int numReadmes = 0;
boolean wentThroughReview = false;
String dateAccessioned = "\"[unknown]\"";
try {
context = new Context();
} catch (SQLException e) {
log.fatal("Unable to open database connection", e);
return Curator.CURATE_FAIL;
}
if (dso.getType() == Constants.COLLECTION) {
report("handle, packageDOI, articleDOI, journal, journalAllowsEmbargo, journalAllowsReview, numKeywords, numKeywordsJournal, numberOfFiles, packageSize, " +
"embargoType, embargoDate, numberOfDownloads, manuscriptNum, numReadmes, wentThroughReview, dateAccessioned");
} else if (dso.getType() == Constants.ITEM) {
Item item = (Item)dso;
try {
handle = item.getHandle();
log.info("handle = " + handle);
if (handle == null) {
// this item is still in workflow - no handle assigned
handle = "in workflow";
}
// package DOI
DCValue[] vals = item.getMetadata("dc.identifier");
if (vals.length == 0) {
setResult("Object has no dc.identifier available " + handle);
log.error("Skipping -- no dc.identifier available for " + handle);
context.abort();
return Curator.CURATE_SKIP;
} else {
for(int i = 0; i < vals.length; i++) {
if (vals[i].value.startsWith("doi:")) {
packageDOI = vals[i].value;
}
}
}
log.debug("packageDOI = " + packageDOI);
// article DOI
vals = item.getMetadata("dc.relation.isreferencedby");
if (vals.length == 0) {
log.debug("Object has no articleDOI (dc.relation.isreferencedby) " + handle);
} else {
articleDOI = vals[0].value;
}
log.debug("articleDOI = " + articleDOI);
// journal
vals = item.getMetadata("prism.publicationName");
if (vals.length == 0) {
setResult("Object has no prism.publicationName available " + handle);
log.error("Skipping -- Object has no prism.publicationName available " + handle);
context.abort();
return Curator.CURATE_SKIP;
} else {
journal = vals[0].value;
}
log.debug("journal = " + journal);
// journalAllowsEmbargo
// embargoes are allowed for all non-integrated journals
// embargoes are also allowed for integrated journals that have set the embargoesAllowed option
if(!integratedJournals.contains(journal) || integratedJournalsThatAllowEmbargo.contains(journal)) {
journalAllowsEmbargo = true;
}
// journalAllowsReview
if(journalsThatAllowReview.contains(journal)) {
journalAllowsReview = true;
}
// accession date
vals = item.getMetadata("dc.date.accessioned");
if (vals.length == 0) {
setResult("Object has no dc.date.accessioned available " + handle);
log.error("Skipping -- Object has no dc.date.accessioned available " + handle);
context.abort();
return Curator.CURATE_SKIP;
} else {
dateAccessioned = vals[0].value;
}
log.debug("dateAccessioned = " + dateAccessioned);
// wentThroughReview
vals = item.getMetadata("dc.description.provenance");
if (vals.length == 0) {
log.warn("That's strange -- Object has no provenance data available " + handle);
} else {
for(DCValue aVal : vals) {
if(aVal.value != null && aVal.value.contains("requiresReviewStep")) {
wentThroughReview = true;
}
}
}
log.debug("wentThroughReview = " + wentThroughReview);
// number of keywords
int intNumKeywords = item.getMetadata("dc.subject").length +
item.getMetadata("dwc.ScientificName").length +
item.getMetadata("dc.coverage.temporal").length +
item.getMetadata("dc.coverage.spatial").length;
numKeywords = "" + intNumKeywords; //convert integer to string by appending
log.debug("numKeywords = " + numKeywords);
// manuscript number
DCValue[] manuvals = item.getMetadata("dc.identifier.manuscriptNumber");
manuscriptNum = null;
if(manuvals.length > 0) {
manuscriptNum = manuvals[0].value;
}
if(manuscriptNum != null && manuscriptNum.trim().length() > 0) {
log.debug("has a real manuscriptNum = " + manuscriptNum);
/*
// number of keywords in journal email -- currently commented out because it wasn't working for 2012 and later.
//find metadata file for the manuscript
int firstdash = manuscriptNum.indexOf("-");
String journalAbbrev = manuscriptNum.substring(0, firstdash);
if(journalAbbrev.startsWith("0") ||
journalAbbrev.startsWith("1") ||
journalAbbrev.startsWith("2") ||
journalAbbrev.startsWith("3") ||
journalAbbrev.startsWith("4") ||
journalAbbrev.startsWith("5") ||
journalAbbrev.startsWith("6") ||
journalAbbrev.startsWith("7") ||
journalAbbrev.startsWith("8") ||
journalAbbrev.startsWith("9")) {
//handle older manuscript numbers from amnat
journalAbbrev = "amNat";
manuscriptNum = "amNat-" + manuscriptNum;
firstdash = 5;
}
if(!journalAbbrev.equals("new")) {
numKeywordsJournal = "0";
String journalDir="/opt/dryad/submission/journalMetadata/";
manuscriptNum = manuscriptNum.substring(firstdash + 1);
int lastdash = manuscriptNum.lastIndexOf("-");
if(lastdash >= 0) {
manuscriptNum = manuscriptNum.substring(0, lastdash);
File journalFile = new File(journalDir + journalAbbrev + "/" + manuscriptNum + ".xml");
//get keywords from the file and count them
if(journalFile.exists()) {
Document journaldoc = docb.parse(new FileInputStream(journalFile));
NodeList nl = journaldoc.getElementsByTagName("keyword");
numKeywordsJournal = "" + nl.getLength();
} else {
report("Unable to find journal file " + journalFile);
log.error("Unable to find journal file " + journalFile);
}
} else {
report("Unable to parse manuscript number " + manuvals[0].value);
log.error("Unable to parse manuscript number " + manuvals[0].value);
}
log.debug("numKeywordsJournal = " + numKeywordsJournal);
}
*/
}
// count the files, and compute statistics that depend on the files
log.debug("getting data file info");
DCValue[] dataFiles = item.getMetadata("dc.relation.haspart");
if (dataFiles.length == 0) {
setResult("Object has no dc.relation.haspart available " + handle);
log.error("Skipping -- Object has no dc.relation.haspart available " + handle);
context.abort();
return Curator.CURATE_SKIP;
} else {
numberOfFiles = "" + dataFiles.length;
packageSize = 0;
// for each data file in the package
for(int i = 0; i < dataFiles.length; i++) {
String fileID = dataFiles[i].value;
log.debug(" ======= processing fileID = " + fileID);
// get the DSpace Item for this fileID
Item fileItem = getDSpaceItem(fileID);
if(fileItem == null) {
log.error("Skipping data file -- it's null");
break;
}
log.debug("file internalID = " + fileItem.getID());
// total package size
// add total size of the bitstreams in this data file
// to the cumulative total for the package
// (includes metadata, readme, and textual conversions for indexing)
for (Bundle bn : fileItem.getBundles()) {
for (Bitstream bs : bn.getBitstreams()) {
packageSize = packageSize + bs.getSize();
}
}
log.debug("total package size (as of file " + fileID + ") = " + packageSize);
// Readmes
// Check for at least one readme bitstream. There may be more, due to indexing and cases
// where the file itself is named readme. We only count one readme per datafile.
boolean readmeFound = false;
for (Bundle bn : fileItem.getBundles()) {
for (Bitstream bs : bn.getBitstreams()) {
String name = bs.getName().trim().toLowerCase();
if(name.startsWith("readme")) {
readmeFound = true;
}
}
}
if(readmeFound) {
numReadmes++;
}
log.debug("total readmes (as of file " + fileID + ") = " + numReadmes);
// embargo setting (of last file processed)
vals = fileItem.getMetadata("dc.type.embargo");
if (vals.length > 0) {
embargoType = vals[0].value;
log.debug("EMBARGO vals " + vals.length + " type " + embargoType);
}
vals = fileItem.getMetadata("dc.date.embargoedUntil");
if (vals.length > 0) {
embargoDate = vals[0].value;
}
if((embargoType == null || embargoType.equals("") || embargoType.equals("none")) &&
(embargoDate != null && !embargoDate.equals(""))) {
// correctly encode embago type to "oneyear" if there is a date set, but the type is blank or none
embargoType = "oneyear";
}
log.debug("embargoType = " + embargoType);
log.debug("embargoDate = " + embargoDate);
// number of downlaods for most downloaded file
// must use the DSpace item ID, since the solr stats system is based on this ID
// The SOLR address is hardcoded to the production system here, because even when we run on test servers,
// it's easiest to use the real stats --the test servers typically don't have useful stats available
URL downloadStatURL = new URL("http://datadryad.org/solr/statistics/select/?indent=on&q=owningItem:" + fileItem.getID());
log.debug("fetching " + downloadStatURL);
Document statsdoc = docb.parse(downloadStatURL.openStream());
NodeList nl = statsdoc.getElementsByTagName("result");
String downloadsAtt = nl.item(0).getAttributes().getNamedItem("numFound").getTextContent();
int currDownloads = Integer.parseInt(downloadsAtt);
if(currDownloads > maxDownloads) {
maxDownloads = currDownloads;
// rather than converting maxDownloads back to a string, just use the string we parsed above
numberOfDownloads = downloadsAtt;
}
log.debug("max downloads (as of file " + fileID + ") = " + numberOfDownloads);
}
}
log.info(handle + " done.");
} catch (Exception e) {
log.fatal("Skipping -- Exception in processing " + handle, e);
setResult("Object has a fatal error: " + handle + "\n" + e.getMessage());
report("Object has a fatal error: " + handle + "\n" + e.getMessage());
context.abort();
return Curator.CURATE_SKIP;
}
} else {
log.info("Skipping -- non-item DSpace object");
setResult("Object skipped (not an item)");
context.abort();
return Curator.CURATE_SKIP;
}
setResult("Last processed item = " + handle + " -- " + packageDOI);
report(handle + ", " + packageDOI + ", " + articleDOI + ", \"" + journal + "\", " +
journalAllowsEmbargo + ", " + journalAllowsReview + ", " + numKeywords + ", " +
numKeywordsJournal + ", " + numberOfFiles + ", " + packageSize + ", " +
embargoType + ", " + embargoDate + ", " + numberOfDownloads + ", " + manuscriptNum + ", " +
numReadmes + ", " + wentThroughReview + ", " + dateAccessioned);
// slow this down a bit so we don't overwhelm the production SOLR server with requests
try {
Thread.sleep(20);
} catch(InterruptedException e) {
// ignore it
}
log.debug("DataPackageStats complete");
try {
context.complete();
} catch (SQLException e) {
log.fatal("Unable to close database connection", e);
}
return Curator.CURATE_SUCCESS;
}
/**
An XML utility method that returns the text content of a node.
**/
private String getNodeText(Node aNode) {
return aNode.getChildNodes().item(0).getNodeValue();
}
private Item getDSpaceItem(String itemID) {
Item dspaceItem = null;
try {
dspaceItem = (Item)identifierService.resolve(context, itemID);
} catch (IdentifierNotFoundException e) {
log.fatal("Unable to get DSpace Item for " + itemID, e);
} catch (IdentifierNotResolvableException e) {
log.fatal("Unable to get DSpace Item for " + itemID, e);
}
return dspaceItem;
}
}
|
/*
* This class is the main grid square
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BattleshipsGameMainPanel extends JPanel implements MouseListener {
private String name;
private boolean isPlayer;
private boolean hasShip;
private boolean isHit;
public BattleshipsGameMainPanel(boolean isPlayer, String name) {
this.isPlayer = isPlayer;
this.name = name;
setBackground(BattleshipsMainFrame.NORMAL_COLOUR);
addMouseListener(this);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setPreferredSize(new Dimension(30, 30));
}
//returns hasShip
public boolean getHasShip() {
return hasShip;
}
//returns isHits
public boolean getIsHit() {
return isHit;
}
//returns the name
public String getName() {
return name;
}
//returns isPlayer
public boolean getIsPlayer() {
return isPlayer;
}
//called when the user fires on that panel
public void setHit() {
isHit = true;
if(hasShip) {
setBackground(BattleshipsMainFrame.HIT_COLOUR);
} else {
setBackground(BattleshipsMainFrame.MISS_COLOUR);
}
}
//called when there is supposed to be a ship there
public void setShip() {
hasShip = true;
if(isPlayer) {
setBackground(BattleshipsMainFrame.SHIP_COLOUR);
}
}
//mouse listeners
public void mouseClicked(MouseEvent e) {
if(!isPlayer) {
BattleshipsGamePanel.controlLocationLabel.setText(name);
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
if(!isHit && !isPlayer) {
setBackground(BattleshipsMainFrame.HOVER_COLOUR);
}
}
public void mouseExited(MouseEvent e) {
if(!isHit && !isPlayer) {
setBackground(BattleshipsMainFrame.NORMAL_COLOUR);
}
}
}
|
package foam.lib.json;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.lang.reflect.InvocationTargetException;
import foam.core.ClassInfo;
import foam.core.PropertyInfo;
import foam.lib.parse.*;
public class ModelParserFactory {
private static HashMap<Class, Parser> parsers_ = new HashMap<Class, Parser>();
public static Parser getInstance(Class c) {
if ( parsers_.containsKey(c) ) {
return parsers_.get(c);
}
ClassInfo info = null;
try {
info = (ClassInfo)c.getMethod("getOwnClassInfo").invoke(null);
} catch(NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
throw new RuntimeException("Failed to build parser for " + info.getId(), e);
}
Parser parser = buildInstance_(info);
parsers_.put(c, parser);
return parser;
}
public static Parser buildInstance_(ClassInfo info) {
List properties = info.getAxiomsByClass(PropertyInfo.class);
Parser[] propertyParsers = new Parser[properties.size()];
Iterator iter = properties.iterator();
int i = 0;
while(iter.hasNext()) {
propertyParsers[i] = new PropertyParser((PropertyInfo)iter.next());
i++;
}
// TODO: Don't fail to parse if we find an unknown property.
return new Repeat0(new Seq0(new Whitespace(),
new Literal(","),
new Whitespace(),
new Alt(propertyParsers)));
}
}
|
package org.jpos.space;
import java.util.StringTokenizer;
import org.jpos.util.NameRegistrar;
/**
* Creates a space based on a space URI.
*
* <p>A space URI has three parts:
* <ul>
* <li>scheme
* <li>name
* <li>optional parameter
* </ul>
* <p>
* <p>
*
* Examples:
*
* <pre>
* // default unnamed space (tspace:default)
* Space sp = SpaceFactory.getSpace ();
*
* // transient space named "test"
* Space sp = SpaceFactory.getSpace ("transient:test");
*
* // persistent space named "test"
* Space sp = SpaceFactory.getSpace ("persistent:test");
*
* // jdbm space named test
* Space sp = SpaceFactory.getSpace ("jdbm:test");
*
* // jdbm space named test, storage located in /tmp/test
* Space sp = SpaceFactory.getSpace ("jdbm:test:/tmp/test");
* </pre>
*
*/
public class SpaceFactory {
public static final String TSPACE = "tspace";
public static final String TRANSIENT = "transient";
public static final String PERSISTENT = "persistent";
public static final String SPACELET = "spacelet";
public static final String JDBM = "jdbm";
public static final String DEFAULT = "default";
/**
* @return the default TransientSpace
*/
public static Space getSpace () {
return getSpace (TSPACE, DEFAULT, null);
}
/**
* @param spaceUri
* @return Space for given URI or null
*/
public static Space getSpace (String spaceUri) {
if (spaceUri == null)
return getSpace ();
Space sp = null;
String scheme = null;
String name = null;
String param = null;
StringTokenizer st = new StringTokenizer (spaceUri, ":");
int count = st.countTokens();
if (count == 0) {
scheme = TSPACE;
name = DEFAULT;
}
else if (count == 1) {
scheme = TSPACE;
name = st.nextToken ();
}
else {
scheme = st.nextToken ();
name = st.nextToken ();
}
if (st.hasMoreTokens()) {
param = st.nextToken ();
}
return getSpace (scheme, name, param);
}
public static Space getSpace (String scheme, String name, String param) {
Space sp = null;
String uri = normalize (scheme, name, param);
synchronized (SpaceFactory.class) {
try {
sp = (Space) NameRegistrar.get (uri);
} catch (NameRegistrar.NotFoundException e) {
if (SPACELET.equals (scheme))
throw new SpaceError (uri + " not found.");
sp = createSpace (scheme, name, param);
NameRegistrar.register (uri, sp);
}
}
if (sp == null) {
throw new SpaceError ("Invalid space: " + uri);
}
return sp;
}
private static Space createSpace (String scheme, String name, String param)
{
Space sp = null;
if (TSPACE.equals (scheme)) {
sp = new TSpace ();
} else if (TRANSIENT.equals (scheme)) {
sp = TransientSpace.getSpace (name);
} else if (PERSISTENT.equals (scheme)) {
sp = PersistentSpace.getSpace (name);
} else if (JDBM.equals (scheme)) {
if (param != null)
sp = JDBMSpace.getSpace (name, param);
else
sp = JDBMSpace.getSpace (name);
}
return sp;
}
private static String normalize (String scheme, String name, String param) {
StringBuffer sb = new StringBuffer (scheme);
sb.append (':');
sb.append (name);
if (param != null) {
sb.append (':');
sb.append (param);
}
return sb.toString();
}
}
|
package Gui2D;
import Gui2D.Maps.Cellar;
import Gui2D.Maps.Forest;
import Gui2D.Maps.House2;
import Gui2D.Maps.Forest;
import Gui2D.Maps.GruulsLair;
import Gui2D.Maps.Map;
import Gui2D.Maps.Menu;
import Gui2D.SpriteController.SpriteController;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author jonas
*/
public class WizardOfTreldan extends Application {
//set all our maps
private static Map cellar;
private static Map gruulslair;
private static Map menu;
private static Map house2;
private static Map forest;
//our global world generator
private SpriteController world;
//set a global stage from the primaryStage
private static Stage primaryStage;
@Override
public void start(Stage primaryStage) {
//set our stage
this.primaryStage = primaryStage;
//remove the top bar of the frame
this.primaryStage.initStyle(StageStyle.UNDECORATED);
//set our width and height
this.primaryStage.setWidth(1024);
this.primaryStage.setHeight(512);
//set the title
this.primaryStage.setTitle("The Wizard of Treldan");
//Init our world sprite controller
world = new SpriteController();
//Init all world maps
cellar = new Cellar(world);
menu = new Menu(world);
house2 = new House2(world);
//set our first scene
primaryStage.setScene(house2.getScene());
forest = new Forest(world);
//set our first scene
primaryStage.setScene(forest.getScene());
gruulslair = new GruulsLair(world);
//set our first scene
primaryStage.setScene(gruulslair.getScene());
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
/**
* Force the game to load menu scene
*/
public static void setMenuScene(){
primaryStage.setScene(menu.getScene());
}
/**
* Force the game to load CellarScene
*/
public static void setCellarScene(){
primaryStage.setScene(cellar.getScene());
}
public static void setForestScene() {
primaryStage.setScene(forest.getScene());
}
public static void setHouse2Scene(){
primaryStage.setScene(house2.getScene());
}
public static void setGruulsLairScene(){
primaryStage.setScene(gruulslair.getScene());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.