answer
stringlengths
17
10.2M
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package com.frc2879.bender; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.Timer; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * 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 SimpleRobot { RobotDrive drivetrain = new RobotDrive(1,2); Joystick joystick = new Joystick(1); public final String name = "Bender Bot"; public final String version = "v1.03"; public final String fullname = name + " " + version; // Defining Joystick Mappings: public final int Button_X = 1; public final int Button_Y = 4; public final int Button_A = 2; public final int Button_B = 3; public final int Button_START = 10; public final int Button_BACK = 9; public final int Button_RIGHT_BUMPER = 6; public final int Button_RIGHT_TRIGGER = 8; public final int Button_LEFT_BUMPER = 5; public final int Button_LEFT_TRIGGER = 7; // Joystick axis(s) public final int Stick_LEFT_Y = 2; public final int Stick_LEFT_X = 1; public final int Stick_RIGHT_X = 4; public final int Stick_RIGHT_Y = 5; // CONFIG VALUES ~~~~~~~~~ int StickSensitivity = 100; boolean SquaredInputs = true; // CONFIG VALUES ~~~~~~~~~ DSOutput dsout; //Called exactly 1 time when the competition starts. protected void robotInit() { dsout = new DSOutput(); dsout.say(1, fullname); saysticksensitivity(); } boolean pbuttonRB = false; boolean pbuttonLB = false; public void saysticksensitivity(){ dsout.clearLine(2); dsout.say(2, "Sensitivity: " + Integer.toString(StickSensitivity)); } /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { drivetrain.setSafetyEnabled(true); while (isOperatorControl() && isEnabled()) { // Update joystick values: double moveL = ((joystick.getRawAxis(Stick_LEFT_Y)) * ((double)(StickSensitivity) / 100)); double spinL = ((joystick.getRawAxis(Stick_LEFT_X)) * ((double)(StickSensitivity) / 100)); //if(buttonpress(pbuttonRB, cbuttonRB, joystick.getRawButton(Button_RIGHT_BUMPER))){ // StickSensitivity = (StickSensitivity) + (10); // saysticksensitivity(); if (joystick.getRawButton(Button_RIGHT_BUMPER)) pbuttonRB = true; else if(pbuttonRB && !joystick.getRawButton(Button_RIGHT_BUMPER)){ StickSensitivity = (StickSensitivity) + (10); saysticksensitivity(); pbuttonRB = false; } if (joystick.getRawButton(Button_LEFT_BUMPER)) pbuttonLB = true; else if(pbuttonLB && !joystick.getRawButton(Button_LEFT_BUMPER)){ StickSensitivity = (StickSensitivity) - (10); saysticksensitivity(); pbuttonLB = false; } // Drive da robot: drivetrain.arcadeDrive(moveL, spinL, SquaredInputs); Timer.delay(0.01); } } /** * This function is called once each time the robot enters test mode. */ public void test() { } }
package client; public class Phrase implements DataItem { /** * @see #setPhrase */ private String phrase = ""; /** * @see #setRequirement */ private RequiredInput requirement = null; public boolean isLegal() { assert phrase != null; return !phrase.isEmpty() && (requirement != null); } /** * @return prase property. * @see #setPhrase */ public String getPhrase() { assert phrase != null; return phrase; } public Phrase setPhrase(String phrase) { if (phrase == null) throw new IllegalArgumentException("phrase: null"); if (phrase.isEmpty()) throw new IllegalArgumentException("phrase: empty"); this.phrase = phrase; return this; } @Override // from DataItem public RequiredInput getRequirement() { assert requirement != null; return requirement; } public Phrase setRequirement(RequiredInput requirement) { if (requirement == null) throw new IllegalArgumentException("requirement: null"); this.requirement = requirement; return this; } }
package com.haxademic.core.app; import com.haxademic.core.data.store.AppStore; import com.haxademic.core.file.FileUtil; import com.jogamp.opengl.GL; import processing.core.PApplet; import processing.core.PImage; public class P extends PApplet { // static app object refs public static PAppletHax p; public static GL gl; public static AppStore store; // helper methods public static PImage getImage(String file) { return P.p.loadImage(FileUtil.getFile(file)); } }
package com.logaritmos; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Rectangle implements Serializable { private static final long serialVersionUID = 5L; private int left; private int right; private int top; private int bottom; public Rectangle(int l,int r, int t, int b){ this.setXaxis(l,r); this.setYaxis(t,b); } // corrige los valores de un rectangulo en cada eje en caso de estar desordenados public static void rectify(Rectangle rect) { rect.setXaxis(rect.left, rect.right); rect.setYaxis(rect.bottom, rect.top); } private void setXaxis(int a, int b){ //el eje crece de izquierda a derecha this.left = min(a,b); this.right = max(a,b); } private void setYaxis(int a, int b){ //el eje Y crece de abajo hacia arriba this.top = max(a,b); this.bottom = min(a,b); } // getters public int getTop() { return this.top; } public int getBottom() { return this.bottom; } public int getLeft() { return this.left; } public int getRight() { return this.right; } public int getHeight() { return abs(this.top - this.bottom); } public int getWidth() { return abs(this.right - this.left); } public double area() { return (double) this.getHeight()*this.getWidth(); } public double deltaArea(Rectangle rect1, Rectangle rect2) { return abs(rect1.area() - rect2.area()); } public boolean intersects(Rectangle aRectangle) { Rectangle minorY; Rectangle majorY; if (this.bottom <= aRectangle.bottom) { minorY = this; majorY = aRectangle; } else { minorY = aRectangle; majorY = this; } return minorY.left <= majorY.left && minorY.right >= majorY.right && minorY.top >= majorY.bottom || minorY.left <= majorY.left && minorY.left <= majorY.right && majorY.top <= majorY.bottom; } public double intersectArea(Rectangle r) { if (!this.intersects(r)) {return 0;} double dx = 0; double dy = 0; if(this.right >= r.left) { if(r.left >= this.left) { dx = min(r.right, this.right) - r.left; } else { if (r.right >= this.right) { dx = this.right - this.left; } else { dx = this.left - r.right; } } } if(this.top >= r.bottom) { if(r.bottom >= this.bottom) { dy = min(this.bottom, r.top); } else { if(r.top >= this.top) { dy = this.top - this.bottom; } else { dy = this.bottom - r.top; } } } return dx*dy; } public static double overlapSum(Rectangle r, ArrayList<Rectangle> rects) { double result = 0; for (Rectangle rec : rects) { result += r.intersectArea(rec); } return result; } public boolean overlaps(Rectangle aRectangle) { return (this.inVertical(aRectangle) && this.inHorizontal(aRectangle)); } private boolean inVertical(Rectangle aRectangle){ return (this.inTop(aRectangle.top) || this.inBottom(aRectangle.bottom)); } private boolean inHorizontal(Rectangle aRectangle){ return (this.inLeft(aRectangle.left) || this.inRight(aRectangle.right)); } private boolean contains(int number, int min ,int max){ return number>=min && number<=max; } private boolean inTop(int aTop){ return contains(aTop,this.bottom,this.top); } private boolean inBottom(int aBottom){ return contains(aBottom,this.bottom,this.top); } private boolean inLeft(int aLeft){ return contains(aLeft,this.left,this.right); } private boolean inRight(int aRight){ return contains(aRight,this.left,this.right); } public void multiMax(int i, int i1, int i2, int i3) { } }
package com.spatialfocus; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.net.MalformedURLException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.h2.tools.Csv; import org.h2.util.DateTimeUtils; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.AttributeDescriptor; import org.opengis.feature.type.AttributeType; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.geotools.*; import org.geotools.coverage.processing.operation.Log; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.shapefile.shp.JTSUtilities; import org.geotools.data.shapefile.shp.ShapeType; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import com.vividsolutions.jts.geom.Geometry; public class Geodata { static Connection dbconn = null; String work_dir = "projects"; String proj_name = null; String sproj_name = null; String operationMode = ""; String evt_xml = "address_pkg.xml"; String evt_met = "address_met.xml"; String evt_rpt = "address_rpt.txt"; String AddressData, AbbrvData, AddrFldMap, SubAddrFldMap, PlaceFldMap, AliasData, ExpertParsingData; String QATests, Transforms; public Geodata(String longName, String shortName) throws Exception { // Get some default names proj_name = longName; sproj_name = shortName; // Load the user settings getParams(); } public void getParams() throws Exception { boolean paramsOk = true; String e = "\n\n"; java.util.Properties configFile = new java.util.Properties(); InputStream pf = this.getClass().getClassLoader().getResourceAsStream("AddressTool.properties"); if ( pf != null ) { configFile.load(pf); operationMode = configFile.getProperty("OperationMode"); work_dir = configFile.getProperty("work_dir"); proj_name = configFile.getProperty("ProjectName"); sproj_name = configFile.getProperty("ShortName"); AddressData = configFile.getProperty("AddressData"); AbbrvData = configFile.getProperty("AbbreviationsFile"); AddrFldMap = configFile.getProperty("AddressFieldMap"); PlaceFldMap = configFile.getProperty("PlaceFieldMap"); SubAddrFldMap = configFile.getProperty("SubAddressFieldMap"); AliasData = configFile.getProperty("AliasData"); ExpertParsingData = configFile.getProperty("ExpertParsingData"); QATests = configFile.getProperty("QATests"); Transforms = configFile.getProperty("Transforms"); File f = new File(AliasData); if ( ! f.exists()) { e = e.concat("Address Alias Data "+ AliasData + " not found \n"); paramsOk = false; } f = new File(AbbrvData); if ( ! f.exists()) { e = e.concat("Abbreviations Data "+ AbbrvData + " not found \n"); paramsOk = false; } f = new File(AddrFldMap); if ( ! f.exists()) { e = e.concat("Address Field Mapping Data "+ AddrFldMap + " not found \n"); paramsOk = false; } f = new File(SubAddrFldMap); if ( ! f.exists()) { e = e.concat("Occupancy Field Mapping Data "+ SubAddrFldMap + " not found \n"); paramsOk = false; } f = new File(PlaceFldMap); if ( ! f.exists()) { e = e.concat("PlaceName Field Mapping Data "+ PlaceFldMap + " not found \n"); paramsOk = false; } } else { AbbrvData = "resources/sql/common_abbr.csv"; AddrFldMap = "resources/sql/mapaddress.csv"; SubAddrFldMap = "resources/sql/mapsubaddress.csv"; AliasData = "resources/sql/common_alias.csv"; ExpertParsingData = null; } File f = new File(AddressData); if (! f.exists()) { e.concat("Address Data "+ AddressData + " not found \n"); paramsOk = false; } if (! operationMode.equals("publish") ) { e.concat("Operational Mode "+ operationMode + " not supported\n"); paramsOk = false; } if (! paramsOk ) { throw new FileNotFoundException(e + "\n" + " Exiting"); } evt_xml = sproj_name + "_pkg.xml"; evt_met = sproj_name + "_met.xml"; evt_rpt = sproj_name + "_rpt.txt"; } public int Init() throws SQLException, Exception { int needInit = 1; File f = new File(work_dir + "/" + sproj_name + ".h2.db"); if ( f.exists()) { needInit = 1; f.delete(); f = new File(work_dir + "/" + sproj_name + ".h2.db"); } if ( dbconn == null || ! dbconn.isValid(500) ) { Class.forName("org.h2.Driver"); dbconn = DriverManager.getConnection("jdbc:h2:" + work_dir + "/" + sproj_name, "sa", ""); if (needInit == 1) { createSupportTables(); } } return 1; } public int createSupportTables() throws Exception { Statement stmt2 = dbconn.createStatement(); File f = new File("resources/sql/support_tables.sql"); if ( ! f.exists() ) { System.out.println("required table templates not found"); return 0; } StringBuilder sqlText = new StringBuilder(); String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(f)); try { while (scanner.hasNextLine()){ sqlText.append(scanner.nextLine() + NL); } } finally{ scanner.close(); } stmt2.execute(sqlText.toString()); stmt2.execute("INSERT INTO project_log (log) values('Address Tool - 0.0.4')"); stmt2.execute("INSERT INTO project_log (log) values('Project - " + proj_name + "')"); stmt2.execute("INSERT INTO project_log (log) values('Short Name - " + sproj_name + "')"); return 1; } public int applyAbbr(String tbl) throws Exception { Statement stmt = dbconn.createStatement(); String s = ""; String[] aas = new String("PostAbbrev PreAbbrev").split(" "); for(int i =0; i < aas.length ; i++) { s = ""; File af = new File("resources/sql/transforms/" + aas[i] + ".sql"); if ( af.exists() ) { try { BufferedReader in = new BufferedReader(new FileReader(af)); String str; while ((str = in.readLine()) != null) { s = s.concat(str + "\n"); } in.close(); } catch (IOException e) { } s = s.replace("%tablename%", tbl); stmt.execute(s); } } return 1; } public int applyTransforms(String tbl) throws Exception { Statement stmt = dbconn.createStatement(); String s = ""; String[] tas = Transforms.split(" "); for(int i =0; i < tas.length ; i++) { s = ""; File tf = new File("resources/sql/transforms/" + tas[i] + ".sql"); if ( tf.exists() ) { try { BufferedReader in = new BufferedReader(new FileReader(tf)); String str; while ((str = in.readLine()) != null) { s = s.concat(str + "\n"); } in.close(); } catch (IOException e) { } s = s.replace("%tablename%", tbl); stmt.execute(s); } } return 1; } public int runQA() throws Exception { Statement stmt = dbconn.createStatement(); String s = ""; String[] qas = QATests.split(" "); File qar = new File(work_dir + "/" + evt_rpt); FileWriter qafw = new FileWriter(qar); for(int i =0; i < qas.length ; i++) { s = ""; File qf = new File("resources/sql/qa/" + qas[i] + ".sql"); if ( qf.exists() ) { try { BufferedReader in = new BufferedReader(new FileReader(qf)); String str; while ((str = in.readLine()) != null) { s = s.concat(str + "\n"); } in.close(); } catch (IOException e) { } String resv = ""; ResultSet rsm = stmt.executeQuery(s); if ( rsm.next() ) { resv = rsm.getObject(1).toString(); } System.out.println("QA Test " + qas[i] + " returned: " + resv); qafw.write("QA Test " + qas[i] + " returned: " + resv); } } if ( qafw != null) { qafw.flush(); qafw.close(); } return 1; } public static Integer h2_stmt(String smt) throws Exception { if ( dbconn.createStatement().execute(smt) ) return 0; // return a failure code return 1; } public static SimpleFeatureSource readGIS(String shpFilepath) throws Exception { SimpleFeatureSource featureSource = null; File shpFile = new File(shpFilepath); try { if((! shpFile.exists()) && (! shpFile.isFile())) { String message = "file is not found"; // throw new FileNotFoundException(message); // the geometry field is not strictly required } Map<String, Serializable> connect = new HashMap<String, Serializable>(); connect.put("url", shpFile.toURI().toURL()); connect.put("charset", "Windows-1252"); DataStore dataStore = DataStoreFinder.getDataStore(connect); String[] typeNames = dataStore.getTypeNames(); String typeName = typeNames[0]; featureSource = dataStore.getFeatureSource(typeName); } catch (FileNotFoundException e) { System.out.println(e.getLocalizedMessage()); e.printStackTrace(); } catch (MalformedURLException e) { System.out.println(e.getLocalizedMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); e.printStackTrace(); } finally { shpFile = null; } return featureSource; } public void importGIS(String shpFilePath) throws Exception { int warningCount = 0; String swkt = null; SimpleFeatureSource featureSource = readGIS(shpFilePath); SimpleFeatureCollection collection = featureSource.getFeatures(); SimpleFeatureIterator iterator = collection.features(); String val; String nam; String sep = ""; FileWriter tw = new FileWriter("tmp/workread.csv"); PrintWriter pw = new PrintWriter(tw); SimpleFeatureType fT = collection.getSchema(); List<AttributeDescriptor> fTS = fT.getAttributeDescriptors(); Iterator<AttributeDescriptor> fTi = fTS.iterator(); while (fTi.hasNext()){ AttributeDescriptor Tn = fTi.next(); Tn.getLocalName(); pw.print(sep + Tn.getLocalName()); sep = "\t"; } pw.println(""); iterator = collection.features(); while (iterator.hasNext()) { SimpleFeature feature = (SimpleFeature) iterator.next(); Geometry geometry = (Geometry) feature.getDefaultGeometry(); ShapeType type = JTSUtilities.findBestGeometryType(geometry); if(! type.isPolygonType() && ! type.isLineType() && !type.isPointType()) { System.out.println("The file contains unexpected geometry types"); warningCount++; break; } if(geometry.isEmpty()) { swkt = ""; } else { swkt = geometry.toText(); } Collection<Property> props = feature.getProperties(); Iterator<Property> it = props.iterator(); sep = ""; while(it.hasNext()) { Property prop = it.next(); if (prop.getValue() != null) { val = prop.getValue().toString(); } else { val = ""; } pw.print(sep + val); sep = "\t"; } pw.println(""); } pw.close(); tw.close(); h2_import("rawdata", "tmp/workread.csv"); File f = new File("tmp/workread.csv"); f.deleteOnExit(); Statement stmt = dbconn.createStatement(); stmt.execute("INSERT INTO table_info( id,name,role,status) values (0,'RAWDATA','address','R')"); } public static int h2_import(String ctable, String cfile) throws Exception { h2_stmt("Drop TABLE if Exists " + ctable + ";"); h2_stmt("CREATE TABLE " + ctable + " as (SELECT * FROM CSVREAD('" + cfile + "', null, 'fieldSeparator=' || CHAR(9)));"); return 1; } public int LoadMaps(String tbl) throws Exception { Statement stmt = dbconn.createStatement(); Scanner scanner; File f = new File("resources/sql/address_table_tmpl.sql"); if ( ! f.exists() ) { BufferedReader fin = new BufferedReader( new InputStreamReader( this.getClass().getClassLoader().getResourceAsStream( "resources/sql/address_table_tmpl.sql"))); scanner = new Scanner(new FileInputStream(f)); } else { scanner = new Scanner(new FileInputStream(f)); } StringBuilder sqlText = new StringBuilder(); String NL = System.getProperty("line.separator"); String s = null; try { while (scanner.hasNextLine()){ sqlText.append(scanner.nextLine() + NL); } } finally{ scanner.close(); } s = sqlText.toString().replaceAll("%tablename%",tbl ); stmt.execute(s); stmt.execute("INSERT INTO table_info( id,name,role,status) values (1,'"+ tbl + "_core" + "','address','I')"); stmt.execute("INSERT INTO table_info( id,name,role,status) values (1,'"+ tbl + "_prelim" + "','address','I')"); h2_import("abbrmap", AbbrvData); h2_import("addressmap", AddrFldMap); h2_import("subaddressmap", SubAddrFldMap); h2_import("aliasmap", AliasData); h2_import("placemap", PlaceFldMap); h2_import("expertparsing", ExpertParsingData); return 1; } public int MapRawFlds (String tbl) throws Exception { Statement stmt = dbconn.createStatement(); Statement stmt2 = dbconn.createStatement(); String s; //Build a SQL string to populate the intermediate format table String si = ""; String sr = ""; String sep = ""; String sra = "ADDRESSID"; ResultSet rs = stmt.executeQuery("Select * from addressmap where tableid = " + "(SELECT id from table_info where name = '" + tbl + "_prelim')"); while ( rs.next() ) { si = si + sep + rs.getObject("MAP"); sr = sr + sep + rs.getObject("RAW"); if (rs.getObject("MAP").toString().equals("ADDRESSID") ) { sra = rs.getObject("RAW").toString(); } sep = " ,"; } s = "INSERT INTO " + tbl + "_prelim" + "(" + si + " )" + "(SELECT " + sr + " FROM RawData )"; stmt.execute(s); // Now Subaddress elements rs = stmt.executeQuery("Select * from subaddressmap where tableid = " + "(SELECT id from table_info where name = '" + tbl + "_core')"); sep = ","; while ( rs.next() ) { si = "ADDRESSID" + sep + rs.getObject("MAP") + ",subaddresstype "; sr = sra + sep + rs.getObject("RAW") + ",'" + rs.getObject("RAW") + "'"; s = "INSERT INTO " + tbl + "_subaddress" + "(" + si + " )" + "(SELECT " + sr + " FROM RawData )"; stmt2.execute(s); } stmt.execute("INSERT INTO " + tbl + "_core (SELECT * from " + tbl + "_prelim )" ); return 1; } public Document writeXMLHdr(Map<String, Object> row) throws Exception { Document doc = null; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements doc = docBuilder.newDocument(); Element rootElement = doc.createElement("AddressCollection"); doc.appendChild(rootElement); Attr attr = doc.createAttribute("version"); attr.setValue("0.4"); rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:addr"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:addr_type"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:gml"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:smil20"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:smil20lang"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:xlink"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:xml"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xmlns:xsi"); attr.setValue("http: rootElement.setAttributeNode(attr); attr = doc.createAttribute("xsi:schemaLocation"); attr.setValue("http: rootElement.setAttributeNode(attr); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } return doc; }; public Document writeXMLRow(Document doc, Map<String, Object> row, Map<String, Object> rowplc, Map<String, Object> rowocc, Map<String, Object> rowalias ) { Object s = null; try { Element rootElement = doc.getDocumentElement(); // incident elements Element address = doc.createElement("NumberedThoroughfareAddress"); rootElement.appendChild(address); Element can, cac; Attr attr; can = doc.createElement("CompleteAddressNumber"); s = row.get("addressnumberprefix"); if ( s != null ) { cac = doc.createElement("AddressNumberPrefix"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("addressnumber"); if ( s != null ) { cac = doc.createElement("AddressNumber"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("addressnumbersuffix"); if ( s != null ) { cac = doc.createElement("AddressNumberSuffix"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } address.appendChild(can); can = doc.createElement("CompleteStreetName"); s = row.get("StreetNamePreModifier"); if ( s != null ) { cac = doc.createElement("StreetNamePreModifier"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("streetnamepredirectional"); if ( s != null ) { cac = doc.createElement("StreetNamePreDirectional"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("streetnamepretype"); if ( s != null ) { cac = doc.createElement("StreetNamePreType"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("streetname"); if ( s != null ) { cac = doc.createElement("StreetName"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("streetnameposttype"); if ( s != null ) { cac = doc.createElement("StreetNamePostype"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("streetnamepostdirectional"); if ( s != null ) { cac = doc.createElement("StreetNamePostDirectional"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } s = row.get("streetnamepostmodifier"); if ( s != null ) { cac = doc.createElement("StreetNamePostModifier"); cac.appendChild(doc.createTextNode(s.toString())); can.appendChild(cac); } address.appendChild(can); can = doc.createElement("CompleteSubaddress"); s = row.get("addressid"); if ( s != null ) { cac = doc.createElement("SubaddressElement"); cac.appendChild(doc.createTextNode(s.toString())); } s = row.get("subaddresstype"); if ( s != null ) { cac = doc.createElement("SubaddressType"); cac.appendChild(doc.createTextNode(s.toString())); } address.appendChild(can); if ( row.get("PlaceStateZip") != null ) { can = doc.createElement("PlaceStateZip"); can.appendChild(doc.createTextNode(s.toString())); s = row.get("PlaceStateZip"); if ( s != null ) { can.appendChild(doc.createTextNode(s.toString())); } } else { can = doc.createElement("CompletePlaceName"); s = rowplc.get("CommunityName"); if ( s != null ) { cac = doc.createElement("PlaceName"); cac.appendChild(doc.createTextNode(s.toString())); attr = doc.createAttribute("PlaceNameType"); attr.setValue("USPSCommunity"); cac.setAttributeNode(attr); } s = rowplc.get("CityName"); if ( s != null ) { cac = doc.createElement("PlaceName"); cac.appendChild(doc.createTextNode(s.toString())); attr = doc.createAttribute("PlaceNameType"); attr.setValue("MunicipalJurisdiction"); cac.setAttributeNode(attr); } s = rowplc.get("County"); if ( s != null ) { cac = doc.createElement("PlaceName"); cac.appendChild(doc.createTextNode(s.toString())); attr = doc.createAttribute("PlaceNameType"); attr.setValue("County"); cac.setAttributeNode(attr); } s = row.get("statename"); if ( s != null ) { cac = doc.createElement("StateName"); cac.appendChild(doc.createTextNode(s.toString())); } s = row.get("zipcode"); if ( s != null ) { cac = doc.createElement("ZipCode"); cac.appendChild(doc.createTextNode(s.toString())); } s = row.get("zipplus4"); if ( s != null ) { cac = doc.createElement("ZipPlus4"); cac.appendChild(doc.createTextNode(s.toString())); } s = row.get("countryname"); if ( s != null ) { cac = doc.createElement("CountryName"); cac.appendChild(doc.createTextNode(s.toString())); } } address.appendChild(can); s = row.get("addressid"); if ( s != null ) { can = doc.createElement("AddressId"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressauthority"); if ( s != null ) { can = doc.createElement("AddressAuthority"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressauthority"); if ( s != null ) { can = doc.createElement("AddressAuthority"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = rowalias.get("relatedaddress1"); if ( s != null ) { can = doc.createElement("RelatedAddressID"); can.appendChild(doc.createTextNode(s.toString())); attr = doc.createAttribute("RelatedAddressType"); attr.setValue(rowalias.get("relationrole1").toString()); can.setAttributeNode(attr); address.appendChild(can); } s = rowalias.get("relatedaddress2"); if ( s != null ) { can = doc.createElement("RelatedAddressID"); can.appendChild(doc.createTextNode(s.toString())); attr = doc.createAttribute("RelatedAddressType"); attr.setValue(rowalias.get("relationrole2").toString()); can.setAttributeNode(attr); address.appendChild(can); } s = row.get("addressxcoordinate"); if ( s != null ) { can = doc.createElement("AddressXCoordinate"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressycoordinate"); if ( s != null ) { can = doc.createElement("AddressYCoordinate"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresslonigtude"); if ( s != null ) { can = doc.createElement("AddressLongitude"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresslatitude"); if ( s != null ) { can = doc.createElement("AddressLatitude"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("usnationalgridcoordinate"); if ( s != null ) { can = doc.createElement("USNationalGridCoordinate"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresselevation"); if ( s != null ) { can = doc.createElement("AddressElevation"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresscoordinatreferencesystem"); if ( s != null ) { can = doc.createElement("AddressCoordinateReferenceSystem"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressparcelidentifiersource"); if ( s != null ) { can = doc.createElement("AddressParcelIdentifierSource"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressparcelidentifier"); if ( s != null ) { can = doc.createElement("AddressParcelIdentifier"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresstransportationsystemname"); if ( s != null ) { can = doc.createElement("AddressTransportationSystemName"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresstransportationsystemauthority"); if ( s != null ) { can = doc.createElement("AddressTransportationSystemAuthority"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresstransportationfeaturetype"); if ( s != null ) { can = doc.createElement("AddressTransportationFeatureType"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresstransportationfeatureid"); if ( s != null ) { can = doc.createElement("AddressTransportationFeatureId"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("relatedaddresstransportationfeatureid"); if ( s != null ) { can = doc.createElement("RelatedAddressTransportationFeatureId"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressclassification"); if ( s != null ) { can = doc.createElement("AddressClassification"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressfeaturetype"); if ( s != null ) { can = doc.createElement("AddressFeatureType"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresslifecyclestatus"); if ( s != null ) { can = doc.createElement("AddressLifecycleStatus"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("officialstatus"); if ( s != null ) { can = doc.createElement("OfficialStatus"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressanomalystatus"); if ( s != null ) { can = doc.createElement("AddressAnomalyStatus"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresssideofstreet"); if ( s != null ) { can = doc.createElement("AddressSideofStreet"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addresszlevel"); if ( s != null ) { can = doc.createElement("AddressZLevel"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressfeaturetype"); if ( s != null ) { can = doc.createElement("AddressFeatureType"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("locationdescription"); if ( s != null ) { can = doc.createElement("LocationDescription"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressfeaturetype"); if ( s != null ) { can = doc.createElement("AddressFeatureType"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("mailableaddress"); if ( s != null ) { can = doc.createElement("MailableAddress"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressstartdate"); if ( s != null ) { can = doc.createElement("AddressStartDate"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressenddate"); if ( s != null ) { can = doc.createElement("AddressEndDate"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("datasetid"); if ( s != null ) { can = doc.createElement("DatasetId"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressreferencesystemid"); if ( s != null ) { can = doc.createElement("AddressReferenceSystemId"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } s = row.get("addressreferencesystemauthority"); if ( s != null ) { can = doc.createElement("AddressReferenceSystemAuthority"); can.appendChild(doc.createTextNode(s.toString())); address.appendChild(can); } } finally { } return doc; } public int writeXMLFtr(Document doc) throws Exception { try { // write the content into xml file TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(work_dir + "/" + evt_xml)); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("Local copy of xml file saved"); } catch (TransformerException tfe) { tfe.printStackTrace(); } return 1; } public Document export_address(Document doc) throws Exception { Statement stmt = dbconn.createStatement(); Statement stmt2 = dbconn.createStatement(); String sql = ""; ResultSet srs = stmt.executeQuery("SELECT * from address_core"); ResultSetMetaData rsm = srs.getMetaData(); // Start Feed Map<String, Object> row = new HashMap<String, Object >(); Map<String, Object> rowplc = new HashMap<String, Object >(); Map<String, Object> rowocc = new HashMap<String, Object >(); Map<String, Object> rowalias = new HashMap<String, Object >(); while ( srs.next() ) { row.clear(); for ( int i = 1; i <= rsm.getColumnCount(); i++ ) { row.put(rsm.getColumnName(i).toLowerCase(), srs.getObject(i) ); } if ( srs.isFirst() ) doc = writeXMLHdr(row); doc = writeXMLRow(doc, row, rowplc, rowocc, rowalias); } writeXMLFtr(doc); srs = stmt.executeQuery("SELECT count(*) from address_core"); srs.first(); String recs; if ( srs.isFirst() ) { recs = srs.getObject(1).toString(); /* log the export */ boolean srs2 = stmt2.execute("INSERT INTO publication_info (pub_records) values " + "(" + recs + ")"); } return doc; } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Geodata g = new Geodata("AddressDB", "Addressdb"); try { g.Init(); g.importGIS("data/Export_Output.shp"); g.LoadMaps("address"); g.MapRawFlds("address"); g.applyAbbr("address"); g.applyTransforms("address"); g.runQA(); Document doc = null; g.export_address(doc); System.out.println("Complete"); } catch (SQLException e) { System.out.print(e.getMessage()); e.printStackTrace(); } catch (Exception e) { System.out.print(e.getMessage()); e.printStackTrace(); } }; }
package com.vmware.vim25.mo; import java.rmi.RemoteException; import com.vmware.vim25.InvalidProperty; import com.vmware.vim25.InvalidState; import com.vmware.vim25.LocalizedMethodFault; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.MethodFault; import com.vmware.vim25.OutOfBounds; import com.vmware.vim25.RuntimeFault; import com.vmware.vim25.TaskInfo; import com.vmware.vim25.TaskInfoState; /** * The managed object class corresponding to the one defined in VI SDK API reference. * @author Steve JIN (sjin@vmware.com) */ public class Task extends ExtensibleManagedObject { public static final String PROPNAME_INFO = "info"; public static final String SUCCESS = "success"; public Task(ServerConnection serverConnection, ManagedObjectReference mor) { super(serverConnection, mor); } public TaskInfo getTaskInfo() throws InvalidProperty, RuntimeFault, RemoteException { return (TaskInfo) getCurrentProperty(PROPNAME_INFO); } public ManagedEntity getAssociatedManagedEntity() { return (ManagedEntity) getManagedObject("info.entity"); } public ManagedEntity[] getLockedManagedEntities() { return (ManagedEntity[]) getManagedObjects("info.locked"); } public void cancelTask() throws RuntimeFault, RemoteException { getVimService().cancelTask(getMOR()); } public void setTaskState(TaskInfoState tis, Object result, LocalizedMethodFault fault) throws InvalidState, RuntimeFault, RemoteException { getVimService().setTaskState(getMOR(), tis, result, fault); } public void updateProgress(int percentDone) throws InvalidState, OutOfBounds, RuntimeFault, RemoteException { getVimService().updateProgress(getMOR(), percentDone); } public String waitForMe() throws InvalidProperty, RuntimeFault, RemoteException { Object[] result = waitForValues( new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { TaskInfoState.success, TaskInfoState.error } }); if (result[0].equals(TaskInfoState.success)) { return SUCCESS; } else { TaskInfo tinfo = (TaskInfo) getCurrentProperty(PROPNAME_INFO); LocalizedMethodFault fault = tinfo.getError(); String error = "Error Occured"; if(fault!=null) { MethodFault mf = fault.getFault(); mf.printStackTrace(); error = mf.getMessage(); } return error; } } }
package stats; import java.text.DecimalFormat; import share.LogWriter; import share.DescEntry; import java.util.Hashtable; import java.util.Calendar; import java.util.GregorianCalendar; public class FatDataBaseOutProducer extends DataBaseOutProducer { /** Creates a new instance of APIDataBaseOutProducer */ public FatDataBaseOutProducer(Hashtable param) { super(param); String testBase = (String)mSqlInput.get("TestBase"); int sep = testBase.indexOf('_'); String testLanguage = testBase.substring(0,sep); testBase = testBase.substring(sep+1); String apiVersion = (String)mSqlInput.get("Version"); String descriptionString = testLanguage+":"+(String)mSqlInput.get("OperatingSystem")+":"+testBase+":"+apiVersion; apiVersion = apiVersion.substring(0, 6); // build date if (mSqlInput.get("Date") != null) { mSqlInput.put("date", mSqlInput.get("Date")); } if (mSqlInput.get("date") == null) { // build date if it's not there Calendar cal = new GregorianCalendar(); DecimalFormat dfmt = new DecimalFormat("00"); String year = Integer.toString(cal.get(GregorianCalendar.YEAR)); // month is starting with "0" String month = dfmt.format(cal.get(GregorianCalendar.MONTH) + 1); String day = dfmt.format(cal.get(GregorianCalendar.DATE)); String dateString = year + "-" + month + "-" + day; mSqlInput.put("date", dateString); } setWriteableEntryTypes(new String[]{"property", "method", "component", "interface", "service"}); mSqlInput.put("test_run.description", descriptionString); mSqlInput.put("api_version_name", apiVersion); } protected boolean prepareDataBase(LogWriter log) { executeSQLCommand("SHOW TABLES"); executeSQLCommand("SELECT id AS \"test_run.id\", api_version_id, description, date FROM test_run" + " WHERE date = \"$date\" AND description = \"$test_run.description\";", true); String id = (String)mSqlInput.get("test_run.id"); // create an entry for this test run if (id == null) { executeSQLCommand("SELECT id AS api_version_id FROM api_version" + " WHERE version = \"$api_version_name\";", true); String api_version_id = (String)mSqlInput.get("api_version_id"); // create an entry for this API if (api_version_id == null) { executeSQLCommand("INSERT api_version (api_name, version)" + " VALUES (\"soapi\", \"$api_version_name\")"); executeSQLCommand("SELECT id AS api_version_id FROM api_version" + " WHERE version = \"$api_version_name\";", true); } // complete entry for the test run executeSQLCommand("INSERT test_run (api_version_id, description, date)" + " VALUES ($api_version_id, \"$test_run.description\", \"$date\");"); executeSQLCommand("SELECT test_run.id AS \"test_run.id\", api_version_id, description, date FROM test_run" + " WHERE date = \"$date\" AND description = \"$test_run.description\";", true); } return true; } // check the database afterwards protected boolean checkDataBase(LogWriter log) { return true; } protected boolean insertEntry(LogWriter log) { executeSQLCommand("SELECT id AS \"entry.id\", name AS \"entry.name\" FROM entry WHERE name = \"$EntryLongName\";", true); if (mSqlInput.get("entry.id") == null) { executeSQLCommand("INSERT entry (name, type)" + " VALUES (\"$EntryLongName\", \"$EntryType\");"); executeSQLCommand("SELECT id AS \"entry.id\", name AS \"entry.name\" FROM entry WHERE name = \"$EntryLongName\";", true); } executeSQLCommand("SELECT id AS \"api_entry.id\", api_version_id AS \"api_entry.api_version_id\", entry_id AS \"api_entry.entry_id\" FROM api_entry" + " WHERE entry_id = $entry.id;", true); if (mSqlInput.get("api_entry.id") == null) { executeSQLCommand("INSERT api_entry (entry_id, api_version_id)"+ " VALUES ($entry.id, $api_version_id);"); executeSQLCommand("SELECT id AS \"api_entry.id\", api_version_id AS \"api_entry.api_version_id\", entry_id AS \"api_entry.entry_id\" FROM api_entry" + " WHERE entry_id = $entry.id;", true); } executeSQLCommand("SELECT status AS \"test_state.status\" FROM test_state"+ " WHERE test_run_id = $test_run.id AND entry_id = $entry.id;", true); String status = (String)mSqlInput.get("test_state.status"); if (status == null) { executeSQLCommand("INSERT test_state (test_run_id, entry_id, status)"+ " VALUES ($test_run.id, $entry.id, \"$EntryState\");"); } else { if (!status.endsWith("OK")) { executeSQLCommand("UPDATE test_state SET status = \"$EntryState\""+ " WHERE test_run_id = $test_run.id AND entry_id = $entry.id;"); } } return true; } public Object getWatcher() { return null; } public void setWatcher(Object watcher) { } }
package org.lemurproject.galago.tupleflow.execution; import java.io.IOException; import java.util.List; import junit.framework.TestCase; import org.lemurproject.galago.tupleflow.ExNihiloSource; import org.lemurproject.galago.tupleflow.IncompatibleProcessorException; import org.lemurproject.galago.tupleflow.Linkage; import org.lemurproject.galago.tupleflow.Parameters; import org.lemurproject.galago.tupleflow.Parameters.Type; import org.lemurproject.galago.tupleflow.Processor; import org.lemurproject.galago.tupleflow.Sorter; import org.lemurproject.galago.tupleflow.TupleFlowParameters; import org.lemurproject.galago.tupleflow.TypeReader; import org.lemurproject.galago.tupleflow.types.TupleflowString; /** * Tests the connection of stages (single/distributed) using (combined/each) connections * * [SIMPLE CONNECTIONS single data streams] * 1.1: single-single-combined * 1 --> 2 [Combined] * * 1.2: single-multi-single (each, combined) * 1 --> 2 [Each] no data * 2 --> 3 [Combined] * * 1.3: single-multi-multi-single (each, each, combined) * 1 --> 2 [Each] no data * 2 --> 3 [Each] * 3 --> 4 [Combined] * * * [COMPLEX MULTICONNECTIONS multiple data streams] * 2.1: two connection types incomming (single-multi-combined + single-multi-each) * 1 --> 2 [Combined] no data * 1 --> 3 [Combined] no data * 2 --> 4 [Combined] * 3 --> 4 [Each] * 4 --> 5 [Combined] * * 2.2: two connection types incomming (multi-multi-combined + multi-multi-each) * 1 --> 2 [Combined] nodata * 1 --> 3 [Each] nodata * 2 --> 4 [Combined] * 3 --> 4 [Each] * 4 --> 5 [Combined] * * 2.3: two connection types incomming (multi-multi-combined + multi-multi-each) * 1 --> 2 [Each] nodata * 1 --> 3 [Each] nodata * 2 --> 4 [Combined] * 3 --> 4 [Each] * 4 --> 5 [Combined] * * 2.4: two connections outgoing (multi-single-combined + multi-multi-each) * 1 --> 2 [Combined] nodata * 2 --> 3 [Combined] * 2 --> 4 [Each] * 3 --> 5 [Combined] * 4 --> 5 [Combined] * * 2.5: two connections outgoing (multi-single-combined + multi-multi-each) * 1 --> 2 [Each] nodata * 2 --> 3 [Combined] * 2 --> 4 [Each] * 3 --> 5 [Combined] * 4 --> 5 [Combined] * * @author sjh */ public class ConnectionTest extends TestCase { public ConnectionTest(String name) { super(name); } /* public void testSingleSingleComb() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new Step(Generator.class, Parameters.parse("{\"name\":\"one\", \"conn\":[\"conn-1-2\"]}"))); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); // should recieve 10 items from one two.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":10, \"connIn\" : [\"conn-1-2\"]}"))); job.add(two); job.connect("one", "two", ConnectionAssignmentType.Combined); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } public void testSingleMultiEach() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new Step(NullSource.class)); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); two.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-2-3", new TupleflowString.ValueOrder())); two.add(new Step(Generator.class, Parameters.parse("{\"name\":\"two\", \"conn\":[\"conn-2-3\"]}"))); job.add(two); Stage three = new Stage("three"); three.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-3", new TupleflowString.ValueOrder())); // should recieve 10 items from each instance of two (20 total) three.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":20, \"connIn\" : [\"conn-2-3\"]}"))); job.add(three); job.connect("one", "two", ConnectionAssignmentType.Each); job.connect("two", "three", ConnectionAssignmentType.Combined); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } public void testMultiMultiEach() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new Step(NullSource.class)); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); two.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-2-3", new TupleflowString.ValueOrder())); two.add(new Step(Generator.class, Parameters.parse("{\"name\":\"two\", \"conn\":[\"conn-2-3\"]}"))); job.add(two); Stage three = new Stage("three"); three.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-3", new TupleflowString.ValueOrder())); three.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-3-4", new TupleflowString.ValueOrder())); three.add(new Step(PassThrough.class, Parameters.parse("{\"name\":\"three\", \"connIn\" : [\"conn-2-3\"], \"connOut\" : [\"conn-3-4\"]}"))); job.add(three); Stage four = new Stage("four"); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-3-4", new TupleflowString.ValueOrder())); // should recieve 10 items from each instance of two - they will be passed through three four.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":20, \"connIn\" : [\"conn-3-4\"]}"))); job.add(four); job.connect("one", "two", ConnectionAssignmentType.Each); job.connect("two", "three", ConnectionAssignmentType.Each); job.connect("three", "four", ConnectionAssignmentType.Combined); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } public void testCombinedCombinedIntoMulti() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-3", new TupleflowString.ValueOrder())); one.add(new Step(NullSource.class)); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); two.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-2-4", new TupleflowString.ValueOrder())); two.add(new Step(Generator.class, Parameters.parse("{\"name\":\"two\", \"conn\":[\"conn-2-4\"]}"))); job.add(two); Stage three = new Stage("three"); three.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-3", new TupleflowString.ValueOrder())); three.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-3-4", new TupleflowString.ValueOrder())); three.add(new Step(Generator.class, Parameters.parse("{\"name\":\"three\", \"conn\":[\"conn-3-4\"]}"))); job.add(three); Stage four = new Stage("four"); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-4", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-3-4", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-4-5", new TupleflowString.ValueOrder())); four.add(new Step(Merge.class, Parameters.parse("{\"name\":\"four\", \"connIn\" : [\"conn-2-4\",\"conn-3-4\"], \"connOut\" : \"conn-4-5\"}"))); job.add(four); Stage five = new Stage("five"); five.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-4-5", new TupleflowString.ValueOrder())); // should recieve 10 items two and 10 from three - they will be passed through four five.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":20, \"connIn\" : [\"conn-4-5\"]}"))); job.add(five); job.connect("one", "two", ConnectionAssignmentType.Combined); job.connect("one", "three", ConnectionAssignmentType.Combined); job.connect("two", "four", ConnectionAssignmentType.Combined); job.connect("three", "four", ConnectionAssignmentType.Each); job.connect("four", "five", ConnectionAssignmentType.Combined); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } public void testCombinedMultiIntoMulti() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-3", new TupleflowString.ValueOrder())); one.add(new Step(NullSource.class)); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); two.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-2-4", new TupleflowString.ValueOrder())); two.add(new Step(Generator.class, Parameters.parse("{\"name\":\"two\", \"conn\":[\"conn-2-4\"]}"))); job.add(two); Stage three = new Stage("three"); three.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-3", new TupleflowString.ValueOrder())); three.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-3-4", new TupleflowString.ValueOrder())); three.add(new Step(Generator.class, Parameters.parse("{\"name\":\"three\", \"conn\":[\"conn-3-4\"]}"))); job.add(three); Stage four = new Stage("four"); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-4", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-3-4", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-4-5", new TupleflowString.ValueOrder())); four.add(new Step(Merge.class, Parameters.parse("{\"name\":\"four\", \"connIn\" : [\"conn-2-4\",\"conn-3-4\"], \"connOut\" : \"conn-4-5\"}"))); job.add(four); Stage five = new Stage("five"); five.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-4-5", new TupleflowString.ValueOrder())); // should recieve 10 items two and 10 from each instance of three (20 total) - they will be passed through four five.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":30, \"connIn\" : [\"conn-4-5\"]}"))); job.add(five); job.connect("one", "two", ConnectionAssignmentType.Combined); job.connect("one", "three", ConnectionAssignmentType.Each); job.connect("two", "four", ConnectionAssignmentType.Combined); job.connect("three", "four", ConnectionAssignmentType.Each); job.connect("four", "five", ConnectionAssignmentType.Combined); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } */ public void testMultiMultiIntoMulti() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-3", new TupleflowString.ValueOrder())); one.add(new Step(NullSource.class)); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); two.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-2-4", new TupleflowString.ValueOrder())); two.add(new Step(Generator.class, Parameters.parse("{\"name\":\"two\", \"conn\":[\"conn-2-4\"]}"))); job.add(two); Stage three = new Stage("three"); three.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-3", new TupleflowString.ValueOrder())); three.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-3-4", new TupleflowString.ValueOrder())); three.add(new Step(Generator.class, Parameters.parse("{\"name\":\"three\", \"conn\":[\"conn-3-4\"]}"))); job.add(three); Stage four = new Stage("four"); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-4", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-3-4", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-4-5", new TupleflowString.ValueOrder())); four.add(new Step(Merge.class, Parameters.parse("{\"name\":\"four\", \"connIn\" : [\"conn-2-4\",\"conn-3-4\"], \"connOut\" : \"conn-4-5\"}"))); job.add(four); Stage five = new Stage("five"); five.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-4-5", new TupleflowString.ValueOrder())); // two generates 10 items per instance (20) - all 20 are duplicated for each instance of four - creating 40 total // three generates 10 items per instance (20) - passed through four without duplication // should recieve 60 total five.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":60, \"connIn\" : [\"conn-4-5\"]}"))); job.add(five); job.connect("one", "two", ConnectionAssignmentType.Each); job.connect("one", "three", ConnectionAssignmentType.Each); job.connect("two", "four", ConnectionAssignmentType.Combined); job.connect("three", "four", ConnectionAssignmentType.Each); job.connect("four", "five", ConnectionAssignmentType.Combined); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } /* public void testSingleIntoSingleMulti() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new Step(NullSource.class)); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); two.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-2-x", new TupleflowString.ValueOrder())); two.add(new Step(Generator.class, Parameters.parse("{\"name\":\"two\", \"conn\":[\"conn-2-x\"]}"))); job.add(two); Stage three = new Stage("three"); three.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-x", new TupleflowString.ValueOrder())); three.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-3-5", new TupleflowString.ValueOrder())); three.add(new Step(PassThrough.class, Parameters.parse("{\"name\":\"three\", \"connIn\" : [\"conn-2-x\"], \"connOut\" : [\"conn-3-5\"]}"))); job.add(three); Stage four = new Stage("four"); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-x", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-4-5", new TupleflowString.ValueOrder())); four.add(new Step(PassThrough.class, Parameters.parse("{\"name\":\"four\", \"connIn\" : [\"conn-2-x\"], \"connOut\" : [\"conn-4-5\"]}"))); job.add(four); Stage five = new Stage("five"); five.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-3-5", new TupleflowString.ValueOrder())); five.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-4-5", new TupleflowString.ValueOrder())); // two generates 10 items // items are passed through both three and four - duplicating the items // should recieve 20 total five.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":20, \"connIn\" : [\"conn-3-5\",\"conn-4-5\"]}"))); job.add(five); job.connect("one", "two", ConnectionAssignmentType.Combined); job.connect("two", "three", ConnectionAssignmentType.Combined); job.connect("two", "four", ConnectionAssignmentType.Each); job.connect("three", "five", ConnectionAssignmentType.Combined); job.connect("four", "five", ConnectionAssignmentType.Combined); System.err.println(job.toDotString()); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } public void testMultiIntoSingleMulti() throws Exception { Job job = new Job(); Stage one = new Stage("one"); one.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-1-2", new TupleflowString.ValueOrder())); one.add(new Step(NullSource.class)); job.add(one); Stage two = new Stage("two"); two.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-1-2", new TupleflowString.ValueOrder())); two.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-2-x", new TupleflowString.ValueOrder())); two.add(new Step(Generator.class, Parameters.parse("{\"name\":\"two\", \"conn\":[\"conn-2-x\"]}"))); job.add(two); Stage three = new Stage("three"); three.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-x", new TupleflowString.ValueOrder())); three.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-3-5", new TupleflowString.ValueOrder())); three.add(new Step(PassThrough.class, Parameters.parse("{\"name\":\"three\", \"connIn\" : [\"conn-2-x\"], \"connOut\" : [\"conn-3-5\"]}"))); job.add(three); Stage four = new Stage("four"); four.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-2-x", new TupleflowString.ValueOrder())); four.add(new StageConnectionPoint(ConnectionPointType.Output, "conn-4-5", new TupleflowString.ValueOrder())); four.add(new Step(PassThrough.class, Parameters.parse("{\"name\":\"four\", \"connIn\" : [\"conn-2-x\"], \"connOut\" : [\"conn-4-5\"]}"))); job.add(four); Stage five = new Stage("five"); five.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-3-5", new TupleflowString.ValueOrder())); five.add(new StageConnectionPoint(ConnectionPointType.Input, "conn-4-5", new TupleflowString.ValueOrder())); // two generates 10 items per instance (20) total // items are passed through both three and four - duplicating the items // should recieve 40 total five.add(new Step(Receiver.class, Parameters.parse("{\"expectedCount\":40, \"connIn\" : [\"conn-3-5\",\"conn-4-5\"]}"))); job.add(five); job.connect("one", "two", ConnectionAssignmentType.Each); job.connect("two", "three", ConnectionAssignmentType.Combined); job.connect("two", "four", ConnectionAssignmentType.Each); job.connect("three", "five", ConnectionAssignmentType.Combined); job.connect("four", "five", ConnectionAssignmentType.Combined); System.err.println(job.toDotString()); job.properties.put("hashCount", "2"); ErrorStore err = new ErrorStore(); Verification.verify(job, err); JobExecutor.runLocally(job, err, new Parameters()); if (err.hasStatements()) { throw new RuntimeException(err.toString()); } } */ // Classes used to generate/pass/recieve data public static class NullSource implements ExNihiloSource { @Override public void run() throws IOException { } @Override public void setProcessor(org.lemurproject.galago.tupleflow.Step processor) throws IncompatibleProcessorException { Linkage.link(this, processor); } public static void verify(TupleFlowParameters parameters, ErrorHandler handler) throws IOException { } } public static class Generator implements ExNihiloSource { TupleFlowParameters params; public Generator(TupleFlowParameters params) { this.params = params; } @Override public void run() throws IOException { String name = params.getJSON().getString("name"); String fmt = "(" + name + "-%d)-i%d-(%s)"; for (String conn : (List<String>) params.getJSON().getList("conn")) { try { Processor<TupleflowString> c = params.getTypeWriter(conn); Sorter s = new Sorter(new TupleflowString.ValueOrder()); s.setProcessor(c); for (int i = 0; i < 10; i++) { s.process(new TupleflowString(String.format(fmt, params.getInstanceId(), i, conn))); } s.close(); } catch (IncompatibleProcessorException ex) { throw new RuntimeException("FAILED TO GENERATE DATA FOR CONNECTION:" + conn); } } } @Override public void setProcessor(org.lemurproject.galago.tupleflow.Step processor) throws IncompatibleProcessorException { Linkage.link(this, processor); } public static void verify(TupleFlowParameters parameters, ErrorHandler handler) throws IOException { if (!parameters.getJSON().isString("name")) { handler.addError("Generator - Could not find the name of the stage in parameters"); } if (!parameters.getJSON().isList("conn", Type.STRING)) { handler.addError("Generator - Could not find any connections specified in parameters"); } for (String conn : (List<String>) parameters.getJSON().getList("conn")) { if (!parameters.writerExists(conn, TupleflowString.class.getName(), TupleflowString.ValueOrder.getSpec())) { handler.addError("Generator - Could not verify connection: " + conn); } } } } public static class PassThrough implements ExNihiloSource { TupleFlowParameters params; String suffix; public PassThrough(TupleFlowParameters params) { this.params = params; String name = params.getJSON().getString("name"); suffix = String.format("-(%s-%d)", name, params.getInstanceId()); } @Override public void run() throws IOException { List<String> connIn = (List<String>) params.getJSON().getList("connIn"); List<String> connOut = (List<String>) params.getJSON().getList("connOut"); for (int i = 0; i < connIn.size(); i++) { TypeReader<TupleflowString> reader = params.getTypeReader(connIn.get(i)); Processor<TupleflowString> writer = params.getTypeWriter(connOut.get(i)); TupleflowString obj = reader.read(); while (obj != null) { obj.value += suffix; writer.process(obj); obj = reader.read(); } writer.close(); } } @Override public void setProcessor(org.lemurproject.galago.tupleflow.Step processor) throws IncompatibleProcessorException { Linkage.link(this, processor); } public static void verify(TupleFlowParameters parameters, ErrorHandler handler) throws IOException { if (!parameters.getJSON().isString("name")) { handler.addError("PassThrough - Could not find the name of the stage in parameters"); } if (!parameters.getJSON().isList("connIn", Type.STRING)) { handler.addError("PassThrough - Could not find any Input connections specified in parameters"); } if (!parameters.getJSON().isList("connOut", Type.STRING)) { handler.addError("PassThrough - Could not find any Output connections specified in parameters"); } } } public static class Merge implements ExNihiloSource { TupleFlowParameters params; String suffix; public Merge(TupleFlowParameters params) { this.params = params; String name = params.getJSON().getString("name"); suffix = String.format("-(%s-%d)", name, params.getInstanceId()); } @Override public void run() throws IOException { List<String> connIn = (List<String>) params.getJSON().getList("connIn"); String connOut = params.getJSON().getString("connOut"); Processor<TupleflowString> writer = params.getTypeWriter(connOut); Sorter sorter = new Sorter(new TupleflowString.ValueOrder(), null, writer); for (int i = 0; i < connIn.size(); i++) { TypeReader<TupleflowString> reader = params.getTypeReader(connIn.get(i)); TupleflowString obj = reader.read(); while (obj != null) { obj.value += suffix; sorter.process(obj); obj = reader.read(); } } sorter.close(); } @Override public void setProcessor(org.lemurproject.galago.tupleflow.Step processor) throws IncompatibleProcessorException { Linkage.link(this, processor); } public static void verify(TupleFlowParameters parameters, ErrorHandler handler) throws IOException { if (!parameters.getJSON().isString("name")) { handler.addError("PassThrough - Could not find the name of the stage in parameters"); } if (!parameters.getJSON().isList("connIn", Type.STRING)) { handler.addError("PassThrough - Could not find any Input connections specified in parameters"); } if (!parameters.getJSON().isString("connOut")) { handler.addError("PassThrough - Could not find an Output connection specified in parameters"); } } } public static class Receiver implements ExNihiloSource { TupleFlowParameters params; public Receiver(TupleFlowParameters params) { this.params = params; } @Override public void run() throws IOException { int counter = 0; List<String> connIn = (List<String>) params.getJSON().getList("connIn"); for (int i = 0; i < connIn.size(); i++) { TypeReader<TupleflowString> reader = params.getTypeReader(connIn.get(i)); TupleflowString obj = reader.read(); while (obj != null) { System.err.println("REC - " + params.getInstanceId() + " : " + obj.value); counter++; obj = reader.read(); } } if(counter != params.getJSON().getLong("expectedCount")){ throw new IOException("Did not receive the expected number of items."); } } @Override public void setProcessor(org.lemurproject.galago.tupleflow.Step processor) throws IncompatibleProcessorException { Linkage.link(this, processor); } public static void verify(TupleFlowParameters parameters, ErrorHandler handler) throws IOException { if (!parameters.getJSON().isList("connIn", Type.STRING)) { handler.addError("PassThrough - Could not find any Input connections specified in parameters"); } } } }
package org.eclipse.birt.report.model.api.filterExtension; import java.util.List; import org.eclipse.birt.report.model.api.filterExtension.interfaces.IFilterExprDefinition; /** * OdaFilterExprHelper */ public class OdaFilterExprHelper extends OdaFilterExprHelperImpl { /** * Returns the list of IFilterExprDefinition. The list contains both of ODA * extension provider registered filter definitions, and BIRT predefined * filter definitions. If under OS BIRT, the list will only contain the * IFilterExprDefinition instance which represent the BIRT predefined ones. * *@param odaDatasetExtensionId * oda datasource extension id. *@param odaDataSourceExtensionId * oda dataset extension id. *@param filterType * the filter type * @return List of IFilterExprDefinition instance. */ public static List<IFilterExprDefinition> getMappedFilterExprDefinitions( String dataSetExtId, String dataSourceExtId, int filterType ) { return birtFilterExprDefList; } /** * Return the IFilterExprDefinition instance based on the passed in BIRT * predefined Filter expression name. The returned IFilterExprDefinition * will provide the information that mapped to a corresponding ODA extension * Filter if there is one. For OS BIRT, the returned IFilterExprDefinition * will not have any map information to the ODA extension filters. * * @param birtFilterExprId * the BIRT predefined fitler expression id. * @param datasetExtId * ODA dataset extension id. Null if is for OS BIRT. * @param datasourceExtId * ODA datasource extension id. Null if is for OS BIRT. * @return Instance of IFilterExprDefinition. IFilterExprDefinition instance * based on the passed in filter expression id. */ public static IFilterExprDefinition getFilterExpressionDefn( String birtFilterExprId, String datasetExtId, String datasourceExtId ) { if ( !birtPredefinedFilterConstants.contains( birtFilterExprId ) ) throw new IllegalArgumentException( "The Birt filter expression Id is not valid." ); List feds = birtFilterExprDefList; if ( feds.size( ) > 0 ) { for ( int i = 0; i < feds.size( ); i++ ) { IFilterExprDefinition fed = (IFilterExprDefinition) feds .get( i ); if ( fed.getBirtFilterExprId( ).equals( birtFilterExprId ) ) return fed; } } return new FilterExprDefinition( birtFilterExprId ); } /** * Indicates if support the ODA extension filter expressions. * * @return true if support, false if not. */ public static boolean supportOdaExtensionFilters( ) { return false; } /** * Indicates if the given data source and data set support the ODA extension * Filters. * * @param dataSourceExtId * the extension id of the data source * @param dataSetExtId * the extension id of the data set * @return true if supported, false, if not supported. */ public static boolean supportODAFilterPushDown( String dataSourceExtId, String dataSetExtId ) { return false; } }
package org.nd4j.autodiff.samediff.internal; import lombok.extern.slf4j.Slf4j; import org.nd4j.autodiff.listeners.At; import org.nd4j.autodiff.listeners.Listener; import org.nd4j.autodiff.listeners.Loss; import org.nd4j.autodiff.listeners.Operation; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.autodiff.samediff.TrainingConfig; import org.nd4j.autodiff.samediff.VariableType; import org.nd4j.base.Preconditions; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.api.MultiDataSet; import org.nd4j.linalg.learning.GradientUpdater; import org.nd4j.linalg.learning.regularization.Regularization; import org.nd4j.linalg.primitives.AtomicDouble; import java.util.*; /** * TrainingSession extends InferenceSession, to add training-specific functionality:<br> * - Application of regularization (L1, L2, weight decay etc)<br> * - Inline updating of variables, using updater/optimizer (Adam, Nesterov, SGD, etc)<br> * - Calculation of regularization scores (Score for L1, L2, etc) * * @author Alex Black */ @Slf4j public class TrainingSession extends InferenceSession { protected TrainingConfig config; protected Map<String, String> gradVarToVarMap; protected Map<String, GradientUpdater> updaters; protected Map<String, Integer> lossVarsToLossIdx; protected double[] currIterLoss; protected Map<Class<?>, AtomicDouble> currIterRegLoss; protected List<Listener> listeners; public TrainingSession(SameDiff sameDiff) { super(sameDiff); } /** * Perform one iteration of training - i.e., do forward and backward passes, and update the parameters * * @param config Training configuration * @param placeholders Current placeholders * @param paramsToTrain Set of parameters that will be trained * @param updaters Current updater state * @param batch Current data/batch (mainly for listeners, should have already been converted to placeholders map) * @param lossVariables Loss variables (names) * @param listeners Listeners (if any) * @param at Current epoch, iteration, etc * @return The Loss at the current iteration */ public Loss trainingIteration(TrainingConfig config, Map<String, INDArray> placeholders, Set<String> paramsToTrain, Map<String, GradientUpdater> updaters, MultiDataSet batch, List<String> lossVariables, List<Listener> listeners, At at) { this.config = config; this.updaters = updaters; //Preprocess listeners, get the relevant ones if (listeners == null) { this.listeners = null; } else { List<Listener> filtered = new ArrayList<>(); for (Listener l : listeners) { if (l.isActive(at.operation())) { filtered.add(l); } } this.listeners = filtered.isEmpty() ? null : filtered; } List<String> requiredActivations = new ArrayList<>(); gradVarToVarMap = new HashMap<>(); //Key: gradient variable. Value: variable that the key is gradient for for (String s : paramsToTrain) { Preconditions.checkState(sameDiff.hasVariable(s), "SameDiff instance does not have a variable with name \"%s\"", s); SDVariable v = sameDiff.getVariable(s); Preconditions.checkState(v.getVariableType() == VariableType.VARIABLE, "Can only train VARIABLE type variable - \"%s\" has type %s", s, v.getVariableType()); SDVariable grad = sameDiff.getVariable(s).getGradient(); if (grad == null) { //In some cases, a variable won't actually impact the loss value, and hence won't have a gradient associated with it //For example: floatVar -> cast to integer -> cast to float -> sum -> loss //In this case, the gradient of floatVar isn't defined (due to no floating point connection to the loss) continue; } requiredActivations.add(grad.getVarName()); gradVarToVarMap.put(grad.getVarName(), s); } //Set up losses lossVarsToLossIdx = new LinkedHashMap<>(); List<String> lossVars; currIterLoss = new double[lossVariables.size()]; currIterRegLoss = new HashMap<>(); for (int i = 0; i < lossVariables.size(); i++) { lossVarsToLossIdx.put(lossVariables.get(i), i); } //Do training iteration List<String> outputVars = new ArrayList<>(gradVarToVarMap.keySet()); //TODO this should be empty, and grads calculated in requiredActivations Map<String, INDArray> m = output(outputVars, placeholders, batch, requiredActivations, listeners, at); double[] finalLoss = new double[currIterLoss.length + currIterRegLoss.size()]; System.arraycopy(currIterLoss, 0, finalLoss, 0, currIterLoss.length); if (currIterRegLoss.size() > 0) { lossVars = new ArrayList<>(lossVariables.size() + currIterRegLoss.size()); lossVars.addAll(lossVariables); int s = currIterRegLoss.size(); //Collect regularization losses for (Map.Entry<Class<?>, AtomicDouble> entry : currIterRegLoss.entrySet()) { lossVars.add(entry.getKey().getSimpleName()); finalLoss[s] = entry.getValue().get(); } } else { lossVars = lossVariables; } Loss loss = new Loss(lossVars, finalLoss); if (listeners != null) { for (Listener l : listeners) { if (l.isActive(Operation.TRAINING)) { l.iterationDone(sameDiff, at, batch, loss); } } } return loss; } @Override public INDArray[] getOutputs(SameDiffOp op, FrameIter outputFrameIter, Set<VarId> opInputs, Set<VarId> allIterInputs, Set<String> constAndPhInputs, List<Listener> listeners, At at, MultiDataSet batch, Set<String> allReqVariables) { //Get outputs from InferenceSession INDArray[] out = super.getOutputs(op, outputFrameIter, opInputs, allIterInputs, constAndPhInputs, listeners, at, batch, allReqVariables); List<String> outputs = op.getOutputsOfOp(); int outIdx = 0; for (String s : outputs) { //If this is a loss variable - record it if (lossVarsToLossIdx.containsKey(s)) { int lossIdx = lossVarsToLossIdx.get(s); INDArray arr = out[outIdx]; double l = arr.isScalar() ? arr.getDouble(0) : arr.sumNumber().doubleValue(); currIterLoss[lossIdx] += l; } //If this is a gradient variable - apply the updater and update the parameter array in-line if (gradVarToVarMap.containsKey(s)) { String varName = gradVarToVarMap.get(s); //log.info("Calculated gradient for variable \"{}\": (grad var name: \"{}\")", varName, s); Variable gradVar = sameDiff.getVariables().get(s); if (gradVar.getInputsForOp() != null && gradVar.getInputsForOp().isEmpty()) { //Should be rare, and we should handle this by tracking dependencies, and only update when safe // (i.e., dependency tracking) throw new IllegalStateException("Op depends on gradient variable: " + s + " for variable " + varName); } GradientUpdater u = updaters.get(varName); Preconditions.checkState(u != null, "No updater found for variable \"%s\"", varName); Variable var = sameDiff.getVariables().get(varName); INDArray gradArr = out[outIdx]; INDArray paramArr = var.getVariable().getArr(); //Pre-updater regularization (L1, L2) List<Regularization> r = config.getRegularization(); if (r != null && r.size() > 0) { double lr = config.getUpdater().hasLearningRate() ? config.getUpdater().getLearningRate(at.iteration(), at.epoch()) : 1.0; for (Regularization reg : r) { if (reg.applyStep() == Regularization.ApplyStep.BEFORE_UPDATER) { if (this.listeners != null) { double score = reg.score(paramArr, at.iteration(), at.epoch()); if (!currIterRegLoss.containsKey(reg.getClass())) { currIterRegLoss.put(reg.getClass(), new AtomicDouble()); } currIterRegLoss.get(reg.getClass()).addAndGet(score); } reg.apply(paramArr, gradArr, lr, at.iteration(), at.epoch()); } } } u.applyUpdater(gradArr, at.iteration(), at.epoch()); //Post-apply regularization (weight decay) if (r != null && r.size() > 0) { double lr = config.getUpdater().hasLearningRate() ? config.getUpdater().getLearningRate(at.iteration(), at.epoch()) : 1.0; for (Regularization reg : r) { if (reg.applyStep() == Regularization.ApplyStep.POST_UPDATER) { if (this.listeners != null) { double score = reg.score(paramArr, at.iteration(), at.epoch()); if (!currIterRegLoss.containsKey(reg.getClass())) { currIterRegLoss.put(reg.getClass(), new AtomicDouble()); } currIterRegLoss.get(reg.getClass()).addAndGet(score); } reg.apply(paramArr, gradArr, lr, at.iteration(), at.epoch()); } } } if (listeners != null) { for (Listener l : listeners) { if (l.isActive(at.operation())) l.preUpdate(sameDiff, at, var, gradArr); } } if (config.isMinimize()) { paramArr.subi(gradArr); } else { paramArr.addi(gradArr); } log.trace("Applied updater to gradient and updated variable: {}", varName); } outIdx++; } return out; } }
package org.onebeartoe.modeling.openscad.test.suite.utils; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.onebeartoe.modeling.openscad.test.suite.model.GeneratePngBaselineResults; import org.onebeartoe.modeling.openscad.test.suite.model.RunProfile; import org.onebeartoe.system.OperatingSystem; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This class tests the specification for the PngGenerator class. */ public class PngGeneratorSpecification { private PngGenerator implementation; public static final String simpleOpenScadPath = "src/test/resources/simple.scad"; private RunProfile runProfile; public static final String macOpensacdPath = "/Applications/OpenSCAD-nightly.app/Contents/MacOS/OpenSCAD"; @BeforeClass public void initializeTest() { implementation = new PngGenerator(); runProfile = new RunProfile(); runProfile.executablePath = openscadPath(); List<Path> paths = new ArrayList(); Path path = Paths.get(simpleOpenScadPath); paths.add(path); runProfile.openscadPaths = paths; } @Test public void generatePngs() throws IOException, InterruptedException { boolean forcePngGeneration = true; GeneratePngBaselineResults results = implementation.generatePngs(forcePngGeneration, runProfile); Map<Path, Duration> pathDurations = results.getPathDurations(); int expected = 1; int actual = pathDurations.size(); assertEquals(actual, expected); assertTrue( results.isSuccess() ); } @Test public void generatePngs_fail_badPath() throws IOException, InterruptedException { boolean forcePngGeneration = false; runProfile.openscadPaths.clear(); String fakePath = "face/fake.scad"; runProfile.openscadPaths.add( Paths.get(fakePath) ); GeneratePngBaselineResults results = implementation.generatePngs(forcePngGeneration, runProfile); assertFalse( results.isSuccess() ); } public static String openscadPath() { OperatingSystem os = new OperatingSystem(); String executablePath; if( os.seemsLikeMac() ) { executablePath = macOpensacdPath; } else { executablePath = "openscad-nightly"; } return executablePath; } }
package org.eclipse.mylyn.internal.tasks.core.externalization; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SafeRunner; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.mylyn.commons.core.CoreUtil; import org.eclipse.mylyn.commons.core.StatusHandler; import org.eclipse.mylyn.commons.net.Policy; import org.eclipse.mylyn.internal.tasks.core.ITasksCoreConstants; import org.eclipse.mylyn.internal.tasks.core.externalization.IExternalizationContext.Kind; /** * @author Rob Elves * @since 3.0 */ public class ExternalizationManager { private static final int LAZY_SAVE_DELAY = 1000 * 60; private static final int SAVE_DELAY = 3000; private final ExternalizationJob saveJob; private IStatus loadStatus; private String rootFolderPath; private static volatile boolean saveDisabled = false; private final List<IExternalizationParticipant> externalizationParticipants; private boolean forceSave = false; public ExternalizationManager(String rootFolderPath) { Assert.isNotNull(rootFolderPath); this.externalizationParticipants = new CopyOnWriteArrayList<IExternalizationParticipant>(); this.forceSave = false; this.saveJob = createJob(); setRootFolderPath(rootFolderPath); } private ExternalizationJob createJob() { ExternalizationJob job = new ExternalizationJob("Task List Save Job"); job.setUser(false); job.setSystem(true); return job; } public void addParticipant(IExternalizationParticipant participant) { Assert.isNotNull(participant); externalizationParticipants.add(participant); } public IStatus load() { try { saveDisabled = true; loadStatus = null; List<IStatus> statusList = new ArrayList<IStatus>(); IProgressMonitor monitor = Policy.monitorFor(null); for (IExternalizationParticipant participant : externalizationParticipants) { IStatus status = load(participant, monitor); if (status != null) { statusList.add(status); } } if (statusList.size() > 0) { loadStatus = new MultiStatus(ITasksCoreConstants.ID_PLUGIN, IStatus.ERROR, statusList.toArray(new IStatus[0]), "Failed to load Task List", null); } return loadStatus; } finally { saveDisabled = false; } } private IStatus load(final IExternalizationParticipant participant, final IProgressMonitor monitor) { final IStatus[] result = new IStatus[1]; final ExternalizationContext context = new ExternalizationContext(Kind.LOAD, rootFolderPath); ISchedulingRule rule = participant.getSchedulingRule(); try { Job.getJobManager().beginRule(rule, monitor); SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable e) { if (e instanceof CoreException) { result[0] = ((CoreException) e).getStatus(); } else { result[0] = new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Load participant failed", e); } } public void run() throws Exception { participant.execute(context, monitor); } }); } finally { Job.getJobManager().endRule(rule); } return result[0]; } public void setRootFolderPath(String rootFolderPath) { Assert.isNotNull(rootFolderPath); this.rootFolderPath = rootFolderPath; saveJob.setContext(new ExternalizationContext(Kind.SAVE, rootFolderPath)); } public void requestSave() { if (!saveDisabled) { if (!CoreUtil.TEST_MODE) { saveJob.schedule(SAVE_DELAY); } else { saveJob.run(new NullProgressMonitor()); } } } public void requestLazySave() { if (!saveDisabled) { if (!CoreUtil.TEST_MODE) { saveJob.schedule(LAZY_SAVE_DELAY); } else { saveJob.run(new NullProgressMonitor()); } } } public void stop() { try { // run save job as early as possible saveJob.wakeUp(); saveJob.join(); } catch (InterruptedException e) { StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Task List save on shutdown canceled.", e)); } } public void requestSaveAndWait(boolean force) throws InterruptedException { try { forceSave = force; saveJob.schedule(); saveJob.join(); } finally { forceSave = false; } } public IStatus getLoadStatus() { return loadStatus; } private class ExternalizationJob extends Job { private volatile IExternalizationContext context; public ExternalizationJob(String jobTitle) { super(jobTitle); } public IExternalizationContext getContext() { return context; } public void setContext(IExternalizationContext saveContext) { this.context = saveContext; } @Override protected IStatus run(IProgressMonitor monitor) { IExternalizationContext context = this.context; switch (context.getKind()) { case SAVE: try { monitor.beginTask("Saving...", externalizationParticipants.size()); for (IExternalizationParticipant participant : externalizationParticipants) { ISchedulingRule rule = participant.getSchedulingRule(); if (forceSave || participant.isDirty()) { try { Job.getJobManager().beginRule(rule, monitor); monitor.setTaskName("Saving " + participant.getDescription()); participant.execute(context, new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN)); } catch (CoreException e) { StatusHandler.log(new Status(IStatus.WARNING, ITasksCoreConstants.ID_PLUGIN, "Save failed for " + participant.getDescription(), e)); } finally { Job.getJobManager().endRule(rule); } } monitor.worked(1); } } finally { monitor.done(); } break; default: StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Unsupported externalization kind: " + context.getKind())); } return Status.OK_STATUS; } } private class ExternalizationContext implements IExternalizationContext { private final Kind kind; private final String rootPath; public ExternalizationContext(IExternalizationContext.Kind kind, String rootPath) { this.kind = kind; this.rootPath = rootPath; } public Kind getKind() { return kind; } public String getRootPath() { return rootPath; } } }
package org.codehaus.plexus.component.configurator.converters.special; import org.codehaus.classworlds.ClassRealmAdapter; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; public final class ClassRealmConverter extends AbstractConfigurationConverter { private final ClassRealm realm; public ClassRealmConverter( final ClassRealm realm ) { this.realm = realm; } public boolean canConvert( final Class<?> type ) { return ClassRealm.class.isAssignableFrom( type ) || org.codehaus.classworlds.ClassRealm.class.isAssignableFrom( type ); } @Override public Object fromConfiguration( final ConverterLookup lookup, final PlexusConfiguration configuration, final Class<?> type, final Class<?> contextType, final ClassLoader loader, final ExpressionEvaluator evaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object result = fromExpression( configuration, evaluator, type ); if ( null == result ) { result = realm; } if ( !ClassRealm.class.isAssignableFrom( type ) && result instanceof ClassRealm ) { result = ClassRealmAdapter.getInstance( (ClassRealm) result ); } return result; } }
package org.metaborg.runtime.task.primitives; import org.metaborg.runtime.task.ITaskEngine; import org.metaborg.runtime.task.Task; import org.metaborg.runtime.task.TaskInsertion; import org.metaborg.runtime.task.TaskManager; import org.metaborg.runtime.task.util.InvokeStrategy; import org.metaborg.runtime.task.util.ListBuilder; import org.spoofax.interpreter.core.IContext; import org.spoofax.interpreter.core.InterpreterException; import org.spoofax.interpreter.library.AbstractPrimitive; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; public class task_api_result_combinations_2_1 extends AbstractPrimitive { public static task_api_result_combinations_2_1 instance = new task_api_result_combinations_2_1(); public task_api_result_combinations_2_1() { super("task_api_result_combinations", 2, 1); } @Override public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException { final ITermFactory factory = env.getFactory(); final ITaskEngine taskEngine = TaskManager.getInstance().getCurrent(); final IStrategoTerm term = tvars[0]; final Strategy collect = svars[0]; final Strategy insert = svars[1]; final IStrategoTerm resultIDs = InvokeStrategy.invoke(env, collect, term); // HACK: produce dependencies if any of the results has not been solved yet. IStrategoList dependencies = factory.makeList(); for(IStrategoTerm taskID : resultIDs) { final Task task = taskEngine.getTask(taskID); if(!task.solved()) dependencies = factory.makeListCons(taskID, dependencies); } if(!dependencies.isEmpty()) { env.setCurrent(factory.makeAppl(factory.makeConstructor("Dependency", 1), dependencies)); return true; } final Iterable<IStrategoTerm> combinations = TaskInsertion.instructionCombinations(taskEngine, env, insert, term, resultIDs); if(combinations == null) return false; env.setCurrent(ListBuilder.makeList(factory, combinations)); return true; } }
package org.opentosca.planbuilder.type.plugin.phpapp.handler; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.FileUtils; import org.eclipse.core.runtime.FileLocator; import org.opentosca.planbuilder.model.tosca.AbstractArtifactReference; import org.opentosca.planbuilder.model.tosca.AbstractDeploymentArtifact; import org.opentosca.planbuilder.model.tosca.AbstractImplementationArtifact; import org.opentosca.planbuilder.model.tosca.AbstractInterface; import org.opentosca.planbuilder.model.tosca.AbstractNodeTemplate; import org.opentosca.planbuilder.model.tosca.AbstractNodeTypeImplementation; import org.opentosca.planbuilder.model.tosca.AbstractOperation; import org.opentosca.planbuilder.model.tosca.AbstractParameter; import org.opentosca.planbuilder.plugins.commons.PluginUtils; import org.opentosca.planbuilder.plugins.commons.Properties; import org.opentosca.planbuilder.plugins.context.TemplatePlanContext; import org.opentosca.planbuilder.plugins.context.TemplatePlanContext.Variable; import org.opentosca.planbuilder.provphase.plugin.invoker.Plugin; import org.opentosca.planbuilder.utils.Utils; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class Handler { private Plugin invokerPlugin = new Plugin(); private final static Logger LOG = LoggerFactory.getLogger(Handler.class); private QName zipArtifactType = new QName("http://docs.oasis-open.org/tosca/ns/2011/12/ToscaBaseTypes", "ArchiveArtifact"); private DocumentBuilderFactory docFactory; private DocumentBuilder docBuilder; /** * Constructor * * @throws ParserConfigurationException is thrown when initializing the DOM * Parsers fails */ public Handler() throws ParserConfigurationException { this.docFactory = DocumentBuilderFactory.newInstance(); this.docFactory.setNamespaceAware(true); this.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } /** * Adds BPEL code to the given context which installs/unzips a * PhpApplication unto an Ubuntu OS * * @param templateContext a initialized TemplateContext * @param nodeTypeImpl an AbstractNodeTypeImplementation, maybe null * @return true iff appending all BPEL code was successful */ public boolean handle(TemplatePlanContext templateContext, AbstractNodeTypeImplementation impl) { /* * fetch relevant variables/properties */ if (templateContext.getNodeTemplate() == null) { Handler.LOG.warn("Appending logic to relationshipTemplate plan is not possible by this plugin"); return false; } // fetch server ip of the vm this apache http php module will be // installed on Variable serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP); if (serverIpPropWrapper == null) { serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP, true); if (serverIpPropWrapper == null) { serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP, false); } } if (serverIpPropWrapper == null) { Handler.LOG.warn("No Infrastructure Node available with ServerIp property"); return false; } // find sshUser and sshKey Variable sshUserVariable = templateContext.getPropertyVariable("SSHUser"); if (sshUserVariable == null) { sshUserVariable = templateContext.getPropertyVariable("SSHUser", true); if (sshUserVariable == null) { sshUserVariable = templateContext.getPropertyVariable("SSHUser", false); } } // if the variable is null now -> the property isn't set properly if (sshUserVariable == null) { return false; } else { if (Utils.isVariableValueEmpty(sshUserVariable, templateContext)) { // the property isn't set in the topology template -> we set it // null here so it will be handled as an external parameter sshUserVariable = null; } } Variable sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey"); if (sshKeyVariable == null) { sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey", true); if (sshKeyVariable == null) { sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey", false); } } // if variable null now -> the property isn't set according to schema if (sshKeyVariable == null) { return false; } else { if (Utils.isVariableValueEmpty(sshKeyVariable, templateContext)) { // see sshUserVariable.. sshKeyVariable = null; } } // add sshUser and sshKey to the input message of the build plan, if // needed if (sshUserVariable == null) { LOG.debug("Adding sshUser field to plan input"); templateContext.addStringValueToPlanRequest("sshUser"); } if (sshKeyVariable == null) { LOG.debug("Adding sshKey field to plan input"); templateContext.addStringValueToPlanRequest("sshKey"); } // find the ubuntu node and its nodeTemplateId String templateId = ""; for (AbstractNodeTemplate nodeTemplate : templateContext.getNodeTemplates()) { if (PluginUtils.isSupportedUbuntuVMNodeType(nodeTemplate.getType().getId())) { templateId = nodeTemplate.getId(); } } if (templateId.equals("")) { Handler.LOG.warn("Couldn't determine NodeTemplateId of Ubuntu Node"); return false; } // adds field into plan input message to give the plan it's own address // for the invoker PortType (callback etc.). This is needed as WSO2 BPS // 2.x can't give that at runtime (bug) LOG.debug("Adding plan callback address field to plan input"); templateContext.addStringValueToPlanRequest("planCallbackAddress_invoker"); // add csarEntryPoint to plan input message LOG.debug("Adding csarEntryPoint field to plan input"); templateContext.addStringValueToPlanRequest("csarEntrypoint"); // install unzip // used for the invokerPlugin. This map contains mappings from internal // variables or data which must be fetched form the input message (value // of map == null) Map<String, Variable> installPackageRequestInputParams = new HashMap<String, Variable>(); // generate string variable for "unzip" package. This way it's easier to // program (no assigns by hand, etc.) String unzipPackageVarName = "unzipPackageVar" + templateContext.getIdForNames(); Variable unzipPackageVar = templateContext.createGlobalStringVariable(unzipPackageVarName, "unzip"); /* * methodName: installPackage params: "hostname", "sshKey", "sshUser", * "packageNames" */ installPackageRequestInputParams.put("hostname", serverIpPropWrapper); // sshKey and user maybe null here, if yes the input will be fetched // from the planinput installPackageRequestInputParams.put("sshKey", sshKeyVariable); installPackageRequestInputParams.put("sshUser", sshUserVariable); installPackageRequestInputParams.put("packageNames", unzipPackageVar); this.invokerPlugin.handle(templateContext, templateId, true, "installPackage", "InterfaceUbuntu", "planCallbackAddress_invoker", installPackageRequestInputParams, new HashMap<String, Variable>(), true); List<AbstractArtifactReference> refs = null; if (impl == null) { refs = this.getDeploymentArtifactRefs(templateContext.getNodeTemplate().getDeploymentArtifacts()); } else { Set<AbstractDeploymentArtifact> das = Utils.computeEffectiveDeploymentArtifacts(templateContext.getNodeTemplate(), impl); refs = this.getDeploymentArtifactRefs(das); } // add file upload of DA if (refs.isEmpty()) { Handler.LOG.warn("No usable DA provided for NodeTemplate"); return false; } LOG.debug("Handling DA references:"); for (AbstractArtifactReference ref : refs) { // upload da ref and unzip it this.invokerPlugin.handleArtifactReferenceUpload(ref, templateContext, serverIpPropWrapper, sshUserVariable, sshKeyVariable, templateId); Map<String, Variable> runScriptRequestInputParams = new HashMap<String, Variable>(); runScriptRequestInputParams.put("hostname", serverIpPropWrapper); runScriptRequestInputParams.put("sshKey", sshKeyVariable); runScriptRequestInputParams.put("sshUser", sshUserVariable); String unzipScriptString = "cd /var/www/html && sudo unzip -q -o ~/" + templateContext.getCSARFileName() + "/" + ref.getReference(); String unzipScriptStringVarName = "unzipZipFile" + templateContext.getIdForNames(); Variable unzipScriptStringVar = templateContext.createGlobalStringVariable(unzipScriptStringVarName, unzipScriptString); runScriptRequestInputParams.put("script", unzipScriptStringVar); this.invokerPlugin.handle(templateContext, templateId, true, "runScript", "InterfaceUbuntu", "planCallbackAddress_invoker", runScriptRequestInputParams, new HashMap<String, Variable>(), false); } if (impl != null) { // call the operations of the lifecycleinterface LOG.debug("Handling Lifecycle operations:"); Map<AbstractOperation, AbstractImplementationArtifact> opIaMap = this.getLifecycleOperations(impl); for (AbstractOperation op : opIaMap.keySet()) { // upload file // fetch parameter values // execute script on vm LOG.debug("Handling operation: " + op.getName()); for (AbstractArtifactReference ref : opIaMap.get(op).getArtifactRef().getArtifactReferences()) { this.invokerPlugin.handleArtifactReferenceUpload(ref, templateContext, serverIpPropWrapper, sshUserVariable, sshKeyVariable, templateId); Map<String, Variable> runScriptRequestInputParams = new HashMap<String, Variable>(); runScriptRequestInputParams.put("hostname", serverIpPropWrapper); runScriptRequestInputParams.put("sshKey", sshKeyVariable); runScriptRequestInputParams.put("sshUser", sshUserVariable); Variable runShScriptStringVar = this.appendBPELAssignOperationShScript(templateContext, op, ref); runScriptRequestInputParams.put("script", runShScriptStringVar); this.invokerPlugin.handle(templateContext, templateId, true, "runScript", "InterfaceUbuntu", "planCallbackAddress_invoker", runScriptRequestInputParams, new HashMap<String, Variable>(), false); } } } return true; } private Variable appendBPELAssignOperationShScript(TemplatePlanContext templateContext, AbstractOperation operation, AbstractArtifactReference reference) { /* * First we initialize a bash script of this form: sudo sh * $InputParamName=ValPlaceHolder* referenceShFileName.sh * * After that we try to generate a xpath 2.0 query of this form: * ..replace * (replace($runShScriptStringVar,"ValPlaceHolder",$PropertyVariableName * ),"ValPlaceHolder",$planInputVar.partName/inputFieldLocalName).. * * With both we have a string with runtime property values or input * params */ Map<String, Variable> inputMappings = new HashMap<String, Variable>(); String runShScriptString = "sudo "; String runShScriptStringVarName = "runShFile" + templateContext.getIdForNames(); String xpathQueryPrefix = ""; String xpathQuerySuffix = ""; for (AbstractParameter parameter : operation.getInputParameters()) { // First compute mappings from operation parameters to // property/inputfield Variable var = templateContext.getPropertyVariable(parameter.getName()); if (var == null) { var = templateContext.getPropertyVariable(parameter.getName(), true); if (var == null) { var = templateContext.getPropertyVariable(parameter.getName(), false); } } inputMappings.put(parameter.getName(), var); // Initialize bash script string variable with placeholders runShScriptString += parameter.getName() + "=$" + parameter.getName() + "$ "; // put together the xpath query xpathQueryPrefix += "replace("; // set the placeholder to replace xpathQuerySuffix += ",'\\$" + parameter.getName() + "\\$',"; if (var == null) { // param is external, query value form input message e.g. /** * Returns a List of ArtifactReferences which point to a ZIP file inside the * the collection of deployment artifacts * * @param das a collection containing DeploymentArtifacts * @return a List of AbstractArtifactReference */ private List<AbstractArtifactReference> getDeploymentArtifactRefs(Collection<AbstractDeploymentArtifact> das) { List<AbstractArtifactReference> result = new ArrayList<AbstractArtifactReference>(); for (AbstractDeploymentArtifact artifact : das) { if (this.isZipArtifact(artifact)) { // check reference for (AbstractArtifactReference ref : artifact.getArtifactRef().getArtifactReferences()) { if (ref.getReference().endsWith(".zip")) { result.add(ref); } } } } return result; } private boolean isZipArtifact(AbstractDeploymentArtifact artifact) { if (artifact.getArtifactType().toString().equals(this.zipArtifactType.toString())) { return true; } else { return false; } } /** * Returns an XPath Query which contructs a valid String, to GET a File from * the openTOSCA API * * @param artifactPath a path inside an ArtifactTemplate * @return a String containing an XPath query */ public String createXPathQueryForURLRemoteFilePath(String artifactPath) { Handler.LOG.debug("Generating XPATH Query for ArtifactPath: " + artifactPath); /** * Loads a BPEL Assign fragment which queries the csarEntrypath from the * input message into String variable. * * @param assignName the name of the BPEL assign * @param xpath2Query the csarEntryPoint XPath query * @param stringVarName the variable to load the queries results into * @return a String containing a BPEL Assign element * @throws IOException is thrown when reading the BPEL fragment form the * resources fails */ public String loadAssignXpathQueryToStringVarFragmentAsString(String assignName, String xpath2Query, String stringVarName) throws IOException { // <!-- {AssignName},{xpath2query}, {stringVarName} --> URL url = FrameworkUtil.getBundle(this.getClass()).getBundleContext().getBundle().getResource("assignStringVarWithXpath2Query.xml"); File bpelFragmentFile = new File(FileLocator.toFileURL(url).getPath()); String template = FileUtils.readFileToString(bpelFragmentFile); template = template.replace("{AssignName}", assignName); template = template.replace("{xpath2query}", xpath2Query); template = template.replace("{stringVarName}", stringVarName); return template; } /** * Loads a BPEL Assign fragment which queries the csarEntrypath from the * input message into String variable. * * @param assignName the name of the BPEL assign * @param csarEntryXpathQuery the csarEntryPoint XPath query * @param stringVarName the variable to load the queries results into * @return a DOM Node representing a BPEL assign element * @throws IOException is thrown when loading internal bpel fragments fails * @throws SAXException is thrown when parsing internal format into DOM * fails */ public Node loadAssignXpathQueryToStringVarFragmentAsNode(String assignName, String xpath2Query, String stringVarName) throws IOException, SAXException { String templateString = this.loadAssignXpathQueryToStringVarFragmentAsString(assignName, xpath2Query, stringVarName); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(templateString)); Document doc = this.docBuilder.parse(is); return doc.getFirstChild(); } }
package com.intellij.openapi.externalSystem.service.execution; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.EnvironmentUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.stream.Stream; import static com.intellij.openapi.util.Pair.pair; public class ExternalSystemJdkUtil { public static final String USE_INTERNAL_JAVA = "#JAVA_INTERNAL"; public static final String USE_PROJECT_JDK = "#USE_PROJECT_JDK"; public static final String USE_JAVA_HOME = "#JAVA_HOME"; @Nullable public static Sdk getJdk(@Nullable Project project, @Nullable String jdkName) throws ExternalSystemJdkException { if (jdkName == null) return null; if (USE_INTERNAL_JAVA.equals(jdkName)) { return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } if (USE_PROJECT_JDK.equals(jdkName)) { if (project != null) { Sdk res = ProjectRootManager.getInstance(project).getProjectSdk(); if (res != null) return res; Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) return sdk; } } if (project == null || project.isDefault()) { Sdk recent = ProjectJdkTable.getInstance().findMostRecentSdkOfType(JavaSdk.getInstance()); return recent != null ? recent : JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } throw new ProjectJdkNotFoundException(); } if (USE_JAVA_HOME.equals(jdkName)) { String javaHome = EnvironmentUtil.getEnvironmentMap().get("JAVA_HOME"); if (StringUtil.isEmptyOrSpaces(javaHome)) throw new UndefinedJavaHomeException(); if (!isValidJdk(javaHome)) throw new InvalidJavaHomeException(javaHome); SimpleJavaSdkType sdkType = SimpleJavaSdkType.getInstance(); String sdkName = sdkType.suggestSdkName(null, javaHome); return sdkType.createJdk(sdkName, javaHome); } Sdk projectJdk = ProjectJdkTable.getInstance().findJdk(jdkName); if (projectJdk != null) { String homePath = projectJdk.getHomePath(); if (!isValidJdk(homePath)) throw new InvalidSdkException(homePath); return projectJdk; } return null; } @NotNull public static Pair<String, Sdk> getAvailableJdk(@Nullable Project project) throws ExternalSystemJdkException { // JavaSdk.getInstance() can be null for non-java IDE SdkType javaSdkType = JavaSdk.getInstance() == null ? SimpleJavaSdkType.getInstance() : JavaSdk.getInstance(); if (project != null) { Stream<Sdk> projectSdks = Stream.concat( Stream.of(ProjectRootManager.getInstance(project).getProjectSdk()), Stream.of(ModuleManager.getInstance(project).getModules()).map(module -> ModuleRootManager.getInstance(module).getSdk())); Sdk projectSdk = projectSdks .filter(sdk -> sdk != null && sdk.getSdkType() == javaSdkType && isValidJdk(sdk.getHomePath())) .findFirst().orElse(null); if (projectSdk != null) { return pair(USE_PROJECT_JDK, projectSdk); } } List<Sdk> allJdks = ProjectJdkTable.getInstance().getSdksOfType(javaSdkType); Sdk mostRecentSdk = allJdks.stream().filter(sdk -> isValidJdk(sdk.getHomePath())).max(javaSdkType.versionComparator()).orElse(null); if (mostRecentSdk != null) { return pair(mostRecentSdk.getName(), mostRecentSdk); } if (!ApplicationManager.getApplication().isUnitTestMode()) { String javaHome = EnvironmentUtil.getEnvironmentMap().get("JAVA_HOME"); if (isValidJdk(javaHome)) { SimpleJavaSdkType simpleJavaSdkType = SimpleJavaSdkType.getInstance(); String sdkName = simpleJavaSdkType.suggestSdkName(null, javaHome); return pair(USE_JAVA_HOME, simpleJavaSdkType.createJdk(sdkName, javaHome)); } } return pair(USE_INTERNAL_JAVA, JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk()); } /** @deprecated trivial (to be removed in IDEA 2019) */ @Deprecated public static boolean checkForJdk(@NotNull Project project, @Nullable String jdkName) { try { final Sdk sdk = getJdk(project, jdkName); return sdk != null && sdk.getHomePath() != null && JdkUtil.checkForJdk(sdk.getHomePath()); } catch (ExternalSystemJdkException ignore) { } return false; } public static boolean isValidJdk(@Nullable String homePath) { return !StringUtil.isEmptyOrSpaces(homePath) && (JdkUtil.checkForJdk(homePath) || JdkUtil.checkForJre(homePath)); } }
package com.redhat.ceylon.eclipse.code.complete; import static com.redhat.ceylon.eclipse.code.complete.CeylonCompletionProcessor.NO_COMPLETIONS; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.appendParameterContextInfo; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.appendPositionalArgs; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getDescriptionFor; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getNamedInvocationDescriptionFor; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getNamedInvocationTextFor; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getPositionalInvocationDescriptionFor; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getPositionalInvocationTextFor; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getTextFor; import static com.redhat.ceylon.eclipse.code.complete.CompletionUtil.getParameters; import static com.redhat.ceylon.eclipse.code.complete.CompletionUtil.getSortedProposedValues; import static com.redhat.ceylon.eclipse.code.complete.CompletionUtil.isInBounds; import static com.redhat.ceylon.eclipse.code.complete.OccurrenceLocation.CLASS_ALIAS; import static com.redhat.ceylon.eclipse.code.complete.OccurrenceLocation.EXTENDS; import static com.redhat.ceylon.eclipse.code.complete.ParameterContextValidator.findCharCount; import static com.redhat.ceylon.eclipse.code.correct.ImportProposals.applyImports; import static com.redhat.ceylon.eclipse.code.correct.ImportProposals.importCallableParameterParamTypes; import static com.redhat.ceylon.eclipse.code.correct.ImportProposals.importDeclaration; import static com.redhat.ceylon.eclipse.code.editor.CeylonSourceViewerConfiguration.LINKED_MODE; import static com.redhat.ceylon.eclipse.code.editor.EditorUtil.addLinkedPosition; import static com.redhat.ceylon.eclipse.code.editor.EditorUtil.installLinkedMode; import static com.redhat.ceylon.eclipse.code.hover.DocumentationHover.getDocumentationFor; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getImageForDeclaration; import static com.redhat.ceylon.eclipse.util.Escaping.escapeName; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.ProposalPosition; import org.eclipse.ltk.core.refactoring.DocumentChange; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.ui.editors.text.EditorsUI; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; import com.redhat.ceylon.eclipse.code.editor.EditorUtil; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; class InvocationCompletionProposal extends CompletionProposal { static void addProgramElementReferenceProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration dec, Scope scope, boolean isMember) { result.add(new InvocationCompletionProposal(offset, prefix, dec.getName(), escapeName(dec), dec, dec.getReference(), scope, cpc, true, false, false, isMember)); } static void addReferenceProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration dec, Scope scope, boolean isMember) { result.add(new InvocationCompletionProposal(offset, prefix, getDescriptionFor(dwp), getTextFor(dwp), dec, dec.getReference(), scope, cpc, true, false, false, isMember)); } static void addInvocationProposals(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, ProducedReference pr, Scope scope, OccurrenceLocation ol, String typeArgs, boolean isMember) { Declaration dec = pr.getDeclaration(); if (dec instanceof Functional) { Unit unit = cpc.getRootNode().getUnit(); boolean isAbstractClass = dec instanceof Class && ((Class) dec).isAbstract(); Functional fd = (Functional) dec; List<ParameterList> pls = fd.getParameterLists(); if (!pls.isEmpty()) { ParameterList parameterList = pls.get(0); List<Parameter> ps = parameterList.getParameters(); if (!isAbstractClass || ol==EXTENDS || ol==CLASS_ALIAS) { if (ps.size()!=getParameters(parameterList, false, false).size()) { result.add(new InvocationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, unit, false, null), getPositionalInvocationTextFor(dwp, ol, pr, unit, false, null), dec, pr, scope, cpc, false, true, false, isMember)); } result.add(new InvocationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, unit, true, typeArgs), getPositionalInvocationTextFor(dwp, ol, pr, unit, true, typeArgs), dec, pr, scope, cpc, true, true, false, isMember)); } if (!isAbstractClass && ol!=EXTENDS && ol!=CLASS_ALIAS && !fd.isOverloaded() && typeArgs==null) { //if there is at least one parameter, //suggest a named argument invocation if (ps.size()!=getParameters(parameterList, false, true).size()) { result.add(new InvocationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, unit, false), getNamedInvocationTextFor(dwp, pr, unit, false), dec, pr, scope, cpc, false, false, true, isMember)); } if (!ps.isEmpty()) { result.add(new InvocationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, unit, true), getNamedInvocationTextFor(dwp, pr, unit, true), dec, pr, scope, cpc, true, false, true, isMember)); } } } } } final class NestedCompletionProposal implements ICompletionProposal, ICompletionProposalExtension2 { private final String op; private final int loc; private final int index; private final boolean basic; private final Declaration dec; NestedCompletionProposal(Declaration dec, int loc, int index, boolean basic, String op) { this.op = op; this.loc = loc; this.index = index; this.basic = basic; this.dec = dec; } public String getAdditionalProposalInfo() { return null; } @Override public void apply(IDocument document) { //the following awfulness is necessary because the //insertion point may have changed (and even its //text may have changed, since the proposal was //instantiated). try { IRegion li = document.getLineInformationOfOffset(loc); int endOfLine = li.getOffset() + li.getLength(); int startOfArgs = getFirstPosition(); int offset = findCharCount(index, document, loc+startOfArgs, endOfLine, ",;", "", true)+1; if (offset>0 && document.getChar(offset)==' ') { offset++; } int nextOffset = findCharCount(index+1, document, loc+startOfArgs, endOfLine, ",;", "", true); int middleOffset = findCharCount(1, document, offset, nextOffset, "=", "", true)+1; if (middleOffset>0 && document.getChar(middleOffset)=='>') { middleOffset++; } while (middleOffset>0 && document.getChar(middleOffset)==' ') { middleOffset++; } if (middleOffset>offset && middleOffset<nextOffset) { offset = middleOffset; } String str = getText(false); if (nextOffset==-1) { nextOffset = offset; } if (document.getChar(nextOffset)=='}') { str += " "; } document.replace(offset, nextOffset-offset, str); } catch (BadLocationException e) { e.printStackTrace(); } //adding imports drops us out of linked mode :( /*try { DocumentChange tc = new DocumentChange("imports", document); tc.setEdit(new MultiTextEdit()); HashSet<Declaration> decs = new HashSet<Declaration>(); CompilationUnit cu = cpc.getRootNode(); importDeclaration(decs, d, cu); if (d instanceof Functional) { List<ParameterList> pls = ((Functional) d).getParameterLists(); if (!pls.isEmpty()) { for (Parameter p: pls.get(0).getParameters()) { MethodOrValue pm = p.getModel(); if (pm instanceof Method) { for (ParameterList ppl: ((Method) pm).getParameterLists()) { for (Parameter pp: ppl.getParameters()) { importSignatureTypes(pp.getModel(), cu, decs); } } } } } } applyImports(tc, decs, cu, document); tc.perform(new NullProgressMonitor()); } catch (Exception e) { e.printStackTrace(); }*/ } private String getText(boolean description) { StringBuilder sb = new StringBuilder() .append(op).append(dec.getName()); if (dec instanceof Class && !basic) { appendPositionalArgs(dec, getUnit(), sb, false, description); } return sb.toString(); } @Override public Point getSelection(IDocument document) { return null; } @Override public String getDisplayString() { return getText(true); } @Override public Image getImage() { return getImageForDeclaration(dec); } @Override public IContextInformation getContextInformation() { return null; } @Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { apply(viewer.getDocument()); } @Override public void selected(ITextViewer viewer, boolean smartToggle) {} @Override public void unselected(ITextViewer viewer) {} @Override public boolean validate(IDocument document, int currentOffset, DocumentEvent event) { if (event==null) { return true; } else { try { IRegion li = document.getLineInformationOfOffset(loc); int endOfLine = li.getOffset() + li.getLength(); int startOfArgs = getFirstPosition(); int offset = findCharCount(index, document, loc+startOfArgs, endOfLine, ",;", "", true)+1; String content = document.get(offset, currentOffset - offset); int eq = content.indexOf("="); if (eq>0) { content = content.substring(eq+1); } String filter = content.trim().toLowerCase(); if ((op+dec.getName()).toLowerCase().startsWith(filter) || dec.getName().toLowerCase().startsWith(filter)) { return true; } } catch (BadLocationException e) { // ignore concurrently modified document } return false; } } } private final CeylonParseController cpc; private final Declaration declaration; private final ProducedReference producedReference; private final Scope scope; private final boolean includeDefaulted; private final boolean namedInvocation; private final boolean positionalInvocation; private final boolean qualified; private InvocationCompletionProposal(int offset, String prefix, String desc, String text, Declaration dec, ProducedReference producedReference, Scope scope, CeylonParseController cpc, boolean includeDefaulted, boolean positionalInvocation, boolean namedInvocation, boolean qualified) { super(offset, prefix, getImageForDeclaration(dec), desc, text); this.cpc = cpc; this.declaration = dec; this.producedReference = producedReference; this.scope = scope; this.includeDefaulted = includeDefaulted; this.namedInvocation = namedInvocation; this.positionalInvocation = positionalInvocation; this.qualified = qualified; } private Unit getUnit() { return cpc.getRootNode().getUnit(); } private DocumentChange createChange(IDocument document) throws BadLocationException { DocumentChange change = new DocumentChange("Complete Invocation", document); change.setEdit(new MultiTextEdit()); HashSet<Declaration> decs = new HashSet<Declaration>(); Tree.CompilationUnit cu = cpc.getRootNode(); if (!qualified) { importDeclaration(decs, declaration, cu); } if (positionalInvocation||namedInvocation) { importCallableParameterParamTypes(declaration, decs, cu); } int il=applyImports(change, decs, cu, document); change.addEdit(new ReplaceEdit(offset-prefix.length(), prefix.length(), text)); offset+=il; return change; } @Override public void apply(IDocument document) { try { createChange(document).perform(new NullProgressMonitor()); } catch (Exception e) { e.printStackTrace(); } if (EditorsUI.getPreferenceStore() .getBoolean(LINKED_MODE)) { activeLinkedMode(document); } } private void activeLinkedMode(IDocument document) { if (declaration instanceof Generic) { Generic generic = (Generic) declaration; ParameterList paramList = null; if (declaration instanceof Functional && (positionalInvocation||namedInvocation)) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty() && !pls.get(0).getParameters().isEmpty()) { paramList = pls.get(0); } } if (paramList!=null) { List<Parameter> params = getParameters(paramList, includeDefaulted, namedInvocation); if (!params.isEmpty()) { enterLinkedMode(document, params, null); return; //NOTE: early exit! } } List<TypeParameter> typeParams = generic.getTypeParameters(); if (!typeParams.isEmpty()) { enterLinkedMode(document, null, typeParams); } } } @Override public Point getSelection(IDocument document) { int first = getFirstPosition(); if (first<=0) { //no arg list return super.getSelection(document); } int next = getNextPosition(document, first); if (next<=0) { //an empty arg list return super.getSelection(document); } int middle = getCompletionPosition(first, next); int start = offset-prefix.length()+first+middle; int len = next-middle; try { if (document.get(start, len).trim().equals("{}")) { start++; len=0; } } catch (BadLocationException e) {} return new Point(start, len); } protected int getCompletionPosition(int first, int next) { return text.substring(first, first+next-1).lastIndexOf(' ')+1; } protected int getFirstPosition() { int index; if (namedInvocation) { index = text.indexOf('{'); } else if (positionalInvocation) { index = text.indexOf('('); } else { index = text.indexOf('<'); } return index+1; } public int getNextPosition(IDocument document, int lastOffset) { int loc = offset-prefix.length(); int comma = -1; try { int start = loc+lastOffset; int end = loc+text.length()-1; if (text.endsWith(";")) { end } comma = findCharCount(1, document, start, end, ",;", "", true) - start; } catch (BadLocationException e) { e.printStackTrace(); } if (comma<0) { int index; if (namedInvocation) { index = text.lastIndexOf('}'); } else if (positionalInvocation) { index = text.lastIndexOf(')'); } else { index = text.lastIndexOf('>'); } return index - lastOffset; } return comma; } public String getAdditionalProposalInfo() { return getDocumentationFor(cpc, declaration); } public void enterLinkedMode(IDocument document, List<Parameter> params, List<TypeParameter> typeParams) { boolean proposeTypeArguments = params==null; int paramCount = proposeTypeArguments ? typeParams.size() : params.size(); if (paramCount==0) return; try { final int loc = offset-prefix.length(); int first = getFirstPosition(); if (first<=0) return; //no arg list int next = getNextPosition(document, first); if (next<=0) return; //empty arg list LinkedModeModel linkedModeModel = new LinkedModeModel(); int seq=0, param=0; while (next>0 && param<paramCount) { boolean voidParam = !proposeTypeArguments && params.get(param).isDeclaredVoid(); if (proposeTypeArguments || positionalInvocation || //don't create linked positions for //void callable parameters in named //argument lists !voidParam) { List<ICompletionProposal> props = new ArrayList<ICompletionProposal>(); if (proposeTypeArguments) { addTypeArgumentProposals(typeParams.get(seq), loc, first, props, seq); } else if (!voidParam) { addValueArgumentProposals(params.get(param), loc, first, props, seq, param==params.size()-1); } int middle = getCompletionPosition(first, next); int start = loc+first+middle; int len = next-middle; if (voidParam) { start++; len=0; } ProposalPosition linkedPosition = new ProposalPosition(document, start, len, seq, props.toArray(NO_COMPLETIONS)); addLinkedPosition(linkedModeModel, linkedPosition); first = first+next+1; next = getNextPosition(document, first); seq++; } param++; } installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(), document, linkedModeModel, this, seq, loc+text.length()); } catch (Exception e) { e.printStackTrace(); } } private void addValueArgumentProposals(Parameter p, final int loc, int first, List<ICompletionProposal> props, int index, boolean last) { if (p.getModel().isDynamicallyTyped()) { return; } ProducedType type = producedReference.getTypedParameter(p) .getType(); if (type==null) return; Unit unit = getUnit(); TypeDeclaration td = type.getDeclaration(); for (DeclarationWithProximity dwp: getSortedProposedValues(scope, unit)) { if (dwp.isUnimported()) { //don't propose unimported stuff b/c adding //imports drops us out of linked mode and //because it results in a pause continue; } Declaration d = dwp.getDeclaration(); final String name = d.getName(); if (d instanceof Value) { if (d.getUnit().getPackage().getNameAsString() .equals(Module.LANGUAGE_MODULE_NAME)) { if (CompletionUtil.isIgnoredLanguageModuleValue(name)) { continue; } } ProducedType vt = ((Value) d).getType(); if (vt!=null && !vt.isNothing() && ((td instanceof TypeParameter) && isInBounds(((TypeParameter)td).getSatisfiedTypes(), vt) || vt.isSubtypeOf(type))) { boolean isIterArg = namedInvocation && last && unit.isIterableParameterType(type); boolean isVarArg = p.isSequenced() && positionalInvocation; props.add(new NestedCompletionProposal(d, loc, index, false, isIterArg || isVarArg ? "*" : "")); } } if (d instanceof Class && !((Class) d).isAbstract() && !d.isAnnotation()) { if (d.getUnit().getPackage().getNameAsString() .equals(Module.LANGUAGE_MODULE_NAME)) { if (CompletionUtil.isIgnoredLanguageModuleClass(name)) { continue; } } ProducedType ct = ((Class) d).getType(); if (ct!=null && !ct.isNothing() && ((td instanceof TypeParameter) && isInBounds(((TypeParameter)td).getSatisfiedTypes(), ct) || ct.getDeclaration().equals(type.getDeclaration()) || ct.isSubtypeOf(type))) { boolean isIterArg = namedInvocation && last && unit.isIterableParameterType(type); boolean isVarArg = p.isSequenced() && positionalInvocation; props.add(new NestedCompletionProposal(d, loc, index, false, isIterArg || isVarArg ? "*" : "")); } } } } private void addTypeArgumentProposals(TypeParameter tp, final int loc, int first, List<ICompletionProposal> props, final int index) { for (DeclarationWithProximity dwp: getSortedProposedValues(scope, getUnit())) { Declaration d = dwp.getDeclaration(); if (d instanceof TypeDeclaration && !dwp.isUnimported()) { TypeDeclaration td = (TypeDeclaration) d; ProducedType t = td.getType(); if (td.getTypeParameters().isEmpty() && !td.isAnnotation() && !(td instanceof NothingType) && !td.inherits(td.getUnit().getExceptionDeclaration())) { if (td.getUnit().getPackage().getNameAsString() .equals(Module.LANGUAGE_MODULE_NAME)) { if (CompletionUtil.isIgnoredLanguageModuleType(td)) { continue; } } if (isInBounds(tp.getSatisfiedTypes(), t)) { props.add(new NestedCompletionProposal(d, loc, index, true, "")); } } } } } @Override public IContextInformation getContextInformation() { if (namedInvocation||positionalInvocation) { //TODO: context info for type arg lists! if (declaration instanceof Functional) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty()) { int argListOffset = isParameterInfo() ? this.offset : offset-prefix.length() + text.indexOf(namedInvocation?'{':'('); return new ParameterContextInformation(declaration, producedReference, getUnit(), pls.get(0), argListOffset, includeDefaulted, namedInvocation /*!isParameterInfo()*/); } } } return null; } boolean isParameterInfo() { return false; } static final class ParameterInfo extends InvocationCompletionProposal { private ParameterInfo(int offset, Declaration dec, ProducedReference producedReference, Scope scope, CeylonParseController cpc, boolean namedInvocation) { super(offset, "", "show parameters", "", dec, producedReference, scope, cpc, true, true, namedInvocation, false); } @Override boolean isParameterInfo() { return true; } @Override public Point getSelection(IDocument document) { return null; } @Override public void apply(IDocument document) {} } static List<IContextInformation> computeParameterContextInformation(final int offset, final Tree.CompilationUnit rootNode, final ITextViewer viewer) { final List<IContextInformation> infos = new ArrayList<IContextInformation>(); rootNode.visit(new Visitor() { @Override public void visit(Tree.InvocationExpression that) { Tree.ArgumentList al = that.getPositionalArgumentList(); if (al==null) { al = that.getNamedArgumentList(); } if (al!=null) { //TODO: should reuse logic for adjusting tokens // from CeylonContentProposer!! Integer start = al.getStartIndex(); Integer stop = al.getStopIndex(); if (start!=null && stop!=null && offset>start) { String string = ""; if (offset>stop) { try { string = viewer.getDocument() .get(stop+1, offset-stop-1); } catch (BadLocationException e) {} } if (string.trim().isEmpty()) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary(); Declaration declaration = mte.getDeclaration(); if (declaration instanceof Functional) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty()) { //Note: This line suppresses the little menu // that gives me a choice of context infos. // Delete it to get a choice of all surrounding // argument lists. infos.clear(); infos.add(new ParameterContextInformation(declaration, mte.getTarget(), rootNode.getUnit(), pls.get(0), al.getStartIndex(), true, al instanceof Tree.NamedArgumentList /*false*/)); } } } } } super.visit(that); } }); return infos; } static void addFakeShowParametersCompletion(final Node node, final CeylonParseController cpc, final List<ICompletionProposal> result) { new Visitor() { @Override public void visit(Tree.InvocationExpression that) { Tree.ArgumentList al = that.getPositionalArgumentList(); if (al==null) { al = that.getNamedArgumentList(); } if (al!=null) { Integer startIndex = al.getStartIndex(); Integer startIndex2 = node.getStartIndex(); if (startIndex!=null && startIndex2!=null && startIndex.intValue()==startIndex2.intValue()) { Tree.Primary primary = that.getPrimary(); if (primary instanceof Tree.MemberOrTypeExpression) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) primary; if (mte.getDeclaration()!=null && mte.getTarget()!=null) { result.add(new ParameterInfo(al.getStartIndex(), mte.getDeclaration(), mte.getTarget(), node.getScope(), cpc, al instanceof Tree.NamedArgumentList)); } } } } super.visit(that); } }.visit(cpc.getRootNode()); } static final class ParameterContextInformation implements IContextInformation { private final Declaration declaration; private final ProducedReference producedReference; private final ParameterList parameterList; private final int argumentListOffset; private final Unit unit; private final boolean includeDefaulted; // private final boolean inLinkedMode; private final boolean namedInvocation; private ParameterContextInformation(Declaration declaration, ProducedReference producedReference, Unit unit, ParameterList parameterList, int argumentListOffset, boolean includeDefaulted, boolean namedInvocation) { // boolean inLinkedMode this.declaration = declaration; this.producedReference = producedReference; this.unit = unit; this.parameterList = parameterList; this.argumentListOffset = argumentListOffset; this.includeDefaulted = includeDefaulted; // this.inLinkedMode = inLinkedMode; this.namedInvocation = namedInvocation; } @Override public String getContextDisplayString() { return "Parameters of '" + declaration.getName() + "'"; } @Override public Image getImage() { return getImageForDeclaration(declaration); } @Override public String getInformationDisplayString() { List<Parameter> ps = getParameters(parameterList, includeDefaulted, namedInvocation); if (ps.isEmpty()) { return "no parameters"; } StringBuilder result = new StringBuilder(); for (Parameter p: ps) { boolean isListedValues = namedInvocation && p==ps.get(ps.size()-1) && p.getModel() instanceof Value && p.getType()!=null && unit.isIterableParameterType(p.getType()); if (includeDefaulted || !p.isDefaulted() || isListedValues) { if (producedReference==null) { result.append(p.getName()); } else { ProducedTypedReference pr = producedReference.getTypedParameter(p); appendParameterContextInfo(result, pr, p, unit, namedInvocation, isListedValues); } if (!isListedValues) { result.append(namedInvocation ? "; " : ", "); } } } if (!namedInvocation && result.length()>0) { result.setLength(result.length()-2); } return result.toString(); } @Override public boolean equals(Object that) { if (that instanceof ParameterContextInformation) { return ((ParameterContextInformation) that).declaration .equals(declaration); } else { return false; } } int getArgumentListOffset() { return argumentListOffset; } } }
package com.fernandocejas.android10.sample.presentation.internal.di.modules; import android.app.Activity; import com.fernandocejas.android10.sample.presentation.internal.di.PerActivity; import dagger.Module; import dagger.Provides; /** * A module to wrap the Activity state and expose it to the graph. */ @Module public class ActivityModule { private final Activity activity; public ActivityModule(Activity activity) { this.activity = activity; } /** * Expose the activity to dependents in the graph. */ @Provides @PerActivity Activity activity() { return this.activity; } }
package com.opengamma.master.historicaltimeseries.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.threeten.bp.LocalDate; import com.opengamma.core.historicaltimeseries.impl.NonVersionedRedisHistoricalTimeSeriesSource; import com.opengamma.core.value.MarketDataRequirementNames; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ExternalIdBundleWithDates; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolutionResult; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolver; import com.opengamma.master.historicaltimeseries.ManageableHistoricalTimeSeriesInfo; import com.opengamma.util.ArgumentChecker; /** * Implements {@link HistoricalTimeSeriesResolver} on top of any Redis HTS source. */ public class RedisSimulationSeriesResolver implements HistoricalTimeSeriesResolver { private static final Logger s_logger = LoggerFactory.getLogger(RedisSimulationSeriesResolver.class); private final NonVersionedRedisHistoricalTimeSeriesSource[] _redisSources; public RedisSimulationSeriesResolver(NonVersionedRedisHistoricalTimeSeriesSource... redisSources) { ArgumentChecker.notNull(redisSources, "sources"); ArgumentChecker.notNegativeOrZero(redisSources.length, "redisSources must not be empty"); _redisSources = redisSources; } @Override public HistoricalTimeSeriesResolutionResult resolve(ExternalIdBundle identifierBundle, LocalDate identifierValidityDate, String dataSource, String dataProvider, String dataField, String resolutionKey) { if (identifierBundle.isEmpty()) { return null; // is this the correct action? } else if (identifierBundle.size() > 1) { s_logger.warn("Attempted to call RedisSimulationSeriesSource with bundle {}. Calls with more than 1 entry in ID bundle are probably misuse of this class.", identifierBundle); } ExternalId externalId = identifierBundle.getExternalIds().iterator().next(); if (!MarketDataRequirementNames.MARKET_VALUE.equals(dataField)) { //s_logger.warn("Redis simulation asked for {} for {}, can only handle market value.", dataField, externalId); return null; } final UniqueId uniqueId = UniqueId.of(externalId.getScheme().getName(), externalId.getValue()); boolean oneMatches = false; for (NonVersionedRedisHistoricalTimeSeriesSource source : _redisSources) { if (source.exists(uniqueId)) { oneMatches = true; break; } } if (!oneMatches) { return null; } ManageableHistoricalTimeSeriesInfo htsInfo = new ManageableHistoricalTimeSeriesInfo() { private static final long serialVersionUID = 1L; @Override public UniqueId getUniqueId() { return uniqueId; } @Override public ExternalIdBundleWithDates getExternalIdBundle() { throw new UnsupportedOperationException("Unsupported operation."); } @Override public String getName() { throw new UnsupportedOperationException("Unsupported operation."); } @Override public String getDataField() { throw new UnsupportedOperationException("Unsupported operation."); } @Override public String getDataSource() { throw new UnsupportedOperationException("Unsupported operation."); } @Override public String getDataProvider() { throw new UnsupportedOperationException("Unsupported operation."); } @Override public String getObservationTime() { throw new UnsupportedOperationException("Unsupported operation."); } @Override public ObjectId getTimeSeriesObjectId() { throw new UnsupportedOperationException("Unsupported operation."); } }; HistoricalTimeSeriesResolutionResult result = new HistoricalTimeSeriesResolutionResult(htsInfo); return result; } }
package ctci; import java.util.Arrays; /** * Given an image represented by a NxN matrix, * where each pixel in the image is 4 bytes, write * a method to rotate the image by 90 degrees. * Do it in place. * @author Debosmit * */ public class ArrayString1_6 { // 4 bytes for every pixel // need it to be static since we are invoking instances of Pixel from main // ideally, it would obviously not be a subclass. // making pixel a subclass here, for clarity and not to ruin the // directory structure. static public class Pixel { // 8-bit signed two's complement integer; it has a minimum value // of -128 and a maximum value of 127 (inclusive) private byte byte3, byte2, byte1, byte0; public Pixel(byte byte3, byte byte2, byte byte1, byte byte0) { this.byte3 = byte3; this.byte2 = byte2; this.byte1 = byte1; this.byte0 = byte0; } public Pixel() { this((byte)0, (byte)0, (byte)0, (byte)0); } public Pixel(byte[] pixels) { if(pixels.length != 4) throw new IllegalArgumentException("Pixel is 4 bytes"); this.byte3 = pixels[3]; this.byte2 = pixels[2]; this.byte1 = pixels[1]; this.byte0 = pixels[0]; } // get bytes for this pixel // range of values [-128, 127] public byte[] getPixels() { return new byte[]{byte3, byte2, byte1, byte0}; } // get true values for this pixel // int[] length -> 4 // range of values [0, 255] // cant return byte array since now values range // from [0, 255] public int[] getTruePixels() { byte[] bytesB = getPixels(); int[] bytesI = new int[bytesB.length]; // scale up all values by 128 // old range [-128, 127] // new range [0, 255] for(int i = 0 ; i < bytesI.length ; i++) bytesI[i] = (int)bytesB[i] + 128; return bytesI; } public String toString() { return Arrays.toString(getTruePixels()); } } public void rotate90(Pixel[][] arr) { if(arr == null) throw new IllegalArgumentException("Array cannot be null"); if(!isSquare(arr)) throw new IllegalArgumentException("Array must be NxN"); if(arr.length == 1) return; int n = arr.length; // rotation stage // layering out the levels of the array // first, we do the outermost layer, i.e. // arr[0][0...n-1] -> arr[0...n-1][n-1] || top layer -> right layer // arr[0...n-1][n-1] -> arr[n-1][n-1...0] || right layer -> bottom layer // arr[n-1][0...n-1] -> arr[0...n-1][0] || bottom layer -> left layer // left layer -> top layer // then move to inner layer and repeat for(int layer = 0 ; layer < n/2 ; layer++) { // layer start index for array to be copied int last = (n - 1) - layer; // work with the current layer for(int i = layer ; i < last ; i++) { // getting value at top[i] Pixel temp = arr[layer][i]; // left[n-1-i] -> top[i] arr[layer][i] = arr[(n - 1) - i][layer]; // bottom[last-i] -> left[n-1-i] arr[(n - 1) - i][layer] = arr[(n - 1) - layer][last - i + layer]; // right[i] -> bottom[last-i] arr[(n - 1) - layer][last - i + layer] = arr[i][(n - 1) - layer]; // top[i] -> right[i] arr[i][(n - 1) - layer] = temp; } } } // tests if the given array is square private boolean isSquare(Pixel[][] arr) { int len = arr.length; for(int i = 0 ; i < len ; i++) if(arr[i].length!=len) return false; return true; } // returns a new number in [min, max]; private byte randomWithRange(int min, int max) { if(max < min) return randomWithRange(max, min); int range = (max - min) + 1; return (byte)((Math.random() * range) + min); } // prints a formatted version of a 2D pixel array private void print2DPixelArray(Pixel[][] arr) { for(int i = 0 ; i < arr.length ; i++) { for(int j = 0 ; j < arr[i].length ; j++) { System.out.print(arr[i][j] + "\t"); } System.out.println(); } } public static void main(String[] args) { ArrayString1_6 rotate = new ArrayString1_6(); final int N = 5; Pixel[][] pixels = new Pixel[N][N]; byte count = -118; for(int i = 0 ; i < N ; i++) { for(int j = 0 ; j < N ; j++) { // establish array of bytes for current pixel byte[] curPixel = new byte[4]; for(int k = curPixel.length - 1 ; k >= 0 ; k // range of byte is [-128, 127] curPixel[k] = count; pixels[i][j] = new Pixel(curPixel); count++; } } System.out.println("Old pixels: "); rotate.print2DPixelArray(pixels); rotate.rotate90(pixels); System.out.println("\nNew pixels: "); rotate.print2DPixelArray(pixels); for(int i = 0 ; i < N ; i++) { for(int j = 0 ; j < N ; j++) { // establish array of bytes for current pixel byte[] curPixel = new byte[4]; for(int k = curPixel.length - 1 ; k >= 0 ; k // range of byte is [-128, 127] curPixel[k] = rotate.randomWithRange(-128, 127); pixels[i][j] = new Pixel(curPixel); count++; } } System.out.println("\n\nOld pixels: "); rotate.print2DPixelArray(pixels); rotate.rotate90(pixels); rotate.rotate90(pixels); rotate.rotate90(pixels); rotate.rotate90(pixels); System.out.println("\nNew pixels: "); rotate.print2DPixelArray(pixels); } }
package org.openas2.message; import org.openas2.params.CompositeParameters; import org.openas2.params.DateParameters; import org.openas2.params.InvalidParameterException; import org.openas2.params.MessageParameters; import org.openas2.params.ParameterParser; import org.openas2.params.RandomParameters; import org.openas2.partner.AS2Partnership; import org.openas2.partner.Partnership; public class AS2Message extends BaseMessage implements Message { private static final long serialVersionUID = 1L; public static final String PROTOCOL_AS2 = "as2"; public String getProtocol() { return PROTOCOL_AS2; } public String generateMessageID() throws InvalidParameterException { CompositeParameters params = new CompositeParameters(false). add("date", new DateParameters()). add("msg", new MessageParameters(this)). add("rand", new RandomParameters()); String idFormat = getPartnership().getAttribute(AS2Partnership.PA_MESSAGEID); if (idFormat == null) { idFormat = "OPENAS2-$date.ddMMyyyyHHmmssZ$-$rand.1234$@$msg.sender.as2_id$_$msg.receiver.as2_id$"; } StringBuffer messageId = new StringBuffer(); messageId.append("<"); messageId.append(ParameterParser.parse(idFormat, params)); messageId.append(">"); return messageId.toString(); } public boolean isRequestingMDN() { Partnership p = getPartnership(); boolean requesting = ((p.getAttribute(AS2Partnership.PA_AS2_MDN_TO) != null) || (p .getAttribute(AS2Partnership.PA_AS2_MDN_OPTIONS) != null)); boolean requested = ((getHeader("Disposition-Notification-To") != null) || (getHeader("Disposition-Notification-Options") != null)); return requesting || requested; } public boolean isRequestingAsynchMDN() { Partnership p = getPartnership(); boolean requesting = ((p.getAttribute(AS2Partnership.PA_AS2_MDN_TO) != null || p.getAttribute(AS2Partnership.PA_AS2_MDN_OPTIONS) != null) && p.getAttribute(AS2Partnership.PA_AS2_RECEIPT_OPTION) != null); boolean requested = ((getHeader("Disposition-Notification-To") != null || (getHeader("Disposition-Notification-Options") != null)) && (getHeader("Receipt-Delivery-Option") != null)); return requesting || requested; } public String getAsyncMDNurl() { return getHeader("Receipt-Delivery-Option"); } }
package ti.modules.titanium.ui; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.AsyncResult; import org.appcelerator.kroll.common.TiMessenger; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.ui.PickerRowProxy.PickerRowListener; import ti.modules.titanium.ui.widget.picker.TiUIPickerColumn; import ti.modules.titanium.ui.widget.picker.TiUISpinnerColumn; import android.app.Activity; import android.os.Message; import android.util.Log; @Kroll.proxy(creatableInModule=UIModule.class) public class PickerColumnProxy extends TiViewProxy implements PickerRowListener { private static final String TAG = "PickerColumnProxy"; private static final int MSG_FIRST_ID = TiViewProxy.MSG_LAST_ID + 1; private static final int MSG_ADD = MSG_FIRST_ID + 100; private static final int MSG_REMOVE = MSG_FIRST_ID + 101; private static final int MSG_SET_ROWS = MSG_FIRST_ID + 102; private PickerColumnListener columnListener = null; private boolean useSpinner = false; private boolean suppressListenerEvents = false; public PickerColumnProxy() { super(); } public PickerColumnProxy(TiContext tiContext) { this(); } public void setColumnListener(PickerColumnListener listener) { columnListener = listener; } public void setUseSpinner(boolean value) { useSpinner = value; } @Override public boolean handleMessage(Message msg) { switch(msg.what){ case MSG_ADD: { AsyncResult result = (AsyncResult)msg.obj; handleAddRow((TiViewProxy)result.getArg()); result.setResult(null); return true; } case MSG_REMOVE: { AsyncResult result = (AsyncResult)msg.obj; handleRemoveRow((TiViewProxy)result.getArg()); result.setResult(null); return true; } case MSG_SET_ROWS: { AsyncResult result = (AsyncResult)msg.obj; handleSetRows((Object[])result.getArg()); result.setResult(null); return true; } } return super.handleMessage(msg); } @Override public void handleCreationDict(KrollDict dict) { super.handleCreationDict(dict); if (dict.containsKey("rows")) { Object rowsAtCreation = dict.get("rows"); if (rowsAtCreation.getClass().isArray()) { Object[] rowsArray = (Object[]) rowsAtCreation; addRows(rowsArray); } } } @Override public void add(TiViewProxy o) { if (TiApplication.isUIThread()) { handleAddRow(o); } else { TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_ADD), o); } } private void handleAddRow(TiViewProxy o) { if (o == null)return; if (o instanceof PickerRowProxy) { ((PickerRowProxy)o).setRowListener(this); super.add((PickerRowProxy)o); if (columnListener != null && !suppressListenerEvents) { int index = children.indexOf(o); columnListener.rowAdded(this, index); } } else { Log.w(TAG, "add() unsupported argument type: " + o.getClass().getSimpleName()); } } @Override public void remove(TiViewProxy o) { if (TiApplication.isUIThread() || peekView() == null) { handleRemoveRow(o); } else { TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_REMOVE), o); } } private void handleRemoveRow(TiViewProxy o) { if (o == null)return; if (o instanceof PickerRowProxy) { int index = children.indexOf(o); super.remove((PickerRowProxy)o); if (columnListener != null && !suppressListenerEvents) { columnListener.rowRemoved(this, index); } } else { Log.w(TAG, "remove() unsupported argment type: " + o.getClass().getSimpleName()); } } @Kroll.method public void addRow(Object row) { if (row instanceof PickerRowProxy) { this.add((PickerRowProxy) row); } else { Log.w(TAG, "Unable to add the row. Invalid type for row."); } } protected void addRows(Object[] rows) { for (Object obj :rows) { if (obj instanceof PickerRowProxy) { this.add((PickerRowProxy)obj); } else { Log.w(TAG, "Unexpected type not added to picker column: " + obj.getClass().getName()); } } } @Kroll.method public void removeRow(Object row) { if (row instanceof PickerRowProxy) { this.remove((PickerRowProxy) row); } else { Log.w(TAG, "Unable to remove the row. Invalid type for row."); } } @Kroll.getProperty @Kroll.method public PickerRowProxy[] getRows() { if (children == null || children.size() == 0) { return null; } return children.toArray(new PickerRowProxy[children.size()]); } @Kroll.setProperty @Kroll.method public void setRows(Object[] rows) { if (TiApplication.isUIThread() || peekView() == null) { handleSetRows(rows); } else { TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_SET_ROWS), rows); } } private void handleSetRows(Object[] rows) { try { suppressListenerEvents = true; if (children != null && children.size() > 0) { int count = children.size(); for (int i = (count - 1); i >= 0; i remove(children.get(i)); } } addRows(rows); } finally { suppressListenerEvents = false; } if (columnListener != null) { columnListener.rowsReplaced(this); } } @Kroll.getProperty @Kroll.method public int getRowCount() { return children.size(); } @Override public TiUIView createView(Activity activity) { if (useSpinner) { return new TiUISpinnerColumn(this); } else { return new TiUIPickerColumn(this); } } public interface PickerColumnListener { void rowAdded(PickerColumnProxy column, int rowIndex); void rowRemoved(PickerColumnProxy column, int oldRowIndex); void rowChanged(PickerColumnProxy column, int rowIndex); void rowSelected(PickerColumnProxy column, int rowIndex); void rowsReplaced(PickerColumnProxy column); // wholesale replace of rows } @Override public void rowChanged(PickerRowProxy row) { if (columnListener != null && !suppressListenerEvents) { int index = children.indexOf(row); columnListener.rowChanged(this, index); } } public void onItemSelected(int rowIndex) { if (columnListener != null && !suppressListenerEvents) { columnListener.rowSelected(this, rowIndex); } } public PickerRowProxy getSelectedRow() { if (!(peekView() instanceof TiUISpinnerColumn)) { return null; } int rowIndex = ((TiUISpinnerColumn)peekView()).getSelectedRowIndex(); if (rowIndex < 0) { return null; } else { return (PickerRowProxy)children.get(rowIndex); } } public int getThisColumnIndex() { return ((PickerProxy)getParent()).getColumnIndex(this); } public void parentShouldRequestLayout() { if (getParent() instanceof PickerProxy) { ((PickerProxy)getParent()).forceRequestLayout(); } } }
package com.splicemachine.derby.impl.sql.execute.operations.batchonce; import com.google.common.base.Strings; import com.splicemachine.db.iapi.error.StandardException; import com.splicemachine.db.iapi.sql.Activation; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext; import com.splicemachine.derby.impl.sql.execute.operations.LocatedRow; import com.splicemachine.derby.impl.sql.execute.operations.SpliceBaseOperation; import com.splicemachine.derby.stream.function.BatchOnceFunction; import com.splicemachine.derby.stream.iapi.DataSet; import com.splicemachine.derby.stream.iapi.DataSetProcessor; import com.splicemachine.derby.stream.iapi.OperationContext; import org.apache.log4j.Logger; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; /** * Replaces a ProjectRestrictNode (below an Update) that would otherwise invoke a subquery for each source row. This * operation will read a batch of rows from the source, transform them into the shape expected by update [old value, new * value, row location], execute the subquery once, and populate new value column of matching rows with the result. * * A complication is that we are using this operations where the subquery is expected to return at most one row for each * source row and must continue to enforce this, throwing LANG_SCALAR_SUBQUERY_CARDINALITY_VIOLATION if more than one * subquery row is returned for each source row. * * Example Query: update A set A.name = (select B.name from B where A.id = B.id) where A.name is null; * * Currently we ONLY support BatchOnce for queries that have a single subquery and where that subquery has a single * equality predicate with one correlated column reference. * * Currently BatchOnce is only used in the case where the subquery tree has a FromBaseTable leaf, no index. So with * or without BatchOnce we always scan the entire subquery table. With BatchOnce however the number of times * we scan the entire subquery tables is potentially divided by this class's configurable BATCH_SIZE. This * can make a 24+hour query execute in a few tens of seconds. * * Related: BatchOnceNode, BatchOnceVisitor, OnceOperation */ public class BatchOnceOperation extends SpliceBaseOperation { private static final Logger LOG = Logger.getLogger(BatchOnceOperation.class); private SpliceOperation source; private SpliceOperation subquerySource; /* Name of the activation field that contains the Update result set. Used to get currentRowLocation */ private String updateResultSetFieldName; /* 1-based column positions for columns in the source we will need. Will be -1 if not available. */ private int sourceRowLocationColumnPosition; private int sourceCorrelatedColumnPosition; private int subqueryCorrelatedColumnPosition; public BatchOnceOperation() { } public BatchOnceOperation(SpliceOperation source, Activation activation, int rsNumber, SpliceOperation subquerySource, String updateResultSetFieldName, int sourceRowLocationColumnPosition, int sourceCorrelatedColumnPosition, int subqueryCorrelatedColumnPosition) throws StandardException { super(activation, rsNumber, 0d, 0d); this.source = source; this.subquerySource = subquerySource.getLeftOperation(); this.updateResultSetFieldName = updateResultSetFieldName; this.sourceRowLocationColumnPosition = sourceRowLocationColumnPosition; this.sourceCorrelatedColumnPosition = sourceCorrelatedColumnPosition; this.subqueryCorrelatedColumnPosition = subqueryCorrelatedColumnPosition; } @Override public void init(SpliceOperationContext context) throws StandardException, IOException { super.init(context); source.init(context); subquerySource.init(context); } @Override public String getName() { return this.getClass().getSimpleName(); } @Override public List<SpliceOperation> getSubOperations() { return Arrays.asList(source); } @Override public int[] getRootAccessedCols(long tableNumber) throws StandardException { return source.getRootAccessedCols(tableNumber); } @Override public boolean isReferencingTable(long tableNumber) { return source.isReferencingTable(tableNumber); } @Override public String prettyPrint(int indentLevel) { String indent = "\n"+ Strings.repeat("\t",indentLevel); return "BatchOnceOperation:" + indent + "resultSetNumber:" + resultSetNumber + indent + "source:" + source.prettyPrint(indentLevel + 1); } @Override public SpliceOperation getLeftOperation() { return source; } @Override public void open() throws StandardException { super.open(); if (source != null) { source.open(); } } @Override public void close() throws StandardException { super.close(); source.close(); } // serialization @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); this.source = (SpliceOperation) in.readObject(); this.subquerySource = (SpliceOperation) in.readObject(); this.updateResultSetFieldName = in.readUTF(); this.sourceRowLocationColumnPosition = in.readInt(); this.sourceCorrelatedColumnPosition = in.readInt(); this.subqueryCorrelatedColumnPosition = in.readInt(); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(this.source); out.writeObject(this.subquerySource); out.writeUTF(this.updateResultSetFieldName); out.writeInt(this.sourceRowLocationColumnPosition); out.writeInt(this.sourceCorrelatedColumnPosition); out.writeInt(this.subqueryCorrelatedColumnPosition); } public SpliceOperation getSubquerySource() { return subquerySource; } public int getSourceCorrelatedColumnPosition() { return sourceCorrelatedColumnPosition; } public int getSubqueryCorrelatedColumnPosition() { return subqueryCorrelatedColumnPosition; } public SpliceOperation getSource() { return source; } @Override public <Op extends SpliceOperation> DataSet<LocatedRow> getDataSet(DataSetProcessor dsp) throws StandardException { DataSet set = source.getDataSet(dsp); OperationContext<BatchOnceOperation> operationContext = dsp.createOperationContext(this); return set.mapPartitions(new BatchOnceFunction(operationContext)); } }
package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.AbstractParser; import com.joelapenna.foursquare.parsers.Parser; import com.joelapenna.foursquare.types.FoursquareType; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.params.HttpClientParams; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.List; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class HttpApi { protected static final String TAG = "HttpApi"; protected static final boolean DEBUG = Foursquare.DEBUG; private static final String CLIENT_VERSION = "iPhone 20090301"; private static final String CLIENT_VERSION_HEADER = "X_foursquare_client_version"; private static final int TIMEOUT = 10; DefaultHttpClient mHttpClient; public HttpApi(DefaultHttpClient httpClient) { mHttpClient = httpClient; } public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) Log.d(TAG, "doHttpRequest: " + httpRequest.getURI()); HttpResponse response = executeHttpRequest(httpRequest); if (DEBUG) Log.d(TAG, "executed HttpRequest for: " + httpRequest.getURI().toString()); switch (response.getStatusLine().getStatusCode()) { case 200: InputStream is = response.getEntity().getContent(); try { return parser.parse(AbstractParser.createXmlPullParser(is)); } finally { is.close(); } case 401: response.getEntity().consumeContent(); throw new FoursquareCredentialsException(response.getStatusLine().toString()); default: if (DEBUG) { Log.d(TAG, "Default case for status code reached: " + response.getStatusLine().toString()); } response.getEntity().consumeContent(); throw new IOException("Unknown HTTP status: " + response.getStatusLine()); } } public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) Log.d(TAG, "doHttpPost: " + url); HttpPost httpPost = createHttpPost(url, nameValuePairs); HttpResponse response = executeHttpRequest(httpPost); if (DEBUG) Log.d(TAG, "executed HttpRequest for: " + httpPost.getURI().toString()); switch (response.getStatusLine().getStatusCode()) { case 200: try { return EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new FoursquareParseException(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new FoursquareCredentialsException(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new FoursquareException(response.getStatusLine().toString()); } } /** * execute() an httpRequest catching exceptions and returning null instead. * * @param httpRequest * @return * @throws IOException */ public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException { if (DEBUG) Log.d(TAG, "executing HttpRequest for: " + httpRequest.getURI().toString()); try { mHttpClient.getConnectionManager().closeExpiredConnections(); return mHttpClient.execute(httpRequest); } catch (IOException e) { httpRequest.abort(); throw e; } } public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) { if (DEBUG) Log.d(TAG, "creating HttpGet for: " + url); String query = URLEncodedUtils.format(Arrays.asList(nameValuePairs), HTTP.UTF_8); HttpGet httpGet = new HttpGet(url + "?" + query); if (DEBUG) Log.d(TAG, "Created: " + httpGet.getURI()); return httpGet; } public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) { if (DEBUG) Log.d(TAG, "creating HttpPost for: " + url); List<NameValuePair> params = Arrays.asList(nameValuePairs); HttpPost httpPost = new HttpPost(url); httpPost.addHeader(CLIENT_VERSION_HEADER, CLIENT_VERSION); try { for (int i = 0; i < params.size(); i++) { if (DEBUG) Log.d(TAG, "Param: " + params.get(i)); } httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } catch (UnsupportedEncodingException e1) { throw new IllegalArgumentException("Unable to encode http parameters."); } if (DEBUG) Log.d(TAG, "Created: " + httpPost); return httpPost; } /** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient() { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); } /** * Create the default HTTP protocol parameters. */ private static final HttpParams createHttpParams() { final HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); return params; } }
package com.azendoo.reactnativesnackbar; import android.support.design.widget.Snackbar; import android.view.View; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import java.util.HashMap; import java.util.Map; public class SnackbarModule extends ReactContextBaseJavaModule{ private static final String REACT_NAME = "RNSnackbar"; public SnackbarModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return REACT_NAME; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put("LENGTH_LONG", Snackbar.LENGTH_LONG); constants.put("LENGTH_SHORT", Snackbar.LENGTH_SHORT); constants.put("LENGTH_INDEFINITE", Snackbar.LENGTH_INDEFINITE); return constants; } @ReactMethod public void show(ReadableMap options, Callback callback) { View view = getCurrentActivity().findViewById(android.R.id.content); if (view == null) return; String title = options.hasKey("title") ? options.getString("title") : "Hello"; int duration = options.hasKey("duration") ? options.getInt("duration") : Snackbar.LENGTH_SHORT; Snackbar snackbar = Snackbar.make(view, title, duration); if (options.hasKey("action")) { View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { callback.invoke(); } }; ReadableMap actionDetails = options.getMap("action"); snackbar.setAction(actionDetails.getString("title"), onClickListener); snackbar.setActionTextColor(actionDetails.getInt("color")); } snackbar.show(); } }
package com.github.ferstl.spring.jdbc.oracle; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter; import org.springframework.jdbc.core.SqlTypeValue; import org.springframework.jdbc.core.StatementCreatorUtils; import org.springframework.jdbc.core.support.AbstractInterruptibleBatchPreparedStatementSetter; import org.springframework.test.annotation.IfProfileValue; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import com.github.ferstl.spring.jdbc.oracle.dsconfig.DataSourceProfile; import static com.github.ferstl.spring.jdbc.oracle.RowCountMatcher.matchesRowCounts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @ActiveProfiles(DataSourceProfile.SINGLE_CONNECTION) //@ActiveProfiles(DataSourceProfile.COMMONS_DBCP) //@ActiveProfiles(DataSourceProfile.TOMCAT_POOL) @ContextConfiguration(classes = DatabaseConfiguration.class) @TransactionConfiguration @Transactional @IfProfileValue(name = "testgroup", value="integration") @RunWith(SpringJUnit4ClassRunner.class) public class OracleJdbcTemplateIntegrationTest { /** SQL that updates one single row. */ private static final String SINGLE_ROW_SQL = "UPDATE test_table t SET t.numval = ? WHERE t.numval = ?"; /** SQL that updates multiple rows. */ private static final String MULTI_ROW_SQL = "UPDATE test_table t SET t.numval = ? WHERE t.numval BETWEEN ? AND ?"; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private Environment env; private int batchSize; @Before public void before() { this.batchSize = this.env.getProperty("db.batchsize", Integer.class); } @Test public void updateCompleteBatchWithArgList() { int nrOfUpdates = 2 * this.batchSize; List<Object[]> batchArgs = new ArrayList<>(nrOfUpdates); for (int i = 0; i < nrOfUpdates; i++) { batchArgs.add(new Object[] { i + 1, i + 11 }); } int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, batchArgs); assertThat(result, matchesRowCounts(this.batchSize, nrOfUpdates)); } @Test public void updateIncompleteBatchWithArgList() { int nrOfUpdates = this.batchSize + 2; List<Object[]> batchArgs = new ArrayList<>(nrOfUpdates); for (int i = 0; i < nrOfUpdates; i++) { batchArgs.add(new Object[] { i + 1, i + 11 }); } int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, batchArgs); assertThat(result, matchesRowCounts(this.batchSize, nrOfUpdates)); } @Test public void noUpdateWithArgList() { int nrOfUpdates = this.batchSize * 2 + 2; List<Object[]> batchArgs = new ArrayList<>(nrOfUpdates); for (int i = 0; i < nrOfUpdates; i++) { batchArgs.add(new Object[] { i + 1, Integer.MAX_VALUE }); } int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, batchArgs); assertEquals(nrOfUpdates, result.length); for (int updateCount : result) { assertEquals(0, updateCount); } } @Test public void updateWithEmptyArgList() { int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, Collections.<Object[]>emptyList()); assertEquals(0, result.length); } @Test public void updateMultipleRowsWithSingleArgList() { Object[] args = new Object[] {9999, 100, 199}; int[] result = this.jdbcTemplate.batchUpdate(MULTI_ROW_SQL, Collections.singletonList(args)); assertEquals(1, result.length); assertEquals(100, result[0]); } @Test public void updateCompleteBatchWithPss() { int nrOfUpdates = this.batchSize * 2; int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, new SingleRowPreparedStatementSetter(nrOfUpdates)); assertThat(result, matchesRowCounts(this.batchSize, nrOfUpdates)); } @Test public void updateIncompleteBatchWithPss() { int nrOfUpdates = this.batchSize + 2; int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, new SingleRowPreparedStatementSetter(nrOfUpdates)); assertThat(result, matchesRowCounts(this.batchSize, nrOfUpdates)); } @Test public void updateWithEmptyPss() { int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, new SingleRowPreparedStatementSetter(0)); assertEquals(0, result.length); } @Test public void updateCompleteBatchWithInterruptiblePss() { int nrOfUpdates = this.batchSize * 2; int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, new SingleRowInterruptiblePreparedStatementSetter(nrOfUpdates)); assertThat(result, matchesRowCounts(this.batchSize, nrOfUpdates)); } @Test public void updateIncompleteBatchWithInterruptiblePss() { int nrOfUpdates = this.batchSize + 2; int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, new SingleRowInterruptiblePreparedStatementSetter(nrOfUpdates)); assertThat(result, matchesRowCounts(this.batchSize, nrOfUpdates)); } @Test public void updateWithEmptyInterruptiblePss() { int[] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, new SingleRowInterruptiblePreparedStatementSetter(0)); assertEquals(0, result.length); } @Test public void updateCompleteBatchWithParameterizedPss() { int customBatchSize = 5; int nrOfUpdates = 2 * customBatchSize; List<int[]> batchArgs = new ArrayList<>(nrOfUpdates); for (int i = 0; i < nrOfUpdates; i++) { batchArgs.add(new int[] { i + 1, i + 11 }); } int[][] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, batchArgs, customBatchSize, new SingleRowParameterizedPreparedStatementSetter()); assertThat(result, RowCountPerBatchMatcher.matchesBatchedRowCounts(customBatchSize, nrOfUpdates)); } @Test public void updateInompleteBatchWithParameterizedPss() { int customBatchSize = 5; int nrOfUpdates = customBatchSize + 2; List<int[]> batchArgs = new ArrayList<>(nrOfUpdates); for (int i = 0; i < nrOfUpdates; i++) { batchArgs.add(new int[] { i + 1, i + 11 }); } int[][] result = this.jdbcTemplate.batchUpdate(SINGLE_ROW_SQL, batchArgs, customBatchSize, new SingleRowParameterizedPreparedStatementSetter()); assertThat(result, RowCountPerBatchMatcher.matchesBatchedRowCounts(customBatchSize, nrOfUpdates)); } @Test public void updateInompleteBatchWithParameterizedPssEmptyArgList() { int customBatchSize = 5; int[][] result = this.jdbcTemplate.batchUpdate( SINGLE_ROW_SQL, Collections.<int[]>emptyList(), customBatchSize, new SingleRowParameterizedPreparedStatementSetter()); assertThat(result, RowCountPerBatchMatcher.matchesBatchedRowCounts(customBatchSize, 0)); } static class SingleRowPreparedStatementSetter implements BatchPreparedStatementSetter { private final int[] parameters; public SingleRowPreparedStatementSetter(int numberOfRows) { this.parameters = new int[numberOfRows]; for (int i = 0; i < numberOfRows; i++) { this.parameters[i] = i + 1; } } @Override public void setValues(PreparedStatement ps, int i) throws SQLException { StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, 42); StatementCreatorUtils.setParameterValue(ps, 2, SqlTypeValue.TYPE_UNKNOWN, this.parameters[i]); } @Override public int getBatchSize() { return this.parameters.length; } } static class SingleRowInterruptiblePreparedStatementSetter extends AbstractInterruptibleBatchPreparedStatementSetter { private final int[] parameters; public SingleRowInterruptiblePreparedStatementSetter(int numberOfRows) { this.parameters = new int[numberOfRows]; for (int i = 0; i < numberOfRows; i++) { this.parameters[i] = i + 1; } } @Override protected boolean setValuesIfAvailable(PreparedStatement ps, int i) throws SQLException { if (i >= this.parameters.length) { return false; } StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, 42); StatementCreatorUtils.setParameterValue(ps, 2, SqlTypeValue.TYPE_UNKNOWN, this.parameters[i]); return true; } } static class SingleRowParameterizedPreparedStatementSetter implements ParameterizedPreparedStatementSetter<int[]> { @Override public void setValues(PreparedStatement ps, int[] argument) throws SQLException { for (int i = 0; i < argument.length; i++) { StatementCreatorUtils.setParameterValue(ps, i + 1, SqlTypeValue.TYPE_UNKNOWN, argument[i]); } } } }
package hudson.model; import hudson.ExtensionPoint; import hudson.Util; import hudson.scm.ChangeLogSet.Entry; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.util.DescriptorList; import hudson.util.RunList; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import javax.servlet.ServletException; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.text.ParseException; /** * Encapsulates the rendering of the list of {@link TopLevelItem}s * that {@link Hudson} owns. * * <p> * This is an extension point in Hudson, allowing different kind of * rendering to be added as plugins. * * <h2>Note for implementors</h2> * <ul> * <li> * {@link View} subtypes need the <tt>newViewDetail.jelly</tt> page, * which is included in the "new view" page. This page should have some * description of what the view is about. * </ul> * * @author Kohsuke Kawaguchi * @see ViewDescriptor * @see ViewGroup */ @ExportedBean public abstract class View extends AbstractModelObject implements AccessControlled, Describable<View>, ExtensionPoint { /** * Container of this view. Set right after the construction * and never change thereafter. */ protected /*final*/ ViewGroup owner; /** * Name of this view. */ protected String name; /** * Message displayed in the view page. */ protected String description; protected View(String name) { this.name = name; } /** * Gets all the items in this collection in a read-only view. */ @Exported(name="jobs") public abstract Collection<TopLevelItem> getItems(); /** * Gets the {@link TopLevelItem} of the given name. */ public TopLevelItem getItem(String name) { return Hudson.getInstance().getItem(name); } /** * Alias for {@link #getItem(String)}. This is the one used in the URL binding. */ public final TopLevelItem getJob(String name) { return getItem(name); } /** * Checks if the job is in this collection. */ public abstract boolean contains(TopLevelItem item); /** * Gets the name of all this collection. * * @see #rename(String) */ @Exported(visibility=2,name="name") public String getViewName() { return name; } /** * Renames this view. */ public void rename(String newName) throws ParseException { if(name.equals(newName)) return; // noop Hudson.checkGoodName(newName); String oldName = name; name = newName; owner.onViewRenamed(this,oldName,newName); } /** * Gets the {@link ViewGroup} that this view belongs to. */ public ViewGroup getOwner() { return owner; } /** * Message displayed in the top page. Can be null. Includes HTML. */ @Exported public String getDescription() { return description; } public abstract ViewDescriptor getDescriptor(); public String getDisplayName() { return getViewName(); } /** * If true, this is a view that renders the top page of Hudson. */ public boolean isDefault() { return Hudson.getInstance().getPrimaryView()==this; } /** * Returns the path relative to the context root. * * Doesn't start with '/' but ends with '/'. (except when this is * Hudson, */ public String getUrl() { if(isDefault()) return ""; return owner.getUrl()+"view/"+getViewName()+'/'; } public String getSearchUrl() { return getUrl(); } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * If views don't want to show top-level actions, this method * can be overridden to return different objects. * * @see Hudson#getActions() */ public List<Action> getActions() { return Hudson.getInstance().getActions(); } /** * Gets the absolute URL of this view. */ @Exported(visibility=2,name="url") public String getAbsoluteUrl() { return Stapler.getCurrentRequest().getRootPath()+'/'+getUrl(); } public Api getApi() { return new Api(this); } /** * Returns the page to redirect the user to, after the view is created. * * The returned string is appended to "/view/foobar/", so for example * to direct the user to the top page of the view, return "", etc. */ public String getPostConstructLandingPage() { return "configure"; } /** * Returns the {@link ACL} for this object. */ public ACL getACL() { return Hudson.getInstance().getAuthorizationStrategy().getACL(this); } public void checkPermission(Permission p) { getACL().checkPermission(p); } public boolean hasPermission(Permission p) { return getACL().hasPermission(p); } /** * Called when a job name is changed or deleted. * * <p> * If this view contains this job, it should update the view membership so that * the renamed job will remain in the view, and the deleted job is removed. * * @param item * The item whose name is being changed. * @param oldName * Old name of the item. Always non-null. * @param newName * New name of the item, if the item is renamed. Or null, if the item is removed. */ public abstract void onJobRenamed(Item item, String oldName, String newName); @ExportedBean(defaultVisibility=2) public static final class UserInfo implements Comparable<UserInfo> { private final User user; /** * When did this user made a last commit on any of our projects? Can be null. */ private Calendar lastChange; /** * Which project did this user commit? Can be null. */ private AbstractProject project; UserInfo(User user, AbstractProject p, Calendar lastChange) { this.user = user; this.project = p; this.lastChange = lastChange; } @Exported public User getUser() { return user; } @Exported public Calendar getLastChange() { return lastChange; } @Exported public AbstractProject getProject() { return project; } /** * Returns a human-readable string representation of when this user was last active. */ public String getLastChangeTimeString() { if(lastChange==null) return "N/A"; long duration = new GregorianCalendar().getTimeInMillis()- ordinal(); return Util.getTimeSpanString(duration); } public String getTimeSortKey() { if(lastChange==null) return "-"; return Util.XS_DATETIME_FORMATTER.format(lastChange.getTime()); } public int compareTo(UserInfo that) { long rhs = that.ordinal(); long lhs = this.ordinal(); if(rhs>lhs) return 1; if(rhs<lhs) return -1; return 0; } private long ordinal() { if(lastChange==null) return 0; return lastChange.getTimeInMillis(); } } /** * Does this {@link View} has any associated user information recorded? */ public final boolean hasPeople() { return People.isApplicable(getItems()); } /** * Gets the users that show up in the changelog of this job collection. */ public final People getPeople() { return new People(this); } @ExportedBean public static final class People { @Exported public final List<UserInfo> users; public final Object parent; public People(Hudson parent) { this.parent = parent; // for Hudson, really load all users Map<User,UserInfo> users = new HashMap<User,UserInfo>(); User unknown = User.getUnknown(); for(User u : User.getAll()) { if(u==unknown) continue; // skip the special 'unknown' user UserInfo info = users.get(u); if(info==null) users.put(u,new UserInfo(u,null,null)); } this.users = toList(users); } public People(View parent) { this.parent = parent; Map<User,UserInfo> users = new HashMap<User,UserInfo>(); for (Item item : parent.getItems()) { for (Job job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; for (AbstractBuild<?,?> build : p.getBuilds()) { for (Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); UserInfo info = users.get(user); if(info==null) users.put(user,new UserInfo(user,p,build.getTimestamp())); else if(info.getLastChange().before(build.getTimestamp())) { info.project = p; info.lastChange = build.getTimestamp(); } } } } } } this.users = toList(users); } private List<UserInfo> toList(Map<User,UserInfo> users) { ArrayList<UserInfo> list = new ArrayList<UserInfo>(); list.addAll(users.values()); Collections.sort(list); return Collections.unmodifiableList(list); } public Api getApi() { return new Api(this); } public static boolean isApplicable(Collection<? extends Item> items) { for (Item item : items) { for (Job job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; for (AbstractBuild<?,?> build : p.getBuilds()) { for (Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); if(user!=null) return true; } } } } } return false; } } @Override public SearchIndexBuilder makeSearchIndex() { return super.makeSearchIndex() .add(new CollectionSearchIndex() {// for jobs in the view protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } }); } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(CONFIGURE); req.setCharacterEncoding("UTF-8"); description = req.getParameter("description"); owner.save(); rsp.sendRedirect("."); // go to the top page } /** * Deletes this view. */ public synchronized void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException { checkPermission(DELETE); owner.deleteView(this); rsp.sendRedirect2(req.getContextPath()+"/"); } /** * Creates a new {@link Item} in this collection. * * <p> * This method should call {@link Hudson#doCreateItem(StaplerRequest, StaplerResponse)} * and then add the newly created item to this view. * * @return * null if fails. */ public abstract Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException; public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rss(req, rsp, " all builds", getBuilds()); } public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rss(req, rsp, " failed builds", getBuilds().failureOnly()); } public RunList getBuilds() { return new RunList(this); } private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException { RSS.forwardToRss(getDisplayName()+ suffix, getUrl(), runs.newBuilds(), Run.FEED_ADAPTER, req, rsp ); } public void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { List<Run> lastBuilds = new ArrayList<Run>(); for (TopLevelItem item : getItems()) { if (item instanceof Job) { Job job = (Job) item; Run lb = job.getLastBuild(); if(lb!=null) lastBuilds.add(lb); } } RSS.forwardToRss(getDisplayName()+" last builds only", getUrl(), lastBuilds, Run.FEED_ADAPTER_LATEST, req, rsp ); } /** * A list of available view types. */ public static final DescriptorList<View> LIST = new DescriptorList<View>(); static { LIST.load(ListView.class); LIST.load(AllView.class); LIST.load(MyView.class); } public static final Comparator<View> SORTER = new Comparator<View>() { public int compare(View lhs, View rhs) { return lhs.getViewName().compareTo(rhs.getViewName()); } }; public static final PermissionGroup PERMISSIONS = new PermissionGroup(View.class,Messages._View_Permissions_Title()); public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._View_CreatePermission_Description(), Permission.CREATE); public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._View_DeletePermission_Description(), Permission.DELETE); public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._View_ConfigurePermission_Description(), Permission.CONFIGURE); // to simplify access from Jelly public static Permission getItemCreatePermission() { return Item.CREATE; } }
package com.rehivetech.beeeon.activity.fragment; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.melnykov.fab.FloatingActionButton; import com.rehivetech.beeeon.Constants; import com.rehivetech.beeeon.R; import com.rehivetech.beeeon.activity.AddAdapterActivity; import com.rehivetech.beeeon.activity.AddSensorActivity; import com.rehivetech.beeeon.activity.MainActivity; import com.rehivetech.beeeon.activity.SensorDetailActivity; import com.rehivetech.beeeon.activity.listItem.LocationListItem; import com.rehivetech.beeeon.activity.listItem.SensorListItem; import com.rehivetech.beeeon.adapter.Adapter; import com.rehivetech.beeeon.adapter.device.Device; import com.rehivetech.beeeon.adapter.device.Facility; import com.rehivetech.beeeon.adapter.location.Location; import com.rehivetech.beeeon.arrayadapter.SenListAdapter; import com.rehivetech.beeeon.asynctask.CallbackTask.CallbackTaskListener; import com.rehivetech.beeeon.asynctask.ReloadFacilitiesTask; import com.rehivetech.beeeon.asynctask.RemoveFacilityTask; import com.rehivetech.beeeon.controller.Controller; import com.rehivetech.beeeon.pair.DelFacilityPair; import com.rehivetech.beeeon.util.Log; import com.rehivetech.beeeon.util.TutorialHelper; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; public class SensorListFragment extends Fragment { private static final String TAG = SensorListFragment.class.getSimpleName(); private static final String LCTN = "lastlocation"; private static final String ADAPTER_ID = "lastAdapterId"; public static boolean ready = false; private SwipeRefreshLayout mSwipeLayout; private MainActivity mActivity; private Controller mController; private ReloadFacilitiesTask mReloadFacilitiesTask; private SenListAdapter mSensorAdapter; private StickyListHeadersListView mSensorList; private FloatingActionButton mFAM; private ArrayList<Integer> mFABMenuIcon = new ArrayList<>(); private ArrayList<String> mFABMenuLabels = new ArrayList<>(); private View mView; private String mActiveLocationId; private String mActiveAdapterId; private boolean isPaused; private ActionMode mMode; // For tutorial private boolean mFirstUseAddAdapter = true; private boolean mFirstUseAddSensor = true; private Device mSelectedItem; private int mSelectedItemPos; private RemoveFacilityTask mRemoveFacilityTask; public SensorListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate()"); ready = false; if (!(getActivity() instanceof MainActivity)) { throw new IllegalStateException("Activity holding SensorListFragment must be MainActivity"); } mActivity = (MainActivity) getActivity(); mController = Controller.getInstance(mActivity); if (savedInstanceState != null) { mActiveLocationId = savedInstanceState.getString(LCTN); mActiveAdapterId = savedInstanceState.getString(ADAPTER_ID); } // Check if tutoril was showed SharedPreferences prefs = mController.getUserSettings(); if (prefs != null) { mFirstUseAddAdapter = prefs.getBoolean(Constants.TUTORIAL_ADD_ADAPTER_SHOWED, true); mFirstUseAddSensor = prefs.getBoolean(Constants.TUTORIAL_ADD_SENSOR_SHOWED, true); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.listofsensors, container, false); redrawDevices(); return mView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated()"); ready = true; // mActivity = (MainActivity) getActivity(); // Init swipe-refreshig layout mSwipeLayout = (SwipeRefreshLayout) mActivity.findViewById(R.id.swipe_container); if (mSwipeLayout == null) { return; } mSwipeLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { Log.d(TAG,"Refreshing list of sensors"); Adapter adapter = mController.getActiveAdapter(); if (adapter == null) { mSwipeLayout.setRefreshing(false); return; } mActivity.redrawMenu(); doReloadFacilitiesTask(adapter.getId()); } }); mSwipeLayout.setColorSchemeColors( R.color.beeeon_primary_cyan, R.color.beeeon_text_color,R.color.beeeon_secundary_pink); } public void onPause() { super.onPause(); Log.d(TAG, "onPause()"); ready = false; if(mMode != null) mMode.finish(); } public void onResume() { super.onResume(); Log.d(TAG, "onResume()"); ready = true; } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); ready = false; if (mReloadFacilitiesTask != null) { mReloadFacilitiesTask.cancel(true); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putString(ADAPTER_ID, mActiveAdapterId); savedInstanceState.putString(LCTN, mActiveLocationId); super.onSaveInstanceState(savedInstanceState); } public boolean redrawDevices() { if (isPaused) { mActivity.setSupportProgressBarIndeterminateVisibility(false); return false; } List<Facility> facilities; List<Location> locations; Log.d(TAG, "LifeCycle: redraw devices list start"); // get UI elements mSwipeLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipe_container); mSensorList = (StickyListHeadersListView) mView.findViewById(R.id.listviewofsensors); TextView noItem = (TextView) mView.findViewById(R.id.nosensorlistview); Button refreshBtn = (Button) mView.findViewById(R.id.sensor_list_refresh_btn); refreshBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Adapter adapter = mController.getActiveAdapter(); doReloadFacilitiesTask(adapter.getId()); } }); mSensorAdapter = new SenListAdapter(mActivity); mFAM = (FloatingActionButton) mView.findViewById(R.id.fab); // All locations on adapter locations = mController.getLocations(mActiveAdapterId); List<Device> devices = new ArrayList<Device>(); for (Location loc : locations) { mSensorAdapter.addHeader(new LocationListItem(loc.getName(),loc.getIconResource(),loc.getId())); // all facilities from actual location facilities = mController.getFacilitiesByLocation(mActiveAdapterId,loc.getId()); for(Facility fac : facilities) { for(int x = 0; x < fac.getDevices().size(); x++) { Device dev = fac.getDevices().get(x); mSensorAdapter.addItem(new SensorListItem(dev,dev.getId(),mActivity,(x==(fac.getDevices().size()-1))?true:false)); } devices.addAll(fac.getDevices()); } } if (mSensorList == null) { mActivity.setSupportProgressBarIndeterminateVisibility(false); Log.e(TAG, "LifeCycle: bad timing or what?"); return false; // TODO: this happens when we're in different activity // (detail), fix that by changing that activity // (fragment?) first? } boolean haveDevices = devices.size() > 0; boolean haveAdapters = mController.getAdapters().size() > 0; // Buttons in floating menu if(!haveAdapters) { // NO Adapter // Set right visibility noItem.setVisibility(View.VISIBLE); noItem.setText(R.string.no_adapter_cap); refreshBtn.setVisibility(View.VISIBLE); mSensorList.setVisibility(View.GONE); if (mSwipeLayout != null) mSwipeLayout.setVisibility(View.GONE); // FAB mFABMenuIcon.add(R.drawable.ic_add_white_24dp); mFABMenuLabels.add(mActivity.getString(R.string.action_addadapter)); SharedPreferences prefs = mController.getUserSettings(); if (!(prefs != null && !prefs.getBoolean(Constants.PERSISTENCE_PREF_IGNORE_NO_ADAPTER, false))) { // TUTORIAL if(mFirstUseAddAdapter && !mController.isDemoMode()) { mFirstUseAddAdapter = false; mActivity.getMenu().closeMenu(); TutorialHelper.showAddAdapterTutorial(mActivity, mView); if (prefs != null) { prefs.edit().putBoolean(Constants.TUTORIAL_ADD_ADAPTER_SHOWED, false).commit(); } } } } else if (!haveDevices) { // Have Adapter but any Devices // Set right visibility noItem.setVisibility(View.VISIBLE); refreshBtn.setVisibility(View.VISIBLE); mSensorList.setVisibility(View.GONE); if (mSwipeLayout != null) mSwipeLayout.setVisibility(View.GONE); // FAB mFABMenuIcon.add(R.drawable.ic_add_white_24dp); mFABMenuIcon.add(R.drawable.ic_add_white_24dp); mFABMenuLabels.add(mActivity.getString(R.string.action_addadapter)); mFABMenuLabels.add(mActivity.getString(R.string.action_addsensor)); if(mFirstUseAddSensor && !mController.isDemoMode()){ mFirstUseAddSensor = false; mActivity.getMenu().closeMenu(); TutorialHelper.showAddSensorTutorial(mActivity, mView); SharedPreferences prefs = mController.getUserSettings(); if (prefs != null) { prefs.edit().putBoolean(Constants.TUTORIAL_ADD_SENSOR_SHOWED, false).commit(); } } } else { // Have adapter and devices noItem.setVisibility(View.GONE); refreshBtn.setVisibility(View.GONE); mSensorList.setVisibility(View.VISIBLE); if (mSwipeLayout != null) mSwipeLayout.setVisibility(View.VISIBLE); // FAB mFABMenuIcon.add(R.drawable.ic_add_white_24dp); mFABMenuIcon.add(R.drawable.ic_add_white_24dp); mFABMenuLabels.add(mActivity.getString(R.string.action_addadapter)); mFABMenuLabels.add(mActivity.getString(R.string.action_addsensor)); } // Listener for add dialogs OnClickListener fabMenuListener = new OnClickListener() { @Override public void onClick(View v) { if (mFABMenuLabels.get(v.getId()).equals(mActivity.getString(R.string.action_addsensor))) { showAddSensorDialog(); } else if (mFABMenuLabels.get(v.getId()).equals(mActivity.getString(R.string.action_addadapter))) { showAddAdapterDialog(); } Log.d(TAG, "FAB MENU HERE " + v.getId()); } }; mFAM.setMenuItems(convertToInt(mFABMenuIcon), mFABMenuLabels.toArray(new String[mFABMenuLabels.size()]), R.style.fab_item_menu,fabMenuListener, getResources().getDrawable(R.drawable.ic_action_cancel)); mFAM.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d(TAG,"FAB BTN HER"); mFAM.triggerMenu(90); } }); mSensorList.setAdapter(mSensorAdapter); mFAM.attachToListView(mSensorList.getWrappedList()); if (haveDevices) { // Capture listview menu item click mSensorList.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Device device = mSensorAdapter.getDevice(position); Bundle bundle = new Bundle(); bundle.putString(SensorDetailActivity.EXTRA_ADAPTER_ID, device.getFacility().getAdapterId()); bundle.putString(SensorDetailActivity.EXTRA_DEVICE_ID, device.getId()); Intent intent = new Intent(mActivity, SensorDetailActivity.class); intent.putExtras(bundle); startActivity(intent); } }); Adapter tmpAda = mController.getAdapter(mActiveAdapterId); if(tmpAda != null) { if(mController.isUserAllowed(tmpAda.getRole())) { mSensorList.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { mMode = ((ActionBarActivity) getActivity()).startSupportActionMode(new ActionModeEditSensors()); mSelectedItem = mSensorAdapter.getDevice(position); mSelectedItemPos = position; mSensorAdapter.getItem(mSelectedItemPos).setIsSelected(); return true; } }); } } } mActivity.setSupportProgressBarIndeterminateVisibility(false); Log.d(TAG, "LifeCycle: getsensors end"); return true; } private int[] convertToInt(ArrayList<Integer> IntegerList) { int s = IntegerList.size(); int[] intArray = new int[s]; for (int i = 0; i < s; i++) { intArray[i] = IntegerList.get(i).intValue(); } return intArray; } protected void showAddAdapterDialog() { Log.d(TAG, "HERE ADD ADAPTER +"); Intent intent = new Intent(mActivity, AddAdapterActivity.class); mActivity.startActivityForResult(intent, Constants.ADD_ADAPTER_REQUEST_CODE); } protected void showAddSensorDialog() { Log.d(TAG, "HERE ADD SENSOR +"); Intent intent = new Intent(mActivity, AddSensorActivity.class); mActivity.startActivityForResult(intent, Constants.ADD_SENSOR_REQUEST_CODE); } public void setMenuID(String locID) { mActiveLocationId = locID; } public void setAdapterID(String adaID) { mActiveAdapterId = adaID; } public void setIsPaused(boolean value) { isPaused = value; } private void doReloadFacilitiesTask(String adapterId) { mReloadFacilitiesTask = new ReloadFacilitiesTask(getActivity().getApplicationContext(), true); mReloadFacilitiesTask.setListener(new CallbackTaskListener() { @Override public void onExecute(boolean success) { mActivity.redrawMainFragment(); mActivity.redrawMenu(); mSwipeLayout.setRefreshing(false); } }); mReloadFacilitiesTask.execute(adapterId); } private void doRemoveFacilityTask(Facility facility) { mRemoveFacilityTask = new RemoveFacilityTask(getActivity().getApplicationContext(),true); DelFacilityPair pair = new DelFacilityPair(facility.getId(), facility.getAdapterId()); mRemoveFacilityTask.setListener(new CallbackTaskListener() { @Override public void onExecute(boolean success) { mActivity.redrawMainFragment(); mActivity.redrawMenu(); if(success) { // Hlaska o uspechu } else { // Hlaska o neuspechu } } }); mRemoveFacilityTask.execute(pair); } class ActionModeEditSensors implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sensorlist_actionmode, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { if (item.getItemId() == R.id.sensor_menu_del) { doRemoveFacilityTask(mSelectedItem.getFacility()); } mode.finish(); return true; } @Override public void onDestroyActionMode(ActionMode mode) { mSensorAdapter.getItem(mSelectedItemPos).setNotSelected(); mSelectedItem = null; mSelectedItemPos = 0; mMode = null; } } }
package com.aayaffe.sailingracecoursemanager.db; import android.content.Context; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.aayaffe.sailingracecoursemanager.events.Event; import com.aayaffe.sailingracecoursemanager.R; import com.aayaffe.sailingracecoursemanager.Users.User; import com.aayaffe.sailingracecoursemanager.Users.Users; import com.aayaffe.sailingracecoursemanager.calclayer.DBObject; import com.aayaffe.sailingracecoursemanager.geographical.AviLocation; import com.aayaffe.sailingracecoursemanager.initializinglayer.Boat; import com.aayaffe.sailingracecoursemanager.initializinglayer.RaceCourseDescription.RaceCourseDescriptor; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserInfo; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import org.jetbrains.annotations.Contract; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; public class FirebaseDB implements IDBManager { private static final String TAG = "FirebaseDB"; public static DatabaseReference fb; public static DataSnapshot ds; private static Event currentEvent; private EventDeleted eventDeleted; private final Context c; private String uid; private final Users users; public final List<CommManagerEventListener> listeneres = new ArrayList<>(); private boolean connected = false; private static FirebaseDB db; public static FirebaseDB getInstance(Context c){ if (db==null){ db = new FirebaseDB(c); } return db; } private FirebaseDB(Context c) { this.c = c; Users.Init(this, PreferenceManager.getDefaultSharedPreferences(c)); users = Users.getInstance(); } @Override public int login() { return 0; } public void setUser() { FirebaseAuth auth = FirebaseAuth.getInstance(); setUser(auth.getCurrentUser()); } public void setUser(FirebaseUser user) { if (user != null) { uid = user.getUid(); Log.d(TAG, "Uid " + getLoggedInUid() + " Is logged in."); if (findUser(uid) == null) { String displayName; try { displayName = getDisplayName(user); } catch (Exception e) { Log.e(TAG, "Error getting display name", e); displayName = "User" + new Random().nextInt(10000); } Users.setCurrentUser(uid, displayName); } Users.setCurrentUser(findUser(uid)); } else { uid = null; Users.setCurrentUser(null); Log.d(TAG, "User has logged out."); } } @Override public void setCommManagerEventListener(CommManagerEventListener listener) { this.listeneres.add(listener); } @Override public int writeBoatObject(DBObject o) { if (o == null || o.userUid == null || o.userUid.isEmpty() || currentEvent == null) return -1; if (isEventExist(currentEvent)) { getEventDBRef(currentEvent).child(c.getString(R.string.db_boats)).child(o.userUid).setValue(o); Log.v(TAG, "writeBoatObject has written boat:" + o.getName()); return 0; } return -1; } private DatabaseReference getEventDBRef(Event e){ return fb.child(c.getString(R.string.db_events)).child(e.getUuid()); } @Contract("null -> false") private boolean isEventExist(Event e) { return !(e == null || e.getUuid() == null) && ds.child(c.getString(R.string.db_events)).hasChild(e.getUuid()); } @Override public int writeBuoyObject(DBObject o) { if (o == null || o.getUUID() == null || currentEvent == null) return -1; if (isEventExist(currentEvent)) { getEventDBRef(currentEvent).child(c.getString(R.string.db_buoys)).child(o.getUuidString()).setValue(o); getEventDBRef(currentEvent).child(c.getString(R.string.db_lastbuoyid)).setValue(o.id); Log.d("FirebaseDB class", "writeBuoyObject has written buoy:" + o.toString()); return 0; } return -1; } @Override public int updateBoatLocation(Event e, DBObject boat, AviLocation loc) { if (loc == null) return -1; if (isBoatExist(e, boat)) { getEventDBRef(e).child(c.getString(R.string.db_boats)).child(boat.userUid).child("aviLocation").setValue(loc); return 0; } return -1; } @Contract("null, _ -> false") private boolean isBoatExist(Event e, DBObject boat) { return !(e == null || !isEventExist(e.getUuid())) && !(boat == null || boat.getUUID() == null) && ds.child(c.getString(R.string.db_events)).child(e.getUuid()).child(c.getString(R.string.db_boats)).hasChild(boat.userUid); //TODO: Decide to use ds or getEventDBREF()? } @Contract("null -> false") private boolean isEventExist(String uuid) { return !(uuid == null || uuid.isEmpty()) && ds.child(c.getString(R.string.db_events)).hasChild(uuid); } @Override public List<DBObject> getAllBoats() { ArrayList<DBObject> ret = new ArrayList<>(); if (ds == null || ds.getValue() == null || currentEvent == null) return ret; for (DataSnapshot ps : ds.child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child(c.getString(R.string.db_boats)).getChildren()) { DBObject o = ps.getValue(DBObject.class); ret.add(o); } return ret; } @Override public List<DBObject> getAllBuoys() { ArrayList<DBObject> ret = new ArrayList<>(); if (ds == null || ds.getValue() == null || currentEvent == null) return ret; for (DataSnapshot ps : ds.child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child(c.getString(R.string.db_buoys)).getChildren()) { DBObject o = ps.getValue(DBObject.class); ret.add(o); } return ret; } @Override public long getNewBuoyId() { if (ds == null || ds.getValue() == null || currentEvent == null) return 1; Long id = (Long) ds.child(c.getString(R.string.db_events)).child(getCurrentEvent().getUuid()).child(c.getString(R.string.db_lastbuoyid)).getValue(); if (id != null) { return id + 1; } else return 1; } @Override public void removeBuoyObject(String uuid) { getEventDBRef(currentEvent).child(c.getString(R.string.db_buoys)).child(uuid).removeValue(); } @Override @Nullable public User findUser(String uid) { if (uid == null || ds == null) return null; try { User u; u = ds.child(c.getString(R.string.db_users)).child(uid).getValue(User.class); return u; } catch (Exception e) { Log.e(TAG, "Error finding user", e); return null; } } @Override public void addUser(User u) { if (u == null) return; if (fb!=null) fb.child(c.getString(R.string.db_users)).child(u.Uid).setValue(u); } @Override public void logout() { FirebaseAuth.getInstance().signOut(); uid = null; } /** * Returns the first event with the name eventName. * null if no event with this name found. * * @param eventName * @return the first event with the name eventName. * null if no event with this name found. */ @Override public Event getEvent(String eventName) { try { for (DataSnapshot ps : ds.child(c.getString(R.string.db_events)).getChildren()) { Event e = ps.getValue(Event.class); if (e.getName().equals(eventName)) return e; } return null; } catch (Exception ex) { Log.e(TAG, "Failed to get Event: " + eventName, ex); return null; } } @Override public long getSupportedVersion() { if (ds == null || ds.getValue() == null) return -1; return (long) ds.child(c.getString(R.string.db_compatible_version)).getValue(); } @Override public DBObject getObjectByUUID(UUID u) { for (DBObject b : getAllBoats()) { if (b.getUUID().equals(u)) return b; } for (DBObject b : getAllBuoys()) { if (b.getUUID().equals(u)) return b; } return null; } @Override public void writeEvent(Event neu) { getEventDBRef(neu).setValue(neu); } @Override public Event getCurrentEvent() { return currentEvent; } @Override public void setCurrentEvent(Event e) { FirebaseDB.currentEvent = e; } @Override public List<DBObject> getAssignedBuoys(DBObject b) { ArrayList<DBObject> ret = new ArrayList<>(); if (b == null || b.userUid == null) return ret; if (ds == null || ds.getValue() == null || currentEvent == null) return ret; Map<String,List<String>> as = (HashMap<String,List<String>>)ds.child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child("Assignments").getValue(); if (as!=null) { List<String> buoys = as.get(b.userUid); if (buoys!=null) { for (String uuid : buoys) { if (uuid != null) { DBObject buoy = getBuoy(uuid); if (buoy != null) ret.add(buoy); } } } } return ret; } @Override public List<DBObject> getAssignedBoats(DBObject b) { ArrayList<DBObject> ret = new ArrayList<>(); if (b == null || b.userUid == null) return ret; if (ds == null || ds.getValue() == null || currentEvent == null) return ret; Map<String,List<String>> as = (HashMap<String,List<String>>)ds.child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child("Assignments").getValue(); if (as!=null) { for (String userUid : as.keySet()) { if (userUid != null) { List<String> buoys = as.get(userUid); if (buoys.contains(b.getUuidString())) { DBObject boat = getBoat(userUid); if (boat != null) ret.add(boat); } } } } return ret; } @Override public void assignBuoy(DBObject boat, String uuid) { if (ds == null || ds.getValue() == null || currentEvent == null) return; DBObject buoy = getBuoy(uuid); if (buoy == null) { Log.e(TAG, "Error finding buoy for assignment"); return; } removeAssignments(boat); removeAssignments(buoy); for (DBObject b : getAssignedBoats(buoy)) { removeAssignment(buoy, b); removeAssignments(b); } for (DBObject b : getAssignedBuoys(boat)) { removeAssignment(b, boat); removeAssignments(b); } List<String> buoysUUID = new ArrayList<>(); buoysUUID.add(uuid); getEventDBRef(currentEvent).child("Assignments").child(boat.userUid).setValue(buoysUUID); } @Override public void removeAssignment(DBObject buoy, DBObject boat) { List<DBObject> buoys = getAssignedBuoys(boat); if (buoys!=null) buoys.remove(buoy); List<String> buoysUUID = new ArrayList<>(); for(DBObject b: buoys){ if ((b!=null)&&(b.getUuidString()!=null)){ buoysUUID.add(b.getUuidString()); } } getEventDBRef(currentEvent).child("Assignments").child(boat.userUid).setValue(buoysUUID); } @Override public void removeAssignments(DBObject b) { for (DBObject o : getAssignedBuoys(b)) { removeAssignment(o, b); } for (DBObject o : getAssignedBoats(b)) { removeAssignment(b, o); } } @Override public DBObject getBoat(String uuid) { if (ds == null || ds.getValue() == null || currentEvent == null || uuid == null || uuid.isEmpty()) return null; return ds.child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child(c.getString(R.string.db_boats)).child(uuid).getValue(DBObject.class); } @Override public DBObject getBoatByUserUid(String uid){ for (DBObject ao : getAllBoats()) { if (isOwnObject(uid, ao)) { return ao; } } return null; } private boolean isOwnObject(String uid, DBObject o) { return o != null && o.userUid!=null && o.userUid.equals(uid); } @Override public List<Boat> getBoatTypes() { ArrayList<Boat> ret = new ArrayList<>(); if (ds == null || ds.getValue() == null) return ret; for (DataSnapshot ps : ds.child(c.getString(R.string.db_boattypes)).getChildren()) { Boat b = ps.getValue(Boat.class); ret.add(b); } return ret; } @Override public void removeBoat(UUID u) { getEventDBRef(currentEvent).child(c.getString(R.string.db_boats)).child(getObjectByUUID(u).userUid).removeValue(); } @Override public void deleteEvent(Event e) { getEventDBRef(e).removeValue(); } @Override public void addRaceCourseDescriptor(RaceCourseDescriptor ct) { fb.child(c.getString(R.string.db_race_course_descriptors)).child(ct.name).setValue(ct); } @Override public List<RaceCourseDescriptor> getRaceCourseDescriptors() { List<RaceCourseDescriptor> ret = new ArrayList<>(); if (ds == null || ds.getValue() == null) return ret; for (DataSnapshot ps : ds.child(c.getString(R.string.db_race_course_descriptors)).getChildren()) { RaceCourseDescriptor b = ps.getValue(RaceCourseDescriptor.class); ret.add(b); } return ret; } @Override public boolean isAdmin(User u) { return u != null && ds.child(c.getString(R.string.db_admins)).hasChild(u.Uid); } @Override public synchronized void removeCommManagerEventListener(CommManagerEventListener onConnectEventListener) { if (listeneres != null) listeneres.remove(onConnectEventListener); } /*** * * @return the Uid of the currently logged in user. * Null if not logged in */ @Override public String getLoggedInUid() { return uid; } private String getDisplayName(FirebaseUser user) { String displayName = user.getDisplayName(); String email = user.getEmail(); // If the above were null, iterate the provider data // and set with the first non null data for (UserInfo userInfo : user.getProviderData()) { if (displayName == null && userInfo.getDisplayName() != null) { displayName = userInfo.getDisplayName(); } if (email == null && userInfo.getEmail() != null) { email = userInfo.getEmail(); } } if (displayName == null) return convertToAcceptableDisplayName(email); return displayName; } /*** * FirebaseDB does not accept emails in the database path (i.e. '.' are not allowed) * There for we will convert to a better display name * @param email * @return email's user name only without '.', '#', '$', '[', or ']' */ @NonNull private String convertToAcceptableDisplayName(String email) { if (email == null) return null; String e = email; e = e.replace('.', ' '); e = e.replace(' e = e.replace('$', ' '); e = e.replace('[', ' '); e = e.replace(']', ' '); int index = e.indexOf('@'); return e.substring(0, index); } @Override public User findUser(UUID uid) { return findUser(uid.toString()); } @Override public DatabaseReference getEventBoatsReference() { return getFireBaseRef().child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child(c.getString(R.string.db_boats)); } @Override public DatabaseReference getFireBaseRef() { return fb; } @Override public DatabaseReference getEventBuoysReference() { return getFireBaseRef().child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child(c.getString(R.string.db_buoys)); } @Override public DBObject getBuoy(String uuid) { if (ds == null || ds.getValue() == null || currentEvent == null) return null; return ds.child(c.getString(R.string.db_events)).child(currentEvent.getUuid()).child(c.getString(R.string.db_buoys)).child(uuid).getValue(DBObject.class); } @Override public void subscribeToEventDeletion(final Event e, boolean subscribe) { if (e == null) { return; } ValueEventListener valeventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() == null && eventDeleted != null) { eventDeleted.onEventDeleted(e); } } @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "EventDeleted:onCancelled", databaseError.toException()); } }; if (e.getUuid() != null) { if (subscribe) { getEventDBRef(e).child(c.getString(R.string.db_uuid)).addValueEventListener(valeventListener); } else { getEventDBRef(e).child(c.getString(R.string.db_uuid)).removeEventListener(valeventListener); } } } @Override public void writeLeaveEvent(User currentUser, Event currentEvent) { if (currentEvent == null || currentUser == null) { return; } DBObject boat = null; for (DBObject o : getAllBoats()) { if ((o.userUid!=null)&&(o.userUid.equals(currentUser.Uid))) { boat = o; break; } } if (boat != null) { boat.setLeftEvent(new Date()); } writeBoatObject(boat); } public interface EventDeleted { void onEventDeleted(Event e); } public void setEventDeleted(EventDeleted eventDeleted) { this.eventDeleted = eventDeleted; } }
package com.williammora.openfeed.activities; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.williammora.openfeed.R; import com.williammora.openfeed.fragments.StatusFragment; public class StatusActivity extends Activity { public static final String EXTRA_STATUS = "EXTRA_STATUS"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_status); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new StatusFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
package edu.illinois.cs465.parkingpterodactyl; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import java.util.LinkedList; public class MainActivity extends AppCompatActivity { Toolbar toolbar; DrawerLayout drawerLayout; ActionBarDrawerToggle actionBarDrawerToggle; FragmentTransaction fragmentTransaction; NavigationView navigationView; LinkedList<Message> messages; LinkedList<ParkingLocations> selectedParkingLocations; // TODO - Come up with a cleaner way to do this. // Variables keeping track of whether or not the overlays have been seen Boolean messageBoardOverlaySeen; Boolean parkingSeen; Boolean mapOverlaySeen; // TODO - this really shouldn't be done this way either... String lastSearch; // Filter variables ParkingLocations.carSize currentCarSize; LinkedList<ParkingLocations.parkingType> allowedParkingTypes; // List of all parking locations LinkedList<ParkingLocations> allParkingLocations; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Help Overlay Code final View topLevelLayout = findViewById(R.id.top_layout); topLevelLayout.setVisibility(View.VISIBLE); topLevelLayout.setOnTouchListener(new View.OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { topLevelLayout.setVisibility(View.INVISIBLE); return false; } }); messageBoardOverlaySeen = false; parkingSeen=false; mapOverlaySeen=false; lastSearch = "Zach"; toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close); drawerLayout.addDrawerListener(actionBarDrawerToggle); fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.main_container, new HomeFragment()); fragmentTransaction.commit(); getSupportActionBar().setTitle("Parking Pterodactyl"); navigationView = (NavigationView)findViewById(R.id.navigation_view); // Create fake starting messages messages = new LinkedList<>(); messages.add(new Message("There is a lot of parking left at the lot on the corner of Springfield and Gregory.")); //create linked list for parking locations allParkingLocations = new LinkedList<>(); //fake parking locations allParkingLocations.add(new ParkingLocations("The Union", 40.109400, -88.230400, ParkingLocations.carSize.SMALL, ParkingLocations.parkingType.STREET)); allParkingLocations.add(new ParkingLocations("Meters on sixth street", 40.111200, -88.232050, ParkingLocations.carSize.LARGE, ParkingLocations.parkingType.STREET)); allParkingLocations.add(new ParkingLocations("Grainger Library", 40.110790, -88.229032, ParkingLocations.carSize.EXTRA_LARGE, ParkingLocations.parkingType.FREE)); selectedParkingLocations = (LinkedList) allParkingLocations.clone(); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch(item.getItemId()){ case R.id.home_id: fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.main_container, new HomeFragment()); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); item.setChecked(true); drawerLayout.closeDrawers(); break; case R.id.messages_id: fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.main_container, new MessageBoardFragment()); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); item.setChecked(true); drawerLayout.closeDrawers(); break; } return true; } }); } @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); actionBarDrawerToggle.syncState(); } }
package fr.ydelouis.selfoss.account; import android.accounts.AccountAuthenticatorActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.CheckedChange; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.EditorAction; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.SystemService; import org.androidannotations.annotations.TextChange; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.androidannotations.annotations.rest.RestService; import java.io.IOException; import fr.ydelouis.selfoss.R; import fr.ydelouis.selfoss.adapter.SyncPeriodAdapter; import fr.ydelouis.selfoss.entity.Success; import fr.ydelouis.selfoss.rest.SelfossRest; import fr.ydelouis.selfoss.sync.SyncManager; import fr.ydelouis.selfoss.sync.SyncPeriod; @EActivity(R.layout.activity_selfossaccount) public class SelfossAccountActivity extends AccountAuthenticatorActivity { private static final long TIME_TO_CLOSE = 1500; @Bean protected SelfossAccount account; @Bean protected SyncManager syncManager; @RestService protected SelfossRest selfossRest; @SystemService protected InputMethodManager inputMethodManager; @ViewById protected EditText url; @ViewById protected CheckBox requireAuth; @ViewById protected View usernamePasswordContainer; @ViewById protected EditText username; @ViewById protected EditText password; @ViewById protected Spinner period; @ViewById protected View validate; @ViewById protected View progress; @ViewById protected TextView validateText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); } @AfterViews protected void updateUi() { url.setText(getDisplayedUrl()); requireAuth.setChecked(account.requireAuth()); username.setText(getDisplayedUsername()); password.setText(account.getPassword()); period.setAdapter(new SyncPeriodAdapter(this)); period.setSelection(SyncPeriod.indexOf(account.getSyncPeriod())); } private String getDisplayedUrl() { String url = account.getUrl(); if (account.requireAuth() != account.useHttps()) { if (account.useHttps()) { url = "https://" + url; } else { url = "http://" + url; } } return url; } private String getDisplayedUsername() { String url = account.getUrl(); String username = account.getUsername(); return url.equals(username) ? "" : username; } @CheckedChange(R.id.requireAuth) protected void onProtectedStateChange(boolean isChecked) { usernamePasswordContainer.setVisibility(isChecked ? View.VISIBLE : View.GONE); } @Click(R.id.validate) @EditorAction(R.id.password) protected void onValidate() { hydrate(); showProgress(); tryLogin(); } private void hydrate() { String url = this.url.getText().toString(); boolean useHttps = useHttps(url); url = removeScheme(url); url = removeTrailingSlash(url); long syncPeriod = SyncPeriod.values()[period.getSelectedItemPosition()].getTime(); if (requireAuth.isChecked()) { String username = this.username.getText().toString(); String password = this.password.getText().toString(); account.create(url, username, password, useHttps, syncPeriod); } else { account.create(url, useHttps, syncPeriod); } account.setTrustAllCertificates(false); } private boolean useHttps(String url) { if (url.startsWith("https: return true; } else if (url.startsWith("http: return false; } else { return requireAuth.isChecked(); } } private String removeScheme(String url) { String schemeMark = ": int start = url.indexOf(schemeMark); if (start != -1) { return url.substring(start+schemeMark.length()); } return url; } private String removeTrailingSlash(String url) { String trailingSlash = "/"; if (url.endsWith(trailingSlash)) { return url.substring(0, url.length()-trailingSlash.length()); } return url; } protected void showProgress() { progress.setVisibility(View.VISIBLE); validateText.setText(R.string.checking); validate.setEnabled(false); inputMethodManager.hideSoftInputFromWindow(url.getWindowToken(), 0); } @Background protected void tryLogin() { try { Success success = selfossRest.login(); handleSuccess(success); } catch (Exception e) { handleException(e); } } private void handleSuccess(Success success) { if (success.isSuccess()) { showSuccess(); quitDelayed(); } else { showUsernamePasswordError(); } } private void handleException(Exception e) { if (isCertificateException(e)) { showCertificateError(); } else { showUrlError(); e.printStackTrace(); } } private boolean isCertificateException(Exception e) { return e.getCause() instanceof IOException && e.getMessage().contains("Hostname") && e.getMessage().contains("was not verified"); } private void hideProgress() { progress.setVisibility(View.GONE); validate.setEnabled(true); validateText.setText(R.string.validate); } @UiThread protected void showSuccess() { progress.setVisibility(View.GONE); validate.setBackgroundResource(R.drawable.bg_button_success); validateText.setText(R.string.success); } @UiThread(delay = TIME_TO_CLOSE) public void quitDelayed() { syncManager.requestSync(); finish(); } @UiThread protected void showUrlError() { showError(); url.setError(getString(R.string.error_url)); } @UiThread protected void showUsernamePasswordError() { showError(); requireAuth.setChecked(true); password.setError(getString(R.string.error_usernamePassword)); } @UiThread protected void showCertificateError() { showError(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.certificate_error); builder.setMessage(getString(R.string.certificate_error_message, account.getUrl())); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { trustAllCertificates(); } }); builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { hideError(); } }); builder.show(); } private void showError() { hideProgress(); validate.setBackgroundResource(R.drawable.bg_button_error); validateText.setText(R.string.error); } @TextChange({ R.id.url, R.id.username, R.id.password }) protected void hideError() { validate.setBackgroundResource(R.drawable.bg_button_default); validateText.setText(R.string.validate); } private void trustAllCertificates() { account.setTrustAllCertificates(true); validate.setBackgroundResource(R.drawable.bg_button_default); showProgress(); tryLogin(); } @OptionsItem(android.R.id.home) protected void quit() { finish(); } }
package me.tankery.app.dynamicsinewave; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.os.SystemClock; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.View; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class DynamicSineWaveView extends View { // Each cycle contains at least 10 points private static final int POINTS_FOR_CYCLE = 10; public static class Wave { public float amplitude; // wave amplitude, relative to view, range from 0 ~ 0.5 public float cycle; // contains how many cycles in scene public float speed; // space per second, relative to view. X means the wave move X times of width per second public Wave(float a, float c, float s) { this.amplitude = a; this.cycle = c; this.speed = s; } public Wave(Wave other) { this.amplitude = other.amplitude; this.cycle = other.cycle; this.speed = other.speed; } } private final List<Wave> waveConfigs = new ArrayList<>(); private final List<Paint> wavePaints = new ArrayList<>(); private final Matrix wavePathScale = new Matrix(); private List<Path> currentPaths = new ArrayList<>(); private Path drawingPath = new Path(); private int viewWidth = 0; private int viewHeight = 0; private float baseWaveAmplitudeFactor = 0.1f; /** * The computation result, a set of wave path can draw. */ private final BlockingQueue<List<Path>> transferPathsQueue = new LinkedBlockingQueue<>(1); /** * animate ticker will set this to true to request further data change. * computer set this to false before compute, after computation, if this still false, * stop and wait for next request, or continue to compute next data change. * * After data change, the computer post a invalidate to redraw. */ private boolean requestFutureChange = false; private final Object requestCondition = new Object(); private long startAnimateTime = 0; private Runnable animateTicker = new Runnable() { public void run() { requestUpdateFrame(); ViewCompat.postOnAnimation(DynamicSineWaveView.this, this); } }; public DynamicSineWaveView(Context context) { super(context); init(); } public DynamicSineWaveView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DynamicSineWaveView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { if (isInEditMode()) { addWave(0.5f, 0.5f, 0, 0, 0); addWave(0.5f, 2.5f, 0, Color.YELLOW, 2); addWave(0.3f, 2f, 0, Color.RED, 2); setBaseWaveAmplitudeFactor(1); tick(); return; } createComputationThread().start(); } /** * Add new wave to the view. * * The first added wave will become the 'base wave', which ignored the color & stroke, and * other wave will multiple with the 'base wave'. * * @param amplitude wave amplitude, relative to view, range from 0 ~ 0.5 * @param cycle contains how many cycles in scene * @param speed space per second, relative to view. X means the wave move X times of width per second * @param color the wave color, ignored when add the 'base wave' * @param stroke wave stroke width, in dimension, ignored when add the 'base wave' * @return wave count (exclude the base wave). */ public int addWave(float amplitude, float cycle, float speed, int color, float stroke) { synchronized (waveConfigs) { waveConfigs.add(new Wave(amplitude, cycle, speed)); } if (waveConfigs.size() > 1) { Paint paint = new Paint(); paint.setColor(color); paint.setStrokeWidth(stroke); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); wavePaints.add(paint); } return wavePaints.size(); } public void clearWave() { synchronized (waveConfigs) { waveConfigs.clear(); } wavePaints.clear(); } public void startAnimation() { startAnimateTime = SystemClock.uptimeMillis(); removeCallbacks(animateTicker); ViewCompat.postOnAnimation(this, animateTicker); } public void stopAnimation() { removeCallbacks(animateTicker); } public void setBaseWaveAmplitudeFactor(float factor) { baseWaveAmplitudeFactor = factor; } public float getBaseWaveAmplitudeFactor() { return baseWaveAmplitudeFactor; } // Update just one frame. public void requestUpdateFrame() { synchronized (requestCondition) { requestFutureChange = true; requestCondition.notify(); } } @Override public void onDraw(Canvas canvas) { if (!transferPathsQueue.isEmpty()) { currentPaths = transferPathsQueue.poll(); if (currentPaths.size() != wavePaints.size()) { throw new RuntimeException("Generated paths size " + currentPaths.size() + " not match the paints size " + wavePaints.size()); } } if (currentPaths.isEmpty()) return; wavePathScale.setScale(viewWidth, viewHeight * baseWaveAmplitudeFactor); wavePathScale.postTranslate(0, viewHeight / 2); for (int i = 0; i < currentPaths.size(); i++) { Path path = currentPaths.get(i); Paint paint = wavePaints.get(i); drawingPath.set(path); drawingPath.transform(wavePathScale); canvas.drawPath(drawingPath, paint); } } @Override public void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); viewWidth = getWidth(); viewHeight = getHeight(); } private Thread createComputationThread() { return new Thread(new Runnable() { @Override public void run() { while (true) { synchronized (requestCondition) { try { if (!requestFutureChange) requestCondition.wait(); if (!requestFutureChange) continue; requestFutureChange = false; } catch (InterruptedException e) { e.printStackTrace(); } } // If tick has new data offered, post a invalidate notify. if (tick()) { postInvalidate(); } } } }); } private boolean tick() { List<Wave> waveList; List<Path> newPaths; synchronized (waveConfigs) { if (waveConfigs.size() < 2) return false; waveList = new ArrayList<>(waveConfigs.size()); newPaths = new ArrayList<>(waveConfigs.size()); for (Wave o : waveConfigs) { waveList.add(new Wave(o)); } } long currentTime = SystemClock.uptimeMillis(); float t = (currentTime - startAnimateTime) / 1000f; float maxCycle = 0; float maxAmplitude = 0; for (int i = 0; i < waveList.size(); i++) { Wave w = waveList.get(i); if (w.cycle > maxCycle) maxCycle = w.cycle; if (w.amplitude > maxAmplitude && i > 0) maxAmplitude = w.amplitude; } int pointCount = (int) (POINTS_FOR_CYCLE * maxCycle); Wave baseWave = waveList.get(0); waveList.remove(0); float normal = baseWave.amplitude / maxAmplitude; List<PointF> baseWavePoints = generateSineWave(baseWave.amplitude, baseWave.cycle, - baseWave.speed * t, pointCount); for (Wave w : waveList) { float space = - w.speed * t; List<PointF> wavePoints = generateSineWave(w.amplitude, w.cycle, space, pointCount); if (wavePoints.size() != baseWavePoints.size()) { throw new RuntimeException("base wave point size " + baseWavePoints.size() + " not match the sub wave point size " + wavePoints.size()); } // multiple up for (int i = 0; i < wavePoints.size(); i++) { PointF p = wavePoints.get(i); PointF base = baseWavePoints.get(i); p.set(p.x, p.y * base.y * normal); } Path path = generatePathForCurve(wavePoints); newPaths.add(path); } // offer the new wave paths & post invalidate to redraw. transferPathsQueue.offer(newPaths); return true; } private List<PointF> generateSineWave(float amplitude, float cycle, float offset, int pointCount) { int count = pointCount; if (count <= 0) count = (int) (POINTS_FOR_CYCLE * cycle); double T = 1. / cycle; double f = 1f / T; List<PointF> points = new ArrayList<>(count); if (count < 2) return points; double dx = 1. / (count - 1); for (double x = 0; x <= 1; x+= dx) { double y = amplitude * Math.sin(2 * Math.PI * f * (x + offset)); points.add(new PointF((float) x, (float) y)); } return points; } private Path generatePathForCurve(List<PointF> points) { Path path = new Path(); if (points.isEmpty()) return path; path.reset(); PointF prevPoint = points.get(0); for (int i = 0; i < points.size(); i++) { PointF point = points.get(i); if (i == 0) { path.moveTo(point.x, point.y); } else { float midX = (prevPoint.x + point.x) / 2; float midY = (prevPoint.y + point.y) / 2; if (i == 1) { path.lineTo(midX, midY); } else { path.quadTo(prevPoint.x, prevPoint.y, midX, midY); } } prevPoint = point; } path.lineTo(prevPoint.x, prevPoint.y); return path; } }
package net.sharermax.m_news.fragment; import android.app.Activity; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import net.sharermax.m_news.R; import net.sharermax.m_news.support.Setting; public class SubscriptionFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { private CheckBoxPreference mStartUpPre; private CheckBoxPreference mHackerPre; private boolean mStartUpEnable; private boolean mHackerEnable; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.subscription); initPreferenceItem(); } private void initPreferenceItem() { mStartUpPre = (CheckBoxPreference)findPreference(Setting.KEY_SUB_STARTUP); mHackerPre = (CheckBoxPreference)findPreference(Setting.KEY_SUB_HACKERNEWS); mStartUpPre.setOnPreferenceChangeListener(this); mHackerPre.setOnPreferenceChangeListener(this); mStartUpEnable = Setting.getInstance(getActivity()).getBoolen(Setting.KEY_SUB_STARTUP, true); mHackerEnable = Setting.getInstance(getActivity()).getBoolen(Setting.KEY_SUB_HACKERNEWS, true); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.getKey().equals(Setting.KEY_SUB_STARTUP) && mStartUpEnable != (boolean)newValue) { getActivity().setResult(Activity.RESULT_OK); return true; } if (preference.getKey().equals(Setting.KEY_SUB_HACKERNEWS) && mHackerEnable != (boolean)newValue) { getActivity().setResult(Activity.RESULT_OK); return true; } getActivity().setResult(Activity.RESULT_CANCELED); return true; } }
package org.openlmis.core.view.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import org.openlmis.core.LMISApp; import org.openlmis.core.R; import org.openlmis.core.manager.SharedPreferenceMgr; import java.util.Set; import roboguice.RoboGuice; import roboguice.inject.InjectView; public class ProductsUpdateBanner extends LinearLayout implements View.OnClickListener { @InjectView(R.id.iv_product_update_banner_clear) View ivClear; @InjectView(R.id.tv_product_update) TextView tvProductUpdate; public ProductsUpdateBanner(Context context) { super(context); init(context); } public ProductsUpdateBanner(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { LayoutInflater.from(context).inflate(R.layout.view_products_update_banner, this); RoboGuice.injectMembers(getContext(), this); RoboGuice.getInjector(getContext()).injectViewMembers(this); if (SharedPreferenceMgr.getInstance().isNeedShowProductsUpdateBanner()) { setVisibility(VISIBLE); setBannerText(); } else { setVisibility(GONE); } if (!LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_show_products_update_banner_529)) { setVisibility(GONE); } } private void setBannerText() { Set<String> showUpdateBannerText = SharedPreferenceMgr.getInstance().getShowUpdateBannerText(); if (showUpdateBannerText.size() == 1) { tvProductUpdate.setText(getContext().getString(R.string.hint_update_banner_tips, showUpdateBannerText.toArray()[0])); } else { tvProductUpdate.setText(getContext().getString(R.string.hint_update_banner_tips, showUpdateBannerText.size() + " Products")); } } @Override protected void onFinishInflate() { super.onFinishInflate(); ivClear.setOnClickListener(this); } @Override public void onClick(View v) { setVisibility(GONE); SharedPreferenceMgr.getInstance().setIsNeedShowProductsUpdateBanner(false, null); } }
package ru.adios.budgeter; import android.os.AsyncTask; import com.google.common.collect.ImmutableList; import org.joda.money.CurrencyUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.util.TreeSet; import java.util.concurrent.ExecutionException; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import java8.util.Optional; import ru.adios.budgeter.api.CurrencyRatesRepository; import ru.adios.budgeter.api.UtcDay; @NotThreadSafe public final class RatesDelegatingBackgroundService implements CurrencyRatesRepository { public interface Callback { void onGetConversionMultiplierBidirectional(Optional<BigDecimal> result); void onGetConversionMultiplierWithIntermediate(Optional<BigDecimal> result); void onGetLatestOptionalConversionMultiplierBidirectional(Optional<BigDecimal> result); void onGetLatestConversionMultiplierWithIntermediate(@Nullable BigDecimal result); void onProcessAllPostponedEvents(); void onGetLatestOptionalConversionMultiplier(Optional<BigDecimal> result); void onGetConversionMultiplier(Optional<BigDecimal> result); void onGetConversionMultiplierStraight(Optional<BigDecimal> result); void onGetLatestConversionMultiplier(@Nullable BigDecimal result); } private static final Logger logger = LoggerFactory.getLogger(RatesDelegatingBackgroundService.class); private final CurrenciesExchangeService exchangeService; private final TreeSet<Callback> callbacksSet = new TreeSet<>(); public RatesDelegatingBackgroundService(CurrenciesExchangeService delegate) { exchangeService = delegate; } public void addCallback(Callback callback) { callbacksSet.add(callback); } public void removeCallback(Callback callback) { callbacksSet.remove(callback); } public void runWithTransaction(final ImmutableList<Runnable> runnables) { exchangeService.runWithTransaction(runnables); } @Override public boolean addTodayRate(CurrencyUnit from, CurrencyUnit to, BigDecimal rate) { return exchangeService.addTodayRate(from, to, rate); } @Override public Optional<BigDecimal> getConversionMultiplierBidirectional(UtcDay day, CurrencyUnit from, CurrencyUnit to) { try { return getConversionMultiplierBidirectionalTask(day, from, to, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getConversionMultiplierBidirectional task exception", e); return Optional.empty(); } } public void doGetConversionMultiplierBidirectional(UtcDay day, CurrencyUnit from, CurrencyUnit to) { getConversionMultiplierBidirectionalTask(day, from, to, true).execute(); } private AsyncTask<Void, Void, Optional<BigDecimal>> getConversionMultiplierBidirectionalTask(final UtcDay day, final CurrencyUnit from, final CurrencyUnit to, final boolean useCallbacks) { return new AsyncTask<Void, Void, Optional<BigDecimal>>() { @Override protected Optional<BigDecimal> doInBackground(Void... params) { return exchangeService.getConversionMultiplierBidirectional(day, from, to); } @Override protected void onPostExecute(Optional<BigDecimal> result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetConversionMultiplierBidirectional(result); } } } }; } @Override public Optional<BigDecimal> getConversionMultiplierWithIntermediate(UtcDay day, CurrencyUnit from, CurrencyUnit to, CurrencyUnit intermediate) { try { return getConversionMultiplierWithIntermediateTask(day, from, to, intermediate, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getConversionMultiplierWithIntermediate task exception", e); return Optional.empty(); } } public void doGetConversionMultiplierWithIntermediate(UtcDay day, CurrencyUnit from, CurrencyUnit to, CurrencyUnit intermediate) { getConversionMultiplierWithIntermediateTask(day, from, to, intermediate, true).execute(); } private AsyncTask<Void, Void, Optional<BigDecimal>> getConversionMultiplierWithIntermediateTask(final UtcDay day, final CurrencyUnit from, final CurrencyUnit to, final CurrencyUnit intermediate, final boolean useCallbacks) { return new AsyncTask<Void, Void, Optional<BigDecimal>>() { @Override protected Optional<BigDecimal> doInBackground(Void... params) { return exchangeService.getConversionMultiplierWithIntermediate(day, from, to, intermediate); } @Override protected void onPostExecute(Optional<BigDecimal> result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetConversionMultiplierWithIntermediate(result); } } } }; } @Override public Optional<BigDecimal> getLatestOptionalConversionMultiplierBidirectional(CurrencyUnit from, CurrencyUnit to) { try { return getLatestOptionalConversionMultiplierBidirectionalTask(from, to, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getLatestOptionalConversionMultiplierBidirectional task exception", e); return Optional.empty(); } } public void doGetLatestOptionalConversionMultiplierBidirectional(CurrencyUnit from, CurrencyUnit to) { getLatestOptionalConversionMultiplierBidirectionalTask(from, to, true).execute(); } private AsyncTask<Void, Void, Optional<BigDecimal>> getLatestOptionalConversionMultiplierBidirectionalTask(final CurrencyUnit from, final CurrencyUnit to, final boolean useCallbacks) { return new AsyncTask<Void, Void, Optional<BigDecimal>>() { @Override protected Optional<BigDecimal> doInBackground(Void... params) { return exchangeService.getLatestOptionalConversionMultiplierBidirectional(from, to); } @Override protected void onPostExecute(Optional<BigDecimal> result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetLatestOptionalConversionMultiplierBidirectional(result); } } } }; } @Nullable @Override public BigDecimal getLatestConversionMultiplierWithIntermediate(CurrencyUnit from, CurrencyUnit to, CurrencyUnit intermediate) { try { return getLatestConversionMultiplierWithIntermediateTask(from, to, intermediate, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getLatestConversionMultiplierWithIntermediate task exception", e); return null; } } public void doGetLatestConversionMultiplierWithIntermediate(CurrencyUnit from, CurrencyUnit to, CurrencyUnit intermediate) { getLatestConversionMultiplierWithIntermediateTask(from, to, intermediate, true).execute(); } private AsyncTask<Void, Void, BigDecimal> getLatestConversionMultiplierWithIntermediateTask(final CurrencyUnit from, final CurrencyUnit to, final CurrencyUnit intermediate, final boolean useCallbacks) { return new AsyncTask<Void, Void, BigDecimal>() { @Override protected BigDecimal doInBackground(Void... params) { try { return exchangeService.getLatestConversionMultiplierWithIntermediate(from, to, intermediate); } catch (RuntimeException ex) { logger.error("Unable to get latest conversion multiplier with intermediate (" + from + ',' + to + ',' + intermediate + ')', ex); return null; } } @Override protected void onPostExecute(@Nullable BigDecimal result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetLatestConversionMultiplierWithIntermediate(result); } } } }; } public void processAllPostponedEvents() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { exchangeService.processAllPostponedEvents(); return null; } @Override protected void onPostExecute(Void aVoid) { for (final Callback c : callbacksSet) { c.onProcessAllPostponedEvents(); } } }.execute(); } @Override public boolean addRate(UtcDay dayUtc, CurrencyUnit from, CurrencyUnit to, BigDecimal rate) { return exchangeService.addRate(dayUtc, from, to, rate); } @Override public Optional<BigDecimal> getLatestOptionalConversionMultiplier(CurrencyUnit from, CurrencyUnit to) { try { return getLatestOptionalConversionMultiplierTask(from, to, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getLatestOptionalConversionMultiplier task exception", e); return null; } } public void doGetLatestOptionalConversionMultiplier(CurrencyUnit from, CurrencyUnit to) { getLatestOptionalConversionMultiplierTask(from, to, true).execute(); } private AsyncTask<Void, Void, Optional<BigDecimal>> getLatestOptionalConversionMultiplierTask(final CurrencyUnit from, final CurrencyUnit to, final boolean useCallbacks) { return new AsyncTask<Void, Void, Optional<BigDecimal>>() { @Override protected Optional<BigDecimal> doInBackground(Void... params) { return exchangeService.getLatestOptionalConversionMultiplier(from, to); } @Override protected void onPostExecute(Optional<BigDecimal> result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetLatestOptionalConversionMultiplier(result); } } } }; } @Override public boolean isRateStale(CurrencyUnit to) { return exchangeService.isRateStale(to); } @Override public Optional<BigDecimal> getConversionMultiplier(UtcDay day, CurrencyUnit from, CurrencyUnit to) { try { return getConversionMultiplierTask(day, from, to, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getConversionMultiplier task exception", e); return null; } } public void doGetConversionMultiplier(UtcDay day, CurrencyUnit from, CurrencyUnit to) { getConversionMultiplierTask(day, from, to, true).execute(); } private AsyncTask<Void, Void, Optional<BigDecimal>> getConversionMultiplierTask(final UtcDay day, final CurrencyUnit from, final CurrencyUnit to, final boolean useCallbacks) { return new AsyncTask<Void, Void, Optional<BigDecimal>>() { @Override protected Optional<BigDecimal> doInBackground(Void... params) { return exchangeService.getConversionMultiplier(day, from, to); } @Override protected void onPostExecute(Optional<BigDecimal> result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetConversionMultiplier(result); } } } }; } @Override public Optional<BigDecimal> getConversionMultiplierStraight(UtcDay day, CurrencyUnit from, CurrencyUnit to) { try { return getConversionMultiplierStraightTask(day, from, to, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getConversionMultiplierStraight task exception", e); return null; } } public void doGetConversionMultiplierStraight(UtcDay day, CurrencyUnit from, CurrencyUnit to) { getConversionMultiplierStraightTask(day, from, to, true).execute(); } private AsyncTask<Void, Void, Optional<BigDecimal>> getConversionMultiplierStraightTask(final UtcDay day, final CurrencyUnit from, final CurrencyUnit to, final boolean useCallbacks) { return new AsyncTask<Void, Void, Optional<BigDecimal>>() { @Override protected Optional<BigDecimal> doInBackground(Void... params) { return exchangeService.getConversionMultiplierStraight(day, from, to); } @Override protected void onPostExecute(Optional<BigDecimal> result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetConversionMultiplierStraight(result); } } } }; } @Override @Nullable public BigDecimal getLatestConversionMultiplier(CurrencyUnit from, CurrencyUnit to) { try { return getLatestConversionMultiplierTask(from, to, false).execute().get(); } catch (InterruptedException | ExecutionException e) { logger.error("getConversionMultiplierStraight task exception", e); return null; } } public void doGetLatestConversionMultiplier(CurrencyUnit from, CurrencyUnit to) { getLatestConversionMultiplierTask(from, to, true).execute(); } private AsyncTask<Void, Void, BigDecimal> getLatestConversionMultiplierTask(final CurrencyUnit from, final CurrencyUnit to, final boolean useCallbacks) { return new AsyncTask<Void, Void, BigDecimal>() { @Override protected BigDecimal doInBackground(Void... params) { try { return exchangeService.getLatestConversionMultiplier(from, to); } catch (RuntimeException ex) { logger.error("Unable to get latest conversion multiplier (" + from + ',' + to + ')', ex); return null; } } @Override protected void onPostExecute(@Nullable BigDecimal result) { if (useCallbacks) { for (final Callback c : callbacksSet) { c.onGetLatestConversionMultiplier(result); } } } }; } public static abstract class EmptyCallback implements Callback { @Override public void onGetConversionMultiplierBidirectional(Optional<BigDecimal> result) {} @Override public void onGetConversionMultiplierWithIntermediate(Optional<BigDecimal> result) {} @Override public void onGetLatestOptionalConversionMultiplierBidirectional(Optional<BigDecimal> result) {} @Override public void onGetLatestConversionMultiplierWithIntermediate(@Nullable BigDecimal result) {} @Override public void onProcessAllPostponedEvents() {} @Override public void onGetLatestOptionalConversionMultiplier(Optional<BigDecimal> result) {} @Override public void onGetConversionMultiplier(Optional<BigDecimal> result) {} @Override public void onGetConversionMultiplierStraight(Optional<BigDecimal> result) {} @Override public void onGetLatestConversionMultiplier(@Nullable BigDecimal result) {} } }
package sword.langbook3.android; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.SparseArray; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static sword.langbook3.android.DbManager.idColumnName; public class AcceptationDetailsActivity extends Activity { private static final class BundleKeys { static final String STATIC_ACCEPTATION = "sa"; static final String DYNAMIC_ACCEPTATION = "da"; } // Specifies the alphabet the user would like to see if possible. // TODO: This should be a shared preference private static final int preferredAlphabet = 4; public static void open(Context context, int staticAcceptation, int dynamicAcceptation) { Intent intent = new Intent(context, AcceptationDetailsActivity.class); intent.putExtra(BundleKeys.STATIC_ACCEPTATION, staticAcceptation); intent.putExtra(BundleKeys.DYNAMIC_ACCEPTATION, dynamicAcceptation); context.startActivity(intent); } private List<SparseArray<String>> readCorrelationArray(SQLiteDatabase db, int acceptation) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.CorrelationArraysTable correlationArrays = DbManager.Tables.correlationArrays; final DbManager.CorrelationsTable correlations = DbManager.Tables.correlations; final DbManager.SymbolArraysTable symbolArrays = DbManager.Tables.symbolArrays; Cursor cursor = db.rawQuery( "SELECT" + " J1." + correlationArrays.getColumnName(correlationArrays.getArrayPositionColumnIndex()) + ",J2." + correlations.getColumnName(correlations.getAlphabetColumnIndex()) + ",J3." + symbolArrays.getColumnName(symbolArrays.getStrColumnIndex()) + " FROM " + acceptations.getName() + " AS J0" + " JOIN " + correlationArrays.getName() + " AS J1 ON J0." + acceptations.getColumnName(acceptations.getCorrelationArrayColumnIndex()) + "=J1." + correlationArrays.getColumnName(correlationArrays.getArrayIdColumnIndex()) + " JOIN " + correlations.getName() + " AS J2 ON J1." + correlationArrays.getColumnName(correlationArrays.getCorrelationColumnIndex()) + "=J2." + correlations.getColumnName(correlations.getCorrelationIdColumnIndex()) + " JOIN " + symbolArrays.getName() + " AS J3 ON J2." + correlations.getColumnName(correlations.getSymbolArrayColumnIndex()) + "=J3." + idColumnName + " WHERE J0." + idColumnName + "=?" + " ORDER BY" + " J1." + correlationArrays.getColumnName(correlationArrays.getArrayPositionColumnIndex()) + ",J2." + correlations.getColumnName(correlations.getAlphabetColumnIndex()) , new String[] { Integer.toString(acceptation) }); final ArrayList<SparseArray<String>> result = new ArrayList<>(); if (cursor != null) { try { if (cursor.moveToFirst()) { SparseArray<String> corr = new SparseArray<>(); int pos = cursor.getInt(0); if (pos != result.size()) { throw new AssertionError("Expected position " + result.size() + ", but it was " + pos); } corr.put(cursor.getInt(1), cursor.getString(2)); while(cursor.moveToNext()) { int newPos = cursor.getInt(0); if (newPos != pos) { result.add(corr); corr = new SparseArray<>(); } pos = newPos; if (newPos != result.size()) { throw new AssertionError("Expected position " + result.size() + ", but it was " + pos); } corr.put(cursor.getInt(1), cursor.getString(2)); } result.add(corr); } } finally { cursor.close(); } } return result; } private String readLanguage(SQLiteDatabase db, int language) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J1." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + ",J1." + strings.getColumnName(strings.getStringColumnIndex()) + " FROM " + acceptations.getName() + " AS J0" + " JOIN " + strings.getName() + " AS J1 ON J0." + idColumnName + "=J1." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " WHERE J0." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + "=?", new String[] { Integer.toString(language) }); String text = null; try { cursor.moveToFirst(); int firstAlphabet = cursor.getInt(0); text = cursor.getString(1); while (firstAlphabet != preferredAlphabet && cursor.moveToNext()) { if (cursor.getInt(0) == preferredAlphabet) { firstAlphabet = preferredAlphabet; text = cursor.getString(1); } } } finally { cursor.close(); } return text; } private static final class LanguageResult { final int acceptation; final int language; final String text; LanguageResult(int acceptation, int language, String text) { this.acceptation = acceptation; this.language = language; this.text = text; } } private LanguageResult readLanguageFromAlphabet(SQLiteDatabase db, int alphabet) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.AlphabetsTable alphabets = DbManager.Tables.alphabets; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J1." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + ",J1." + idColumnName + ",J2." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + ",J2." + strings.getColumnName(strings.getStringColumnIndex()) + " FROM " + alphabets.getName() + " AS J0" + " JOIN " + acceptations.getName() + " AS J1 ON J0." + alphabets.getColumnName(alphabets.getLanguageColumnIndex()) + "=J1." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + " JOIN " + strings.getName() + " AS J2 ON J1." + idColumnName + "=J2." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(alphabet) }); int lang = -1; int langAcc = -1; String text = null; try { cursor.moveToFirst(); lang = cursor.getInt(0); langAcc = cursor.getInt(1); int firstAlphabet = cursor.getInt(2); text = cursor.getString(3); while (firstAlphabet != preferredAlphabet && cursor.moveToNext()) { if (cursor.getInt(2) == preferredAlphabet) { lang = cursor.getInt(0); langAcc = cursor.getInt(1); firstAlphabet = preferredAlphabet; text = cursor.getString(3); } } } finally { cursor.close(); } return new LanguageResult(langAcc, lang, text); } private static final class AcceptationResult { final int acceptation; final String text; AcceptationResult(int acceptation, String text) { this.acceptation = acceptation; this.text = text; } } private AcceptationResult readDefinition(SQLiteDatabase db, int acceptation) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.BunchConceptsTable bunchConcepts = DbManager.Tables.bunchConcepts; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J2." + idColumnName + ",J3." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + ",J3." + strings.getColumnName(strings.getStringColumnIndex()) + " FROM " + acceptations.getName() + " AS J0" + " JOIN " + bunchConcepts.getName() + " AS J1 ON J0." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + "=J1." + bunchConcepts.getColumnName(bunchConcepts.getConceptColumnIndex()) + " JOIN " + acceptations.getName() + " AS J2 ON J1." + bunchConcepts.getColumnName(bunchConcepts.getBunchColumnIndex()) + "=J2." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + " JOIN " + strings.getName() + " AS J3 ON J2." + idColumnName + "=J3." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(acceptation) }); AcceptationResult result = null; if (cursor != null) { try { if (cursor.moveToFirst()) { int acc = cursor.getInt(0); int firstAlphabet = cursor.getInt(1); String text = cursor.getString(2); while (firstAlphabet != preferredAlphabet && cursor.moveToNext()) { if (cursor.getInt(1) == preferredAlphabet) { acc = cursor.getInt(0); text = cursor.getString(2); break; } } result = new AcceptationResult(acc, text); } } finally { cursor.close(); } } return result; } private AcceptationResult[] readSubTypes(SQLiteDatabase db, int acceptation, int language) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.AlphabetsTable alphabets = DbManager.Tables.alphabets; final DbManager.BunchConceptsTable bunchConcepts = DbManager.Tables.bunchConcepts; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J2." + idColumnName + ",J3." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + ",J3." + strings.getColumnName(strings.getStringColumnIndex()) + " FROM " + acceptations.getName() + " AS J0" + " JOIN " + bunchConcepts.getName() + " AS J1 ON J0." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + "=J1." + bunchConcepts.getColumnName(bunchConcepts.getBunchColumnIndex()) + " JOIN " + acceptations.getName() + " AS J2 ON J1." + bunchConcepts.getColumnName(bunchConcepts.getConceptColumnIndex()) + "=J2." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + " JOIN " + strings.getName() + " AS J3 ON J2." + idColumnName + "=J3." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " JOIN " + alphabets.getName() + " AS J4 ON J3." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + "=J4." + idColumnName + " WHERE J0." + idColumnName + "=?" + " AND J4." + alphabets.getColumnName(alphabets.getLanguageColumnIndex()) + "=?" + " ORDER BY J2." + idColumnName, new String[] { Integer.toString(acceptation), Integer.toString(language) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final ArrayList<AcceptationResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int alphabet = cursor.getInt(1); String text = cursor.getString(2); while (cursor.moveToNext()) { if (cursor.getInt(0) == acc) { if (alphabet != preferredAlphabet && cursor.getInt(1) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(2); } } else { result.add(new AcceptationResult(acc, text)); acc = cursor.getInt(0); alphabet = cursor.getInt(1); text = cursor.getString(2); } } result.add(new AcceptationResult(acc, text)); return result.toArray(new AcceptationResult[result.size()]); } } finally { cursor.close(); } } return new AcceptationResult[0]; } private static final class BunchInclusionResult { final int acceptation; final boolean dynamic; final String text; BunchInclusionResult(int acceptation, boolean dynamic, String text) { this.acceptation = acceptation; this.dynamic = dynamic; this.text = text; } } private BunchInclusionResult[] readBunchesWhereIncluded(SQLiteDatabase db, int acceptation) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.BunchAcceptationsTable bunchAcceptations = DbManager.Tables.bunchAcceptations; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J0." + bunchAcceptations.getColumnName(bunchAcceptations.getBunchColumnIndex()) + ",J1." + idColumnName + ",J2." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + ",J2." + strings.getColumnName(strings.getStringColumnIndex()) + ",J0." + bunchAcceptations.getColumnName(bunchAcceptations.getAgentSetColumnIndex()) + " FROM " + bunchAcceptations.getName() + " AS J0" + " JOIN " + acceptations.getName() + " AS J1 ON J0." + bunchAcceptations.getColumnName(bunchAcceptations.getBunchColumnIndex()) + "=J1." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + " JOIN " + strings.getName() + " AS J2 ON J1." + idColumnName + "=J2." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " WHERE J0." + bunchAcceptations.getColumnName(bunchAcceptations.getAcceptationColumnIndex()) + "=?", new String[] { Integer.toString(acceptation) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final int nullAgentSet = DbManager.Tables.agentSets.nullReference(); ArrayList<BunchInclusionResult> result = new ArrayList<>(); int bunch = cursor.getInt(0); int acc = cursor.getInt(1); int firstAlphabet = cursor.getInt(2); String text = cursor.getString(3); int agentSet = cursor.getInt(4); while (cursor.moveToNext()) { if (firstAlphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { acc = cursor.getInt(1); text = cursor.getString(3); firstAlphabet = preferredAlphabet; } if (bunch != cursor.getInt(0)) { result.add(new BunchInclusionResult(acc, agentSet != nullAgentSet, text)); bunch = cursor.getInt(0); agentSet = cursor.getInt(4); acc = cursor.getInt(1); firstAlphabet = cursor.getInt(2); text = cursor.getString(3); } } result.add(new BunchInclusionResult(acc, agentSet != nullAgentSet, text)); return result.toArray(new BunchInclusionResult[result.size()]); } } finally { cursor.close(); } } return new BunchInclusionResult[0]; } private static final class BunchChildResult { final int acceptation; final boolean dynamic; final String text; BunchChildResult(int acceptation, boolean dynamic, String text) { this.acceptation = acceptation; this.dynamic = dynamic; this.text = text; } } private BunchChildResult[] readBunchChildren(SQLiteDatabase db, int acceptation) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.BunchAcceptationsTable bunchAcceptations = DbManager.Tables.bunchAcceptations; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J1." + bunchAcceptations.getColumnName(bunchAcceptations.getAcceptationColumnIndex()) + ",J2." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + ",J2." + strings.getColumnName(strings.getStringColumnIndex()) + ",J1." + bunchAcceptations.getColumnName(bunchAcceptations.getAgentSetColumnIndex()) + " FROM " + acceptations.getName() + " AS J0" + " JOIN " + bunchAcceptations.getName() + " AS J1 ON J0." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + "=J1." + bunchAcceptations.getColumnName(bunchAcceptations.getBunchColumnIndex()) + " JOIN " + strings.getName() + " AS J2 ON J1." + bunchAcceptations.getColumnName(bunchAcceptations.getAcceptationColumnIndex()) + "=J2." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " WHERE J0." + idColumnName + "=?" + " ORDER BY J1." + bunchAcceptations.getColumnName(bunchAcceptations.getAcceptationColumnIndex()), new String[] { Integer.toString(acceptation) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final int nullAgentSet = DbManager.Tables.agentSets.nullReference(); ArrayList<BunchChildResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int alphabet = cursor.getInt(1); String text = cursor.getString(2); int agentSet = cursor.getInt(3); while (cursor.moveToNext()) { if (acc == cursor.getInt(0)) { if (alphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(2); } } else { result.add(new BunchChildResult(acc, agentSet != nullAgentSet, text)); acc = cursor.getInt(0); alphabet = cursor.getInt(1); text = cursor.getString(2); agentSet = cursor.getInt(3); } } result.add(new BunchChildResult(acc, agentSet != nullAgentSet, text)); return result.toArray(new BunchChildResult[result.size()]); } } finally { cursor.close(); } } return new BunchChildResult[0]; } private static final class SynonymTranslationResult { final int acceptation; final int language; final String text; SynonymTranslationResult(int acceptation, int language, String text) { this.acceptation = acceptation; this.language = language; this.text = text; } } private SynonymTranslationResult[] readSynonymsAndTranslations(SQLiteDatabase db, int acceptation) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.AlphabetsTable alphabets = DbManager.Tables.alphabets; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; final DbManager.LanguagesTable languages = DbManager.Tables.languages; Cursor cursor = db.rawQuery( "SELECT" + " J1." + idColumnName + ",J4." + idColumnName + ",J2." + strings.getColumnName(strings.getStringColumnIndex()) + " FROM " + acceptations.getName() + " AS J0" + " JOIN " + acceptations.getName() + " AS J1 ON J0." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + "=J1." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + " JOIN " + strings.getName() + " AS J2 ON J1." + idColumnName + "=J2." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " JOIN " + alphabets.getName() + " AS J3 ON J2." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + "=J3." + idColumnName + " JOIN " + languages.getName() + " AS J4 ON J3." + alphabets.getColumnName(alphabets.getLanguageColumnIndex()) + "=J4." + idColumnName + " WHERE J0." + idColumnName + "=?" + " AND J0." + acceptations.getColumnName(acceptations.getWordColumnIndex()) + "!=J1." + acceptations.getColumnName(acceptations.getWordColumnIndex()) + " AND J3." + idColumnName + "=J4." + languages.getColumnName(languages.getMainAlphabetColumnIndex()), new String[] { Integer.toString(acceptation) }); SynonymTranslationResult[] result = null; if (cursor != null) { try { result = new SynonymTranslationResult[cursor.getCount()]; if (cursor.moveToFirst()) { int index = 0; do { result[index++] = new SynonymTranslationResult(cursor.getInt(0), cursor.getInt(1), cursor.getString(2)); } while (cursor.moveToNext()); } } finally { cursor.close(); } } else { result = new SynonymTranslationResult[0]; } return result; } private static final class MorphologyResult { final int dynamicAcceptation; final int rule; final String ruleText; final String text; MorphologyResult(int dynamicAcceptation, int rule, String ruleText, String text) { this.dynamicAcceptation = dynamicAcceptation; this.rule = rule; this.ruleText = ruleText; this.text = text; } } private MorphologyResult[] readMorphologies(SQLiteDatabase db, int acceptation) { final DbManager.AcceptationsTable acceptations = DbManager.Tables.acceptations; final DbManager.StringQueriesTable strings = DbManager.Tables.stringQueries; final DbManager.RuledConceptsTable ruledConcepts = DbManager.Tables.ruledConcepts; Cursor cursor = db.rawQuery( "SELECT" + " J2." + idColumnName + ",J4." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + ",J3." + strings.getColumnName(strings.getStringColumnIndex()) + ",J5." + strings.getColumnName(strings.getStringAlphabetColumnIndex()) + ",J5." + strings.getColumnName(strings.getStringColumnIndex()) + " FROM " + acceptations.getName() + " AS J0" + " JOIN " + ruledConcepts.getName() + " AS J1 ON J0." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + "=J1." + ruledConcepts.getColumnName(ruledConcepts.getConceptColumnIndex()) + " JOIN " + acceptations.getName() + " AS J2 ON J1." + idColumnName + "=J2." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + " JOIN " + strings.getName() + " AS J3 ON J2." + idColumnName + "=J3." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " JOIN " + acceptations.getName() + " AS J4 ON J1." + ruledConcepts.getColumnName(ruledConcepts.getRuleColumnIndex()) + "=J4." + acceptations.getColumnName(acceptations.getConceptColumnIndex()) + " JOIN " + strings.getName() + " AS J5 ON J4." + idColumnName + "=J5." + strings.getColumnName(strings.getDynamicAcceptationColumnIndex()) + " WHERE J0." + idColumnName + "=?" + " AND J3." + strings.getColumnName(strings.getMainAcceptationColumnIndex()) + "=?" + " ORDER BY J2." + idColumnName, new String[] { Integer.toString(acceptation) , Integer.toString(acceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { ArrayList<MorphologyResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int rule = cursor.getInt(1); String text = cursor.getString(2); int alphabet = cursor.getInt(3); String ruleText = cursor.getString(4); while (cursor.moveToNext()) { if (cursor.getInt(0) == acc) { if (alphabet != preferredAlphabet && cursor.getInt(3) == preferredAlphabet) { alphabet = preferredAlphabet; ruleText = cursor.getString(4); } } else { result.add(new MorphologyResult(acc, rule, ruleText, text)); acc = cursor.getInt(0); rule = cursor.getInt(1); text = cursor.getString(2); alphabet = cursor.getInt(3); ruleText = cursor.getString(4); } } result.add(new MorphologyResult(acc, rule, ruleText, text)); return result.toArray(new MorphologyResult[result.size()]); } } finally { cursor.close(); } } return new MorphologyResult[0]; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acceptation_details_activity); if (!getIntent().hasExtra(BundleKeys.STATIC_ACCEPTATION)) { throw new IllegalArgumentException("staticAcceptation not provided"); } final int staticAcceptation = getIntent().getIntExtra(BundleKeys.STATIC_ACCEPTATION, 0); DbManager dbManager = new DbManager(this); SQLiteDatabase db = dbManager.getReadableDatabase(); final StringBuilder sb = new StringBuilder("Displaying details for acceptation ") .append(staticAcceptation) .append("\n * Correlation: "); List<SparseArray<String>> correlationArray = readCorrelationArray(db, staticAcceptation); for (int i = 0; i < correlationArray.size(); i++) { if (i != 0) { sb.append(" - "); } final SparseArray<String> correlation = correlationArray.get(i); for (int j = 0; j < correlation.size(); j++) { if (j != 0) { sb.append('/'); } sb.append(correlation.valueAt(j)); } } final LanguageResult languageResult = readLanguageFromAlphabet(db, correlationArray.get(0).keyAt(0)); sb.append("\n * Language: ").append(languageResult.text); final SparseArray<String> languageStrs = new SparseArray<>(); languageStrs.put(languageResult.language, languageResult.text); final AcceptationResult definition = readDefinition(db, staticAcceptation); if (definition != null) { sb.append("\n * Type of: ").append(definition.text); } boolean subTypeFound = false; for (AcceptationResult subType : readSubTypes(db, staticAcceptation, languageResult.language)) { if (!subTypeFound) { sb.append("\n * Subtypes:"); subTypeFound = true; } sb.append("\n ").append(subType.text); } final SynonymTranslationResult[] synonymTranslationResults = readSynonymsAndTranslations(db, staticAcceptation); boolean synonymFound = false; for (SynonymTranslationResult result : synonymTranslationResults) { if (result.language == languageResult.language) { if (!synonymFound) { sb.append("\n * Synonyms: "); synonymFound = true; } else { sb.append(", "); } sb.append(result.text); } } boolean translationFound = false; for (SynonymTranslationResult result : synonymTranslationResults) { final int language = result.language; if (language != languageResult.language) { if (!translationFound) { sb.append("\n * Translations:"); translationFound = true; } String langStr = languageStrs.get(language); if (langStr == null) { langStr = readLanguage(db, language); languageStrs.put(language, langStr); } sb.append("\n ").append(langStr).append(" -> ").append(result.text); } } boolean parentBunchFound = false; for (BunchInclusionResult result : readBunchesWhereIncluded(db, staticAcceptation)) { if (!parentBunchFound) { sb.append("\n * Bunches where included:"); parentBunchFound = true; } sb.append("\n ").append(result.text); if (result.dynamic) { sb.append(" *"); } } boolean morphologyFound = false; for (MorphologyResult result : readMorphologies(db, staticAcceptation)) { if (!morphologyFound) { sb.append("\n * Morphologies:"); morphologyFound = true; } sb.append("\n ").append(result.ruleText).append(" -> ").append(result.text); } boolean bunchChildFound = false; for (BunchChildResult result : readBunchChildren(db, staticAcceptation)) { if (!bunchChildFound) { sb.append("\n * Acceptations included in this bunch:"); bunchChildFound = true; } sb.append("\n ").append(result.text); if (result.dynamic) { sb.append(" *"); } } final TextView tv = findViewById(R.id.textView); tv.setText(sb.toString()); } }
package com.google.android.stardroid.units; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static junit.framework.Assert.assertEquals; /** * Tests that require roboelectric for API calls. */ @RunWith(RobolectricTestRunner.class) @Config(manifest=Config.NONE) public class LatLongRoboTest { @Test public void latLong_testDistance() { LatLong point1 = new LatLong(0, 0); LatLong point2 = new LatLong(90, 0); assertEquals(90f, point1.distanceFrom(point2)); } @Test public void latLong_testDistance2() { LatLong point1 = new LatLong(45, 45); LatLong point2 = new LatLong(90, 0); assertEquals(45f, point1.distanceFrom(point2), 0.05); } }
package com.example.ssteeve.dpd_android; import android.support.annotation.Nullable; import android.util.Log; import org.json.JSONObject; import java.io.IOException; import java.util.Dictionary; import java.util.Enumeration; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class DPDRequest { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); static void makeRequest(String endpoint, @Nullable Map<String, Object> params, String method, @Nullable String jsonBody, @Nullable Dictionary<String, Object> requestHeader, @Nullable Class mappableObject, RequestCallBack requestCallBack) { String url = DPDConstants.sRootUrl + endpoint; if (params != null && params.size() > 0) { String paramString = new JSONObject(params).toString(); url = url + "?" + paramString; } Request.Builder requestBuilder = new Request.Builder(); requestBuilder.addHeader("Content-Type", "application/json"); requestBuilder.addHeader("Accept-Encoding", "gzip"); if (DPDCredentials.getInstance().getAccessToken() != null) requestBuilder.addHeader("accessToken", DPDCredentials.getInstance().getAccessToken()); if (DPDCredentials.getInstance().getSessionId() != null) requestBuilder.addHeader("Cookie", DPDCredentials.getInstance().getSessionId()); if (requestHeader != null && requestHeader.size() > 0) { for (Enumeration<String> key = requestHeader.keys(); requestHeader.keys().hasMoreElements();) { requestBuilder.addHeader(key.toString(), requestHeader.get(key).toString()); } } Request request; RequestBody body = RequestBody.create(JSON, jsonBody != null ? jsonBody : ""); if (method == HTTPMethod.POST) { request = requestBuilder .url(url) .post(body) .build(); } else if(method == HTTPMethod.PUT) { request = requestBuilder .url(url) .put(body) .build(); } else if (method == HTTPMethod.DELETE) { request = requestBuilder .url(url) .delete(body) .build(); } else { request = requestBuilder .url(url) .build(); } Log.d("DPDRequest", "*********************** URL *********************" + url); if(request.body() != null) { Log.d("DPDRequest", "*********************** HEADERS *********************" + request.headers().toString()); } Log.d("DPDRequest", "*********************** Body *********************" + request.body().toString()); new BackendOperation(DPDConstants.sRootUrl, request, requestBuilder, requestCallBack); } }
package matlab; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class OffsetTracker { private final Map<TextPosition, OffsetChange> offsetChangeMap; public OffsetTracker() { this.offsetChangeMap = new TreeMap<TextPosition, OffsetChange>(); } public void recordOffsetChange(TextPosition pos, int lineOffsetChange, int colOffsetChange) { OffsetChange existingOC = offsetChangeMap.get(pos); OffsetChange newOC = new OffsetChange(lineOffsetChange, colOffsetChange); if(existingOC == null) { offsetChangeMap.put(pos, newOC); } else { existingOC.incorporate(newOC); } } public void recordOffsetChange(int line, int col, int lineOffsetChange, int colOffsetChange) { recordOffsetChange(new TextPosition(line, col), lineOffsetChange, colOffsetChange); } public void recordOffsetChange(int pos, int lineOffsetChange, int colOffsetChange) { recordOffsetChange(new TextPosition(pos), lineOffsetChange, colOffsetChange); } public PositionMap buildPositionMap() { //TODO-AC: verify correctness of map? SortedMap<TextPosition, Offset> offsetMap = new TreeMap<TextPosition, Offset>(); Offset currOffset = new Offset(0, 0); //NB: must iterate in order of increasing position for(Map.Entry<TextPosition, OffsetChange> entry : offsetChangeMap.entrySet()) { currOffset.incorporate(entry.getValue()); offsetMap.put(entry.getKey(), new Offset(currOffset)); } return new OffsetPositionMap(offsetMap); } private static class OffsetChange { int lineOffsetChange; int colOffsetChange; OffsetChange(int lineOffsetChange, int colOffsetChange) { this.lineOffsetChange = lineOffsetChange; this.colOffsetChange = colOffsetChange; } OffsetChange(OffsetChange other) { this(other.lineOffsetChange, other.colOffsetChange); } void incorporate(OffsetChange other) { this.lineOffsetChange += other.lineOffsetChange; this.colOffsetChange += other.colOffsetChange; } } private static class Offset { int lineOffset; int colOffset; Offset(int lineOffset, int colOffset) { this.lineOffset = lineOffset; this.colOffset = colOffset; } Offset(Offset other) { this(other.lineOffset, other.colOffset); } void incorporate(OffsetChange change) { this.lineOffset += change.lineOffsetChange; this.colOffset += change.colOffsetChange; } TextPosition forwardOffset(TextPosition original) { return new TextPosition(original.getLine() + lineOffset, original.getColumn() + colOffset); } TextPosition reverseOffset(TextPosition original) { return new TextPosition(original.getLine() - lineOffset, original.getColumn() - colOffset); } } private static class OffsetPositionMap extends PositionMap { private final SortedMap<TextPosition, Offset> offsetMap; public OffsetPositionMap(SortedMap<TextPosition, Offset> offsetMap) { this.offsetMap = offsetMap; } @Override //TODO-AC: return null if the character has been deleted? public TextPosition sourceToDest(TextPosition source) { Offset offset = null; if(offsetMap.containsKey(source)) { offset = offsetMap.get(source); } else { SortedMap<TextPosition, Offset> headMap = offsetMap.headMap(source); if(headMap.isEmpty()) { offset = new Offset(0, 0); } else { offset = headMap.get(headMap.lastKey()); } } return offset.forwardOffset(source); } @Override //TODO-AC: return null if the character has been added? public TextPosition destToSource(TextPosition dest) { Offset offset = new Offset(0, 0); for(Map.Entry<TextPosition, Offset> entry : offsetMap.entrySet()) { TextPosition sourcePos = entry.getKey(); Offset currOffset = entry.getValue(); TextPosition destPos = currOffset.forwardOffset(sourcePos); int comp = destPos.compareTo(dest); if(comp == 0) { return sourcePos; } else if(comp < 0) { //not there yet offset = currOffset; } else { //too far - use previous, as stored in offset return offset.reverseOffset(dest); } } //stepping off the end is the same as going too far return offset.reverseOffset(dest); } } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.text.ParseException; import java.util.Date; /** * Defines a period of time. A period may be specified as either a start date * and end date, or a start date and duration. NOTE: End dates and durations are * implicitly derived when not explicitly specified. This means that you cannot * rely on the returned values from the getters to deduce whether a period has * an explicit end date or duration. * * @author Ben Fortuna */ public class Period implements Serializable, Comparable { private static final long serialVersionUID = 7321090422911676490L; private DateTime start; private DateTime end; private Dur duration; /** * Constructor. * * @param aValue * a string representation of a period * @throws ParseException * where the specified string is not a valid representation */ public Period(final String aValue) throws ParseException { start = new DateTime(aValue.substring(0, aValue.indexOf('/'))); // period may end in either a date-time or a duration.. try { end = new DateTime(aValue.substring(aValue.indexOf('/') + 1)); } catch (ParseException pe) { // duration = DurationFormat.getInstance().parse(aValue); duration = new Dur(aValue); } } /** * Constructs a new period with the specied start and end date. * * @param start * the start date of the period * @param end * the end date of the period */ public Period(final DateTime start, final DateTime end) { this.start = start; this.end = end; } /** * Constructs a new period with the specified start date and duration. * * @param start * the start date of the period * @param duration * the duration of the period */ public Period(final DateTime start, final Dur duration) { this.start = start; this.duration = duration; } /** * Returns the duration of this period. If an explicit duration is not * specified, the duration is derived from the end date. * * @return the duration of this period in milliseconds. */ public final Dur getDuration() { if (end != null) { return new Dur(start, end); } return duration; } /** * Returns the end date of this period. If an explicit end date is not * specified, the end date is derived from the duration. * * @return the end date of this period. */ public final DateTime getEnd() { if (end == null) { DateTime derived = new DateTime(duration.getTime(start).getTime()); derived.setUtc(start.isUtc()); return derived; } return end; } /** * @return Returns the start. */ public final DateTime getStart() { return start; } /** * Determines if the specified date occurs within this period (inclusive of * period start and end). * @param date * @return true if the specified date occurs within the current period * */ public final boolean includes(final Date date) { return includes(date, true); } /** * Decides whether a date falls within this period. * @param date the date to be tested * @param inclusive specifies whether period start and end are included * in the calculation * @return true if the date is in the perod, false otherwise */ public final boolean includes(final Date date, final boolean inclusive) { if (inclusive) { return (!getStart().after(date) && !getEnd().before(date)); } return (getStart().before(date) && getEnd().after(date)); } /** * Decides whether this period is completed before the given period starts. * * @param period * a period that may or may not start after this period ends * @return true if the specified period starts after this periods ends, * otherwise false */ public final boolean before(final Period period) { return (getEnd().before(period.getStart())); } /** * Decides whether this period starts after the given period ends. * * @param period * a period that may or may not end before this period starts * @return true if the specified period end before this periods starts, * otherwise false */ public final boolean after(final Period period) { return (getStart().after(period.getEnd())); } /** * Decides whether this period intersects with another one. * * @param period * a possible intersecting period * @return true if the specified period intersects this one, false * otherwise. */ public final boolean intersects(final Period period) { // Test for our start date in period // (Exclude if it is the end date of test range) if (period.includes(getStart()) && !period.getEnd().equals(getStart())) { return true; } // Test for test range's start date in our range // (Exclude if it is the end date of our range) else if (includes(period.getStart()) && !getEnd().equals(period.getStart())) { return true; } return false; } /** * Decides whether these periods are serial without a gap. * * @return true if one period immediately follows the other, false otherwise */ public final boolean adjacent(final Period period) { if (getStart().equals(period.getEnd())) { return true; } else if (getEnd().equals(period.getStart())) { return true; } return false; } /** * Decides whether the given period is completely contained within this one. * * @param period * the period that may be contained by this one * @return true if this period covers all the dates of the specified period, * otherwise false */ public final boolean contains(final Period period) { // Test for period's start and end dates in our range return (includes(period.getStart()) && includes(period.getEnd())); } /** * Creates a period that encompasses both this period and another one. If * the other period is null, return a copy of this period. NOTE: Resulting * periods are specified by explicitly setting a start date and end date * (i.e. durations are implied). * * @param period * the period to add to this one * @return a period */ public final Period add(final Period period) { DateTime newPeriodStart = null; DateTime newPeriodEnd = null; if (period == null) { newPeriodStart = getStart(); newPeriodEnd = getEnd(); } else { if (getStart().before(period.getStart())) { newPeriodStart = getStart(); } else { newPeriodStart = period.getStart(); } if (getEnd().after(period.getEnd())) { newPeriodEnd = getEnd(); } else { newPeriodEnd = period.getEnd(); } } return new Period(newPeriodStart, newPeriodEnd); } /** * @see java.lang.Object#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); b.append(start); b.append('/'); if (end != null) { b.append(end); } else { // b.append(DurationFormat.getInstance().format(duration)); b.append(duration); } return b.toString(); } /* * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public final int compareTo(final Object arg0) { return compareTo((Period) arg0); } /** * Compares the specified period with this period. * * @param arg0 * @return */ public final int compareTo(final Period arg0) { // Throws documented exception if type is wrong or parameter is null if (arg0 == null) { throw new ClassCastException("Cannot compare this object to null"); } int startCompare = getStart().compareTo(arg0.getStart()); if (startCompare != 0) { return startCompare; } // start dates are equal, compare end dates.. else if (end != null) { int endCompare = end.compareTo(arg0.getEnd()); if (endCompare != 0) { return endCompare; } } // ..or durations return getDuration().compareTo(arg0.getDuration()); } /** * Overrides the equality test, compares fields of instances for equality. * * @param o * object being compared for equality * @return true if the objects are equal, false otherwise */ public final boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Period)) { return false; } final Period period = (Period) o; if (!getStart().equals(period.getStart())) { return false; } else if (!getEnd().equals(period.getEnd())) { return false; } return true; } /** * Override hashCode() with code that checks fields in this object. * * @return hascode for this object */ public final int hashCode() { int result; result = getStart().hashCode(); result = 29 * result + getEnd().hashCode(); return result; } }
package org.jfree.chart.axis; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.List; import java.util.Locale; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueAxisPlot; import org.jfree.chart.text.TextAnchor; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.Range; import org.jfree.data.RangeType; /** * An axis for displaying numerical data. * <P> * If the axis is set up to automatically determine its range to fit the data, * you can ensure that the range includes zero (statisticians usually prefer * this) by setting the <code>autoRangeIncludesZero</code> flag to * <code>true</code>. * <P> * The <code>NumberAxis</code> class has a mechanism for automatically * selecting a tick unit that is appropriate for the current axis range. This * mechanism is an adaptation of code suggested by Laurence Vanhelsuwe. */ public class NumberAxis extends ValueAxis implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 2805933088476185789L; /** The default value for the autoRangeIncludesZero flag. */ public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true; /** The default value for the autoRangeStickyZero flag. */ public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true; /** The default tick unit. */ public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit( 1.0, new DecimalFormat("0")); /** The default setting for the vertical tick labels flag. */ public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false; /** * The range type (can be used to force the axis to display only positive * values or only negative values). */ private RangeType rangeType; /** * A flag that affects the axis range when the range is determined * automatically. If the auto range does NOT include zero and this flag * is TRUE, then the range is changed to include zero. */ private boolean autoRangeIncludesZero; /** * A flag that affects the size of the margins added to the axis range when * the range is determined automatically. If the value 0 falls within the * margin and this flag is TRUE, then the margin is truncated at zero. */ private boolean autoRangeStickyZero; /** The tick unit for the axis. */ private NumberTickUnit tickUnit; /** The override number format. */ private NumberFormat numberFormatOverride; /** An optional band for marking regions on the axis. */ private MarkerAxisBand markerBand; /** * Default constructor. */ public NumberAxis() { this(null); } /** * Constructs a number axis, using default values where necessary. * * @param label the axis label (<code>null</code> permitted). */ public NumberAxis(String label) { super(label, NumberAxis.createStandardTickUnits()); this.rangeType = RangeType.FULL; this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO; this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO; this.tickUnit = DEFAULT_TICK_UNIT; this.numberFormatOverride = null; this.markerBand = null; } /** * Returns the axis range type. * * @return The axis range type (never <code>null</code>). * * @see #setRangeType(RangeType) */ public RangeType getRangeType() { return this.rangeType; } /** * Sets the axis range type. * * @param rangeType the range type (<code>null</code> not permitted). * * @see #getRangeType() */ public void setRangeType(RangeType rangeType) { if (rangeType == null) { throw new IllegalArgumentException("Null 'rangeType' argument."); } this.rangeType = rangeType; notifyListeners(new AxisChangeEvent(this)); } /** * Returns the flag that indicates whether or not the automatic axis range * (if indeed it is determined automatically) is forced to include zero. * * @return The flag. */ public boolean getAutoRangeIncludesZero() { return this.autoRangeIncludesZero; } /** * Sets the flag that indicates whether or not the axis range, if * automatically calculated, is forced to include zero. * <p> * If the flag is changed to <code>true</code>, the axis range is * recalculated. * <p> * Any change to the flag will trigger an {@link AxisChangeEvent}. * * @param flag the new value of the flag. * * @see #getAutoRangeIncludesZero() */ public void setAutoRangeIncludesZero(boolean flag) { if (this.autoRangeIncludesZero != flag) { this.autoRangeIncludesZero = flag; if (isAutoRange()) { autoAdjustRange(); } notifyListeners(new AxisChangeEvent(this)); } } /** * Returns a flag that affects the auto-range when zero falls outside the * data range but inside the margins defined for the axis. * * @return The flag. * * @see #setAutoRangeStickyZero(boolean) */ public boolean getAutoRangeStickyZero() { return this.autoRangeStickyZero; } /** * Sets a flag that affects the auto-range when zero falls outside the data * range but inside the margins defined for the axis. * * @param flag the new flag. * * @see #getAutoRangeStickyZero() */ public void setAutoRangeStickyZero(boolean flag) { if (this.autoRangeStickyZero != flag) { this.autoRangeStickyZero = flag; if (isAutoRange()) { autoAdjustRange(); } notifyListeners(new AxisChangeEvent(this)); } } /** * Returns the tick unit for the axis. * <p> * Note: if the <code>autoTickUnitSelection</code> flag is * <code>true</code> the tick unit may be changed while the axis is being * drawn, so in that case the return value from this method may be * irrelevant if the method is called before the axis has been drawn. * * @return The tick unit for the axis. * * @see #setTickUnit(NumberTickUnit) * @see ValueAxis#isAutoTickUnitSelection() */ public NumberTickUnit getTickUnit() { return this.tickUnit; } /** * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to * all registered listeners. A side effect of calling this method is that * the "auto-select" feature for tick units is switched off (you can * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)} * method). * * @param unit the new tick unit (<code>null</code> not permitted). * * @see #getTickUnit() * @see #setTickUnit(NumberTickUnit, boolean, boolean) */ public void setTickUnit(NumberTickUnit unit) { // defer argument checking... setTickUnit(unit, true, true); } /** * Sets the tick unit for the axis and, if requested, sends an * {@link AxisChangeEvent} to all registered listeners. In addition, an * option is provided to turn off the "auto-select" feature for tick units * (you can restore it using the * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method). * * @param unit the new tick unit (<code>null</code> not permitted). * @param notify notify listeners? * @param turnOffAutoSelect turn off the auto-tick selection? */ public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect) { if (unit == null) { throw new IllegalArgumentException("Null 'unit' argument."); } this.tickUnit = unit; if (turnOffAutoSelect) { setAutoTickUnitSelection(false, false); } if (notify) { notifyListeners(new AxisChangeEvent(this)); } } /** * Returns the number format override. If this is non-null, then it will * be used to format the numbers on the axis. * * @return The number formatter (possibly <code>null</code>). * * @see #setNumberFormatOverride(NumberFormat) */ public NumberFormat getNumberFormatOverride() { return this.numberFormatOverride; } /** * Sets the number format override. If this is non-null, then it will be * used to format the numbers on the axis. * * @param formatter the number formatter (<code>null</code> permitted). * * @see #getNumberFormatOverride() */ public void setNumberFormatOverride(NumberFormat formatter) { this.numberFormatOverride = formatter; notifyListeners(new AxisChangeEvent(this)); } /** * Returns the (optional) marker band for the axis. * * @return The marker band (possibly <code>null</code>). * * @see #setMarkerBand(MarkerAxisBand) */ public MarkerAxisBand getMarkerBand() { return this.markerBand; } /** * Sets the marker band for the axis. * <P> * The marker band is optional, leave it set to <code>null</code> if you * don't require it. * * @param band the new band (<code>null<code> permitted). * * @see #getMarkerBand() */ public void setMarkerBand(MarkerAxisBand band) { this.markerBand = band; notifyListeners(new AxisChangeEvent(this)); } /** * Configures the axis to work with the specified plot. If the axis has * auto-scaling, then sets the maximum and minimum values. */ public void configure() { if (isAutoRange()) { autoAdjustRange(); } } /** * Rescales the axis to ensure that all data is visible. */ protected void autoAdjustRange() { Plot plot = getPlot(); if (plot == null) { return; // no plot, no data } if (plot instanceof ValueAxisPlot) { ValueAxisPlot vap = (ValueAxisPlot) plot; Range r = vap.getDataRange(this); if (r == null) { r = getDefaultAutoRange(); } double upper = r.getUpperBound(); double lower = r.getLowerBound(); if (this.rangeType == RangeType.POSITIVE) { lower = Math.max(0.0, lower); upper = Math.max(0.0, upper); } else if (this.rangeType == RangeType.NEGATIVE) { lower = Math.min(0.0, lower); upper = Math.min(0.0, upper); } if (getAutoRangeIncludesZero()) { lower = Math.min(lower, 0.0); upper = Math.max(upper, 0.0); } double range = upper - lower; // if fixed auto range, then derive lower bound... double fixedAutoRange = getFixedAutoRange(); if (fixedAutoRange > 0.0) { lower = upper - fixedAutoRange; } else { // ensure the autorange is at least <minRange> in size... double minRange = getAutoRangeMinimumSize(); if (range < minRange) { double expand = (minRange - range) / 2; upper = upper + expand; lower = lower - expand; if (lower == upper) { // see bug report 1549218 double adjust = Math.abs(lower) / 10.0; lower = lower - adjust; upper = upper + adjust; } if (this.rangeType == RangeType.POSITIVE) { if (lower < 0.0) { upper = upper - lower; lower = 0.0; } } else if (this.rangeType == RangeType.NEGATIVE) { if (upper > 0.0) { lower = lower - upper; upper = 0.0; } } } if (getAutoRangeStickyZero()) { if (upper <= 0.0) { upper = Math.min(0.0, upper + getUpperMargin() * range); } else { upper = upper + getUpperMargin() * range; } if (lower >= 0.0) { lower = Math.max(0.0, lower - getLowerMargin() * range); } else { lower = lower - getLowerMargin() * range; } } else { upper = upper + getUpperMargin() * range; lower = lower - getLowerMargin() * range; } } setRange(new Range(lower, upper), false, false); } } /** * Converts a data value to a coordinate in Java2D space, assuming that the * axis runs along one edge of the specified dataArea. * <p> * Note that it is possible for the coordinate to fall outside the plotArea. * * @param value the data value. * @param area the area for plotting the data. * @param edge the axis location. * * @return The Java2D coordinate. * * @see #java2DToValue(double, Rectangle2D, RectangleEdge) */ public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge) { Range range = getRange(); double axisMin = range.getLowerBound(); double axisMax = range.getUpperBound(); double min = 0.0; double max = 0.0; if (RectangleEdge.isTopOrBottom(edge)) { min = area.getX(); max = area.getMaxX(); } else if (RectangleEdge.isLeftOrRight(edge)) { max = area.getMinY(); min = area.getMaxY(); } if (isInverted()) { return max - ((value - axisMin) / (axisMax - axisMin)) * (max - min); } else { return min + ((value - axisMin) / (axisMax - axisMin)) * (max - min); } } /** * Converts a coordinate in Java2D space to the corresponding data value, * assuming that the axis runs along one edge of the specified dataArea. * * @param java2DValue the coordinate in Java2D space. * @param area the area in which the data is plotted. * @param edge the location. * * @return The data value. * * @see #valueToJava2D(double, Rectangle2D, RectangleEdge) */ public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge) { Range range = getRange(); double axisMin = range.getLowerBound(); double axisMax = range.getUpperBound(); double min = 0.0; double max = 0.0; if (RectangleEdge.isTopOrBottom(edge)) { min = area.getX(); max = area.getMaxX(); } else if (RectangleEdge.isLeftOrRight(edge)) { min = area.getMaxY(); max = area.getY(); } if (isInverted()) { return axisMax - (java2DValue - min) / (max - min) * (axisMax - axisMin); } else { return axisMin + (java2DValue - min) / (max - min) * (axisMax - axisMin); } } /** * Calculates the value of the lowest visible tick on the axis. * * @return The value of the lowest visible tick on the axis. * * @see #calculateHighestVisibleTickValue() */ protected double calculateLowestVisibleTickValue() { double unit = getTickUnit().getSize(); double index = Math.ceil(getRange().getLowerBound() / unit); return index * unit; } /** * Calculates the value of the highest visible tick on the axis. * * @return The value of the highest visible tick on the axis. * * @see #calculateLowestVisibleTickValue() */ protected double calculateHighestVisibleTickValue() { double unit = getTickUnit().getSize(); double index = Math.floor(getRange().getUpperBound() / unit); return index * unit; } /** * Calculates the number of visible ticks. * * @return The number of visible ticks on the axis. */ protected int calculateVisibleTickCount() { double unit = getTickUnit().getSize(); Range range = getRange(); return (int) (Math.floor(range.getUpperBound() / unit) - Math.ceil(range.getLowerBound() / unit) + 1); } /** * Draws the axis on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device (<code>null</code> not permitted). * @param cursor the cursor location. * @param plotArea the area within which the axes and data should be drawn * (<code>null</code> not permitted). * @param dataArea the area within which the data should be drawn * (<code>null</code> not permitted). * @param edge the location of the axis (<code>null</code> not permitted). * @param plotState collects information about the plot * (<code>null</code> permitted). * * @return The axis state (never <code>null</code>). */ public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState) { AxisState state = null; // if the axis is not visible, don't draw it... if (!isVisible()) { state = new AxisState(cursor); // even though the axis is not visible, we need ticks for the // gridlines... List ticks = refreshTicks(g2, state, dataArea, edge); state.setTicks(ticks); return state; } // draw the tick marks and labels... state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge, plotState); // // draw the marker band (if there is one)... // if (getMarkerBand() != null) { // if (edge == RectangleEdge.BOTTOM) { // cursor = cursor - getMarkerBand().getHeight(g2); // getMarkerBand().draw(g2, plotArea, dataArea, 0, cursor); // draw the axis label... state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state, plotState); createAndAddEntity(cursor, state, dataArea, edge, plotState); return state; } /** * Creates the standard tick units. * <P> * If you don't like these defaults, create your own instance of TickUnits * and then pass it to the setStandardTickUnits() method in the * NumberAxis class. * * @return The standard tick units. * * @see #setStandardTickUnits(TickUnitSource) * @see #createIntegerTickUnits() */ public static TickUnitSource createStandardTickUnits() { TickUnits units = new TickUnits(); DecimalFormat df000 = new DecimalFormat("0.0000000000"); DecimalFormat df00 = new DecimalFormat("0.000000000"); DecimalFormat df0 = new DecimalFormat("0.00000000"); DecimalFormat df1 = new DecimalFormat("0.0000000"); DecimalFormat df2 = new DecimalFormat("0.000000"); DecimalFormat df3 = new DecimalFormat("0.00000"); DecimalFormat df4 = new DecimalFormat("0.0000"); DecimalFormat df5 = new DecimalFormat("0.000"); DecimalFormat df6 = new DecimalFormat("0.00"); DecimalFormat df7 = new DecimalFormat("0.0"); DecimalFormat df8 = new DecimalFormat(" DecimalFormat df9 = new DecimalFormat(" DecimalFormat df10 = new DecimalFormat(" // we can add the units in any order, the TickUnits collection will // sort them... units.add(new NumberTickUnit(0.000000001, df00, 2)); units.add(new NumberTickUnit(0.00000001, df0, 2)); units.add(new NumberTickUnit(0.0000001, df1, 2)); units.add(new NumberTickUnit(0.000001, df2, 2)); units.add(new NumberTickUnit(0.00001, df3, 2)); units.add(new NumberTickUnit(0.0001, df4, 2)); units.add(new NumberTickUnit(0.001, df5, 2)); units.add(new NumberTickUnit(0.01, df6, 2)); units.add(new NumberTickUnit(0.1, df7, 2)); units.add(new NumberTickUnit(1, df8, 2)); units.add(new NumberTickUnit(10, df8, 2)); units.add(new NumberTickUnit(100, df8, 2)); units.add(new NumberTickUnit(1000, df8, 2)); units.add(new NumberTickUnit(10000, df8, 2)); units.add(new NumberTickUnit(100000, df8, 2)); units.add(new NumberTickUnit(1000000, df9, 2)); units.add(new NumberTickUnit(10000000, df9, 2)); units.add(new NumberTickUnit(100000000, df9, 2)); units.add(new NumberTickUnit(1000000000, df10, 2)); units.add(new NumberTickUnit(10000000000.0, df10, 2)); units.add(new NumberTickUnit(100000000000.0, df10, 2)); units.add(new NumberTickUnit(0.0000000025, df000, 5)); units.add(new NumberTickUnit(0.000000025, df00, 5)); units.add(new NumberTickUnit(0.00000025, df0, 5)); units.add(new NumberTickUnit(0.0000025, df1, 5)); units.add(new NumberTickUnit(0.000025, df2, 5)); units.add(new NumberTickUnit(0.00025, df3, 5)); units.add(new NumberTickUnit(0.0025, df4, 5)); units.add(new NumberTickUnit(0.025, df5, 5)); units.add(new NumberTickUnit(0.25, df6, 5)); units.add(new NumberTickUnit(2.5, df7, 5)); units.add(new NumberTickUnit(25, df8, 5)); units.add(new NumberTickUnit(250, df8, 5)); units.add(new NumberTickUnit(2500, df8, 5)); units.add(new NumberTickUnit(25000, df8, 5)); units.add(new NumberTickUnit(250000, df8, 5)); units.add(new NumberTickUnit(2500000, df9, 5)); units.add(new NumberTickUnit(25000000, df9, 5)); units.add(new NumberTickUnit(250000000, df9, 5)); units.add(new NumberTickUnit(2500000000.0, df10, 5)); units.add(new NumberTickUnit(25000000000.0, df10, 5)); units.add(new NumberTickUnit(250000000000.0, df10, 5)); units.add(new NumberTickUnit(0.000000005, df00, 5)); units.add(new NumberTickUnit(0.00000005, df0, 5)); units.add(new NumberTickUnit(0.0000005, df1, 5)); units.add(new NumberTickUnit(0.000005, df2, 5)); units.add(new NumberTickUnit(0.00005, df3, 5)); units.add(new NumberTickUnit(0.0005, df4, 5)); units.add(new NumberTickUnit(0.005, df5, 5)); units.add(new NumberTickUnit(0.05, df6, 5)); units.add(new NumberTickUnit(0.5, df7, 5)); units.add(new NumberTickUnit(5L, df8, 5)); units.add(new NumberTickUnit(50L, df8, 5)); units.add(new NumberTickUnit(500L, df8, 5)); units.add(new NumberTickUnit(5000L, df8, 5)); units.add(new NumberTickUnit(50000L, df8, 5)); units.add(new NumberTickUnit(500000L, df8, 5)); units.add(new NumberTickUnit(5000000L, df9, 5)); units.add(new NumberTickUnit(50000000L, df9, 5)); units.add(new NumberTickUnit(500000000L, df9, 5)); units.add(new NumberTickUnit(5000000000L, df10, 5)); units.add(new NumberTickUnit(50000000000L, df10, 5)); units.add(new NumberTickUnit(500000000000L, df10, 5)); return units; } /** * Returns a collection of tick units for integer values. * * @return A collection of tick units for integer values. * * @see #setStandardTickUnits(TickUnitSource) * @see #createStandardTickUnits() */ public static TickUnitSource createIntegerTickUnits() { TickUnits units = new TickUnits(); DecimalFormat df0 = new DecimalFormat("0"); DecimalFormat df1 = new DecimalFormat(" units.add(new NumberTickUnit(1, df0, 2)); units.add(new NumberTickUnit(2, df0, 2)); units.add(new NumberTickUnit(5, df0, 5)); units.add(new NumberTickUnit(10, df0, 2)); units.add(new NumberTickUnit(20, df0, 2)); units.add(new NumberTickUnit(50, df0, 5)); units.add(new NumberTickUnit(100, df0, 2)); units.add(new NumberTickUnit(200, df0, 2)); units.add(new NumberTickUnit(500, df0, 5)); units.add(new NumberTickUnit(1000, df1, 2)); units.add(new NumberTickUnit(2000, df1, 2)); units.add(new NumberTickUnit(5000, df1, 5)); units.add(new NumberTickUnit(10000, df1, 2)); units.add(new NumberTickUnit(20000, df1, 2)); units.add(new NumberTickUnit(50000, df1, 5)); units.add(new NumberTickUnit(100000, df1, 2)); units.add(new NumberTickUnit(200000, df1, 2)); units.add(new NumberTickUnit(500000, df1, 5)); units.add(new NumberTickUnit(1000000, df1, 2)); units.add(new NumberTickUnit(2000000, df1, 2)); units.add(new NumberTickUnit(5000000, df1, 5)); units.add(new NumberTickUnit(10000000, df1, 2)); units.add(new NumberTickUnit(20000000, df1, 2)); units.add(new NumberTickUnit(50000000, df1, 5)); units.add(new NumberTickUnit(100000000, df1, 2)); units.add(new NumberTickUnit(200000000, df1, 2)); units.add(new NumberTickUnit(500000000, df1, 5)); units.add(new NumberTickUnit(1000000000, df1, 2)); units.add(new NumberTickUnit(2000000000, df1, 2)); units.add(new NumberTickUnit(5000000000.0, df1, 5)); units.add(new NumberTickUnit(10000000000.0, df1, 2)); return units; } /** * Creates a collection of standard tick units. The supplied locale is * used to create the number formatter (a localised instance of * <code>NumberFormat</code>). * <P> * If you don't like these defaults, create your own instance of * {@link TickUnits} and then pass it to the * <code>setStandardTickUnits()</code> method. * * @param locale the locale. * * @return A tick unit collection. * * @see #setStandardTickUnits(TickUnitSource) */ public static TickUnitSource createStandardTickUnits(Locale locale) { TickUnits units = new TickUnits(); NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); // we can add the units in any order, the TickUnits collection will // sort them... units.add(new NumberTickUnit(0.0000001, numberFormat, 2)); units.add(new NumberTickUnit(0.000001, numberFormat, 2)); units.add(new NumberTickUnit(0.00001, numberFormat, 2)); units.add(new NumberTickUnit(0.0001, numberFormat, 2)); units.add(new NumberTickUnit(0.001, numberFormat, 2)); units.add(new NumberTickUnit(0.01, numberFormat, 2)); units.add(new NumberTickUnit(0.1, numberFormat, 2)); units.add(new NumberTickUnit(1, numberFormat, 2)); units.add(new NumberTickUnit(10, numberFormat, 2)); units.add(new NumberTickUnit(100, numberFormat, 2)); units.add(new NumberTickUnit(1000, numberFormat, 2)); units.add(new NumberTickUnit(10000, numberFormat, 2)); units.add(new NumberTickUnit(100000, numberFormat, 2)); units.add(new NumberTickUnit(1000000, numberFormat, 2)); units.add(new NumberTickUnit(10000000, numberFormat, 2)); units.add(new NumberTickUnit(100000000, numberFormat, 2)); units.add(new NumberTickUnit(1000000000, numberFormat, 2)); units.add(new NumberTickUnit(10000000000.0, numberFormat, 2)); units.add(new NumberTickUnit(0.00000025, numberFormat, 5)); units.add(new NumberTickUnit(0.0000025, numberFormat, 5)); units.add(new NumberTickUnit(0.000025, numberFormat, 5)); units.add(new NumberTickUnit(0.00025, numberFormat, 5)); units.add(new NumberTickUnit(0.0025, numberFormat, 5)); units.add(new NumberTickUnit(0.025, numberFormat, 5)); units.add(new NumberTickUnit(0.25, numberFormat, 5)); units.add(new NumberTickUnit(2.5, numberFormat, 5)); units.add(new NumberTickUnit(25, numberFormat, 5)); units.add(new NumberTickUnit(250, numberFormat, 5)); units.add(new NumberTickUnit(2500, numberFormat, 5)); units.add(new NumberTickUnit(25000, numberFormat, 5)); units.add(new NumberTickUnit(250000, numberFormat, 5)); units.add(new NumberTickUnit(2500000, numberFormat, 5)); units.add(new NumberTickUnit(25000000, numberFormat, 5)); units.add(new NumberTickUnit(250000000, numberFormat, 5)); units.add(new NumberTickUnit(2500000000.0, numberFormat, 5)); units.add(new NumberTickUnit(25000000000.0, numberFormat, 5)); units.add(new NumberTickUnit(0.0000005, numberFormat, 5)); units.add(new NumberTickUnit(0.000005, numberFormat, 5)); units.add(new NumberTickUnit(0.00005, numberFormat, 5)); units.add(new NumberTickUnit(0.0005, numberFormat, 5)); units.add(new NumberTickUnit(0.005, numberFormat, 5)); units.add(new NumberTickUnit(0.05, numberFormat, 5)); units.add(new NumberTickUnit(0.5, numberFormat, 5)); units.add(new NumberTickUnit(5L, numberFormat, 5)); units.add(new NumberTickUnit(50L, numberFormat, 5)); units.add(new NumberTickUnit(500L, numberFormat, 5)); units.add(new NumberTickUnit(5000L, numberFormat, 5)); units.add(new NumberTickUnit(50000L, numberFormat, 5)); units.add(new NumberTickUnit(500000L, numberFormat, 5)); units.add(new NumberTickUnit(5000000L, numberFormat, 5)); units.add(new NumberTickUnit(50000000L, numberFormat, 5)); units.add(new NumberTickUnit(500000000L, numberFormat, 5)); units.add(new NumberTickUnit(5000000000L, numberFormat, 5)); units.add(new NumberTickUnit(50000000000L, numberFormat, 5)); return units; } /** * Returns a collection of tick units for integer values. * Uses a given Locale to create the DecimalFormats. * * @param locale the locale to use to represent Numbers. * * @return A collection of tick units for integer values. * * @see #setStandardTickUnits(TickUnitSource) */ public static TickUnitSource createIntegerTickUnits(Locale locale) { TickUnits units = new TickUnits(); NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); units.add(new NumberTickUnit(1, numberFormat, 2)); units.add(new NumberTickUnit(2, numberFormat, 2)); units.add(new NumberTickUnit(5, numberFormat, 5)); units.add(new NumberTickUnit(10, numberFormat, 2)); units.add(new NumberTickUnit(20, numberFormat, 2)); units.add(new NumberTickUnit(50, numberFormat, 5)); units.add(new NumberTickUnit(100, numberFormat, 2)); units.add(new NumberTickUnit(200, numberFormat, 2)); units.add(new NumberTickUnit(500, numberFormat, 5)); units.add(new NumberTickUnit(1000, numberFormat, 2)); units.add(new NumberTickUnit(2000, numberFormat, 2)); units.add(new NumberTickUnit(5000, numberFormat, 5)); units.add(new NumberTickUnit(10000, numberFormat, 2)); units.add(new NumberTickUnit(20000, numberFormat, 2)); units.add(new NumberTickUnit(50000, numberFormat, 5)); units.add(new NumberTickUnit(100000, numberFormat, 2)); units.add(new NumberTickUnit(200000, numberFormat, 2)); units.add(new NumberTickUnit(500000, numberFormat, 5)); units.add(new NumberTickUnit(1000000, numberFormat, 2)); units.add(new NumberTickUnit(2000000, numberFormat, 2)); units.add(new NumberTickUnit(5000000, numberFormat, 5)); units.add(new NumberTickUnit(10000000, numberFormat, 2)); units.add(new NumberTickUnit(20000000, numberFormat, 2)); units.add(new NumberTickUnit(50000000, numberFormat, 5)); units.add(new NumberTickUnit(100000000, numberFormat, 2)); units.add(new NumberTickUnit(200000000, numberFormat, 2)); units.add(new NumberTickUnit(500000000, numberFormat, 5)); units.add(new NumberTickUnit(1000000000, numberFormat, 2)); units.add(new NumberTickUnit(2000000000, numberFormat, 2)); units.add(new NumberTickUnit(5000000000.0, numberFormat, 5)); units.add(new NumberTickUnit(10000000000.0, numberFormat, 2)); return units; } /** * Estimates the maximum tick label height. * * @param g2 the graphics device. * * @return The maximum height. */ protected double estimateMaximumTickLabelHeight(Graphics2D g2) { RectangleInsets tickLabelInsets = getTickLabelInsets(); double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom(); Font tickLabelFont = getTickLabelFont(); FontRenderContext frc = g2.getFontRenderContext(); result += tickLabelFont.getLineMetrics("123", frc).getHeight(); return result; } /** * Estimates the maximum width of the tick labels, assuming the specified * tick unit is used. * <P> * Rather than computing the string bounds of every tick on the axis, we * just look at two values: the lower bound and the upper bound for the * axis. These two values will usually be representative. * * @param g2 the graphics device. * @param unit the tick unit to use for calculation. * * @return The estimated maximum width of the tick labels. */ protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit unit) { RectangleInsets tickLabelInsets = getTickLabelInsets(); double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight(); if (isVerticalTickLabels()) { // all tick labels have the same width (equal to the height of the // font)... FontRenderContext frc = g2.getFontRenderContext(); LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc); result += lm.getHeight(); } else { // look at lower and upper bounds... FontMetrics fm = g2.getFontMetrics(getTickLabelFont()); Range range = getRange(); double lower = range.getLowerBound(); double upper = range.getUpperBound(); String lowerStr = ""; String upperStr = ""; NumberFormat formatter = getNumberFormatOverride(); if (formatter != null) { lowerStr = formatter.format(lower); upperStr = formatter.format(upper); } else { lowerStr = unit.valueToString(lower); upperStr = unit.valueToString(upper); } double w1 = fm.stringWidth(lowerStr); double w2 = fm.stringWidth(upperStr); result += Math.max(w1, w2); } return result; } /** * Selects an appropriate tick value for the axis. The strategy is to * display as many ticks as possible (selected from an array of 'standard' * tick units) without the labels overlapping. * * @param g2 the graphics device. * @param dataArea the area defined by the axes. * @param edge the axis location. */ protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { if (RectangleEdge.isTopOrBottom(edge)) { selectHorizontalAutoTickUnit(g2, dataArea, edge); } else if (RectangleEdge.isLeftOrRight(edge)) { selectVerticalAutoTickUnit(g2, dataArea, edge); } } /** * Selects an appropriate tick value for the axis. The strategy is to * display as many ticks as possible (selected from an array of 'standard' * tick units) without the labels overlapping. * * @param g2 the graphics device. * @param dataArea the area defined by the axes. * @param edge the axis location. */ protected void selectHorizontalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { double tickLabelWidth = estimateMaximumTickLabelWidth(g2, getTickUnit()); // start with the current tick unit... TickUnitSource tickUnits = getStandardTickUnits(); TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit()); double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge); // then extrapolate... double guess = (tickLabelWidth / unit1Width) * unit1.getSize(); NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit( guess); double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge); tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2); if (tickLabelWidth > unit2Width) { unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2); } setTickUnit(unit2, false, false); } /** * Selects an appropriate tick value for the axis. The strategy is to * display as many ticks as possible (selected from an array of 'standard' * tick units) without the labels overlapping. * * @param g2 the graphics device. * @param dataArea the area in which the plot should be drawn. * @param edge the axis location. */ protected void selectVerticalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { double tickLabelHeight = estimateMaximumTickLabelHeight(g2); // start with the current tick unit... TickUnitSource tickUnits = getStandardTickUnits(); TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit()); double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge); // then extrapolate... double guess = (tickLabelHeight / unitHeight) * unit1.getSize(); NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(guess); double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge); tickLabelHeight = estimateMaximumTickLabelHeight(g2); if (tickLabelHeight > unit2Height) { unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2); } setTickUnit(unit2, false, false); } /** * Calculates the positions of the tick labels for the axis, storing the * results in the tick label list (ready for drawing). * * @param g2 the graphics device. * @param state the axis state. * @param dataArea the area in which the plot should be drawn. * @param edge the location of the axis. * * @return A list of ticks. * */ public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { List result = new java.util.ArrayList(); if (RectangleEdge.isTopOrBottom(edge)) { result = refreshTicksHorizontal(g2, dataArea, edge); } else if (RectangleEdge.isLeftOrRight(edge)) { result = refreshTicksVertical(g2, dataArea, edge); } return result; } /** * Calculates the positions of the tick labels for the axis, storing the * results in the tick label list (ready for drawing). * * @param g2 the graphics device. * @param dataArea the area in which the data should be drawn. * @param edge the location of the axis. * * @return A list of ticks. */ protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { List result = new java.util.ArrayList(); Font tickLabelFont = getTickLabelFont(); g2.setFont(tickLabelFont); if (isAutoTickUnitSelection()) { selectAutoTickUnit(g2, dataArea, edge); } TickUnit tu = getTickUnit(); double size = tu.getSize(); int count = calculateVisibleTickCount(); double lowestTickValue = calculateLowestVisibleTickValue(); if (count <= ValueAxis.MAXIMUM_TICK_COUNT) { int minorTickSpaces = getMinorTickCount(); if (minorTickSpaces <= 0) { minorTickSpaces = tu.getMinorTickCount(); } for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) { double minorTickValue = lowestTickValue - size * minorTick / minorTickSpaces; if (getRange().contains(minorTickValue)){ result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER, TextAnchor.CENTER, 0.0)); } } for (int i = 0; i < count; i++) { double currentTickValue = lowestTickValue + (i * size); String tickLabel; NumberFormat formatter = getNumberFormatOverride(); if (formatter != null) { tickLabel = formatter.format(currentTickValue); } else { tickLabel = getTickUnit().valueToString(currentTickValue); } TextAnchor anchor = null; TextAnchor rotationAnchor = null; double angle = 0.0; if (isVerticalTickLabels()) { anchor = TextAnchor.CENTER_RIGHT; rotationAnchor = TextAnchor.CENTER_RIGHT; if (edge == RectangleEdge.TOP) { angle = Math.PI / 2.0; } else { angle = -Math.PI / 2.0; } } else { if (edge == RectangleEdge.TOP) { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; } else { anchor = TextAnchor.TOP_CENTER; rotationAnchor = TextAnchor.TOP_CENTER; } } Tick tick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle); result.add(tick); double nextTickValue = lowestTickValue + ((i + 1) * size); for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) { double minorTickValue = currentTickValue + (nextTickValue - currentTickValue) * minorTick / minorTickSpaces; if (getRange().contains(minorTickValue)) { result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER, TextAnchor.CENTER, 0.0)); } } } } return result; } /** * Calculates the positions of the tick labels for the axis, storing the * results in the tick label list (ready for drawing). * * @param g2 the graphics device. * @param dataArea the area in which the plot should be drawn. * @param edge the location of the axis. * * @return A list of ticks. */ protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { List result = new java.util.ArrayList(); result.clear(); Font tickLabelFont = getTickLabelFont(); g2.setFont(tickLabelFont); if (isAutoTickUnitSelection()) { selectAutoTickUnit(g2, dataArea, edge); } TickUnit tu = getTickUnit(); double size = tu.getSize(); int count = calculateVisibleTickCount(); double lowestTickValue = calculateLowestVisibleTickValue(); if (count <= ValueAxis.MAXIMUM_TICK_COUNT) { int minorTickSpaces = getMinorTickCount(); if (minorTickSpaces <= 0) { minorTickSpaces = tu.getMinorTickCount(); } for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) { double minorTickValue = lowestTickValue - size * minorTick / minorTickSpaces; if (getRange().contains(minorTickValue)) { result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER, TextAnchor.CENTER, 0.0)); } } for (int i = 0; i < count; i++) { double currentTickValue = lowestTickValue + (i * size); String tickLabel; NumberFormat formatter = getNumberFormatOverride(); if (formatter != null) { tickLabel = formatter.format(currentTickValue); } else { tickLabel = getTickUnit().valueToString(currentTickValue); } TextAnchor anchor = null; TextAnchor rotationAnchor = null; double angle = 0.0; if (isVerticalTickLabels()) { if (edge == RectangleEdge.LEFT) { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; angle = -Math.PI / 2.0; } else { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; angle = Math.PI / 2.0; } } else { if (edge == RectangleEdge.LEFT) { anchor = TextAnchor.CENTER_RIGHT; rotationAnchor = TextAnchor.CENTER_RIGHT; } else { anchor = TextAnchor.CENTER_LEFT; rotationAnchor = TextAnchor.CENTER_LEFT; } } Tick tick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle); result.add(tick); double nextTickValue = lowestTickValue + ((i + 1) * size); for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) { double minorTickValue = currentTickValue + (nextTickValue - currentTickValue) * minorTick / minorTickSpaces; if (getRange().contains(minorTickValue)) { result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER, TextAnchor.CENTER, 0.0)); } } } } return result; } /** * Returns a clone of the axis. * * @return A clone * * @throws CloneNotSupportedException if some component of the axis does * not support cloning. */ public Object clone() throws CloneNotSupportedException { NumberAxis clone = (NumberAxis) super.clone(); if (this.numberFormatOverride != null) { clone.numberFormatOverride = (NumberFormat) this.numberFormatOverride.clone(); } return clone; } /** * Tests the axis for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof NumberAxis)) { return false; } NumberAxis that = (NumberAxis) obj; if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) { return false; } if (this.autoRangeStickyZero != that.autoRangeStickyZero) { return false; } if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) { return false; } if (!ObjectUtilities.equal(this.numberFormatOverride, that.numberFormatOverride)) { return false; } if (!this.rangeType.equals(that.rangeType)) { return false; } return super.equals(obj); } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { if (getLabel() != null) { return getLabel().hashCode(); } else { return 0; } } }
package sun.misc; import java.lang.reflect.Field; // Hack to compile on Java 9 with `--release 8` public final class Unsafe { public static Unsafe getUnsafe() { return null; } public native long objectFieldOffset(Field f); public native int arrayBaseOffset(Class<?> clazz); public native int arrayIndexScale(Class<?> clazz); public native Object getObject(Object o, long offset); public native void putObject(Object o, long offset, Object value); public native void putByte(Object o, long offset, byte value); public native void putShort(Object o, long offset, short value); public native void putInt(Object o, long offset, int value); public native long getLong(Object o, long offset); public native void putLong(Object o, long offset, long value); public native double getDouble(Object o, long offset); public native void putDouble(Object o, long offset, double value); public native void copyMemory(Object from, long offset, Object to, long offset2, long nBytes); public native boolean compareAndSwapLong(java.lang.Object arg0, long arg1, long arg2, long arg3); }
package by.euanpa.gbs.database; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.net.Uri; import android.util.Log; import by.euanpa.gbs.database.contracts.BindContract; import by.euanpa.gbs.database.contracts.BusStopContract; import by.euanpa.gbs.database.contracts.RouteContract; import by.euanpa.gbs.database.contracts.TimeContract; public class GbsProvider extends ContentProvider { DbHelper dbHelper; private static final int ROUTE_INDEX = 0; private static final int BUS_STOP_INDEX = 1; private static final int TIME_INDEX = 2; private static final int BIND_INDEX = 3; private static final UriMatcher sURIMatcher = new UriMatcher( UriMatcher.NO_MATCH); private static final String TAG = GbsProvider.class.getSimpleName(); static { sURIMatcher.addURI(RouteContract.AUTHORITY, RouteContract.RouteColumns.ROUTE_PATH, ROUTE_INDEX); sURIMatcher.addURI(BusStopContract.AUTHORITY, BusStopContract.BusStopColumns.BUS_STOP_PATH, BUS_STOP_INDEX); sURIMatcher.addURI(TimeContract.AUTHORITY, TimeContract.TimeColumns.TIME_PATH, TIME_INDEX); sURIMatcher.addURI(BindContract.AUTHORITY, BindContract.BindColumns.BIND_PATH, BIND_INDEX); } public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } @Override public String getType(Uri uri) { switch (sURIMatcher.match(uri)) { case ROUTE_INDEX: return RouteContract.RouteColumns.ROUTE_TYPE; case BUS_STOP_INDEX: return BusStopContract.BusStopColumns.BUS_STOP_TYPE; case TIME_INDEX: return TimeContract.TimeColumns.TIME_TYPE; case BIND_INDEX: return BindContract.BindColumns.BIND_TYPE; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { Uri _uri = null; long id = 0; switch (sURIMatcher.match(uri)) { case ROUTE_INDEX: id = dbHelper.addRoute(values); _uri = ContentUris.withAppendedId( RouteContract.RouteColumns.ROUTE_URI, id); getContext().getContentResolver().notifyChange(_uri, null); case BUS_STOP_INDEX: id = dbHelper.addBusStop(values); _uri = ContentUris.withAppendedId( BusStopContract.BusStopColumns.BUS_STOP_URI, id); getContext().getContentResolver().notifyChange(_uri, null); case TIME_INDEX: id = dbHelper.addTime(values); _uri = ContentUris.withAppendedId( TimeContract.TimeColumns.TIME_URI, id); getContext().getContentResolver().notifyChange(_uri, null); case BIND_INDEX: id = dbHelper.addBind(values); _uri = ContentUris.withAppendedId( BindContract.BindColumns.BIND_URI, id); getContext().getContentResolver().notifyChange(_uri, null); break; default: throw new SQLException("Failed to insert row into " + uri); } return _uri; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { Log.i(TAG, "bulk insert (Provider checked) " + values[0]); DbHelper.bulkInsertTime(dbHelper, values); getContext().getContentResolver().notifyChange(uri, null); return values.length; } @Override public boolean onCreate() { dbHelper = new DbHelper(getContext(), null, null, 0); if (dbHelper != null) { return true; } return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor cursor = null; switch (sURIMatcher.match(uri)) { case ROUTE_INDEX: //cursor = dbHelper.getTweets(projection,selection, // selectionArgs, sortOrder); // cursor.setNotificationUri(getContext().getContentResolver(), uri); break; default: throw new SQLException("Failed to insert row into " + uri); } return cursor; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } }
package miner.parse; import java.io.*; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import miner.parse.util.HtmlUtil; import miner.parse.util.JsonUtil; import miner.spider.httpclient.Crawl4HttpClient; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Element; import miner.parse.data.Packer; import miner.parse.data.DataItem; import org.jsoup.nodes.Attributes; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class DocObject { private String document; private DocType doc_type; public Map<String, Element> html_map; public Map<String, String> json_map; private HtmlUtil h_util; private JsonUtil j_util; public DocType get_type() { return this.doc_type; } public Map<String, String> get_json_map() { return this.json_map; } public Map<String, Element> get_html_map() { return this.html_map; } public String search(String content){ if(doc_type.equals(DocType.HTML)){ for(Map.Entry<String,Element> e:html_map.entrySet()){ if(e.getValue().text().equals(content)){ return e.getKey(); } Attributes a=e.getValue().attributes(); Iterator<Attribute> it=a.iterator(); while (it.hasNext()){ Attribute attr=it.next(); String key=attr.getKey(); String value=attr.getValue(); if(value.equals(content)){ return e.getKey()+"."+key; } } } } else if(doc_type.equals(DocType.JSON)||doc_type.equals(DocType.JSONP)){ for(Map.Entry<String,String> e:json_map.entrySet()){ if(e.getValue().equals(content)){ return e.getKey(); } } } else if(doc_type.equals(DocType.TEXT)){ //to be added... }else if(doc_type.equals(DocType.XML)){ //to be added... } return "no path found..."; } public DocObject(String document, DocType doc_type) { if (doc_type.equals(DocType.JSONP)) { this.document = document.substring(document.indexOf('{'), document.length() - 1); } else { this.document = document; } this.doc_type = doc_type; this.html_map = new HashMap<String, Element>(); this.json_map = new HashMap<String, String>(); } public DocObject(String path, CharSet char_set) { String encoding = "UTF8"; String tail_str = path.split("\\.")[1]; if (tail_str.equals("js")) { doc_type = DocType.JSON; } else if (tail_str.equals("html") || tail_str.equals("htm")) { doc_type = DocType.HTML; } else if (tail_str.equals("xml")) { doc_type = DocType.XML; } else { doc_type = null; } if (char_set.equals(CharSet.UTF8)) { encoding = "UTF8"; } else if (char_set.equals(CharSet.GBK)) { encoding = "GBK"; } else if (char_set.equals(CharSet.GB2312)) { encoding = "GB2312"; } this.document = get_doc_str(path, encoding); this.html_map = new HashMap<String, Element>(); this.json_map = new HashMap<String, String>(); } private String get_doc_str(String doc_path, String encoding) { File file = new File(doc_path); String doc_str = ""; if (file.isFile() && file.exists()) { InputStreamReader read; try { read = new InputStreamReader(new FileInputStream(file), encoding); BufferedReader buffered_reader = new BufferedReader(read); String line = null; while ((line = buffered_reader.readLine()) != null) { doc_str += line; } buffered_reader.close(); read.close(); } catch (Exception e) { e.printStackTrace(); } } return doc_str; } public void parse() { if (doc_type.equals(DocType.HTML)) { parse_html(); } else if (doc_type.equals(DocType.JSON)) { parse_json(); } } public void parse_json() { j_util = new JsonUtil(this.document, this); j_util.parse(); } public void parse_html() { h_util = new HtmlUtil(this.document, this); h_util.parse(); } public String get_value(String path, String tag) { if (doc_type.equals(DocType.HTML)) { Element e = html_map.get(path); if(e==null){ return "none"; }else{ String result; if (tag.equals("text")) { result = e.text(); } else { result = e.attr(tag); } return result; } } else if (doc_type.equals(DocType.JSON) || doc_type.equals(DocType.JSONP)) { String result="none"; if(json_map.get(path)!=null){ result=json_map.get(path); } return result; } return "none"; } public static void testParse(String doc_str) { long start = System.currentTimeMillis(); /* docsetmap */ Map<String, RuleItem> data_rule_map = new HashMap<String, RuleItem>(); data_rule_map.put("id_name", new RuleItem("name_name", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dt0.a0.title")); data_rule_map.put("id_phone", new RuleItem("name_phone", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dd0.em0.b0.text")); data_rule_map.put("id_address", new RuleItem("name_address", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dd1.span1.text")); data_rule_map.put("id_sale", new RuleItem("name_sale", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dd2.a0.text")); data_rule_map.put("id_page_link", new RuleItem("name_page_link", "html0.body0.div8.div0.div0.div1.div0.a_1_6_.href")); /* map */ Set<DataItem> data_item_set = new HashSet<DataItem>(); // data_item_set.add(new DataItem("1", "1", "1", "1", "none", "none", // "none", "none", "id_name","id_phone","id_address","id_sale")); data_item_set.add(new DataItem("1", "1", "1", "1", "none", "none", "none", "none", "id_page_link")); Generator g = new Generator(); g.create_obj(doc_str); for (Map.Entry<String, RuleItem> entry : data_rule_map.entrySet()) { g.set_rule(entry.getValue()); } g.generate_data(); // System.out.println(g.get_doc_obj().search("010-84916660")); Map<String, Object> m = g.get_result(); Iterator<DataItem> data_item_it = data_item_set.iterator(); while (data_item_it.hasNext()) { Packer packer = new Packer(data_item_it.next(), m, data_rule_map); String[] result_str=packer.pack(); for(int i=0;i<result_str.length;i++){ System.out.println(result_str[i]); } } long end = System.currentTimeMillis(); System.out.println("time:"+(double)(end-start)/1000); } public static void main(String[] args) { /* * Document: * doc,charset * Data Parse: * Item: * id->name,path,tag,type * Data Pack: * Item: * data_id,project_id,task_id,workstation_id,row_key,foreign_key,foreign_value,link,id0,id1,id2... * */ // File file = new File("/Users/white/Desktop/workspace/test.html"); // String doc_str = ""; // if (file.isFile() && file.exists()) { // InputStreamReader read; // try { // read = new InputStreamReader(new FileInputStream(file), // "UTF8"); // BufferedReader buffered_reader = new BufferedReader(read); // String line = null; // while ((line = buffered_reader.readLine()) != null) { // doc_str += line; // buffered_reader.close(); // read.close(); // } catch (Exception e) { // e.printStackTrace(); // System.out.println(doc_str); String doc_str=null; try { Document doc = Jsoup.connect("http://dealer.xcar.com.cn/d1_475/?type=1&page=1").get(); doc_str=doc.toString(); // System.out.println(doc_str); }catch (IOException e){ e.printStackTrace(); } long start = System.currentTimeMillis(); /* docsetmap */ Map<String, RuleItem> data_rule_map = new HashMap<String, RuleItem>(); data_rule_map.put("id_name", new RuleItem("name_name", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dt0.a0.title")); data_rule_map.put("id_phone", new RuleItem("name_phone", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dd0.em0.b0.text")); data_rule_map.put("id_address", new RuleItem("name_address", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dd1.span1.text")); data_rule_map.put("id_sale", new RuleItem("name_sale", "html0.body0.div8.div0.div0.div1.ul0.li_1_9_.dl0.dd2.a0.text")); data_rule_map.put("id_page_link", new RuleItem("name_page_link", "html0.body0.div8.div0.div0.div1.div0.a_1_6_.href")); /* map */ Set<DataItem> data_item_set = new HashSet<DataItem>(); data_item_set.add(new DataItem("1", "1", "1", "1", "none", "none", "none", "none", "id_name","id_phone","id_address","id_sale")); data_item_set.add(new DataItem("1", "1", "1", "1", "none", "none", "none", "none","id_page_link")); Generator g = new Generator(); g.create_obj(doc_str); for (Map.Entry<String, RuleItem> entry : data_rule_map.entrySet()) { g.set_rule(entry.getValue()); } g.generate_data(); System.out.println(g.get_doc_obj().search("/d1_475/?type=1&page=12")); // System.out.println(g.get_doc_obj().search("")); // System.out.println(g.get_doc_obj().search("/d1_475/?type=1&page=4")); // System.out.println(g.get_doc_obj().search("/d1_475/?type=1&page=5")); // System.out.println(g.get_doc_obj().search("/d1_475/?type=1&page=6")); Map<String, Object> m = g.get_result(); Iterator<DataItem> data_item_it = data_item_set.iterator(); while (data_item_it.hasNext()) { Packer packer = new Packer(data_item_it.next(), m, data_rule_map); String[] result_str=packer.pack(); for(int i=0;i<result_str.length;i++){ System.out.println(result_str[i]); } } long end = System.currentTimeMillis(); System.out.println("time:"+(double)(end-start)/1000); } }
package client; import client.audio.*; import client.gui.*; import common.*; import common.messages.*; import java.awt.Color; import java.awt.Component; import java.awt.event.*; import java.awt.geom.Rectangle2D; import java.awt.Window; import java.util.logging.Logger; import java.util.logging.Level; import java.util.Vector; import javax.swing.Timer; /** * This class describes the game loop for this game */ public class GameEngine implements Constants, ActionListener, ActionCallback { // SINGLETONS public static Logger logger = Logger.getLogger(CLIENT_LOGGER_NAME); public static GameEngine gameEngine; public boolean gameOver; public Map gameMap; public ClientViewArea gameViewArea; public LocalPlayer localPlayer; public InputListener localInputListener; // Actor lists and sub-lists public Vector<Actor> actorList; // This contains all actors in the game public Vector<Stone> stoneList; // This only contains stones public Vector<Player> playerList; // This only contains players public Vector<Projectile> bulletList; // This only contains bullets public Vector<Actor> miscList; // This contains stuff that doesn't fit in // any of the other public long lastTime; public float currentTime; public Timer timer; public Timer frameRate; public Vector<MapChangeListener> mapListeners; // Sound stuff public GameSoundSystem soundSystem; public SoundEffect soundBump, soundDeath, soundFire; // CONSTRUCTORS public GameEngine(Map m, byte playerID, String name, boolean bot) { preSetup(m); localPlayer = bot ? new ComputerPlayer(playerID, name, this) : new HumanPlayer(localInputListener, playerID, name); postSetup(true); } public GameEngine(Map m) { preSetup(m); localPlayer = new HumanPlayer(localInputListener); postSetup(false); } // end GameEngine() constructor private void preSetup(Map m) { gameEngine = this; gameOver = false; gameMap = m; mapListeners = new Vector<MapChangeListener>(); actorList = new Vector<Actor>(); stoneList = new Vector<Stone>(); playerList = new Vector<Player>(); bulletList = new Vector<Projectile>(); miscList = new Vector<Actor>(); gameViewArea = new ClientViewArea(this); addButton(-5, -5, 45, 15, "Quit", Color.red); localInputListener = new InputListener(); localInputListener.attachListeners(gameViewArea); triggerMapListeners(); // Sound engine stuff: soundSystem = new GameSoundSystem(); soundBump = soundSystem.loadSoundEffect(SOUND_BUMP); soundDeath = soundSystem.loadSoundEffect(SOUND_DEATH); soundFire = soundSystem.loadSoundEffect(SOUND_FIRE); } private void postSetup(boolean fixed) { // if (fixed) // gameMap.placePlayer(localPlayer, null); // else gameMap.placePlayer(localPlayer); MouseTracker mouseTracker = localPlayer instanceof ComputerPlayer ? new RandomMouseTracker(localInputListener, gameViewArea) : new MouseTracker(localInputListener, gameViewArea); localPlayer.setAimingTarget(mouseTracker); DoubleTracker doubleTracker = new DoubleTracker(mouseTracker, localPlayer); TrackingObject playerTracker = new TrackingObject(doubleTracker); gameViewArea.viewTracker = playerTracker; gameViewArea.setLocalPlayer(localPlayer); addActor(localPlayer); addActor(mouseTracker); addActor(doubleTracker); addActor(playerTracker); } // GETTERS public LocalPlayer getLocalPlayer() { return this.localPlayer; } public Map getGameMap() { return this.gameMap; } public boolean getGameOver() { return this.gameOver; } public ClientViewArea getGameViewArea() { return this.gameViewArea; } public InputListener getInputListener() { return this.localInputListener; } // SETTERS public void setLocalPlayer(LocalPlayer p) { this.localPlayer = p; } public void setGameMap(Map m) { this.gameMap = m; triggerMapListeners(); } // OPERATIONS public void addActor(Actor a) { synchronized(actorList) { actorList.add(a); if (a instanceof Stone) synchronized(stoneList) { stoneList.add((Stone) a); } else if (a instanceof Projectile) synchronized(bulletList) { bulletList.add((Projectile) a); } else if (a instanceof Player) synchronized(playerList) { playerList.add((Player) a); } else synchronized(miscList) { miscList.add(a); } } } public void removeActor(Actor a) { if(a == null) return; synchronized(actorList) { actorList.remove(a); if (a instanceof Projectile) synchronized(bulletList) { bulletList.remove((Projectile) a); } else if (a instanceof Player) synchronized(playerList) { playerList.remove((Player) a); } else synchronized(miscList) { miscList.remove(a); } } } public boolean isGameOver() { return this.gameOver; } public void gameOver() { gameOver = true; if (timer != null) timer.stop(); // This code finds the Window that contains the gameViewArea and tells // it to disapear Component c = gameViewArea.getParent(); while (!(c instanceof Window) && c != null) c = c.getParent(); if (c != null) ((Window) c).setVisible(false); } public void gameStep() { checkCollisions(); updateWorld(); Thread.yield(); } public void play() { initialize(); timer = new Timer(TIMER_TICK, this); timer.start(); timer.setCoalesce(true); // while (!isGameOver()) { // gameStep(); // try { Thread.sleep(10); } // catch (InterruptedException er) { } } protected void triggerMapListeners() { for (MapChangeListener mcl : mapListeners) mcl.mapChanged(gameMap); } public void addMapListener(MapChangeListener listener) { mapListeners.add(listener); } public void initialize() { // Copy the map as a bunch of Stones for (int x = 0; x < gameMap.getWidth(); x++) for (int y = 0; y < gameMap.getHeight(); y++) { if (gameMap.isWall(x, y)) { stoneList.add(new Stone(x, y)); actorList.add(stoneList.get(stoneList.size() - 1)); } } lastTime = System.currentTimeMillis(); currentTime = 0; } // end initialize() public void checkCollisions() { // Environment, Player and projectile collision code goes here Rectangle2D bounds1, bounds2; Actor actor1, actor2; // Check players against stones Player p; for (int i = 0; i < playerList.size(); i++) { p = playerList.get(i); if (!p.isAlive()) { removeActor(p); continue; } float px = p.getX(), py = p.getY(); int ix = (int) px, iy = (int) py; if (px < 0 || py < 0) continue; if (px >= gameMap.getWidth() || py >= gameMap.getHeight()) continue; px = px - ix; py = py - iy; if (px < 0.25 && gameMap.isWall(ix - 1, iy)) p.collideLeft(); else if (px > 0.75 && gameMap.isWall(ix + 1, iy)) p.collideRight(); if (py < 0.25 && gameMap.isWall(ix, iy - 1)) p.collideUp(); else if (py > 0.72 && gameMap.isWall(ix, iy + 1)) p.collideDown(); } // for (int i=0; i < stoneList.size(); i ++) // actor1 = stoneList.get(i); // bounds1 = actor1.getBounds(); // for (int j=0; j < playerList.size(); j ++) // actor2 = playerList.get(j); // bounds2 = actor2.getBounds(); // if (bounds1.intersects(bounds2)) // actor1.collision(actor2); // actor2.collision(actor1); // } // end check players against stones // Check bullets against players and stones for (int i = 0; i < bulletList.size(); i++) { actor1 = bulletList.get(i); if (!actor1.isAlive()) { removeActor(actor1); continue; } bounds1 = actor1.getBounds(); for (int j = 0; j < playerList.size(); j++) { actor2 = playerList.get(j); bounds2 = actor2.getBounds(); if (bounds1.intersects(bounds2)) { actor1.collision(actor2); actor2.collision(actor1); } } // for (int j=0; j < stoneList.size(); j ++) // actor2 = stoneList.get(j); // bounds2 = actor2.getBounds(); // if (bounds1.intersects(bounds2)) // actor1.collision(actor2); // actor2.collision(actor1); // Simpler check: if (gameMap.isWall((int) actor1.getX(), (int) actor1.getY())) { actor1.collision(null); } } // end check bullets against players and stones // //Vector actorList = this.gameViewArea.actorList; // Rectangle2D playerBounds = this.localPlayer.getBounds(); // for (int i = 0; i < actorList.size(); i = i + 1) { // Actor actor1 = actorList.get(i); // if (actor1 instanceof TrackingObject) continue; // Rectangle2D bound1 = actor1.getBounds(); // if (bound1.intersects(playerBounds)) { // this.localPlayer.collision(actor1); // actor1.collision(this.localPlayer); // for (int j = i + 1; j < actorList.size(); j = j + 1) { // Actor actor2 = actorList.get(j); // if (actor2 instanceof TrackingObject) continue; // Rectangle2D bound2 = actor2.getBounds(); // if (bound1.intersects(bound2)) { // actor1.collision(actor2); // actor2.collision(actor1); } // end checkCollisions() public void updateWorld() { long thisTime = System.currentTimeMillis(); float dTime = 0.001f * (thisTime - lastTime); boolean repaint = false; // for (Actor a : actorList) // if (a.animate(dTime)) // repaint = true; synchronized(playerList) { for (Actor a : playerList) { if (a.animate(dTime, currentTime)) repaint = true; } } synchronized(bulletList) { for (Actor a : bulletList) { if (a.animate(dTime, currentTime)) repaint = true; } } synchronized(miscList) { for (Actor a : miscList) { if (a.animate(dTime, currentTime)) repaint = true; } } lastTime = thisTime; currentTime += dTime; if (repaint) { /* * This may not actually be desireable. If you bump or fire then * stop moving, it won't repaint */ } gameViewArea.repaint(); } // end updateWorld() public void actionPerformed(ActionEvent e) { gameStep(); } protected void addButton(int x, int y, int width, int height, String label) { addButton(x, y, width, height, label, Color.green); } protected void addButton(int x, int y, int width, int height, String label, Color c) { SimpleButton b = new SimpleButton(x, y, width, height, label, c); b.addCallback(this); gameViewArea.addWidget(b); } public void actionCallback(InteractiveWidget source, int buttons) { if (source.getLabel().equalsIgnoreCase("Quit")) { gameOver(); } } /** * Plays a bump sound effect at the specified volume. If the sound is * already playing at a lower volume, it is stopped and restarted at the * louder volume, otherwise nothing happens. * * @param volume * The volume at which to play. */ public void playBump(float volume) { playSound(volume, soundBump); } /** * Plays a player death sound effect at the specified volume * * @param volume * The volume at which to play */ public void playDeath(float volume) { playSound(volume, soundDeath); } /** * Plays a gun fire sound effect at the specified volume * * @param volume * The volume at which to play */ public void playFire(float volume) { playSound(volume, soundFire); } /** * A slightly more generic sound playing method so we don't have to * duplicate code all over the place. This actually handles playing or not * playing the sound. * * @param volume * @param sound */ private void playSound(float volume, SoundEffect sound) { // If we failed to find any audio lines, all sounds will be null if (sound == null) return; if (sound.isPlaying()) { if (sound.getVolume() <= volume) sound.stop(); else return; } // sound.setVolume(volume); // sound.play(); } public void registerActionListeners(Component c) { localInputListener.attachListeners(c); c.addKeyListener(gameViewArea); } public void registerActionListeners(Window w) { localInputListener.attachListeners(w); } public void unregisterActionListeners(Component c) { localInputListener.detachListeners(c); c.removeKeyListener(gameViewArea); } public void unregisterActionListenerst(Window w) { localInputListener.detachListeners(w); } public synchronized void processPlayerMotion(PlayerMotionMessage message) { // Get the index of the player int playerIndex = getPlayerIndex(message.getPlayerId()); // Do not process a player if they have not been added if(playerIndex == -1) { SpawnPoint sp = new SpawnPoint(message.getPosition()); processPlayerJoin(new PlayerJoinMessage(message.getPlayerId(), RESOLVING_NAME, null, sp)); } if (playerIndex < 0) return; try { // Update the co-ordinates of the player Player player = playerList.get(playerIndex); if (player instanceof RemotePlayer) ((RemotePlayer) player).addMotionPacket(message); } catch (Exception ex) { ex.printStackTrace(); } } public synchronized void processPlayerJoin(PlayerJoinMessage message) { // Get the index of the player int playerIndex = getPlayerIndex(message.getPlayerId()); Player player; // Creating a new player if(playerIndex == -1) { player = new RemotePlayer(message.getPlayerId(),message.getName()); logger.log(Level.FINE,"Player Added: " + player.getPlayerID()); gameMap.placePlayer(player,message.getSpawnPoint()); addActor(player); } // Updating information about the player else { player = playerList.get(playerIndex); logger.log(Level.FINE,"Player Info Updated: " + player.getPlayerID()); player.setPlayerName(message.getName()); } } public void processProjectile(ProjectileMessage message) { // Get the index of the player int playerIndex = getPlayerIndex(message.getPlayerId()); // Do not process this message if the player has not joined the game if (playerIndex == -1) return; Player player = playerList.get(playerIndex); if (player instanceof RemotePlayer) { // Add the projectile to the list addActor(new Projectile(message.getStartPosition(), message.getDirection(), player.getCurrentTime(), player.getCurrentTime(), player.getPlayerID(), player.getTeam())); // Signal that the remote player has fired player.fire(); logger.log(Level.FINE,"Player " + player.getPlayerID() + " fired!"); } } /** * Retrieve a player given their ID. */ public int getPlayerIndex(int playerId) { int index = -1; for (int i = 0; i < playerList.size(); i++) { if (playerList.get(i).getPlayerID() == playerId) { index = i; break; } } return index; } public Player getPlayer(byte playerId) { synchronized(playerList) { for(Player player : playerList) { if(player.getPlayerID() == playerId) return player; } } return null; } } // end class GameEngine
package com.facebook.react.views.textinput; import androidx.annotation.Nullable; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; /** * Event emitted by EditText native view when text changes. VisibleForTesting from {@link * TextInputEventsTestCase}. */ public class ReactTextChangedEvent extends Event<ReactTextChangedEvent> { public static final String EVENT_NAME = "topChange"; private String mText; private int mEventCount; @Deprecated public ReactTextChangedEvent(int viewId, String text, int eventCount) { this(-1, viewId, text, eventCount); } public ReactTextChangedEvent(int surfaceId, int viewId, String text, int eventCount) { super(surfaceId, viewId); mText = text; mEventCount = eventCount; } @Override public String getEventName() { return EVENT_NAME; } @Nullable @Override protected WritableMap getEventData() { WritableMap eventData = Arguments.createMap(); eventData.putString("text", mText); eventData.putInt("eventCount", mEventCount); eventData.putInt("target", getViewTag()); return eventData; } }
package com.facebook.react.views.textinput; import static com.facebook.react.uimanager.UIManagerHelper.getReactContext; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.BlendMode; import android.graphics.BlendModeColorFilter; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.Layout; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextWatcher; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.core.view.ViewCompat; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.JavaOnlyArray; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactSoftException; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableNativeMap; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeArray; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.BaseViewManager; import com.facebook.react.uimanager.LayoutShadowNode; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.Spacing; import com.facebook.react.uimanager.StateWrapper; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerHelper; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewDefaults; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper; import com.facebook.react.views.scroll.ScrollEvent; import com.facebook.react.views.scroll.ScrollEventType; import com.facebook.react.views.text.DefaultStyleValuesUtil; import com.facebook.react.views.text.ReactBaseTextShadowNode; import com.facebook.react.views.text.ReactTextUpdate; import com.facebook.react.views.text.ReactTextViewManagerCallback; import com.facebook.react.views.text.TextAttributeProps; import com.facebook.react.views.text.TextInlineImageSpan; import com.facebook.react.views.text.TextLayoutManager; import com.facebook.react.views.text.TextTransform; import com.facebook.yoga.YogaConstants; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.Map; /** Manages instances of TextInput. */ @ReactModule(name = ReactTextInputManager.REACT_CLASS) public class ReactTextInputManager extends BaseViewManager<ReactEditText, LayoutShadowNode> { public static final String TAG = ReactTextInputManager.class.getSimpleName(); public static final String REACT_CLASS = "AndroidTextInput"; private static final int[] SPACING_TYPES = { Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM, }; private static final int FOCUS_TEXT_INPUT = 1; private static final int BLUR_TEXT_INPUT = 2; private static final int SET_MOST_RECENT_EVENT_COUNT = 3; private static final int SET_TEXT_AND_SELECTION = 4; private static final int INPUT_TYPE_KEYBOARD_NUMBER_PAD = InputType.TYPE_CLASS_NUMBER; private static final int INPUT_TYPE_KEYBOARD_DECIMAL_PAD = INPUT_TYPE_KEYBOARD_NUMBER_PAD | InputType.TYPE_NUMBER_FLAG_DECIMAL; private static final int INPUT_TYPE_KEYBOARD_NUMBERED = INPUT_TYPE_KEYBOARD_DECIMAL_PAD | InputType.TYPE_NUMBER_FLAG_SIGNED; private static final int PASSWORD_VISIBILITY_FLAG = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD & ~InputType.TYPE_TEXT_VARIATION_PASSWORD; private static final int AUTOCAPITALIZE_FLAGS = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; private static final String KEYBOARD_TYPE_EMAIL_ADDRESS = "email-address"; private static final String KEYBOARD_TYPE_NUMERIC = "numeric"; private static final String KEYBOARD_TYPE_DECIMAL_PAD = "decimal-pad"; private static final String KEYBOARD_TYPE_NUMBER_PAD = "number-pad"; private static final String KEYBOARD_TYPE_PHONE_PAD = "phone-pad"; private static final String KEYBOARD_TYPE_VISIBLE_PASSWORD = "visible-password"; private static final InputFilter[] EMPTY_FILTERS = new InputFilter[0]; private static final int UNSET = -1; protected @Nullable ReactTextViewManagerCallback mReactTextViewManagerCallback; @Override public String getName() { return REACT_CLASS; } @Override public ReactEditText createViewInstance(ThemedReactContext context) { ReactEditText editText = new ReactEditText(context); int inputType = editText.getInputType(); editText.setInputType(inputType & (~InputType.TYPE_TEXT_FLAG_MULTI_LINE)); editText.setReturnKeyType("done"); return editText; } @Override public ReactBaseTextShadowNode createShadowNodeInstance() { return new ReactTextInputShadowNode(); } public ReactBaseTextShadowNode createShadowNodeInstance( @Nullable ReactTextViewManagerCallback reactTextViewManagerCallback) { return new ReactTextInputShadowNode(reactTextViewManagerCallback); } @Override public Class<? extends LayoutShadowNode> getShadowNodeClass() { return ReactTextInputShadowNode.class; } @Nullable @Override public Map<String, Object> getExportedCustomBubblingEventTypeConstants() { return MapBuilder.<String, Object>builder() .put( "topSubmitEditing", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onSubmitEditing", "captured", "onSubmitEditingCapture"))) .put( "topEndEditing", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onEndEditing", "captured", "onEndEditingCapture"))) .put( "topTextInput", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onTextInput", "captured", "onTextInputCapture"))) .put( "topFocus", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onFocus", "captured", "onFocusCapture"))) .put( "topBlur", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onBlur", "captured", "onBlurCapture"))) .put( "topKeyPress", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onKeyPress", "captured", "onKeyPressCapture"))) .build(); } @Nullable @Override public Map<String, Object> getExportedCustomDirectEventTypeConstants() { return MapBuilder.<String, Object>builder() .put( ScrollEventType.getJSEventName(ScrollEventType.SCROLL), MapBuilder.of("registrationName", "onScroll")) .build(); } @Override public @Nullable Map<String, Integer> getCommandsMap() { return MapBuilder.of("focusTextInput", FOCUS_TEXT_INPUT, "blurTextInput", BLUR_TEXT_INPUT); } @Override public void receiveCommand( ReactEditText reactEditText, int commandId, @Nullable ReadableArray args) { switch (commandId) { case FOCUS_TEXT_INPUT: this.receiveCommand(reactEditText, "focus", args); break; case BLUR_TEXT_INPUT: this.receiveCommand(reactEditText, "blur", args); break; case SET_MOST_RECENT_EVENT_COUNT: // TODO: delete, this is no longer used from JS break; case SET_TEXT_AND_SELECTION: this.receiveCommand(reactEditText, "setTextAndSelection", args); break; } } @Override public void receiveCommand( ReactEditText reactEditText, String commandId, @Nullable ReadableArray args) { switch (commandId) { case "focus": case "focusTextInput": reactEditText.requestFocusFromJS(); break; case "blur": case "blurTextInput": reactEditText.clearFocusFromJS(); break; case "setMostRecentEventCount": // TODO: delete, this is no longer used from JS break; case "setTextAndSelection": int mostRecentEventCount = args.getInt(0); if (mostRecentEventCount == UNSET) { return; } String text = args.getString(1); int start = args.getInt(2); int end = args.getInt(3); if (end == UNSET) { end = start; } reactEditText.maybeSetTextFromJS( getReactTextUpdate(text, mostRecentEventCount, start, end)); reactEditText.maybeSetSelection(mostRecentEventCount, start, end); break; } } // TODO: if we're able to fill in all these values and call maybeSetText when appropriate // I think this is all that's needed to fully support TextInput in Fabric private ReactTextUpdate getReactTextUpdate( String text, int mostRecentEventCount, int start, int end) { SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(TextTransform.apply(text, TextTransform.UNSET)); return new ReactTextUpdate( sb, mostRecentEventCount, false, 0, 0, 0, 0, Gravity.NO_GRAVITY, 0, 0, start, end); } @Override public void updateExtraData(ReactEditText view, Object extraData) { if (extraData instanceof ReactTextUpdate) { ReactTextUpdate update = (ReactTextUpdate) extraData; // TODO T58784068: delete this block of code, these are always unset in Fabric int paddingLeft = (int) update.getPaddingLeft(); int paddingTop = (int) update.getPaddingTop(); int paddingRight = (int) update.getPaddingRight(); int paddingBottom = (int) update.getPaddingBottom(); if (paddingLeft != UNSET || paddingTop != UNSET || paddingRight != UNSET || paddingBottom != UNSET) { view.setPadding( paddingLeft != UNSET ? paddingLeft : view.getPaddingLeft(), paddingTop != UNSET ? paddingTop : view.getPaddingTop(), paddingRight != UNSET ? paddingRight : view.getPaddingRight(), paddingBottom != UNSET ? paddingBottom : view.getPaddingBottom()); } if (update.containsImages()) { Spannable spannable = update.getText(); TextInlineImageSpan.possiblyUpdateInlineImageSpans(spannable, view); } view.maybeSetTextFromState(update); view.maybeSetSelection( update.getJsEventCounter(), update.getSelectionStart(), update.getSelectionEnd()); } } @ReactProp(name = ViewProps.FONT_SIZE, defaultFloat = ViewDefaults.FONT_SIZE_SP) public void setFontSize(ReactEditText view, float fontSize) { view.setFontSize(fontSize); } @ReactProp(name = ViewProps.FONT_FAMILY) public void setFontFamily(ReactEditText view, String fontFamily) { view.setFontFamily(fontFamily); } @ReactProp(name = ViewProps.MAX_FONT_SIZE_MULTIPLIER, defaultFloat = Float.NaN) public void setMaxFontSizeMultiplier(ReactEditText view, float maxFontSizeMultiplier) { view.setMaxFontSizeMultiplier(maxFontSizeMultiplier); } @ReactProp(name = ViewProps.FONT_WEIGHT) public void setFontWeight(ReactEditText view, @Nullable String fontWeight) { view.setFontWeight(fontWeight); } @ReactProp(name = ViewProps.FONT_STYLE) public void setFontStyle(ReactEditText view, @Nullable String fontStyle) { view.setFontStyle(fontStyle); } @ReactProp(name = ViewProps.INCLUDE_FONT_PADDING, defaultBoolean = true) public void setIncludeFontPadding(ReactEditText view, boolean includepad) { view.setIncludeFontPadding(includepad); } @ReactProp(name = "importantForAutofill") public void setImportantForAutofill(ReactEditText view, @Nullable String value) { int mode = View.IMPORTANT_FOR_AUTOFILL_AUTO; if ("no".equals(value)) { mode = View.IMPORTANT_FOR_AUTOFILL_NO; } else if ("noExcludeDescendants".equals(value)) { mode = View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS; } else if ("yes".equals(value)) { mode = View.IMPORTANT_FOR_AUTOFILL_YES; } else if ("yesExcludeDescendants".equals(value)) { mode = View.IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS; } setImportantForAutofill(view, mode); } private void setImportantForAutofill(ReactEditText view, int mode) { // Autofill hints were added in Android API 26. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return; } view.setImportantForAutofill(mode); } private void setAutofillHints(ReactEditText view, String... hints) { // Autofill hints were added in Android API 26. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return; } view.setAutofillHints(hints); } @ReactProp(name = "onSelectionChange", defaultBoolean = false) public void setOnSelectionChange(final ReactEditText view, boolean onSelectionChange) { if (onSelectionChange) { view.setSelectionWatcher(new ReactSelectionWatcher(view)); } else { view.setSelectionWatcher(null); } } @ReactProp(name = "blurOnSubmit") public void setBlurOnSubmit(ReactEditText view, @Nullable Boolean blurOnSubmit) { view.setBlurOnSubmit(blurOnSubmit); } @ReactProp(name = "onContentSizeChange", defaultBoolean = false) public void setOnContentSizeChange(final ReactEditText view, boolean onContentSizeChange) { if (onContentSizeChange) { view.setContentSizeWatcher(new ReactContentSizeWatcher(view)); } else { view.setContentSizeWatcher(null); } } @ReactProp(name = "onScroll", defaultBoolean = false) public void setOnScroll(final ReactEditText view, boolean onScroll) { if (onScroll) { view.setScrollWatcher(new ReactScrollWatcher(view)); } else { view.setScrollWatcher(null); } } @ReactProp(name = "onKeyPress", defaultBoolean = false) public void setOnKeyPress(final ReactEditText view, boolean onKeyPress) { view.setOnKeyPress(onKeyPress); } // Sets the letter spacing as an absolute point size. // This extra handling, on top of what ReactBaseTextShadowNode already does, is required for the // correct display of spacing in placeholder (hint) text. @ReactProp(name = ViewProps.LETTER_SPACING, defaultFloat = 0) public void setLetterSpacing(ReactEditText view, float letterSpacing) { view.setLetterSpacingPt(letterSpacing); } @ReactProp(name = ViewProps.ALLOW_FONT_SCALING, defaultBoolean = true) public void setAllowFontScaling(ReactEditText view, boolean allowFontScaling) { view.setAllowFontScaling(allowFontScaling); } @ReactProp(name = "placeholder") public void setPlaceholder(ReactEditText view, @Nullable String placeholder) { view.setHint(placeholder); } @ReactProp(name = "placeholderTextColor", customType = "Color") public void setPlaceholderTextColor(ReactEditText view, @Nullable Integer color) { if (color == null) { view.setHintTextColor(DefaultStyleValuesUtil.getDefaultTextColorHint(view.getContext())); } else { view.setHintTextColor(color); } } @ReactProp(name = "selectionColor", customType = "Color") public void setSelectionColor(ReactEditText view, @Nullable Integer color) { if (color == null) { view.setHighlightColor( DefaultStyleValuesUtil.getDefaultTextColorHighlight(view.getContext())); } else { view.setHighlightColor(color); } setCursorColor(view, color); } @ReactProp(name = "cursorColor", customType = "Color") public void setCursorColor(ReactEditText view, @Nullable Integer color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { Drawable cursorDrawable = view.getTextCursorDrawable(); if (cursorDrawable != null) { cursorDrawable.setColorFilter(new BlendModeColorFilter(color, BlendMode.SRC_IN)); view.setTextCursorDrawable(cursorDrawable); } return; } if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) { // Pre-Android 10, there was no supported API to change the cursor color programmatically. // In Android 9.0, they changed the underlying implementation, // but also "dark greylisted" the new field, rendering it unusable. return; } // The evil code that follows uses reflection to achieve this on Android 8.1 and below. // Based on try { // Get the original cursor drawable resource. Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes"); cursorDrawableResField.setAccessible(true); int drawableResId = cursorDrawableResField.getInt(view); // The view has no cursor drawable. if (drawableResId == 0) { return; } Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId); if (color != null) { drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN); } Drawable[] drawables = {drawable, drawable}; // Update the current cursor drawable with the new one. Field editorField = TextView.class.getDeclaredField("mEditor"); editorField.setAccessible(true); Object editor = editorField.get(view); Field cursorDrawableField = editor.getClass().getDeclaredField("mCursorDrawable"); cursorDrawableField.setAccessible(true); cursorDrawableField.set(editor, drawables); } catch (NoSuchFieldException ex) { // Ignore errors to avoid crashing if these private fields don't exist on modified // or future android versions. } catch (IllegalAccessException ex) { } } @ReactProp(name = "caretHidden", defaultBoolean = false) public void setCaretHidden(ReactEditText view, boolean caretHidden) { view.setCursorVisible(!caretHidden); } @ReactProp(name = "contextMenuHidden", defaultBoolean = false) public void setContextMenuHidden(ReactEditText view, boolean contextMenuHidden) { final boolean _contextMenuHidden = contextMenuHidden; view.setOnLongClickListener( new View.OnLongClickListener() { public boolean onLongClick(View v) { return _contextMenuHidden; }; }); } @ReactProp(name = "selectTextOnFocus", defaultBoolean = false) public void setSelectTextOnFocus(ReactEditText view, boolean selectTextOnFocus) { view.setSelectAllOnFocus(selectTextOnFocus); } @ReactProp(name = ViewProps.COLOR, customType = "Color") public void setColor(ReactEditText view, @Nullable Integer color) { if (color == null) { ColorStateList defaultContextTextColor = DefaultStyleValuesUtil.getDefaultTextColor(view.getContext()); if (defaultContextTextColor != null) { view.setTextColor(defaultContextTextColor); } else { Context c = view.getContext(); ReactSoftException.logSoftException( TAG, new IllegalStateException( "Could not get default text color from View Context: " + (c != null ? c.getClass().getCanonicalName() : "null"))); } } else { view.setTextColor(color); } } @ReactProp(name = "underlineColorAndroid", customType = "Color") public void setUnderlineColor(ReactEditText view, @Nullable Integer underlineColor) { // Drawable.mutate() can sometimes crash due to an AOSP bug: Drawable background = view.getBackground(); Drawable drawableToMutate = background; if (background.getConstantState() != null) { try { drawableToMutate = background.mutate(); } catch (NullPointerException e) { FLog.e(TAG, "NullPointerException when setting underlineColorAndroid for TextInput", e); } } if (underlineColor == null) { drawableToMutate.clearColorFilter(); } else { drawableToMutate.setColorFilter(underlineColor, PorterDuff.Mode.SRC_IN); } } @ReactProp(name = ViewProps.TEXT_ALIGN) public void setTextAlign(ReactEditText view, @Nullable String textAlign) { if ("justify".equals(textAlign)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { view.setJustificationMode(Layout.JUSTIFICATION_MODE_INTER_WORD); } view.setGravityHorizontal(Gravity.LEFT); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { view.setJustificationMode(Layout.JUSTIFICATION_MODE_NONE); } if (textAlign == null || "auto".equals(textAlign)) { view.setGravityHorizontal(Gravity.NO_GRAVITY); } else if ("left".equals(textAlign)) { view.setGravityHorizontal(Gravity.LEFT); } else if ("right".equals(textAlign)) { view.setGravityHorizontal(Gravity.RIGHT); } else if ("center".equals(textAlign)) { view.setGravityHorizontal(Gravity.CENTER_HORIZONTAL); } else { throw new JSApplicationIllegalArgumentException("Invalid textAlign: " + textAlign); } } } @ReactProp(name = ViewProps.TEXT_ALIGN_VERTICAL) public void setTextAlignVertical(ReactEditText view, @Nullable String textAlignVertical) { if (textAlignVertical == null || "auto".equals(textAlignVertical)) { view.setGravityVertical(Gravity.NO_GRAVITY); } else if ("top".equals(textAlignVertical)) { view.setGravityVertical(Gravity.TOP); } else if ("bottom".equals(textAlignVertical)) { view.setGravityVertical(Gravity.BOTTOM); } else if ("center".equals(textAlignVertical)) { view.setGravityVertical(Gravity.CENTER_VERTICAL); } else { throw new JSApplicationIllegalArgumentException( "Invalid textAlignVertical: " + textAlignVertical); } } @ReactProp(name = "inlineImageLeft") public void setInlineImageLeft(ReactEditText view, @Nullable String resource) { int id = ResourceDrawableIdHelper.getInstance().getResourceDrawableId(view.getContext(), resource); view.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0); } @ReactProp(name = "inlineImagePadding") public void setInlineImagePadding(ReactEditText view, int padding) { view.setCompoundDrawablePadding(padding); } @ReactProp(name = "editable", defaultBoolean = true) public void setEditable(ReactEditText view, boolean editable) { view.setEnabled(editable); } @ReactProp(name = ViewProps.NUMBER_OF_LINES, defaultInt = 1) public void setNumLines(ReactEditText view, int numLines) { view.setLines(numLines); } @ReactProp(name = "maxLength") public void setMaxLength(ReactEditText view, @Nullable Integer maxLength) { InputFilter[] currentFilters = view.getFilters(); InputFilter[] newFilters = EMPTY_FILTERS; if (maxLength == null) { if (currentFilters.length > 0) { LinkedList<InputFilter> list = new LinkedList<>(); for (int i = 0; i < currentFilters.length; i++) { if (!(currentFilters[i] instanceof InputFilter.LengthFilter)) { list.add(currentFilters[i]); } } if (!list.isEmpty()) { newFilters = (InputFilter[]) list.toArray(new InputFilter[list.size()]); } } } else { if (currentFilters.length > 0) { newFilters = currentFilters; boolean replaced = false; for (int i = 0; i < currentFilters.length; i++) { if (currentFilters[i] instanceof InputFilter.LengthFilter) { currentFilters[i] = new InputFilter.LengthFilter(maxLength); replaced = true; } } if (!replaced) { newFilters = new InputFilter[currentFilters.length + 1]; System.arraycopy(currentFilters, 0, newFilters, 0, currentFilters.length); currentFilters[currentFilters.length] = new InputFilter.LengthFilter(maxLength); } } else { newFilters = new InputFilter[1]; newFilters[0] = new InputFilter.LengthFilter(maxLength); } } view.setFilters(newFilters); } @ReactProp(name = "autoCompleteType") public void setTextContentType(ReactEditText view, @Nullable String autoCompleteType) { if (autoCompleteType == null) { setImportantForAutofill(view, View.IMPORTANT_FOR_AUTOFILL_NO); } else if ("username".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_USERNAME); } else if ("password".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_PASSWORD); } else if ("email".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_EMAIL_ADDRESS); } else if ("name".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_NAME); } else if ("tel".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_PHONE); } else if ("street-address".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_POSTAL_ADDRESS); } else if ("postal-code".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_POSTAL_CODE); } else if ("cc-number".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_CREDIT_CARD_NUMBER); } else if ("cc-csc".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE); } else if ("cc-exp".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE); } else if ("cc-exp-month".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH); } else if ("cc-exp-year".equals(autoCompleteType)) { setAutofillHints(view, View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR); } else if ("off".equals(autoCompleteType)) { setImportantForAutofill(view, View.IMPORTANT_FOR_AUTOFILL_NO); } else { throw new JSApplicationIllegalArgumentException( "Invalid autoCompleteType: " + autoCompleteType); } } @ReactProp(name = "autoCorrect") public void setAutoCorrect(ReactEditText view, @Nullable Boolean autoCorrect) { // clear auto correct flags, set SUGGESTIONS or NO_SUGGESTIONS depending on value updateStagedInputTypeFlag( view, InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS, autoCorrect != null ? (autoCorrect.booleanValue() ? InputType.TYPE_TEXT_FLAG_AUTO_CORRECT : InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) : 0); } @ReactProp(name = "multiline", defaultBoolean = false) public void setMultiline(ReactEditText view, boolean multiline) { updateStagedInputTypeFlag( view, multiline ? 0 : InputType.TYPE_TEXT_FLAG_MULTI_LINE, multiline ? InputType.TYPE_TEXT_FLAG_MULTI_LINE : 0); } @ReactProp(name = "secureTextEntry", defaultBoolean = false) public void setSecureTextEntry(ReactEditText view, boolean password) { updateStagedInputTypeFlag( view, password ? 0 : InputType.TYPE_NUMBER_VARIATION_PASSWORD | InputType.TYPE_TEXT_VARIATION_PASSWORD, password ? InputType.TYPE_TEXT_VARIATION_PASSWORD : 0); checkPasswordType(view); } // This prop temporarily takes both numbers and strings. // Number values are deprecated and will be removed in a future release. // See T46146267 @ReactProp(name = "autoCapitalize") public void setAutoCapitalize(ReactEditText view, Dynamic autoCapitalize) { int autoCapitalizeValue = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; if (autoCapitalize.getType() == ReadableType.Number) { autoCapitalizeValue = autoCapitalize.asInt(); } else if (autoCapitalize.getType() == ReadableType.String) { final String autoCapitalizeStr = autoCapitalize.asString(); if (autoCapitalizeStr.equals("none")) { autoCapitalizeValue = 0; } else if (autoCapitalizeStr.equals("characters")) { autoCapitalizeValue = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; } else if (autoCapitalizeStr.equals("words")) { autoCapitalizeValue = InputType.TYPE_TEXT_FLAG_CAP_WORDS; } else if (autoCapitalizeStr.equals("sentences")) { autoCapitalizeValue = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; } } updateStagedInputTypeFlag(view, AUTOCAPITALIZE_FLAGS, autoCapitalizeValue); } @ReactProp(name = "keyboardType") public void setKeyboardType(ReactEditText view, @Nullable String keyboardType) { int flagsToSet = InputType.TYPE_CLASS_TEXT; if (KEYBOARD_TYPE_NUMERIC.equalsIgnoreCase(keyboardType)) { flagsToSet = INPUT_TYPE_KEYBOARD_NUMBERED; } else if (KEYBOARD_TYPE_NUMBER_PAD.equalsIgnoreCase(keyboardType)) { flagsToSet = INPUT_TYPE_KEYBOARD_NUMBER_PAD; } else if (KEYBOARD_TYPE_DECIMAL_PAD.equalsIgnoreCase(keyboardType)) { flagsToSet = INPUT_TYPE_KEYBOARD_DECIMAL_PAD; } else if (KEYBOARD_TYPE_EMAIL_ADDRESS.equalsIgnoreCase(keyboardType)) { flagsToSet = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_CLASS_TEXT; } else if (KEYBOARD_TYPE_PHONE_PAD.equalsIgnoreCase(keyboardType)) { flagsToSet = InputType.TYPE_CLASS_PHONE; } else if (KEYBOARD_TYPE_VISIBLE_PASSWORD.equalsIgnoreCase(keyboardType)) { // This will supercede secureTextEntry={false}. If it doesn't, due to the way // the flags work out, the underlying field will end up a URI-type field. flagsToSet = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD; } updateStagedInputTypeFlag(view, InputType.TYPE_MASK_CLASS, flagsToSet); checkPasswordType(view); } @ReactProp(name = "returnKeyType") public void setReturnKeyType(ReactEditText view, String returnKeyType) { view.setReturnKeyType(returnKeyType); } @ReactProp(name = "disableFullscreenUI", defaultBoolean = false) public void setDisableFullscreenUI(ReactEditText view, boolean disableFullscreenUI) { view.setDisableFullscreenUI(disableFullscreenUI); } private static final int IME_ACTION_ID = 0x670; @ReactProp(name = "returnKeyLabel") public void setReturnKeyLabel(ReactEditText view, String returnKeyLabel) { view.setImeActionLabel(returnKeyLabel, IME_ACTION_ID); } @ReactPropGroup( names = { ViewProps.BORDER_RADIUS, ViewProps.BORDER_TOP_LEFT_RADIUS, ViewProps.BORDER_TOP_RIGHT_RADIUS, ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, ViewProps.BORDER_BOTTOM_LEFT_RADIUS }, defaultFloat = YogaConstants.UNDEFINED) public void setBorderRadius(ReactEditText view, int index, float borderRadius) { if (!YogaConstants.isUndefined(borderRadius)) { borderRadius = PixelUtil.toPixelFromDIP(borderRadius); } if (index == 0) { view.setBorderRadius(borderRadius); } else { view.setBorderRadius(borderRadius, index - 1); } } @ReactProp(name = "borderStyle") public void setBorderStyle(ReactEditText view, @Nullable String borderStyle) { view.setBorderStyle(borderStyle); } @ReactProp(name = "showSoftInputOnFocus", defaultBoolean = true) public void showKeyboardOnFocus(ReactEditText view, boolean showKeyboardOnFocus) { view.setShowSoftInputOnFocus(showKeyboardOnFocus); } @ReactProp(name = "autoFocus", defaultBoolean = false) public void setAutoFocus(ReactEditText view, boolean autoFocus) { view.setAutoFocus(autoFocus); } @ReactPropGroup( names = { ViewProps.BORDER_WIDTH, ViewProps.BORDER_LEFT_WIDTH, ViewProps.BORDER_RIGHT_WIDTH, ViewProps.BORDER_TOP_WIDTH, ViewProps.BORDER_BOTTOM_WIDTH, }, defaultFloat = YogaConstants.UNDEFINED) public void setBorderWidth(ReactEditText view, int index, float width) { if (!YogaConstants.isUndefined(width)) { width = PixelUtil.toPixelFromDIP(width); } view.setBorderWidth(SPACING_TYPES[index], width); } @ReactPropGroup( names = { "borderColor", "borderLeftColor", "borderRightColor", "borderTopColor", "borderBottomColor" }, customType = "Color") public void setBorderColor(ReactEditText view, int index, Integer color) { float rgbComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int) color & 0x00FFFFFF); float alphaComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int) color >>> 24); view.setBorderColor(SPACING_TYPES[index], rgbComponent, alphaComponent); } @Override protected void onAfterUpdateTransaction(ReactEditText view) { super.onAfterUpdateTransaction(view); view.maybeUpdateTypeface(); view.commitStagedInputType(); } // Sets the correct password type, since numeric and text passwords have different types private static void checkPasswordType(ReactEditText view) { if ((view.getStagedInputType() & INPUT_TYPE_KEYBOARD_NUMBERED) != 0 && (view.getStagedInputType() & InputType.TYPE_TEXT_VARIATION_PASSWORD) != 0) { // Text input type is numbered password, remove text password variation, add numeric one updateStagedInputTypeFlag( view, InputType.TYPE_TEXT_VARIATION_PASSWORD, InputType.TYPE_NUMBER_VARIATION_PASSWORD); } } private static void updateStagedInputTypeFlag( ReactEditText view, int flagsToUnset, int flagsToSet) { view.setStagedInputType((view.getStagedInputType() & ~flagsToUnset) | flagsToSet); } private static EventDispatcher getEventDispatcher( ReactContext reactContext, ReactEditText editText) { return UIManagerHelper.getEventDispatcherForReactTag(reactContext, editText.getId()); } private class ReactTextInputTextWatcher implements TextWatcher { private EventDispatcher mEventDispatcher; private ReactEditText mEditText; private String mPreviousText; public ReactTextInputTextWatcher( final ReactContext reactContext, final ReactEditText editText) { mEventDispatcher = getEventDispatcher(reactContext, editText); mEditText = editText; mPreviousText = null; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Incoming charSequence gets mutated before onTextChanged() is invoked mPreviousText = s.toString(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (mEditText.mDisableTextDiffing) { return; } // Rearranging the text (i.e. changing between singleline and multiline attributes) can // also trigger onTextChanged, call the event in JS only when the text actually changed if (count == 0 && before == 0) { return; } Assertions.assertNotNull(mPreviousText); String newText = s.toString().substring(start, start + count); String oldText = mPreviousText.substring(start, start + before); // Don't send same text changes if (count == before && newText.equals(oldText)) { return; } // Fabric: update representation of AttributedString JavaOnlyMap attributedString = mEditText.mAttributedString; if (attributedString != null && attributedString.hasKey("fragments")) { String changedText = s.subSequence(start, start + count).toString(); String completeStr = attributedString.getString("string"); String newCompleteStr = completeStr.substring(0, start) + changedText + (completeStr.length() > start + before ? completeStr.substring(start + before) : ""); attributedString.putString("string", newCompleteStr); // Loop through all fragments and change them in-place JavaOnlyArray fragments = (JavaOnlyArray) attributedString.getArray("fragments"); int positionInAttributedString = 0; boolean found = false; for (int i = 0; i < fragments.size() && !found; i++) { JavaOnlyMap fragment = (JavaOnlyMap) fragments.getMap(i); String fragmentStr = fragment.getString("string"); int positionBefore = positionInAttributedString; positionInAttributedString += fragmentStr.length(); if (positionInAttributedString < start) { continue; } int relativePosition = start - positionBefore; found = true; // Does the change span multiple Fragments? // If so, we put any new text entirely in the first // Fragment that we edit. For example, if you select two words // across Fragment boundaries, "one | two", and replace them with a // character "x", the first Fragment will replace "one " with "x", and the // second Fragment will replace "two" with an empty string. int remaining = fragmentStr.length() - relativePosition; String newString = fragmentStr.substring(0, relativePosition) + changedText + (fragmentStr.substring(relativePosition + Math.min(before, remaining))); fragment.putString("string", newString); // If we're changing 10 characters (before=10) and remaining=3, // we want to remove 3 characters from this fragment (`Math.min(before, remaining)`) // and 7 from the next Fragment (`before = 10 - 3`) if (remaining < before) { changedText = ""; start += remaining; before = before - remaining; found = false; } } } // Fabric: communicate to C++ layer that text has changed // We need to call `incrementAndGetEventCounter` here explicitly because this // update may race with other updates. // TODO: currently WritableNativeMaps/WritableNativeArrays cannot be reused so // we must recreate these data structures every time. It would be nice to have a // reusable data-structure to use for TextInput because constructing these and copying // on every keystroke is very expensive. if (mEditText.mStateWrapper != null && attributedString != null) { WritableMap map = new WritableNativeMap(); WritableMap newAttributedString = new WritableNativeMap(); WritableArray fragments = new WritableNativeArray(); for (int i = 0; i < attributedString.getArray("fragments").size(); i++) { ReadableMap readableFragment = attributedString.getArray("fragments").getMap(i); WritableMap fragment = new WritableNativeMap(); fragment.putDouble("reactTag", readableFragment.getInt("reactTag")); fragment.putString("string", readableFragment.getString("string")); fragments.pushMap(fragment); } newAttributedString.putString("string", attributedString.getString("string")); newAttributedString.putArray("fragments", fragments); map.putInt("mostRecentEventCount", mEditText.incrementAndGetEventCounter()); map.putMap("textChanged", newAttributedString); mEditText.mStateWrapper.updateState(map); } // The event that contains the event counter and updates it must be sent first. // TODO: t7936714 merge these events mEventDispatcher.dispatchEvent( new ReactTextChangedEvent( mEditText.getId(), s.toString(), mEditText.incrementAndGetEventCounter())); mEventDispatcher.dispatchEvent( new ReactTextInputEvent(mEditText.getId(), newText, oldText, start, start + before)); } @Override public void afterTextChanged(Editable s) {} } @Override protected void addEventEmitters( final ThemedReactContext reactContext, final ReactEditText editText) { editText.addTextChangedListener(new ReactTextInputTextWatcher(reactContext, editText)); editText.setOnFocusChangeListener( new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { EventDispatcher eventDispatcher = getEventDispatcher(reactContext, editText); if (hasFocus) { eventDispatcher.dispatchEvent(new ReactTextInputFocusEvent(editText.getId())); } else { eventDispatcher.dispatchEvent(new ReactTextInputBlurEvent(editText.getId())); eventDispatcher.dispatchEvent( new ReactTextInputEndEditingEvent( editText.getId(), editText.getText().toString())); } } }); editText.setOnEditorActionListener( new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) { if ((actionId & EditorInfo.IME_MASK_ACTION) != 0 || actionId == EditorInfo.IME_NULL) { boolean blurOnSubmit = editText.getBlurOnSubmit(); boolean isMultiline = editText.isMultiline(); // Motivation: // * blurOnSubmit && isMultiline => Clear focus; prevent default behaviour (return // true); // * blurOnSubmit && !isMultiline => Clear focus; prevent default behaviour (return // true); // * !blurOnSubmit && isMultiline => Perform default behaviour (return false); // * !blurOnSubmit && !isMultiline => Prevent default behaviour (return true). // Additionally we always generate a `submit` event. EventDispatcher eventDispatcher = getEventDispatcher(reactContext, editText); eventDispatcher.dispatchEvent( new ReactTextInputSubmitEditingEvent( editText.getId(), editText.getText().toString())); if (blurOnSubmit) { editText.clearFocus(); } // Prevent default behavior except when we want it to insert a newline. if (blurOnSubmit || !isMultiline) { return true; } // If we've reached this point, it means that the TextInput has 'blurOnSubmit' set to // false and 'multiline' set to true. But it's still possible to get IME_ACTION_NEXT // and IME_ACTION_PREVIOUS here in case if 'disableFullscreenUI' is false and Android // decides to render this EditText in the full screen mode (when a phone has the // landscape orientation for example). The full screen EditText also renders an action // button specified by the 'returnKeyType' prop. We have to prevent Android from // requesting focus from the next/previous focusable view since it must only be // controlled from JS. return actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_PREVIOUS; } return true; } }); } private class ReactContentSizeWatcher implements ContentSizeWatcher { private ReactEditText mEditText; private EventDispatcher mEventDispatcher; private int mPreviousContentWidth = 0; private int mPreviousContentHeight = 0; public ReactContentSizeWatcher(ReactEditText editText) { mEditText = editText; ReactContext reactContext = getReactContext(editText); mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); } @Override public void onLayout() { int contentWidth = mEditText.getWidth(); int contentHeight = mEditText.getHeight(); // Use instead size of text content within EditText when available if (mEditText.getLayout() != null) { contentWidth = mEditText.getCompoundPaddingLeft() + mEditText.getLayout().getWidth() + mEditText.getCompoundPaddingRight(); contentHeight = mEditText.getCompoundPaddingTop() + mEditText.getLayout().getHeight() + mEditText.getCompoundPaddingBottom(); } if (contentWidth != mPreviousContentWidth || contentHeight != mPreviousContentHeight) { mPreviousContentHeight = contentHeight; mPreviousContentWidth = contentWidth; mEventDispatcher.dispatchEvent( new ReactContentSizeChangedEvent( mEditText.getId(), PixelUtil.toDIPFromPixel(contentWidth), PixelUtil.toDIPFromPixel(contentHeight))); } } } private class ReactSelectionWatcher implements SelectionWatcher { private ReactEditText mReactEditText; private EventDispatcher mEventDispatcher; private int mPreviousSelectionStart; private int mPreviousSelectionEnd; public ReactSelectionWatcher(ReactEditText editText) { mReactEditText = editText; ReactContext reactContext = getReactContext(editText); mEventDispatcher = getEventDispatcher(reactContext, editText); } @Override public void onSelectionChanged(int start, int end) { // Android will call us back for both the SELECTION_START span and SELECTION_END span in text // To prevent double calling back into js we cache the result of the previous call and only // forward it on if we have new values // Apparently Android might call this with an end value that is less than the start value int realStart = Math.min(start, end); int realEnd = Math.max(start, end); if (mPreviousSelectionStart != realStart || mPreviousSelectionEnd != realEnd) { mEventDispatcher.dispatchEvent( new ReactTextInputSelectionEvent(mReactEditText.getId(), realStart, realEnd)); mPreviousSelectionStart = realStart; mPreviousSelectionEnd = realEnd; } } } private class ReactScrollWatcher implements ScrollWatcher { private ReactEditText mReactEditText; private EventDispatcher mEventDispatcher; private int mPreviousHoriz; private int mPreviousVert; public ReactScrollWatcher(ReactEditText editText) { mReactEditText = editText; ReactContext reactContext = getReactContext(editText); mEventDispatcher = getEventDispatcher(reactContext, editText); } @Override public void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) { if (mPreviousHoriz != horiz || mPreviousVert != vert) { ScrollEvent event = ScrollEvent.obtain( mReactEditText.getId(), ScrollEventType.SCROLL, horiz, vert, 0f, // can't get x velocity 0f, // can't get y velocity 0, // can't get content width 0, // can't get content height mReactEditText.getWidth(), mReactEditText.getHeight()); mEventDispatcher.dispatchEvent(event); mPreviousHoriz = horiz; mPreviousVert = vert; } } } @Override public @Nullable Map getExportedViewConstants() { return MapBuilder.of( "AutoCapitalizationType", MapBuilder.of( "none", 0, "characters", InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS, "words", InputType.TYPE_TEXT_FLAG_CAP_WORDS, "sentences", InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)); } @Override public void setPadding(ReactEditText view, int left, int top, int right, int bottom) { view.setPadding(left, top, right, bottom); } /** * May be overriden by subclasses that would like to provide their own instance of the internal * {@code EditText} this class uses to determine the expected size of the view. */ protected EditText createInternalEditText(ThemedReactContext themedReactContext) { return new EditText(themedReactContext); } @Override public Object updateState( ReactEditText view, ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper) { ReadableNativeMap state = stateWrapper.getState(); // Do we need to communicate theme back to C++? // If so, this should only need to be done once per surface. if (!state.getBoolean("hasThemeData")) { WritableNativeMap update = new WritableNativeMap(); ReactContext reactContext = UIManagerHelper.getReactContext(view); if (reactContext instanceof ThemedReactContext) { ThemedReactContext themedReactContext = (ThemedReactContext) reactContext; EditText editText = createInternalEditText(themedReactContext); // Even though we check `data["textChanged"].empty()` before using the value in C++, // state updates crash without this value on key exception. It's unintuitive why // folly::dynamic is crashing there and if there's any way to fix on the native side, // so leave this here until we can figure out a better way of key-existence-checking in C++. update.putNull("textChanged"); update.putDouble( "themePaddingStart", PixelUtil.toDIPFromPixel(ViewCompat.getPaddingStart(editText))); update.putDouble( "themePaddingEnd", PixelUtil.toDIPFromPixel(ViewCompat.getPaddingEnd(editText))); update.putDouble("themePaddingTop", PixelUtil.toDIPFromPixel(editText.getPaddingTop())); update.putDouble( "themePaddingBottom", PixelUtil.toDIPFromPixel(editText.getPaddingBottom())); stateWrapper.updateState(update); } else { ReactSoftException.logSoftException( TAG, new IllegalStateException( "ReactContext is not a ThemedReactContent: " + (reactContext != null ? reactContext.getClass().getName() : "null"))); } } ReadableMap attributedString = state.getMap("attributedString"); ReadableMap paragraphAttributes = state.getMap("paragraphAttributes"); Spannable spanned = TextLayoutManager.getOrCreateSpannableForText( view.getContext(), attributedString, mReactTextViewManagerCallback); int textBreakStrategy = TextAttributeProps.getTextBreakStrategy(paragraphAttributes.getString("textBreakStrategy")); view.mStateWrapper = stateWrapper; return ReactTextUpdate.buildReactTextUpdateFromState( spanned, state.getInt("mostRecentEventCount"), false, // TODO add this into local Data TextAttributeProps.getTextAlignment(props), textBreakStrategy, TextAttributeProps.getJustificationMode(props), attributedString); } }
package com.battlelancer.seriesguide.getglueapi; import com.actionbarsherlock.app.ActionBar; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.getglueapi.GetGlue.CheckInTask; import com.battlelancer.seriesguide.ui.BaseActivity; import com.battlelancer.seriesguide.util.ShareUtils; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthProvider; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * Executes the OAuthRequestTokenTask to retrieve a request token and authorize * it by the user. After the request is authorized, this will get the callback. */ public class PrepareRequestTokenActivity extends BaseActivity { final String TAG = "PrepareRequestTokenActivity"; private OAuthConsumer mConsumer; private OAuthProvider mProvider; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.oauthscreen); final ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(getString(R.string.oauthmessage)); actionBar.setDisplayShowTitleEnabled(true); Resources res = getResources(); this.mConsumer = new CommonsHttpOAuthConsumer(res.getString(R.string.getglue_consumer_key), res.getString(R.string.getglue_consumer_secret)); this.mProvider = new CommonsHttpOAuthProvider(GetGlue.REQUEST_URL, GetGlue.ACCESS_URL, GetGlue.AUTHORIZE_URL); Log.i(TAG, "Starting task to retrieve request token."); new OAuthRequestTokenTask(this, mConsumer, mProvider).execute(); } /** * Called when the OAuthRequestTokenTask finishes (user has authorized the * request token). The callback URL will be intercepted here. */ @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); final Uri uri = intent.getData(); if (uri != null && uri.getScheme().equals(GetGlue.OAUTH_CALLBACK_SCHEME)) { Log.i(TAG, "Callback received, retrieving Access Token"); new RetrieveAccessTokenTask(mConsumer, mProvider, this).execute(uri); finish(); } } public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Integer> { private static final int AUTH_FAILED = 0; private static final int AUTH_SUCCESS = 1; private SharedPreferences mPrefs; private OAuthProvider mProvider; private OAuthConsumer mConsumer; private Context mContext; public RetrieveAccessTokenTask(OAuthConsumer consumer, OAuthProvider provider, Context context) { mPrefs = PreferenceManager.getDefaultSharedPreferences(context); mProvider = provider; mConsumer = consumer; mContext = context; } /** * Retrieve the oauth_verifier, and store the oauth and * oauth_token_secret for future API calls. */ @Override protected Integer doInBackground(Uri... params) { final Uri uri = params[0]; final String oauth_verifier = uri.getQueryParameter("oauth_verifier"); try { mProvider.retrieveAccessToken(mConsumer, oauth_verifier); mPrefs.edit().putString(GetGlue.OAUTH_TOKEN, mConsumer.getToken()) .putString(GetGlue.OAUTH_TOKEN_SECRET, mConsumer.getTokenSecret()).commit(); Log.i(TAG, "OAuth - Access Token Retrieved"); return AUTH_SUCCESS; } catch (OAuthMessageSignerException e) { Log.e(TAG, "OAuth - Access Token Retrieval Error", e); } catch (OAuthNotAuthorizedException e) { Log.e(TAG, "OAuth - Access Token Retrieval Error", e); } catch (OAuthExpectationFailedException e) { Log.e(TAG, "OAuth - Access Token Retrieval Error", e); } catch (OAuthCommunicationException e) { Log.e(TAG, "OAuth - Access Token Retrieval Error", e); } return AUTH_FAILED; } @Override protected void onPostExecute(Integer result) { switch (result) { case AUTH_SUCCESS: Bundle extras = getIntent().getExtras(); String comment = extras.getString(ShareUtils.KEY_GETGLUE_COMMENT); String imdbId = extras.getString(ShareUtils.KEY_GETGLUE_IMDBID); new CheckInTask(imdbId, comment, mContext).execute(); break; case AUTH_FAILED: Toast.makeText(getApplicationContext(), getString(R.string.checkinfailed), Toast.LENGTH_LONG).show(); break; } } } }
package uk.ac.ncl.openlab.intake24.client; import org.pcollections.PVector; import org.pcollections.TreePVector; import org.workcraft.gwt.shared.client.Function1; import org.workcraft.gwt.shared.client.Function2; import org.workcraft.gwt.shared.client.Option; import org.workcraft.gwt.shared.client.Pair; import uk.ac.ncl.openlab.intake24.client.api.errors.ErrorReport; import uk.ac.ncl.openlab.intake24.client.api.errors.ErrorReportingService; import uk.ac.ncl.openlab.intake24.client.survey.*; import uk.ac.ncl.openlab.intake24.client.survey.portionsize.DefaultPortionSizeScripts; import uk.ac.ncl.openlab.intake24.client.survey.portionsize.MilkInHotDrinkPortionSizeScript; import uk.ac.ncl.openlab.intake24.client.survey.portionsize.MilkInHotDrinkPortionSizeScriptLoader; import uk.ac.ncl.openlab.intake24.client.survey.portionsize.PortionSize; import java.util.HashMap; import static org.workcraft.gwt.shared.client.CollectionUtils.foldl; import static org.workcraft.gwt.shared.client.CollectionUtils.map; public class ProcessMilkInHotDrinks implements Function1<Survey, Survey> { public PVector<Pair<Integer, Integer>> findPairs(final Meal meal) { return foldl(meal.foods, TreePVector.<Pair<Integer, Integer>>empty(), new Function2<PVector<Pair<Integer, Integer>>, FoodEntry, PVector<Pair<Integer, Integer>>>() { @Override public PVector<Pair<Integer, Integer>> apply(final PVector<Pair<Integer, Integer>> pairs, final FoodEntry next) { return next.accept(new FoodEntry.Visitor<PVector<Pair<Integer, Integer>>>() { @Override public PVector<Pair<Integer, Integer>> visitRaw(RawFood food) { return pairs; } @Override public PVector<Pair<Integer, Integer>> visitEncoded(EncodedFood food) { if (food.isInCategory(SpecialData.FOOD_CODE_MILK_IN_HOT_DRINK)) { // Foods from MHDK category must use milk-in-a-hot-drink for portion size estimation, // but this requirement currently has to be maintained manually and is often violated. // This will skip foods that are in MHDK but whose portion size has been estimated // using a different method to prevent crashes in the post process function. if (!food.completedPortionSize().method.equals(MilkInHotDrinkPortionSizeScript.name)) { return pairs; } else return food.link.linkedTo.accept(new Option.Visitor<UUID, PVector<Pair<Integer, Integer>>>() { @Override public PVector<Pair<Integer, Integer>> visitSome(UUID drink_id) { return pairs.plus(Pair.create(meal.foodIndex(next), meal.foodIndex(drink_id))); } @Override public PVector<Pair<Integer, Integer>> visitNone() { String details = "Milk from this category must be linked to a hot drink: \"" + food.description() + "\" in meal \"" + meal.name + "\""; UncaughtExceptionHandler.reportError(new RuntimeException(details)); return pairs; } }); } else return pairs; } @Override public PVector<Pair<Integer, Integer>> visitTemplate(TemplateFood food) { return pairs; } @Override public PVector<Pair<Integer, Integer>> visitMissing(MissingFood food) { return pairs; } @Override public PVector<Pair<Integer, Integer>> visitCompound(CompoundFood food) { return pairs; } }); } }); } public Meal processPair(Meal meal, Pair<Integer, Integer> pair) { EncodedFood milk = meal.foods.get(pair.left).asEncoded(); EncodedFood drink = meal.foods.get(pair.right).asEncoded(); CompletedPortionSize milk_ps = milk.completedPortionSize(); CompletedPortionSize drink_ps = drink.completedPortionSize(); double milkPart; if (!milk_ps.data.containsKey(MilkInHotDrinkPortionSizeScript.MILK_VOLUME_KEY)) { // Previously only standard milk percentage options were allowed, this has been changed to allow custom // percentage values to be defined in survey schemes. This branch is intended to prevent crashes in case if // partially completed surveys are cached using the old mechanism. int milkPartIndex = Integer.parseInt(milk_ps.data.get(MilkInHotDrinkPortionSizeScript.MILK_PART_INDEX_KEY)); milkPart = DefaultPortionSizeScripts.defaultMilkInHotDrinkPercentages.get(milkPartIndex).weight; } else { milkPart = Double.parseDouble(milk_ps.data.get(MilkInHotDrinkPortionSizeScript.MILK_VOLUME_KEY)); } double drinkVolume = Double.parseDouble(drink_ps.data.get("servingWeight")); double drinkLeftoverVolume = Double.parseDouble(drink_ps.data.get("leftoversWeight")); double finalDrinkVolume = drinkVolume * (1 - milkPart); double finalDrinkLeftoverVolume = drinkLeftoverVolume * (1 - milkPart); double finalMilkVolume = drinkVolume * milkPart; double finalMilkLeftoverVolume = drinkLeftoverVolume * milkPart; HashMap<String, String> finalMilkData = new HashMap<String, String>(milk_ps.data); finalMilkData.put("servingWeight", Double.toString(finalMilkVolume)); finalMilkData.put("leftoversWeight", Double.toString(finalMilkLeftoverVolume)); HashMap<String, String> finalDrinkData = new HashMap<String, String>(drink_ps.data); finalDrinkData.put("servingWeight", Double.toString(finalDrinkVolume)); finalDrinkData.put("leftoversWeight", Double.toString(finalDrinkLeftoverVolume)); CompletedPortionSize finalMilkPs = new CompletedPortionSize(milk_ps.method, finalMilkData); CompletedPortionSize finalDrinkPs = new CompletedPortionSize(milk_ps.method, finalDrinkData); return meal.updateFood(pair.left, milk.withPortionSize(PortionSize.complete(finalMilkPs))) .updateFood(pair.right, drink.withPortionSize(PortionSize.complete(finalDrinkPs))); } public Meal processMeal(Meal meal) { return foldl(findPairs(meal), meal, new Function2<Meal, Pair<Integer, Integer>, Meal>() { @Override public Meal apply(Meal arg1, Pair<Integer, Integer> arg2) { return processPair(arg1, arg2); } }); } @Override public Survey apply(Survey survey) { return survey.withMeals(map(survey.meals, new Function1<Meal, Meal>() { @Override public Meal apply(Meal argument) { return processMeal(argument); } })); } }
package heufybot.modules; import heufybot.utils.FileUtils; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Searcher { private String rootLogPath; public Searcher(String rootLogPath) { this.rootLogPath = rootLogPath; } public String firstSeen(String source, String searchTerms) { File[] logsFolder = new File(rootLogPath).listFiles(); Arrays.sort(logsFolder); for(File file : logsFolder) { int dateStart = file.getPath().lastIndexOf(File.separator) + 1; String date = "[" + file.getPath().substring(dateStart, dateStart + 10) + "] "; String[] lines = FileUtils.readFile(file.getPath()).split("\n"); Pattern normalPattern = Pattern.compile(".*<(.?" + searchTerms + ")> .*", Pattern.CASE_INSENSITIVE); Pattern actionPattern = Pattern.compile(".*\\* (" + searchTerms + ") .*", Pattern.CASE_INSENSITIVE); for(String line : lines) { Matcher matcher = normalPattern.matcher(line); if(matcher.find()) { return date + line; } else { matcher = actionPattern.matcher(line); if(matcher.find()) { return date + line; } } } } return "No user matching \"" + searchTerms + "\" was found in the logs."; } public String lastSeen(String source, String searchTerms, boolean includeToday) { File[] logsFolder = new File(rootLogPath).listFiles(); Arrays.sort(logsFolder); Date today = new Date(); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String todayString = formatter.format(today); for(int i = logsFolder.length - 1; i >= 1; i { File file = logsFolder[i]; int dateStart = file.getPath().lastIndexOf(File.separator) + 1; String date = "[" + file.getPath().substring(dateStart, dateStart + 10) + "] "; if(!(includeToday && date.equals(todayString))) { String[] lines = FileUtils.readFile(file.getPath()).split("\n"); Pattern normalPattern = Pattern.compile(".*<(.?" + searchTerms + ")> .*", Pattern.CASE_INSENSITIVE); Pattern actionPattern = Pattern.compile(".*\\* (" + searchTerms + ") .*", Pattern.CASE_INSENSITIVE); for(String line : lines) { Matcher matcher = normalPattern.matcher(line); if(matcher.find()) { return date + line; } else { matcher = actionPattern.matcher(line); if(matcher.find()) { return date + line; } } } } } return "No user matching \"" + searchTerms + "\" was found in the logs."; } }
package WriterImplementation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import Exception.DBManagerException; import Exception.VariableManagerException; import Model.DatabaseConfig; import Model.Variable; import Model.VariableList; import WriterInterface.GenericWriterInterface; public class PHPGenericWriterImpl implements GenericWriterInterface { private static PHPGenericWriterImpl _genericWriterImpl; private PHPGenericWriterImpl() { if( _genericWriterImpl != null ) { throw new InstantiationError( "More instances of this object cannot be created." ); } } private synchronized static void createInstance(){ if(_genericWriterImpl==null){ _genericWriterImpl = new PHPGenericWriterImpl(); } } public static PHPGenericWriterImpl getInstace(){ if(_genericWriterImpl==null) createInstance(); return _genericWriterImpl; } @Override public void header(String path) { FileWriterImpl.getInstace().fileDelete(path); File f ; try { f = FileWriterImpl.getInstace().fileCreate(path); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } FileWriterImpl.getInstace().writeLine("<?php ", f); } @Override public void getInputVars(String path, List<String> input) throws VariableManagerException{ printInputVars(path, input, "_GET"); } @Override public void postInputVars(String path, List<String> input) throws VariableManagerException{ printInputVars(path, input, "_POST"); } private void printInputVars(String path, List<String> input, String method) throws VariableManagerException{ File f ; try { f = FileWriterImpl.getInstace().fileCreate(path); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } FileWriterImpl.getInstace().writeLine("if("+method+"){",f ); for(String var : input){ String line = "\t$"+var+" = $"+method+"[\""+var+"\"];"; FileWriterImpl.getInstace().writeLine(line, f); VariableManagerImpl.getInstace().addVariable(var, path); } FileWriterImpl.getInstace().writeLine("}",f ); } @Override public void addDatabase(String alias, String host, String port, String user, String passsword, String databaseName) throws DBManagerException{ String filename = "config/db_"+alias+".php"; header(filename); File f; try { f = FileWriterImpl.getInstace().fileCreate(filename); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } FileWriterImpl.getInstace().writeLine("$_db_config_host="+host, f); FileWriterImpl.getInstace().writeLine("$_db_config_port="+port, f); FileWriterImpl.getInstace().writeLine("$_db_config_user="+user, f); FileWriterImpl.getInstace().writeLine("$_db_config_password="+passsword, f); FileWriterImpl.getInstace().writeLine("$_db_config_databaseName="+databaseName, f); EOF(filename); DatabaseConfig databaseConfig = new DatabaseConfig(); databaseConfig.setAlias(alias); databaseConfig.setConfigFileName(filename); databaseConfig.setDatabaseName(databaseName); databaseConfig.setPassword(passsword); databaseConfig.setPort(port); databaseConfig.setURL(host); databaseConfig.setUser(user); DBManagerImpl.getInstace().addDatabaseConfig(databaseConfig); } @Override public void useDatabase(String alias, String path) { File f; try { f = FileWriterImpl.getInstace().fileCreate(path); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } //get database config DatabaseConfig db = DBManagerImpl.getInstace().getDatabaseConfig(alias); //include of connection details FileWriterImpl.getInstace().writeLine("include '"+db.getConfigFileName()+"';", f); //PDO connection to database String phpCode = "/* Connect to an ODBC database using driver invocation */\n" + "$_dsn = 'mysql:dbname=$_db_config_databaseName;host=$_db_config_host';\n" + "\n" + "try {\n" + " $dbh = new PDO($_dsn, $_db_config_user, $_db_config_password);\n" + "} catch (PDOException $e) {\n" + " echo 'Connection failed: ' . $e->getMessage();\n" + "}"; FileWriterImpl.getInstace().writeLine(phpCode, f); } @Override public void beginTransaction(String path){ String phpCode="try {\n"+ " $dbn->beginTransaction();\n"; try { FileWriterImpl.getInstace().writeLine(phpCode, FileWriterImpl.getInstace().fileCreate(path)); } catch (IOException e) { e.printStackTrace(); } } @Override public void endTransaction(String path){ String phpCode = " $dbn->commit();\n" + "} catch(PDOException $ex) {\n" + " //Something went wrong rollback!\n" + " $dbn->rollBack();\n" + " echo $ex->getMessage();\n" + "}"; try { FileWriterImpl.getInstace().writeLine(phpCode, FileWriterImpl.getInstace().fileCreate(path)); } catch (IOException e) { e.printStackTrace(); } } /* (non-Javadoc) * example of query * $stmt = $db->prepare("UPDATE table SET name=? WHERE id=?"); * $stmt->execute(array($name, $id)); * $affected_rows = $stmt->rowCount(); * @see WriterInterface.GenericWriterInterface#executeSqlQuery(java.lang.String, java.lang.String, java.util.List) */ @Override public void executeSqlQuery(String path, String query, List<Variable> queryParameters){ File f; try { f = FileWriterImpl.getInstace().fileCreate(path); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } FileWriterImpl.getInstace().writeLine("$dbn->query($sqlQuery);", f); String phpCode= "try {\n" + "$sqlQuery=\""+query+"\"; \n"+ " $stmt = $dbn->prepare($sqlQuery); \n"; boolean useArrayOfParameters = false; if(queryParameters!=null){ if(queryParameters.size()>0){ useArrayOfParameters= true; } } if(useArrayOfParameters){ phpCode+="$stmt->execute(array("; int paramNumber = 0; for (Variable variable : queryParameters) { if(paramNumber!=0){ phpCode+= ", "; } phpCode+= "$"+variable.getName()+" "; } phpCode+= "));\n"; }else{ phpCode+="$stmt->execute();"; } phpCode += "} catch(PDOException $ex) {\n" + " echo \"An Error occured!\"; \n" + "}"; FileWriterImpl.getInstace().writeLine(phpCode, f); } @Override public void executeSqlQueryAndGetResultInVariable(String path, String query, List<Variable> queryParameters, String variableName) throws VariableManagerException{ executeSqlQuery(path, query, queryParameters); try { FileWriterImpl.getInstace().writeLine("$"+variableName+"= $stmt->fetchAll(PDO::FETCH_ASSOC);", FileWriterImpl.getInstace().fileCreate(path)); } catch (IOException e) { e.printStackTrace(); } VariableManagerImpl.getInstace().addVariable(variableName, path); } @Override public void executeSqlUpdateAndGetAffectedRowsNumberIntoVariable(String path, String query, List<Variable> queryParameters, String resultVariableName) throws VariableManagerException{ executeSqlQuery(path, query, queryParameters); try { FileWriterImpl.getInstace().writeLine("$"+resultVariableName+"= $stmt->rowCount();", FileWriterImpl.getInstace().fileCreate(path)); } catch (IOException e) { e.printStackTrace(); } VariableManagerImpl.getInstace().addVariable(resultVariableName, path); } @Override public void countResultRowsNumberAndGetResultInVariable(String path, String rowsVariableName, String countResultVariableName) throws VariableManagerException{ File f; try { f = FileWriterImpl.getInstace().fileCreate(path); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } String phpCode = "$"+countResultVariableName+" = $"+rowsVariableName+"->rowCount();"; FileWriterImpl.getInstace().writeLine(phpCode, f); VariableManagerImpl.getInstace().addVariable(countResultVariableName, path); } @Override public void getLastInsertedIdIntoVariable(String path, String resultVariableName) throws VariableManagerException { File f; try { f = FileWriterImpl.getInstace().fileCreate(path); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } String phpCode = "$"+resultVariableName+" = $dbn->lastInsertId();"; FileWriterImpl.getInstace().writeLine(phpCode, f); VariableManagerImpl.getInstace().addVariable(resultVariableName, path); } @Override public void EOF(String path) { File f ; try { f = FileWriterImpl.getInstace().fileCreate(path); } catch (IOException ex) { Logger.getLogger(PHPGenericWriterImpl.class.getName()).log(Level.SEVERE, null, ex); return; } FileWriterImpl.getInstace().writeLine("?>", f); } @Override public void printVariableAsJSON(String path, String variableName) { String line="echo json_encode(\"$"+variableName+"\");"; try { FileWriterImpl.getInstace().writeLine(line, FileWriterImpl.getInstace().fileCreate(path)); } catch (IOException e) { e.printStackTrace(); } } @Override public void printVariableAsXML(String path, String variableName) { String line="echo xmlrpc_encode(\"$"+variableName+"\");"; try { FileWriterImpl.getInstace().writeLine(line, FileWriterImpl.getInstace().fileCreate(path)); } catch (IOException e) { e.printStackTrace(); } } @Override public void writeArithmeticAndGetResultInVariable(String path, String arithmetic, VariableList variableList, String resultVariableName) { List<String> values = new ArrayList<>(); for (Variable var : variableList.getVars()) { values.add("$"+var.getName()); } String arithmeticLine = String.format(arithmetic.replace("?", "%s"), values.toArray()); String line = resultVariableName+"="+arithmeticLine+";"; try { FileWriterImpl.getInstace().writeLine(line, FileWriterImpl.getInstace().fileCreate(path)); } catch (IOException e) { e.printStackTrace(); } } }
package br.com.fiap.banco.util; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Locale; import br.com.fiap.banco.constantes.Tarifas; import br.com.fiap.banco.entidades.Conta; import br.com.fiap.banco.entidades.Emprestimo; public class CaluladorEmprestimoUtil { private static DecimalFormat df2 = new DecimalFormat(".##", DecimalFormatSymbols.getInstance(new Locale("en", "US"))); public static List<Emprestimo> calcularEmprestimo(Conta conta, double valor, int qtdeParcelas) { List<Emprestimo> parcelas = new ArrayList<>(); double valorParcela = valor / qtdeParcelas; for (int i = 1; i <= qtdeParcelas; i++) { Emprestimo emprestimo = new Emprestimo(); emprestimo.setConta(conta); emprestimo.setParcelaPaga(false); emprestimo.setNumeroParcela(i); emprestimo.setDataVencimento(LocalDate.now().plusMonths(i)); valorParcela += valorParcela * ((double) Tarifas.EMPRESTIMO.getJurosMensais() / 100); emprestimo.setValorParcela(Double.valueOf(df2.format(valorParcela))); parcelas.add(emprestimo); } return parcelas; } }
package org.zoneproject.extractor.rssreader; import java.util.ArrayList; import org.zoneproject.extractor.utils.Item; /** * * @author Desclaux Christophe <christophe@zouig.org> */ public class App { private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(App.class); public static int SIM_DOWNLOADS = 100; public App(){ String [] tmp = {}; App.main(tmp); } public static void main( String[] args ) { String [] sources = RSSGetter.getSources(); DownloadNewsThread[] th = new DownloadNewsThread[SIM_DOWNLOADS]; for(int i = 0; i < sources.length; i+=SIM_DOWNLOADS){ for(int curSource = i; (curSource < (i+SIM_DOWNLOADS)) && (curSource < sources.length); curSource++){ th[curSource-i] = new DownloadNewsThread(sources[curSource]); th[curSource-i].start(); } for(int curSource = i; (curSource < (i+SIM_DOWNLOADS)) && (curSource < sources.length); curSource++){ try { if(th[curSource-i] == null)continue; th[curSource-i].join(); th[curSource-i]=null; } catch (InterruptedException ex) { logger.warn(ex); } } } logger.info("Done"); } }
package uk.gov.ons.ctp.response.action.scheduled.plan; import javax.inject.Inject; import javax.inject.Named; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.scheduling.annotation.Scheduled; import lombok.extern.slf4j.Slf4j; import uk.gov.ons.ctp.response.action.service.ActionPlanJobService; /** * This bean will have the actionPlanJobService injected into it by spring on * constructions. It will then schedule the running of the actionPlanJobService * createAndExecuteAllActionPlanJobs using details from the AppConfig */ @Named @Slf4j public class PlanScheduler implements HealthIndicator { @Inject private ActionPlanJobService actionPlanJobServiceImpl; private PlanExecutionInfo executionInfo = new PlanExecutionInfo(); /** * schedule the Execution of Action Plans It is simply a scheduled trigger for * the service layer method. * */ @Scheduled(fixedDelayString = "#{appConfig.planExecution.delayMilliSeconds}") public void run() { log.info("Executing ActionPlans"); try { executionInfo = new PlanExecutionInfo(); executionInfo.setExecutedJobs(actionPlanJobServiceImpl.createAndExecuteAllActionPlanJobs()); } catch (Exception e) { log.error("Exception in action plan scheduler", e); } } @Override public Health health() { return Health.up() .withDetail("planExecutionInfo", executionInfo) .build(); } }
package ru.stqa.sch.addressbook.tests; import com.thoughtworks.xstream.XStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import ru.stqa.sch.addressbook.model.GroupData; import ru.stqa.sch.addressbook.model.Groups; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class GroupCreationTest extends TestBase { @DataProvider public Iterator<Object[]> validGroups() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/groups.xml"))) { String xml = ""; String line = reader.readLine(); while (line != null) { xml += line; line = reader.readLine(); } XStream xstream = new XStream(); xstream.processAnnotations(GroupData.class); List<GroupData> groups = (List<GroupData>) xstream.fromXML(xml); return groups.stream().map((g) -> new Object[]{g}).collect(Collectors.toList()).iterator(); } } @Test(dataProvider = "validGroups") public void testGroupCreation(GroupData group) { app.goTo().groupPage(); Groups before = app.db().groups(); app.group().create(group); assertThat(app.group().count(), equalTo(before.size() + 1)); Groups after = app.db().groups(); assertThat(after, equalTo( before.withAdded(group.withId(after.stream().mapToInt((g) -> g.getId()).max().getAsInt())))); } }
package ru.stqa.pft.addressbook.tests; import org.testng.Assert; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.GroupData; import java.util.HashSet; import java.util.List; public class GroupCreationTest extends TestBase { @Test public void testGroupCreation() { app.getNavigationHelper().gotoGroupPage(); List<GroupData> before = app.getGroupHelper().getGroupList(); GroupData group = new GroupData("Test2", null, null); app.getGroupHelper().createGroup(group); List<GroupData> after = app.getGroupHelper().getGroupList(); Assert.assertEquals(after.size(), before.size() +1); group.setId(after.stream().max((o1, o2) -> Integer.compare(o1.getId(), o2.getId())).get().getId()); before.add(group); Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after)); } }
package io.github.eddieringle.android.libs.andicons.sets; import android.content.Context; import android.graphics.Typeface; public class OcticonsSet { public static final String OCTICONS_FONT = "octicons_regular.ttf"; public static final int MINI = 0xf000; public static final int MEGA = 0xf200; public static final int IC_PRIVATE_REPO = 0x0000; public static final int IC_PUBLIC_REPO = 0x0001; public static final int IC_REPO_FORKED = 0x0002; public static final int IC_CREATE = 0x0003; public static final int IC_DELETE = 0x0004; public static final int IC_PUSH = 0x0005; public static final int IC_PULL = 0x0006; public static final int IC_WIKI = 0x0007; public static final int IC_README = 0x0007; public static final int IC_OCTOCAT = 0x0008; public static final int IC_BLACKTOCAT = 0x0009; public static final int IC_INVERTOCAT = 0x000a; public static final int IC_DOWNLOAD = 0x000b; public static final int IC_UPLOAD = 0x000c; public static final int IC_KEYBOARD = 0x000d; public static final int IC_GIST = 0x000e; public static final int IC_GIST_PRIVATE = 0x000f; public static final int IC_CODE_FILE = 0x0010; public static final int IC_DOWNLOAD_UNKNOWN = 0x0010; public static final int IC_TEXT_FILE = 0x0011; public static final int IC_DOWNLOAD_TEXT = 0x0011; public static final int IC_DOWNLOAD_MEDIA = 0x0012; public static final int IC_DOWNLOAD_ZIP = 0x0013; public static final int IC_DOWNLOAD_PDF = 0x0014; public static final int IC_DOWNLOAD_TAG = 0x0015; public static final int IC_DIRECTORY = 0x0016; public static final int IC_SUBMODULE = 0x0017; public static final int IC_PERSON = 0x0018; public static final int IC_TEAM = 0x0019; public static final int IC_MEMBER_ADDED = 0x001a; public static final int IC_MEMBER_REMOVED = 0x001b; public static final int IC_FOLLOW = 0x001c; public static final int IC_WATCHING = 0x001d; public static final int IC_UNWATCH = 0x001e; public static final int IC_COMMIT = 0x001f; public static final int IC_PUBLIC_FORK = 0x0020; public static final int IC_FORK = 0x0020; public static final int IC_PRIVATE_FORK = 0x0021; public static final int IC_PULL_REQUEST = 0x0022; public static final int IC_MERGE = 0x0023; public static final int IC_PUBLIC_MIRROR = 0x0024; public static final int IC_PRIVATE_MIRROR = 0x0025; public static final int IC_ISSUE_OPENED = 0x0026; public static final int IC_ISSUE_REOPENED = 0x0027; public static final int IC_ISSUE_CLOSED = 0x0028; public static final int IC_ISSUE_COMMENT = 0x0029; public static final int IC_STAR = 0x002a; public static final int IC_COMMIT_COMMENT = 0x002b; public static final int IC_HELP = 0x002c; public static final int IC_EXCLAMATION = 0x002d; public static final int IC_SEARCH_INPUT = 0x002e; public static final int IC_ADVANCED_SEARCH = 0x002f; public static final int IC_NOTIFICATIONS = 0x0030; public static final int IC_ACCOUNT_SETTINGS = 0x0031; public static final int IC_LOGOUT = 0x0032; public static final int IC_ADMIN_TOOLS = 0x0033; public static final int IC_FEED = 0x0034; public static final int IC_CLIPBOARD = 0x0035; /* UNOFFICIAL NAME */ public static final int IC_APPLE = 0x0036; public static final int IC_WINDOWS = 0x0037; public static final int IC_IOS = 0x0038; public static final int IC_ANDROID = 0x0039; public static final int IC_CONFIRM = 0x003a; public static final int IC_UNREAD_NOTE = 0x003b; public static final int IC_READ_NOTE = 0x003c; public static final int IC_ARR_UP = 0x003d; public static final int IC_ARR_RIGHT = 0x003e; public static final int IC_ARR_DOWN = 0x003f; public static final int IC_ARR_LEFT = 0x0040; public static final int IC_PIN = 0x0041; public static final int IC_GIFT = 0x0042; public static final int IC_GRAPH = 0x0043; public static final int IC_WRENCH = 0x0044; public static final int IC_CREDIT_CARD = 0x0045; public static final int IC_TIME = 0x0046; public static final int IC_RUBY = 0x0047; public static final int IC_PODCAST = 0x0048; public static final int IC_KEY = 0x0049; public static final int IC_FORCE_PUSH = 0x004a; public static final int IC_SYNC = 0x004b; public static final int IC_CLONE = 0x004c; public static final int IC_DIFF = 0x004d; public static final int IC_WATCHERS = 0x004e; public static final int IC_DISCUSSION = 0x004f; public static final int IC_DELETE_NOTE = 0x0050; public static final int IC_REMOVE_CLOSE = 0x0050; public static final int IC_REPLY = 0x0051; public static final int IC_MAIL_STATUS = 0x0052; public static final int IC_BLOCK = 0x0053; public static final int IC_TAG_CREATE = 0x0054; public static final int IC_TAG_DELETE = 0x0055; public static final int IC_BRANCH_CREATE = 0x0056; public static final int IC_BRANCH_DELETE = 0x0057; public static final int IC_EDIT = 0x0058; public static final int IC_INFO = 0x0059; public static final int IC_ARR_COLLAPSED = 0x005a; public static final int IC_ARR_EXPANDED = 0x005b; public static final int IC_LINK = 0x005c; public static final int IC_ADD = 0x005d; public static final int IC_REORDER = 0x005e; public static final int IC_CODE = 0x005f; public static final int IC_LOCATION = 0x0060; public static final int IC_U_LIST = 0x0061; public static final int IC_O_LIST = 0x0062; public static final int IC_QUOTEMARK = 0x0063; public static final int IC_VERSION = 0x0064; public static final int IC_BRIGHTNESS = 0x0065; public static final int IC_FULLSCREEN = 0x0066; public static final int IC_NORMALSCREEN = 0x0067; public static final int IC_CALENDAR = 0x0068; public static final int IC_BEER = 0x0069; public static final int IC_LOCK = 0x006a; public static final int IC_SECURE = 0x006a; public static final int IC_ADDED = 0x006b; public static final int IC_REMOVED = 0x006c; public static final int IC_MODIFIED = 0x006d; public static final int IC_MOVED = 0x006e; public static final int IC_ADD_COMMENT = 0x006f; public static final int IC_HORIZONTAL_RULE = 0x0070; public static final int IC_ARR_RIGHT_MINI = 0x0071; public static final int IC_JUMP_DOWN = 0x0072; public static final int IC_JUMP_UP = 0x0073; public static final int IC_REFERENCE = 0x0074; public static final int IC_MILESTONE = 0x0075; public static final int IC_SAVE_DOCUMENT = 0x0076; public static final int IC_MEGAPHONE = 0x0077; public static Typeface getTypeface(Context context) { return Typeface.createFromAsset(context.getAssets(), OCTICONS_FONT); } }
package ti.modules.titanium.ui.widget.searchview; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.util.TiRHelper; import org.appcelerator.titanium.util.TiRHelper.ResourceNotFoundException; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.ui.widget.searchbar.TiUISearchBar.OnSearchChangeListener; import android.support.v7.widget.SearchView; import android.widget.EditText; public class TiUISearchView extends TiUIView implements SearchView.OnQueryTextListener, SearchView.OnCloseListener { private SearchView searchView; private boolean changeEventEnabled = false; public static final String TAG = "SearchView"; protected OnSearchChangeListener searchChangeListener; public TiUISearchView(TiViewProxy proxy) { super(proxy); searchView = new SearchView(proxy.getActivity()); searchView.setOnQueryTextListener(this); searchView.setOnCloseListener(this); searchView.setOnQueryTextFocusChangeListener(this); setNativeView(searchView); } @Override public void processProperties(KrollDict props) { super.processProperties(props); // Check if the hint text is specified when the view is created. if (props.containsKey(TiC.PROPERTY_HINT_TEXT)) { searchView.setQueryHint(props.getString(TiC.PROPERTY_HINT_TEXT)); } changeEventEnabled = false; if (props.containsKey(TiC.PROPERTY_VALUE)) { searchView.setQuery(props.getString(TiC.PROPERTY_VALUE), false); } changeEventEnabled = true; if (props.containsKey(TiC.PROPERTY_ICONIFIED)) { searchView.setIconified(props.getBoolean(TiC.PROPERTY_ICONIFIED)); } if (props.containsKey(TiC.PROPERTY_ICONIFIED_BY_DEFAULT)) { searchView.setIconifiedByDefault(props.getBoolean(TiC.PROPERTY_ICONIFIED_BY_DEFAULT)); } if (props.containsKey(TiC.PROPERTY_SUBMIT_ENABLED)) { searchView.setSubmitButtonEnabled((props.getBoolean(TiC.PROPERTY_SUBMIT_ENABLED))); } if (props.containsKey(TiC.PROPERTY_COLOR)) { try { int id = TiRHelper.getResource("id.search_src_text"); EditText text = (EditText) searchView.findViewById(id); if (text != null) { text.setTextColor(TiConvert.toColor(props, TiC.PROPERTY_COLOR)); } } catch (ResourceNotFoundException e) { Log.e(TAG, "Could not find SearchView EditText"); } } } @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_COLOR)) { try { int id = TiRHelper.getResource("id.search_src_text"); EditText text = (EditText) searchView.findViewById(id); if (text != null) { text.setTextColor(TiConvert.toColor((String) newValue)); } } catch (ResourceNotFoundException e) { Log.e(TAG, "Could not find SearchView EditText"); } } else if (key.equals(TiC.PROPERTY_HINT_TEXT)) { searchView.setQueryHint((String) newValue); } else if (key.equals(TiC.PROPERTY_VALUE)) { searchView.setQuery((String) newValue, false); } else if (key.equals(TiC.PROPERTY_ICONIFIED)) { searchView.setIconified(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_ICONIFIED_BY_DEFAULT)) { searchView.setIconifiedByDefault(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_SUBMIT_ENABLED)) { searchView.setSubmitButtonEnabled(TiConvert.toBoolean(newValue)); } else { super.propertyChanged(key, oldValue, newValue, proxy); } } @Override public boolean onClose() { fireEvent(TiC.EVENT_CANCEL, null); return false; } @Override public boolean onQueryTextChange(String query) { proxy.setProperty(TiC.PROPERTY_VALUE, query); if (searchChangeListener != null) { searchChangeListener.filterBy(query); } if (changeEventEnabled) fireEvent(TiC.EVENT_CHANGE, null); return false; } @Override public boolean onQueryTextSubmit(String query) { TiUIHelper.showSoftKeyboard(nativeView, false); fireEvent(TiC.EVENT_SUBMIT, null); return false; } public void setOnSearchChangeListener(OnSearchChangeListener listener) { searchChangeListener = listener; } }
package com.chickenkiller.upods2.view.controller; import android.app.Fragment; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.models.RadioItem; import com.chickenkiller.upods2.views.ControllableScrollView; public class FragmentRadioItemDetails extends Fragment implements View.OnTouchListener { private static final int MAGIC_NUMBER = -250; //Don't know what it does private static final float BOTTOM_SCROLL_BRODER_PERENT = 0.35f; private static final float TOP_SCROLL_BRODER_PERENT = 0.85f; private static int bottomScrollBorder; private static int topScrollBorder; public static String TAG = "media_details"; private RadioItem radioItem; private RelativeLayout rlDetailedContent; private ControllableScrollView svDetails; private TextView tvDetailedDescription; private TextView tvDetailedHeader; private ImageView imgDetailedHeader; private ImageView imgDetailedTopCover; private int moveDeltayY; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.fragment_media_details, container, false); rlDetailedContent = (RelativeLayout) view.findViewById(R.id.rlDetailedContent); tvDetailedDescription = (TextView) view.findViewById(R.id.tvDetailedDescription); tvDetailedHeader = (TextView) view.findViewById(R.id.tvDetailedHeader); imgDetailedHeader = (ImageView) view.findViewById(R.id.imgDetailedHeader); imgDetailedTopCover = (ImageView) view.findViewById(R.id.imgDetailedCover); svDetails = (ControllableScrollView) view.findViewById(R.id.svDetails); svDetails.setEnabled(false); moveDeltayY = 0; if (radioItem != null) { Glide.with(getActivity()).load("http: Glide.with(getActivity()).load(radioItem.getCoverImageUrl()).centerCrop().crossFade().into(imgDetailedTopCover); tvDetailedHeader.setText(radioItem.getName()); tvDetailedDescription.setText(radioItem.getDescription()); } rlDetailedContent.setOnTouchListener(this); initFragmentScrollConstants(); return view; } private void initFragmentScrollConstants() { DisplayMetrics displaymetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels; bottomScrollBorder = height - (int) (height * BOTTOM_SCROLL_BRODER_PERENT); topScrollBorder = height - (int) (height * TOP_SCROLL_BRODER_PERENT); } public void setRadioItem(RadioItem radioItem) { this.radioItem = radioItem; } @Override public boolean onTouch(View view, MotionEvent event) { final int Y = (int) event.getRawY(); LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) rlDetailedContent.getLayoutParams(); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: moveDeltayY = Y - lParams.topMargin; break; case MotionEvent.ACTION_UP: { if (lParams.topMargin >= bottomScrollBorder) { getActivity().onBackPressed(); } else if (lParams.topMargin <= topScrollBorder) { lParams.topMargin = 0; lParams.bottomMargin = 0; view.setLayoutParams(lParams); svDetails.setEnabled(true); rlDetailedContent.setOnTouchListener(null); } break; } case MotionEvent.ACTION_POINTER_DOWN: break; case MotionEvent.ACTION_POINTER_UP: break; case MotionEvent.ACTION_MOVE: int newMargin = Y - moveDeltayY < 0 ? 0 : Y - moveDeltayY; lParams.topMargin = newMargin; lParams.bottomMargin = MAGIC_NUMBER; view.setLayoutParams(lParams); break; } return true; } }
package com.optimalorange.cooltechnologies.ui.fragment; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.etsy.android.grid.StaggeredGridView; import com.optimalorange.cooltechnologies.R; import com.optimalorange.cooltechnologies.entity.Video; import com.optimalorange.cooltechnologies.ui.PlayVideoActivity; import com.optimalorange.cooltechnologies.ui.SearchActivity; import com.optimalorange.cooltechnologies.ui.view.PullRefreshLayout; import com.optimalorange.cooltechnologies.util.Utils; import com.optimalorange.cooltechnologies.util.VideosRequest; import com.optimalorange.cooltechnologies.util.VolleySingleton; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.LinkedList; import java.util.List; public class ListVideosFragment extends Fragment { // Fragment /** * Videogenre<br/> * Type: String * * @see #newInstance(String genre) */ public static final String ARGUMENT_KEY_GENRE = ListVideosFragment.class.getName() + ".argument.KEY_GENRE"; private static final String CATEGORY_LABEL_OF_TECH = ""; private String mYoukuClientId; private VolleySingleton mVolleySingleton; private String mGenre; private int mPage = 1; private StaggeredGridView mGridView; private PullRefreshLayout mPullRefreshLayout; private ItemsAdapter mItemsAdapter; private LinkedList<Video> mListVideos = new LinkedList<Video>(); /** * VideoentityVideo * * @return VideoRequest */ private VideosRequest buildQueryVideosRequest() { VideosRequest.Builder builder = new VideosRequest.Builder() .setClient_id(mYoukuClientId) .setCategory(CATEGORY_LABEL_OF_TECH) .setPage(mPage) .setPeriod(VideosRequest.Builder.PERIOD.WEEK) .setOrderby(VideosRequest.Builder.ORDER_BY.VIEW_COUNT) .setResponseListener(new Response.Listener<List<Video>>() { @Override public void onResponse(List<Video> videos) { for (Video mVideo : videos) { mListVideos.add(mVideo); if (mItemsAdapter != null) { mItemsAdapter.notifyDataSetChanged(); } if (mPullRefreshLayout != null) { mPullRefreshLayout.setRefreshing(false); } } } }) .setErrorListener(new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); //Video mPage++; //mGenremGenreVideo if (mGenre != null) { builder.setGenre(mGenre); } return builder.build(); } /** * {@link ListVideosFragment} * * @param genre Videogenre * @return * @see #ARGUMENT_KEY_GENRE */ public static ListVideosFragment newInstance(String genre) { ListVideosFragment fragment = new ListVideosFragment(); Bundle arguments = new Bundle(); arguments.putString(ARGUMENT_KEY_GENRE, genre); fragment.setArguments(arguments); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Arguments if (getArguments() != null) { mGenre = getArguments().getString(ARGUMENT_KEY_GENRE); } mYoukuClientId = getString(R.string.youku_client_id); mVolleySingleton = VolleySingleton.getInstance(getActivity()); mVolleySingleton.addToRequestQueue(buildQueryVideosRequest()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_list_videos, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mGridView = (StaggeredGridView) view.findViewById(R.id.grid_view); mPullRefreshLayout = (PullRefreshLayout) view.findViewById(R.id.pull_refresh_layout); mItemsAdapter = new ItemsAdapter(mListVideos, mVolleySingleton.getImageLoader()); mGridView.setAdapter(mItemsAdapter); mPullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //Video mListVideos.clear(); mPage = 1; mItemsAdapter.notifyDataSetChanged(); //Video mVolleySingleton.addToRequestQueue(buildQueryVideosRequest()); } }); //item mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent mIntent = new Intent(getActivity(), PlayVideoActivity.class); mIntent.putExtra(PlayVideoActivity.EXTRA_KEY_VIDEO_ID, mListVideos.get(i).getId()); startActivity(mIntent); } }); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){ inflater.inflate(R.menu.menu_fragment_list_videos, menu); } @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case R.id.action_search: startActivity(new Intent(getActivity(), SearchActivity.class)); return true; } return super.onOptionsItemSelected(item); } /** * * * @author Zhou Peican */ private class ItemsAdapter extends BaseAdapter { private LinkedList<Video> mVideos; private ImageLoader mImageLoader; public ItemsAdapter(LinkedList<Video> mVideos, ImageLoader mImageLoader) { super(); this.mVideos = mVideos; this.mImageLoader = mImageLoader; } @Override public int getCount() { return mVideos.size(); } @Override public Object getItem(int position) { return mVideos.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder vh; if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_videos, parent, false); vh = new ViewHolder(); vh.thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail); vh.duration = (TextView) convertView.findViewById(R.id.duration); vh.title = (TextView) convertView.findViewById(R.id.title); vh.viewCount = (TextView) convertView.findViewById(R.id.view_count); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } mImageLoader.get(mVideos.get(position).getThumbnail_v2(), ImageLoader.getImageListener(vh.thumbnail, R.drawable.ic_launcher, R.drawable.ic_launcher)); vh.duration.setText(Utils.getDurationString(mVideos.get(position).getDuration())); vh.title.setText(mVideos.get(position).getTitle()); vh.viewCount.setText(String.format(getString(R.string.view_count), Utils.formatViewCount(mVideos.get(position).getView_count(), parent.getContext()))); //Video if (position == mListVideos.size() - 2) { mVolleySingleton.addToRequestQueue(buildQueryVideosRequest()); } return convertView; } private class ViewHolder { ImageView thumbnail; TextView duration; TextView title; TextView viewCount; } } }
package org.atlasapi.application; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import org.atlasapi.entity.Sourced; import org.atlasapi.entity.Sourceds; import org.atlasapi.media.entity.Publisher; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; public class ApplicationSources { private final boolean precedence; private final List<SourceReadEntry> reads; private final List<Publisher> writes; private final Optional<List<Publisher>> contentHierarchyPrecedence; private final ImmutableSet<Publisher> enabledReadSources; private final Boolean imagePrecedenceEnabled; private static final Predicate<SourceReadEntry> ENABLED_READS_FILTER = new Predicate<SourceReadEntry>() { @Override public boolean apply(@Nullable SourceReadEntry input) { return input.getSourceStatus().isEnabled(); } }; private static final Function<SourceReadEntry, Publisher> SOURCEREADS_TO_PUBLISHER = new Function<SourceReadEntry, Publisher>() { @Override public Publisher apply(@Nullable SourceReadEntry input) { return input.getPublisher(); } }; private static final Function<SourceReadEntry, Publisher> READ_TO_PUBLISHER = new Function<SourceReadEntry, Publisher>() { @Override public Publisher apply(@Nullable SourceReadEntry input) { return input.getPublisher(); }}; private static final Comparator<SourceReadEntry> SORT_READS_BY_PUBLISHER = new Comparator<SourceReadEntry>() { @Override public int compare(SourceReadEntry a, SourceReadEntry b) { return a.getPublisher().compareTo(b.getPublisher()); }}; private ApplicationSources(Builder builder) { this.precedence = builder.precedence; this.reads = ImmutableList.copyOf(builder.reads); this.writes = ImmutableList.copyOf(builder.writes); this.contentHierarchyPrecedence = builder.contentHierarchyPrecedence; this.imagePrecedenceEnabled = builder.imagePrecedenceEnabled; this.enabledReadSources = ImmutableSet.copyOf( Iterables.transform( Iterables.filter(this.getReads(), ENABLED_READS_FILTER), SOURCEREADS_TO_PUBLISHER) );; } public boolean isPrecedenceEnabled() { return precedence; } public List<SourceReadEntry> getReads() { return reads; } public List<Publisher> getWrites() { return writes; } public Ordering<Publisher> publisherPrecedenceOrdering() { return Ordering.explicit(Lists.transform(reads, READ_TO_PUBLISHER)); } private Optional<Ordering<Publisher>> contentHierarchyPrecedenceOrdering() { if (contentHierarchyPrecedence.isPresent()) { return Optional.of(Ordering.explicit(contentHierarchyPrecedence.get())); } else { return Optional.absent(); } } public Optional<List<Publisher>> contentHierarchyPrecedence() { return contentHierarchyPrecedence; } private ImmutableList<Publisher> peoplePrecedence() { return ImmutableList.of(Publisher.RADIO_TIMES, Publisher.PA, Publisher.BBC, Publisher.C4, Publisher.ITV); } public boolean peoplePrecedenceEnabled() { return peoplePrecedence() != null; } public Ordering<Publisher> peoplePrecedenceOrdering() { // Add missing publishers return orderingIncludingMissingPublishers(peoplePrecedence()); } private Ordering<Publisher> orderingIncludingMissingPublishers(List<Publisher> publishers) { List<Publisher> fullListOfPublishers = Lists.newArrayList(publishers); for (Publisher publisher : Publisher.values()) { if (!fullListOfPublishers.contains(publisher)) { fullListOfPublishers.add(publisher); } } return Ordering.explicit(fullListOfPublishers); } public Ordering<Sourced> getSourcedPeoplePrecedenceOrdering() { return peoplePrecedenceOrdering().onResultOf(Sourceds.toPublisher()); } /** * Temporary: these should be persisted and not hardcoded */ private ImmutableList<Publisher> imagePrecedence() { return ImmutableList.of(Publisher.PA, Publisher.BBC, Publisher.C4); } public boolean imagePrecedenceEnabled() { // The default behaviour should be enabled if not specified return imagePrecedenceEnabled == null || imagePrecedenceEnabled; } public Ordering<Publisher> imagePrecedenceOrdering() { return publisherPrecedenceOrdering(); } public Ordering<Sourced> getSourcedImagePrecedenceOrdering() { return imagePrecedenceOrdering().onResultOf(Sourceds.toPublisher()); } public ImmutableSet<Publisher> getEnabledReadSources() { return this.enabledReadSources; } public boolean isReadEnabled(Publisher source) { return this.getEnabledReadSources().contains(source); } public boolean isWriteEnabled(Publisher source) { return this.getWrites().contains(source); } public SourceStatus readStatusOrDefault(Publisher source) { for (SourceReadEntry entry : this.getReads()) { if (entry.getPublisher().equals(source)) { return entry.getSourceStatus(); } } return SourceStatus.fromV3SourceStatus(source.getDefaultSourceStatus()); } public Ordering<Sourced> getSourcedReadOrdering() { Ordering<Publisher> ordering = this.publisherPrecedenceOrdering(); return ordering.onResultOf(Sourceds.toPublisher()); } public Optional<Ordering<Sourced>> getSourcedContentHierarchyOrdering() { if (!contentHierarchyPrecedence.isPresent()) { return Optional.absent(); } Ordering<Publisher> ordering = orderingIncludingMissingPublishers(this.contentHierarchyPrecedence.get()); return Optional.of(ordering.onResultOf(Sourceds.toPublisher())); } private static final ApplicationSources dflts = createDefaults(); private static final ApplicationSources createDefaults() { ApplicationSources dflts = ApplicationSources.builder() .build() .copyWithMissingSourcesPopulated(); for (Publisher source : Publisher.all()) { if (source.enabledWithNoApiKey()) { dflts = dflts.copyWithChangedReadableSourceStatus(source, SourceStatus.AVAILABLE_ENABLED); } } return dflts; } // Build a default configuration, this will get popualated with publishers // with default source status public static ApplicationSources defaults() { return dflts; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ApplicationSources) { ApplicationSources other = (ApplicationSources) obj; if (this.isPrecedenceEnabled() == other.isPrecedenceEnabled()) { boolean readsEqual = this.getReads().equals(other.getReads()); boolean writesEqual = this.getWrites().containsAll(other.getWrites()) && this.getWrites().size() == other.getWrites().size(); return readsEqual && writesEqual; } } return false; } public ApplicationSources copyWithChangedReadableSourceStatus(Publisher source, SourceStatus status) { List<SourceReadEntry> reads = Lists.newLinkedList(); for (SourceReadEntry entry : this.getReads()) { if (entry.getPublisher().equals(source)) { reads.add(new SourceReadEntry(source, status)); } else { reads.add(entry); } } return this.copy().withReadableSources(reads).build(); } /* * Adds any missing sources to the application. */ public ApplicationSources copyWithMissingSourcesPopulated() { List<SourceReadEntry> readsAll = Lists.newLinkedList(); Set<Publisher> publishersSeen = Sets.newHashSet(); for (SourceReadEntry read : this.getReads()) { readsAll.add(read); publishersSeen.add(read.getPublisher()); } for (Publisher source : Publisher.values()) { if (!publishersSeen.contains(source)) { SourceStatus status = SourceStatus.fromV3SourceStatus(source.getDefaultSourceStatus()); readsAll.add(new SourceReadEntry(source, status)); } } return this.copy().withReadableSources(readsAll).build(); } public Builder copy() { return builder() .withPrecedence(this.isPrecedenceEnabled()) .withReadableSources(this.getReads()) .withImagePrecedenceEnabled(this.imagePrecedenceEnabled) .withContentHierarchyPrecedence(this.contentHierarchyPrecedence().orNull()) .withWritableSources(this.getWrites()); } public static Builder builder() { return new Builder(); } public static class Builder { private Optional<List<Publisher>> contentHierarchyPrecedence = Optional.absent(); public boolean precedence = false; private Boolean imagePrecedenceEnabled = true; private List<SourceReadEntry> reads = Lists.newLinkedList(); private List<Publisher> writes = Lists.newLinkedList(); public Builder withPrecedence(boolean precedence) { this.precedence = precedence; return this; } public Builder withContentHierarchyPrecedence(List<Publisher> contentHierarchyPrecedence) { if (contentHierarchyPrecedence != null) { this.contentHierarchyPrecedence = Optional.of(ImmutableList.copyOf(contentHierarchyPrecedence)); } else { this.contentHierarchyPrecedence = Optional.absent(); } return this; } public Builder withReadableSources(List<SourceReadEntry> reads) { this.reads = reads; return this; } public Builder withWritableSources(List<Publisher> writes) { this.writes = writes; return this; } public Builder withImagePrecedenceEnabled(Boolean imagePrecedenceEnabled) { this.imagePrecedenceEnabled = imagePrecedenceEnabled; return this; } public ApplicationSources build() { // If precedence not enabled then sort reads by publisher key order if (!this.precedence) { Collections.sort(Lists.newArrayList(this.reads), SORT_READS_BY_PUBLISHER); } return new ApplicationSources(this); } } }
package nodomain.freeyourgadget.gadgetbridge.activities; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanRecord; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.ParcelUuid; import android.os.Parcelable; import android.support.v4.app.ActivityCompat; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Objects; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.adapter.DeviceCandidateAdapter; import nodomain.freeyourgadget.gadgetbridge.devices.DeviceCoordinator; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.impl.GBDeviceCandidate; import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; import nodomain.freeyourgadget.gadgetbridge.util.AndroidUtils; import nodomain.freeyourgadget.gadgetbridge.util.DeviceHelper; import nodomain.freeyourgadget.gadgetbridge.util.GB; public class DiscoveryActivity extends AbstractGBActivity implements AdapterView.OnItemClickListener { private static final Logger LOG = LoggerFactory.getLogger(DiscoveryActivity.class); private static final long SCAN_DURATION = 60000; // 60s private ScanCallback newLeScanCallback = null; private final Handler handler = new Handler(); private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { switch (Objects.requireNonNull(intent.getAction())) { case BluetoothAdapter.ACTION_DISCOVERY_STARTED: if (isScanning != Scanning.SCANNING_BTLE && isScanning != Scanning.SCANNING_NEW_BTLE) { discoveryStarted(Scanning.SCANNING_BT); } break; case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: handler.post(new Runnable() { @Override public void run() { // continue with LE scan, if available if (isScanning == Scanning.SCANNING_BT) { checkAndRequestLocationPermission(); if (GBApplication.isRunningLollipopOrLater()) { startDiscovery(Scanning.SCANNING_NEW_BTLE); } else { startDiscovery(Scanning.SCANNING_BTLE); } } else { discoveryFinished(); } } }); break; case BluetoothAdapter.ACTION_STATE_CHANGED: int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); bluetoothStateChanged(newState); break; case BluetoothDevice.ACTION_FOUND: { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, GBDevice.RSSI_UNKNOWN); handleDeviceFound(device, rssi); break; } case BluetoothDevice.ACTION_UUID: { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, GBDevice.RSSI_UNKNOWN); Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID); ParcelUuid[] uuids2 = AndroidUtils.toParcelUuids(uuids); handleDeviceFound(device, rssi, uuids2); break; } case BluetoothDevice.ACTION_BOND_STATE_CHANGED: { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device != null && bondingDevice != null && device.getAddress().equals(bondingDevice.getMacAddress())) { int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE); if (bondState == BluetoothDevice.BOND_BONDED) { handleDeviceBonded(); } } } } } }; private void connectAndFinish(GBDevice device) { GB.toast(DiscoveryActivity.this, getString(R.string.discovery_trying_to_connect_to, device.getName()), Toast.LENGTH_SHORT, GB.INFO); GBApplication.deviceService().connect(device, true); finish(); } private void createBond(final GBDeviceCandidate deviceCandidate, int bondingStyle) { if (bondingStyle == DeviceCoordinator.BONDING_STYLE_NONE) { return; } if (bondingStyle == DeviceCoordinator.BONDING_STYLE_ASK) { new AlertDialog.Builder(this) .setCancelable(true) .setTitle(DiscoveryActivity.this.getString(R.string.discovery_pair_title, deviceCandidate.getName())) .setMessage(DiscoveryActivity.this.getString(R.string.discovery_pair_question)) .setPositiveButton(DiscoveryActivity.this.getString(R.string.discovery_yes_pair), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doCreatePair(deviceCandidate); } }) .setNegativeButton(R.string.discovery_dont_pair, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { GBDevice device = DeviceHelper.getInstance().toSupportedDevice(deviceCandidate); connectAndFinish(device); } }) .show(); } else { doCreatePair(deviceCandidate); } } private void doCreatePair(GBDeviceCandidate deviceCandidate) { GB.toast(DiscoveryActivity.this, getString(R.string.discovery_attempting_to_pair, deviceCandidate.getName()), Toast.LENGTH_SHORT, GB.INFO); if (deviceCandidate.getDevice().createBond()) { // async, wait for bonding event to finish this activity LOG.info("Bonding in progress..."); bondingDevice = deviceCandidate; } else { GB.toast(DiscoveryActivity.this, getString(R.string.discovery_bonding_failed_immediately, deviceCandidate.getName()), Toast.LENGTH_SHORT, GB.ERROR); } } private void handleDeviceBonded() { GB.toast(DiscoveryActivity.this, getString(R.string.discovery_successfully_bonded, bondingDevice.getName()), Toast.LENGTH_SHORT, GB.INFO); GBDevice device = DeviceHelper.getInstance().toSupportedDevice(bondingDevice); connectAndFinish(device); } private final BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { LOG.warn(device.getName() + ": " + ((scanRecord != null) ? scanRecord.length : -1)); logMessageContent(scanRecord); handleDeviceFound(device, (short) rssi); } }; // why use a method to get callback? // because this callback need API >= 21 // we cant add @TARGETAPI("Lollipop") at class header // so use a method with SDK check to return this callback private ScanCallback getScanCallback() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { newLeScanCallback = new ScanCallback() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); try { ScanRecord scanRecord = result.getScanRecord(); ParcelUuid[] uuids = null; if (scanRecord != null) { //logMessageContent(scanRecord.getBytes()); List<ParcelUuid> serviceUuids = scanRecord.getServiceUuids(); if (serviceUuids != null) { uuids = serviceUuids.toArray(new ParcelUuid[0]); } } LOG.warn(result.getDevice().getName() + ": " + ((scanRecord != null) ? scanRecord.getBytes().length : -1)); handleDeviceFound(result.getDevice(), (short) result.getRssi(), uuids); } catch (NullPointerException e) { LOG.warn("Error handling scan result", e); } } }; } return newLeScanCallback; } public void logMessageContent(byte[] value) { if (value != null) { for (byte b : value) { LOG.warn("DATA: " + String.format("0x%2x", b) + " - " + (char) (b & 0xff)); } } } private final Runnable stopRunnable = new Runnable() { @Override public void run() { stopDiscovery(); } }; private ProgressBar progressView; private BluetoothAdapter adapter; private final ArrayList<GBDeviceCandidate> deviceCandidates = new ArrayList<>(); private DeviceCandidateAdapter cadidateListAdapter; private Button startButton; private Scanning isScanning = Scanning.SCANNING_OFF; private GBDeviceCandidate bondingDevice; private enum Scanning { SCANNING_BT, SCANNING_BTLE, SCANNING_NEW_BTLE, SCANNING_OFF } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_discovery); startButton = findViewById(R.id.discovery_start); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onStartButtonClick(startButton); } }); progressView = findViewById(R.id.discovery_progressbar); progressView.setProgress(0); progressView.setIndeterminate(true); progressView.setVisibility(View.GONE); ListView deviceCandidatesView = findViewById(R.id.discovery_deviceCandidatesView); cadidateListAdapter = new DeviceCandidateAdapter(this, deviceCandidates); deviceCandidatesView.setAdapter(cadidateListAdapter); deviceCandidatesView.setOnItemClickListener(this); IntentFilter bluetoothIntents = new IntentFilter(); bluetoothIntents.addAction(BluetoothDevice.ACTION_FOUND); bluetoothIntents.addAction(BluetoothDevice.ACTION_UUID); bluetoothIntents.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); bluetoothIntents.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); bluetoothIntents.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); bluetoothIntents.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(bluetoothReceiver, bluetoothIntents); startDiscovery(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelableArrayList("deviceCandidates", deviceCandidates); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); ArrayList<Parcelable> restoredCandidates = savedInstanceState.getParcelableArrayList("deviceCandidates"); if (restoredCandidates != null) { deviceCandidates.clear(); for (Parcelable p : restoredCandidates) { deviceCandidates.add((GBDeviceCandidate) p); } } } public void onStartButtonClick(View button) { LOG.debug("Start Button clicked"); if (isScanning()) { stopDiscovery(); } else { startDiscovery(); } } @Override protected void onDestroy() { try { unregisterReceiver(bluetoothReceiver); } catch (IllegalArgumentException e) { LOG.warn("Tried to unregister Bluetooth Receiver that wasn't registered."); } super.onDestroy(); } private void handleDeviceFound(BluetoothDevice device, short rssi) { ParcelUuid[] uuids = device.getUuids(); if (uuids == null) { if (device.fetchUuidsWithSdp()) { return; } } handleDeviceFound(device, rssi, uuids); } private void handleDeviceFound(BluetoothDevice device, short rssi, ParcelUuid[] uuids) { LOG.debug("found device: " + device.getName() + ", " + device.getAddress()); if (LOG.isDebugEnabled()) { if (uuids != null && uuids.length > 0) { for (ParcelUuid uuid : uuids) { LOG.debug(" supports uuid: " + uuid.toString()); } } } if (device.getBondState() == BluetoothDevice.BOND_BONDED) { return; // ignore already bonded devices } GBDeviceCandidate candidate = new GBDeviceCandidate(device, rssi, uuids); DeviceType deviceType = DeviceHelper.getInstance().getSupportedType(candidate); if (deviceType.isSupported()) { candidate.setDeviceType(deviceType); LOG.info("Recognized supported device: " + candidate); int index = deviceCandidates.indexOf(candidate); if (index >= 0) { deviceCandidates.set(index, candidate); // replace } else { deviceCandidates.add(candidate); } cadidateListAdapter.notifyDataSetChanged(); } } /** * Pre: bluetooth is available, enabled and scanning is off. * Post: BT is discovering */ private void startDiscovery() { if (isScanning()) { LOG.warn("Not starting discovery, because already scanning."); return; } startDiscovery(Scanning.SCANNING_BT); } private void startDiscovery(Scanning what) { LOG.info("Starting discovery: " + what); discoveryStarted(what); // just to make sure if (ensureBluetoothReady()) { if (what == Scanning.SCANNING_BT) { startBTDiscovery(); } else if (what == Scanning.SCANNING_BTLE) { if (GB.supportsBluetoothLE()) { startBTLEDiscovery(); } else { discoveryFinished(); } } else if (what == Scanning.SCANNING_NEW_BTLE) { if (GB.supportsBluetoothLE()) { startNEWBTLEDiscovery(); } else { discoveryFinished(); } } } else { discoveryFinished(); GB.toast(DiscoveryActivity.this, getString(R.string.discovery_enable_bluetooth), Toast.LENGTH_SHORT, GB.ERROR); } } private boolean isScanning() { return isScanning != Scanning.SCANNING_OFF; } private void stopDiscovery() { LOG.info("Stopping discovery"); if (isScanning()) { Scanning wasScanning = isScanning; // unfortunately, we don't always get a call back when stopping the scan, so // we do it manually; BEFORE stopping the scan! discoveryFinished(); if (wasScanning == Scanning.SCANNING_BT) { stopBTDiscovery(); } else if (wasScanning == Scanning.SCANNING_BTLE) { stopBTLEDiscovery(); } else if (wasScanning == Scanning.SCANNING_NEW_BTLE) { stopNewBTLEDiscovery(); } handler.removeMessages(0, stopRunnable); } } private void stopBTLEDiscovery() { if (adapter != null) adapter.stopLeScan(leScanCallback); } private void stopBTDiscovery() { if (adapter != null) adapter.cancelDiscovery(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void stopNewBTLEDiscovery() { if (adapter == null) return; BluetoothLeScanner bluetoothLeScanner = adapter.getBluetoothLeScanner(); if (bluetoothLeScanner == null) { LOG.warn("could not get BluetoothLeScanner()!"); return; } if (newLeScanCallback == null) { LOG.warn("newLeScanCallback == null!"); return; } bluetoothLeScanner.stopScan(newLeScanCallback); } private void bluetoothStateChanged(int newState) { discoveryFinished(); if (newState == BluetoothAdapter.STATE_ON) { this.adapter = BluetoothAdapter.getDefaultAdapter(); startButton.setEnabled(true); } else { this.adapter = null; startButton.setEnabled(false); } } private void discoveryFinished() { isScanning = Scanning.SCANNING_OFF; progressView.setVisibility(View.GONE); startButton.setText(getString(R.string.discovery_start_scanning)); } private void discoveryStarted(Scanning what) { isScanning = what; progressView.setVisibility(View.VISIBLE); startButton.setText(getString(R.string.discovery_stop_scanning)); } private boolean ensureBluetoothReady() { boolean available = checkBluetoothAvailable(); startButton.setEnabled(available); if (available) { adapter.cancelDiscovery(); // must not return the result of cancelDiscovery() // appears to return false when currently not scanning return true; } return false; } private boolean checkBluetoothAvailable() { BluetoothManager bluetoothService = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); if (bluetoothService == null) { LOG.warn("No bluetooth available"); this.adapter = null; return false; } BluetoothAdapter adapter = bluetoothService.getAdapter(); if (adapter == null) { LOG.warn("No bluetooth available"); this.adapter = null; return false; } if (!adapter.isEnabled()) { LOG.warn("Bluetooth not enabled"); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(enableBtIntent); this.adapter = null; return false; } this.adapter = adapter; return true; } // New BTLE Discovery use startScan (List<ScanFilter> filters, // ScanSettings settings, // ScanCallback callback) // It's added on API21 @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startNEWBTLEDiscovery() { // Only use new API when user uses Lollipop+ device LOG.info("Start New BTLE Discovery"); handler.removeMessages(0, stopRunnable); handler.sendMessageDelayed(getPostMessage(stopRunnable), SCAN_DURATION); adapter.getBluetoothLeScanner().startScan(getScanFilters(), getScanSettings(), getScanCallback()); } private List<ScanFilter> getScanFilters() { List<ScanFilter> allFilters = new ArrayList<>(); for (DeviceCoordinator coordinator : DeviceHelper.getInstance().getAllCoordinators()) { allFilters.addAll(coordinator.createBLEScanFilters()); } return allFilters; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private ScanSettings getScanSettings() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return new ScanSettings.Builder() .setScanMode(android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_LATENCY) .setMatchMode(android.bluetooth.le.ScanSettings.MATCH_MODE_STICKY) .build(); } else { return new ScanSettings.Builder() .setScanMode(android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_LATENCY) .build(); } } private void startBTLEDiscovery() { LOG.info("Starting BTLE Discovery"); handler.removeMessages(0, stopRunnable); handler.sendMessageDelayed(getPostMessage(stopRunnable), SCAN_DURATION); adapter.startLeScan(leScanCallback); } private void startBTDiscovery() { LOG.info("Starting BT Discovery"); handler.removeMessages(0, stopRunnable); handler.sendMessageDelayed(getPostMessage(stopRunnable), SCAN_DURATION); adapter.startDiscovery(); } private void checkAndRequestLocationPermission() { if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 0); } } private Message getPostMessage(Runnable runnable) { Message m = Message.obtain(handler, runnable); m.obj = runnable; return m; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { GBDeviceCandidate deviceCandidate = deviceCandidates.get(position); if (deviceCandidate == null) { LOG.error("Device candidate clicked, but item not found"); return; } stopDiscovery(); DeviceCoordinator coordinator = DeviceHelper.getInstance().getCoordinator(deviceCandidate); LOG.info("Using device candidate " + deviceCandidate + " with coordinator: " + coordinator.getClass()); Class<? extends Activity> pairingActivity = coordinator.getPairingActivity(); if (pairingActivity != null) { Intent intent = new Intent(this, pairingActivity); intent.putExtra(DeviceCoordinator.EXTRA_DEVICE_CANDIDATE, deviceCandidate); startActivity(intent); } else { GBDevice device = DeviceHelper.getInstance().toSupportedDevice(deviceCandidate); int bondingStyle = coordinator.getBondingStyle(device); if (bondingStyle == DeviceCoordinator.BONDING_STYLE_NONE) { LOG.info("No bonding needed, according to coordinator, so connecting right away"); connectAndFinish(device); return; } try { BluetoothDevice btDevice = adapter.getRemoteDevice(deviceCandidate.getMacAddress()); switch (btDevice.getBondState()) { case BluetoothDevice.BOND_NONE: { createBond(deviceCandidate, bondingStyle); break; } case BluetoothDevice.BOND_BONDING: // async, wait for bonding event to finish this activity bondingDevice = deviceCandidate; break; case BluetoothDevice.BOND_BONDED: handleDeviceBonded(); break; } } catch (Exception e) { LOG.error("Error pairing device: " + deviceCandidate.getMacAddress()); } } } @Override protected void onPause() { super.onPause(); stopBTDiscovery(); stopBTLEDiscovery(); if (GB.supportsBluetoothLE()) { stopNewBTLEDiscovery(); } } }
package com.axelor.gradle.support; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.composite.internal.IncludedBuildInternal; import org.gradle.plugins.ide.eclipse.EclipsePlugin; import org.gradle.plugins.ide.eclipse.EclipseWtpPlugin; import org.gradle.plugins.ide.eclipse.model.AccessRule; import org.gradle.plugins.ide.eclipse.model.Classpath; import org.gradle.plugins.ide.eclipse.model.Container; import org.gradle.plugins.ide.eclipse.model.EclipseClasspath; import org.gradle.plugins.ide.eclipse.model.EclipseModel; import org.gradle.plugins.ide.eclipse.model.Library; import org.gradle.plugins.ide.eclipse.model.SourceFolder; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.axelor.common.FileUtils; import com.axelor.gradle.AppPlugin; import com.axelor.gradle.AxelorPlugin; import com.axelor.gradle.tasks.GenerateCode; import com.axelor.gradle.tasks.TomcatRun; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.io.Files; public class EclipseSupport extends AbstractSupport { @Override public void apply(Project project) { project.getPlugins().apply(EclipsePlugin.class); project.getPlugins().apply(EclipseWtpPlugin.class); project.afterEvaluate(p -> { if (project.getPlugins().hasPlugin(AxelorPlugin.class)) { project.getTasks().getByName(EclipsePlugin.ECLIPSE_CP_TASK_NAME) .dependsOn(GenerateCode.TASK_NAME); } if (project.getPlugins().hasPlugin(AppPlugin.class)) { project.getTasks().create("generateEclipseLauncher", task -> { final File cpFile = new File(project.getRootDir(), ".classpath"); task.onlyIf(t -> cpFile.exists()); task.doLast(a -> generateLauncher(project)); final Task generateLauncher = project.getTasks().getByName("generateLauncher"); if (generateLauncher != null) { generateLauncher.finalizedBy(task); } }); // Fix wtp issue in included builds (with buildship) project.getGradle().getIncludedBuilds().stream() .map(ib -> ((IncludedBuildInternal) ib).getConfiguredBuild().getRootProject()) .flatMap(ib -> Stream.concat(Arrays.asList(ib).stream(), ib.getSubprojects().stream())) .filter(ip -> ip.getPlugins().hasPlugin(EclipseWtpPlugin.class)) .map(ip -> ip.getTasks().getByName("eclipseWtp")) .forEach(it -> project.getTasks().getByName("eclipseWtp").dependsOn(it)); } }); final EclipseModel eclipse = project.getExtensions().getByType(EclipseModel.class); final EclipseClasspath ecp = eclipse.getClasspath(); ecp.setDefaultOutputDir(project.file("bin/main")); ecp.getFile().whenMerged((Classpath cp) -> { // separate output for main & test sources cp.getEntries().stream() .filter(it -> it instanceof SourceFolder).map(it -> (SourceFolder) it) .filter(it -> it.getPath().startsWith("src/main/") || it.getPath().endsWith("src-gen")) .forEach(it -> it.setOutput("bin/main")); cp.getEntries().stream() .filter(it -> it instanceof SourceFolder).map(it -> (SourceFolder) it) .filter(it -> it.getPath().startsWith("src/test/")) .forEach(it -> it.setOutput("bin/test")); // remove self-dependency cp.getEntries().removeIf(it -> it instanceof SourceFolder && ((SourceFolder) it).getPath().contains(project.getName())); cp.getEntries().removeIf(it -> it instanceof Library && ((Library) it).getPath().contains(project.getName() + "/build")); // add access rule for nashorn api cp.getEntries() .stream() .filter(it -> it instanceof Container).map(it -> (Container) it) .filter(it -> it.getPath().contains("org.eclipse.jdt.launching.JRE_CONTAINER"))
package at.fhj.swd14.pse.tag; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public final class TagConverter { private TagConverter() { } /** * Converts a Tag to a TagDto * * @param tag * @return tagDto */ public static TagDto convert(Tag tag) { if (tag == null) { return null; } return new TagDto(tag.getId(), tag.getName()); } /** * Converts a TagDto to a Tag * * @param tagDto * @return tag */ public static Tag convert(TagDto tagDto) { if (tagDto == null) { return null; } return new Tag(tagDto.getId(), tagDto.getName()); } /** * Converts a List of Tags to a List of TagDtos * * @param tags * @return tagDtos */ public static List<TagDto> convertToDtoList(Collection<Tag> tags) { if (tags == null) { return new ArrayList<>(); } return tags.stream().map(TagConverter::convert).collect(Collectors.toList()); } /** * Converts a List of TagDtos to a List of Tags * * @param tagDtos * @return tags */ public static List<Tag> convertToList(Collection<TagDto> tagDtos) { if (tagDtos == null) { return new ArrayList<>(); } return tagDtos.stream().map(TagConverter::convert).collect(Collectors.toList()); } }
package org.sourcepit.b2.model.builder.util; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.inject.Named; import org.codehaus.plexus.interpolation.AbstractValueSource; import org.osgi.framework.Version; import org.sourcepit.b2.model.module.AbstractReference; import org.sourcepit.b2.model.module.FeatureInclude; import org.sourcepit.b2.model.module.ModuleModelFactory; import org.sourcepit.b2.model.module.PluginInclude; import org.sourcepit.b2.model.module.RuledReference; import org.sourcepit.b2.model.module.VersionMatchRule; import org.sourcepit.common.utils.path.PathMatcher; import org.sourcepit.common.utils.props.PropertiesSource; import org.sourcepit.tools.shared.resources.harness.StringInterpolator; import com.google.common.base.Strings; @Named public class DefaultConverter implements SitesConverter, BasicConverter, FeaturesConverter, ProductsConverter { public boolean isSkipInterpolator(PropertiesSource moduleProperties) { return moduleProperties.getBoolean("b2.skipInterpolator", false); } public boolean isSkipGenerator(PropertiesSource moduleProperties) { return moduleProperties.getBoolean("b2.skipGenerator", false); } public boolean isPotentialModuleDirectory(PropertiesSource moduleProperties, File baseDir, File file) { if (file.isDirectory() && file.exists() && new File(file, "module.xml").exists()) { final String pattern = interpolate(moduleProperties, "b2.moduleDirFilter", "**"); final PathMatcher moduleDirMacher = PathMatcher.parseFilePatterns(baseDir, pattern); if (moduleDirMacher.isMatch(file.getAbsolutePath())) { return true; } } return false; } public List<String> getAssemblyNames(PropertiesSource moduleProperties) { final List<String> assemblies = new ArrayList<String>(); final String rawAssemblies = moduleProperties.get("b2.assemblies"); if (rawAssemblies != null) { for (String rawAssembly : rawAssemblies.split(",")) { final String assembly = rawAssembly.trim(); if (assembly.length() > 0 && !assemblies.contains(assembly)) { assemblies.add(assembly); } } } return assemblies; } public String getAssemblyClassifier(PropertiesSource properties, String assemblyName) { if (assemblyName.length() == 0) { throw new IllegalArgumentException("assemblyName must not be empty."); } // TODO assert result is valid id return properties.get(assemblyKey(assemblyName, "classifier"), toValidId(assemblyName)); } public AggregatorMode getAggregatorMode(PropertiesSource moduleProperties, String assemblyName) { final String literal = get(moduleProperties, assemblyKey(assemblyName, "aggregator.mode"), b2Key("aggregator.mode")); return literal == null ? AggregatorMode.OFF : AggregatorMode.valueOf(literal.toUpperCase()); } public PathMatcher getAggregatorFeatureMatcherForAssembly(PropertiesSource moduleProperties, String assemblyName) { final String patterns = moduleProperties.get(assemblyKey(assemblyName, "aggregator.featuresFilter"), "**"); return PathMatcher.parse(patterns, ".", ","); } public PathMatcher getFeatureMatcherForAssembly(PropertiesSource moduleProperties, String assemblyName) { final String patterns = moduleProperties.get(assemblyKey(assemblyName, "featuresFilter"), "**"); return PathMatcher.parse(patterns, ".", ","); } public PathMatcher getPluginMatcherForAssembly(PropertiesSource moduleProperties, String assemblyName) { final String patterns = moduleProperties.get(assemblyKey(assemblyName, "pluginsFilter"), "!**"); return PathMatcher.parse(patterns, ".", ","); } public List<FeatureInclude> getIncludedFeaturesForAssembly(PropertiesSource moduleProperties, String assemblyName) { final String key = "includedFeatures"; final String rawIncludes = get(moduleProperties, assemblyKey(assemblyName, key), assemblyKey(null, key), b2Key(key)); return toFeatureIncludeList(rawIncludes); } public List<PluginInclude> getIncludedPluginsForAssembly(PropertiesSource moduleProperties, String assemblyName) { final String key = "includedPlugins"; final String rawIncludes = get(moduleProperties, assemblyKey(assemblyName, key), assemblyKey(null, key), b2Key(key)); return toPluginIncludeList(rawIncludes); } public List<RuledReference> getRequiredFeaturesForAssembly(PropertiesSource moduleProperties, String assemblyName) { final String key = "requiredFeatures"; final String rawIncludes = get(moduleProperties, assemblyKey(assemblyName, key), assemblyKey(null, key), b2Key(key)); return toRuledReferenceList(rawIncludes); } public List<RuledReference> getRequiredPluginsForAssembly(PropertiesSource moduleProperties, String assemblyName) { final String key = "requiredPlugins"; final String rawIncludes = get(moduleProperties, assemblyKey(assemblyName, key), assemblyKey(null, key), b2Key(key)); return toRuledReferenceList(rawIncludes); } public String getFacetClassifier(PropertiesSource properties, String facetName) { if (facetName.length() == 0) { throw new IllegalArgumentException("facetName must not be empty."); } // TODO assert result is valid id return properties.get(facetKey(facetName, "classifier"), toValidId(facetName)); } public PathMatcher getPluginMatcherForFacet(PropertiesSource moduleProperties, String facetName) { final String patterns = moduleProperties.get(facetKey(facetName, "pluginsFilter"), "**"); return PathMatcher.parse(patterns, ".", ","); } public List<FeatureInclude> getIncludedFeaturesForFacet(PropertiesSource moduleProperties, String facetName, boolean isSource) { final String key = isSource ? "includedSourceFeatures" : "includedFeatures"; final String rawIncludes = get(moduleProperties, facetKey(facetName, key), facetKey(null, key), b2Key(key)); return toFeatureIncludeList(rawIncludes); } private List<FeatureInclude> toFeatureIncludeList(final String rawIncludes) { final List<FeatureInclude> result = new ArrayList<FeatureInclude>(); if (rawIncludes != null) { for (String rawInclude : rawIncludes.split(",")) { final String include = rawInclude.trim(); if (include.length() > 0) { result.add(toFeatureInclude(include)); } } } return result; } public List<PluginInclude> getIncludedPluginsForFacet(PropertiesSource moduleProperties, String facetName, boolean isSource) { final String key = isSource ? "includedSourcePlugins" : "includedPlugins"; final String rawIncludes = get(moduleProperties, facetKey(facetName, key), facetKey(null, key), b2Key(key)); return toPluginIncludeList(rawIncludes); } private List<PluginInclude> toPluginIncludeList(final String rawIncludes) { final List<PluginInclude> result = new ArrayList<PluginInclude>(); if (rawIncludes != null) { for (String rawInclude : rawIncludes.split(",")) { final String include = rawInclude.trim(); if (include.length() > 0) { result.add(toPluginInclude(include)); } } } return result; } public List<RuledReference> getRequiredFeaturesForFacet(PropertiesSource moduleProperties, String facetName, boolean isSource) { final String key = isSource ? "requiredSourceFeatures" : "requiredFeatures"; final String requirements = get(moduleProperties, facetKey(facetName, key), facetKey(null, key), b2Key(key)); return toRuledReferenceList(requirements); } public List<RuledReference> getRequiredPluginsForFacet(PropertiesSource moduleProperties, String facetName, boolean isSource) { final String key = isSource ? "requiredSourcePlugins" : "requiredPlugins"; final String requirements = get(moduleProperties, facetKey(facetName, key), facetKey(null, key), b2Key(key)); return toRuledReferenceList(requirements); } private static List<RuledReference> toRuledReferenceList(String rawRequirements) { final List<RuledReference> result = new ArrayList<RuledReference>(); // foo.feature:1.0.0:compatible, if (rawRequirements != null) { for (String rawRequirement : rawRequirements.split(",")) { final String requirement = rawRequirement.trim(); if (requirement.length() > 0) { result.add(toRuledReference(requirement)); } } } return result; } private static RuledReference toRuledReference(String string) { final RuledReference ref = ModuleModelFactory.eINSTANCE.createRuledReference(); final String[] segments = string.split(":"); if (segments.length < 1 || segments.length > 3) { throw new IllegalArgumentException(string + " is not a valid requirement specification"); } parseAndSetIdAndVersion(string, ref, segments); if (segments.length > 2) { final String ruleString = segments[2].trim(); final VersionMatchRule rule = VersionMatchRule.get(ruleString); if (rule == null) { throw new IllegalArgumentException("'" + ruleString + "' in " + string + " is not a valid version matching rule"); } ref.setVersionMatchRule(rule); } return ref; } private static void parseAndSetIdAndVersion(String reference, final AbstractReference ref, final String[] segments) { // TODO assert is valid ref.setId(segments[0].trim()); if (segments.length > 1) { final String versionString = segments[1].trim(); try { new Version(versionString); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("'" + versionString + "' in " + reference + " is not a valid version"); } ref.setVersion(versionString); } } private static FeatureInclude toFeatureInclude(String include) { // foo:1.0.0:optional final FeatureInclude inc = ModuleModelFactory.eINSTANCE.createFeatureInclude(); final String[] segments = include.split(":"); if (segments.length < 1 || segments.length > 3) { throw new IllegalArgumentException(include + " is not a valid feature include specification"); } parseAndSetIdAndVersion(include, inc, segments); if (segments.length > 2) { final String optionalString = segments[2].trim(); if (!"optional".equals(optionalString)) { throw new IllegalArgumentException("'" + optionalString + "' in " + include + " must be 'optional' or missing"); } inc.setOptional(true); } return inc; } private static PluginInclude toPluginInclude(String include) { // foo:1.0.0:unpack final PluginInclude inc = ModuleModelFactory.eINSTANCE.createPluginInclude(); final String[] segments = include.split(":"); if (segments.length < 1 || segments.length > 3) { throw new IllegalArgumentException(include + " is not a valid plugin include specification"); } parseAndSetIdAndVersion(include, inc, segments); inc.setUnpack(false); if (segments.length > 2) { final String optionalString = segments[2].trim(); if (!"unpack".equals(optionalString)) { throw new IllegalArgumentException("'" + optionalString + "' in " + include + " must be 'optional' or missing"); } inc.setUnpack(true); } return inc; } private static String assemblyKey(String assemblyName, String key) { if (Strings.isNullOrEmpty(assemblyName)) { return b2Key("assemblies." + key); } return b2Key("assemblies." + assemblyName + "." + key); } private static String facetKey(String facetName, String key) { if (Strings.isNullOrEmpty(facetName)) { return b2Key("facets." + key); } return b2Key("facets." + facetName + "." + key); } private static String b2Key(String key) { return "b2." + key; } private static String get(PropertiesSource moduleProperties, String... keys) { for (String key : keys) { final String value = moduleProperties.get(key); if (value != null) { return value; } } return null; } private static String interpolate(final PropertiesSource moduleProperties, String key, String defaultValue) { StringInterpolator s = new StringInterpolator(); s.setEscapeString("\\"); s.getValueSources().add(new AbstractValueSource(false) { public Object getValue(String expression) { return moduleProperties.get(expression); } }); final String value = moduleProperties.get(key, defaultValue); return value == null ? value : s.interpolate(value); } public String getFeatureId(PropertiesSource properties, String moduleId, String classifier, boolean isSource) { final StringBuilder sb = new StringBuilder(); if (classifier != null) { sb.append(classifier); } if (isSource) { if (sb.length() > 0) { sb.append('.'); } sb.append(properties.get("b2.featuresSourceClassifier", "sources")); } return idOfProject(moduleId, sb.toString(), "feature"); } public String getSourcePluginId(PropertiesSource moduleProperties, String pluginId) { final StringBuilder sb = new StringBuilder(); sb.append(pluginId); if (sb.length() > 0) { sb.append('.'); sb.append(moduleProperties.get("b2.pluginsSourceClassifier", "source")); } return sb.toString(); } public String getSiteId(PropertiesSource moduleProperties, String moduleId, String classifier) { return idOfProject(moduleId, classifier, "site"); } private static String idOfProject(String moduleId, String classifier, String appendix) { final StringBuilder sb = new StringBuilder(); sb.append(moduleId); if (classifier != null && classifier.length() > 0) { sb.append('.'); sb.append(classifier); } if (appendix != null && appendix.length() > 0) { sb.append("."); sb.append(appendix); } return sb.toString(); } protected static String toValidId(String string) { // TODO assert not empty return toJavaIdentifier(string.toLowerCase()); } private static String toJavaIdentifier(String aString) { if (aString.length() == 0) { return "_"; } final StringBuilder res = new StringBuilder(); int idx = 0; char c = aString.charAt(idx); if (Character.isJavaIdentifierStart(c)) { res.append(c); idx++; } else if (Character.isJavaIdentifierPart(c)) { res.append('_'); } while (idx < aString.length()) { c = aString.charAt(idx++); res.append(Character.isJavaIdentifierPart(c) || c == '.' ? c : '_'); } return res.toString(); } public String getModuleVersion(PropertiesSource moduleProperties) { return moduleProperties.get("b2.moduleVersion", "0.1.0.qualifier"); } public String getNameSpace(PropertiesSource moduleProperties) { return moduleProperties.get("b2.moduleNameSpace", "b2.module"); } public PathMatcher getResourceMatcherForProduct(PropertiesSource moduleProperties, String productId) { String patterns = get(moduleProperties, productKey(productId, "resources"), productKey(null, "resources")); if (patterns == null) { patterns = "!**"; } return PathMatcher.parse(patterns, "/", ","); } private static String productKey(String productId, String key) { if (Strings.isNullOrEmpty(productId)) { return b2Key("products." + key); } return b2Key("products." + productId + "." + key); } }
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.job.ExecutionContext; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.bll.memory.MemoryUtils; import org.ovirt.engine.core.bll.network.MacPoolManager; import org.ovirt.engine.core.bll.network.VmInterfaceManager; import org.ovirt.engine.core.bll.network.vm.VnicProfileHelper; import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageDependent; import org.ovirt.engine.core.bll.snapshots.SnapshotsManager; import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.DiskImagesValidator; import org.ovirt.engine.core.bll.validator.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.ImportVmParameters; import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters; import org.ovirt.engine.core.common.action.RemoveMemoryVolumesParameters; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.asynctasks.AsyncTaskCreationInfo; import org.ovirt.engine.core.common.asynctasks.EntityInfo; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.CopyVolumeType; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.DiskImageDynamic; import org.ovirt.engine.core.common.businessentities.DiskInterface; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.ImageDbOperationScope; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmStatistics; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmTemplateStatus; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.network.VmNic; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.validation.group.ImportClonedEntity; import org.ovirt.engine.core.common.validation.group.ImportEntity; import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NotImplementedException; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.utils.GuidUtils; import org.ovirt.engine.core.utils.linq.Function; import org.ovirt.engine.core.utils.linq.LinqUtils; import org.ovirt.engine.core.utils.linq.Predicate; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.utils.ovf.OvfLogEventHandler; import org.ovirt.engine.core.utils.ovf.VMStaticOvfLogHandler; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; @DisableInPrepareMode @NonTransactiveCommandAttribute(forceCompensation = true) @LockIdNameAttribute(isReleaseAtEndOfExecute = false) public class ImportVmCommand<T extends ImportVmParameters> extends MoveOrCopyTemplateCommand<T> implements QuotaStorageDependent, TaskHandlerCommand<T> { private static final Log log = LogFactory.getLog(ImportVmCommand.class); private static VmStatic vmStaticForDefaultValues = new VmStatic(); private List<DiskImage> imageList; /** * Map which contains the disk id (new generated id if the disk is cloned) and the disk parameters from the export * domain. */ private final Map<Guid, DiskImage> newDiskIdForDisk = new HashMap<>(); private final List<String> macsAdded = new ArrayList<String>(); private final SnapshotsManager snapshotsManager = new SnapshotsManager(); public ImportVmCommand(T parameters) { super(parameters); } @Override protected void init(T parameters) { super.init(parameters); setVmId(parameters.getContainerId()); setVm(parameters.getVm()); setVdsGroupId(parameters.getVdsGroupId()); if (parameters.getVm() != null && getVm().getDiskMap() != null) { imageList = new ArrayList<DiskImage>(); for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { imageList.add((DiskImage) disk); } } } ensureDomainMap(imageList, parameters.getDestDomainId()); } @Override protected Map<String, Pair<String, String>> getSharedLocks() { return Collections.singletonMap(getParameters().getContainerId().toString(), LockMessagesMatchUtil.makeLockingPair( LockingGroup.REMOTE_VM, getVmIsBeingImportedMessage())); } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { if (!StringUtils.isBlank(getParameters().getVm().getName())) { return Collections.singletonMap(getParameters().getVm().getName(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_NAME, VdcBllMessages.ACTION_TYPE_FAILED_NAME_ALREADY_USED)); } return null; } private String getVmIsBeingImportedMessage() { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_IMPORTED.name()); if (getVmName() != null) { builder.append(String.format("$VmName %1$s", getVmName())); } return builder.toString(); } protected ImportVmCommand(Guid commandId) { super(commandId); } @Override public Guid getVmId() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm().getId(); } return super.getVmId(); } @Override public VM getVm() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm(); } return super.getVm(); } @Override protected boolean canDoAction() { Map<Guid, StorageDomain> domainsMap = new HashMap<Guid, StorageDomain>(); if (!canDoActionBeforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); } return canDoActionAfterCloneVm(domainsMap); } @Override protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__IMPORT); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); } private void initImportClonedVm() { Guid guid = Guid.newGuid(); getVm().setId(guid); setVmId(guid); getVm().setName(getParameters().getVm().getName()); getVm().setStoragePoolId(getParameters().getStoragePoolId()); getParameters().setVm(getVm()); for (VmNic iface : getVm().getInterfaces()) { iface.setId(Guid.newGuid()); } } private boolean canDoActionBeforeCloneVm(Map<Guid, StorageDomain> domainsMap) { List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); if (getVm() != null) { setDescription(getVmName()); } if (!checkStoragePool()) { return false; } Set<Guid> destGuids = new HashSet<Guid>(imageToDestinationDomainMap.values()); for (Guid destGuid : destGuids) { StorageDomain storageDomain = getStorageDomain(destGuid); StorageDomainValidator validator = new StorageDomainValidator(storageDomain); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } domainsMap.put(destGuid, storageDomain); } if (getParameters().isImportAsNewEntity() && !getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORT_CLONE_NOT_COLLAPSED); } setSourceDomainId(getParameters().getSourceDomainId()); StorageDomainValidator validator = new StorageDomainValidator(getSourceDomain()); if (validator.isDomainExistAndActive().isValid() && getSourceDomain().getStorageDomainType() != StorageDomainType.ImportExport) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); } List<VM> vms = getVmsFromExportDomain(); if (vms == null) { return false; } VM vm = LinqUtils.firstOrNull(vms, new Predicate<VM>() { @Override public boolean eval(VM evalVm) { return evalVm.getId().equals(getParameters().getVm().getId()); } }); if (vm != null) { // At this point we should work with the VM that was read from // the OVF setVm(vm); // Iterate over all the VM images (active image and snapshots) for (DiskImage image : getVm().getImages()) { if (Guid.Empty.equals(image.getVmSnapshotId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CORRUPTED_VM_SNAPSHOT_ID); } if (getParameters().getCopyCollapse()) { // If copy collapse sent then iterate over the images got from the parameters, until we got // a match with the image from the VM. for (DiskImage p : imageList) { // copy the new disk volume format/type if provided, // only if requested by the user if (p.getImageId().equals(image.getImageId())) { if (p.getVolumeFormat() != null) { image.setvolumeFormat(p.getVolumeFormat()); } if (p.getVolumeType() != null) { image.setVolumeType(p.getVolumeType()); } // Validate the configuration of the image got from the parameters. if (!validateImageConfig(canDoActionMessages, domainsMap, image)) { return false; } break; } } } else { // If no copy collapse sent, validate each image configuration (snapshot or active image). if (!validateImageConfig(canDoActionMessages, domainsMap, image)) { return false; } } image.setStoragePoolId(getParameters().getStoragePoolId()); // we put the source domain id in order that copy will // work properly. // we fix it to DestDomainId in // MoveOrCopyAllImageGroups(); image.setStorageIds(new ArrayList<Guid>(Arrays.asList(getParameters().getSourceDomainId()))); } Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getVm().getImages()); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { Guid id = entry.getKey(); List<DiskImage> diskList = entry.getValue(); getVm().getDiskMap().put(id, ImagesHandler.getActiveVolumeDisk(diskList)); } } return true; } /** * Load images from Import/Export domain. * @return A {@link List} of {@link VM}s, or <code>null</code> if the query to the export domain failed. */ protected List<VM> getVmsFromExportDomain() { GetAllFromExportDomainQueryParameters p = new GetAllFromExportDomainQueryParameters (getParameters().getStoragePoolId(), getParameters().getSourceDomainId()); VdcQueryReturnValue qRetVal = getBackend().runInternalQuery(VdcQueryType.GetVmsFromExportDomain, p); return qRetVal.getSucceeded() ? qRetVal.<List<VM>>getReturnValue() : null; } private boolean validateImageConfig(List<String> canDoActionMessages, Map<Guid, StorageDomain> domainsMap, DiskImage image) { return ImagesHandler.checkImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(image.getId())) .getStorageStaticData(), image, canDoActionMessages); } private boolean canDoActionAfterCloneVm(Map<Guid, StorageDomain> domainsMap) { VM vm = getParameters().getVm(); // check that the imported vm guid is not in engine if (!validateNoDuplicateVm()) { return false; } if (!validateNoDuplicateDiskImages(imageList)) { return false; } if (!validateDiskInterface(imageList)) { return false; } setVmTemplateId(getVm().getVmtGuid()); if (!templateExists() || !checkTemplateInStorageDomain() || !checkImagesGUIDsLegal() || !canAddVm()) { return false; } if (!VmTemplateHandler.BlankVmTemplateId.equals(getVm().getVmtGuid()) && getVmTemplate() != null && getVmTemplate().getStatus() == VmTemplateStatus.Locked) { return failCanDoAction(VdcBllMessages.VM_TEMPLATE_IMAGE_IS_LOCKED); } if (getParameters().getCopyCollapse() && vm.getDiskMap() != null) { for (Disk disk : vm.getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage key = (DiskImage) getVm().getDiskMap().get(disk.getId()); if (key != null) { if (!ImagesHandler.checkImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(key.getId())) .getStorageStaticData(), (DiskImageBase) disk, getReturnValue().getCanDoActionMessages())) { return false; } } } } } // if collapse true we check that we have the template on source // (backup) domain if (getParameters().getCopyCollapse() && !isTemplateExistsOnExportDomain()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORTED_TEMPLATE_IS_MISSING, String.format("$DomainName %1$s", getStorageDomainStaticDAO().get(getParameters().getSourceDomainId()).getStorageName())); } if (!validateVdsCluster()) { return false; } Map<StorageDomain, Integer> domainMap = getSpaceRequirementsForStorageDomains(imageList); if (!setDomainsForMemoryImages(domainMap)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } for (Map.Entry<StorageDomain, Integer> entry : domainMap.entrySet()) { if (!doesStorageDomainhaveSpaceForRequest(entry.getKey(), entry.getValue())) { return false; } } if (!validateUsbPolicy()) { return false; } if (!validateMacAddress(Entities.<VmNic, VmNetworkInterface> upcast(getVm().getInterfaces()))) { return false; } return true; } /** * This method fills the given map of domain to the required size for storing memory images * within it, and also update the memory volume in each snapshot that has memory volume with * the right storage pool and storage domain where it is going to be imported. * * @param domain2requiredSize * Maps domain to size required for storing memory volumes in it * @return true if we managed to assign storage domain for every memory volume, false otherwise */ private boolean setDomainsForMemoryImages(Map<StorageDomain, Integer> domain2requiredSize) { Map<String, String> handledMemoryVolumes = new HashMap<String, String>(); for (Snapshot snapshot : getVm().getSnapshots()) { String memoryVolume = snapshot.getMemoryVolume(); if (memoryVolume.isEmpty()) { continue; } if (handledMemoryVolumes.containsKey(memoryVolume)) { // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(handledMemoryVolumes.get(memoryVolume)); continue; } VM vm = getVmFromSnapshot(snapshot); int requiredSizeForMemory = (int) Math.ceil((vm.getTotalMemorySizeInBytes() + HibernateVmCommand.META_DATA_SIZE_IN_BYTES) * 1.0 / BYTES_IN_GB); StorageDomain storageDomain = VmHandler.findStorageDomainForMemory( getParameters().getStoragePoolId(),requiredSizeForMemory, domain2requiredSize); if (storageDomain == null) { return false; } domain2requiredSize.put(storageDomain, domain2requiredSize.get(storageDomain) + requiredSizeForMemory); String modifiedMemoryVolume = MemoryUtils.changeStorageDomainAndPoolInMemoryState( memoryVolume, storageDomain.getId(), getParameters().getStoragePoolId()); // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(modifiedMemoryVolume); // save it in case we'll find other snapshots with the same memory volume handledMemoryVolumes.put(memoryVolume, modifiedMemoryVolume); } return true; } /** * Validates that there is no duplicate VM. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateNoDuplicateVm() { VmStatic duplicateVm = getVmStaticDAO().get(getVm().getId()); if (duplicateVm != null) { return failCanDoAction(VdcBllMessages.VM_CANNOT_IMPORT_VM_EXISTS, String.format("$VmName %1$s", duplicateVm.getName())); } return true; } protected boolean isDiskExists(Guid id) { return getBaseDiskDao().exists(id); } protected boolean validateDiskInterface(Iterable<DiskImage> images) { for (DiskImage diskImage : images) { if (diskImage.getDiskInterface() == DiskInterface.VirtIO_SCSI && !FeatureSupported.virtIoScsi(getVdsGroup().getcompatibility_version())) { return failCanDoAction(VdcBllMessages.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL); } } return true; } protected boolean validateNoDuplicateDiskImages(Iterable<DiskImage> images) { if (!getParameters().isImportAsNewEntity()) { DiskImagesValidator diskImagesValidator = new DiskImagesValidator(images); return validate(diskImagesValidator.diskImagesAlreadyExist()); } return true; } /** * Validates that that the required cluster exists. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateVdsCluster() { List<VDSGroup> groups = getVdsGroupDAO().getAllForStoragePool(getParameters().getStoragePoolId()); for (VDSGroup group : groups) { if (group.getId().equals(getParameters().getVdsGroupId())) { return true; } } return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } /** * Validates the USB policy. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateUsbPolicy() { VM vm = getParameters().getVm(); VmHandler.updateImportedVmUsbPolicy(vm.getStaticData()); return VmHandler.isUsbPolicyLegal(vm.getUsbPolicy(), vm.getOs(), getVdsGroup(), getReturnValue().getCanDoActionMessages()); } private boolean isTemplateExistsOnExportDomain() { if (VmTemplateHandler.BlankVmTemplateId.equals(getParameters().getVm().getVmtGuid())) { return true; } VdcQueryReturnValue qRetVal = Backend.getInstance().runInternalQuery( VdcQueryType.GetTemplatesFromExportDomain, new GetAllFromExportDomainQueryParameters(getParameters().getStoragePoolId(), getParameters().getSourceDomainId())); if (qRetVal.getSucceeded()) { Map<VmTemplate, ?> templates = qRetVal.getReturnValue(); for (VmTemplate template : templates.keySet()) { if (getParameters().getVm().getVmtGuid().equals(template.getId())) { return true; } } } return false; } protected boolean checkTemplateInStorageDomain() { boolean retValue = getParameters().isImportAsNewEntity() || checkIfDisksExist(imageList); if (retValue && !VmTemplateHandler.BlankVmTemplateId.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { List<StorageDomain> domains = Backend.getInstance() .runInternalQuery(VdcQueryType.GetStorageDomainsByVmTemplateId, new IdQueryParameters(getVm().getVmtGuid())).getReturnValue(); List<Guid> domainsId = LinqUtils.foreach(domains, new Function<StorageDomain, Guid>() { @Override public Guid eval(StorageDomain storageDomainStatic) { return storageDomainStatic.getId(); } }); if (Collections.disjoint(domainsId, imageToDestinationDomainMap.values())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } return retValue; } private boolean templateExists() { if (getVmTemplate() == null && !getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); } return true; } protected boolean checkImagesGUIDsLegal() { for (DiskImage image : getVm().getImages()) { Guid imageGUID = image.getImageId(); Guid storagePoolId = image.getStoragePoolId() != null ? image.getStoragePoolId() : Guid.Empty; Guid storageDomainId = getParameters().getSourceDomainId(); Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; VDSReturnValue retValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DoesImageExist, new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId, imageGUID)); if (Boolean.FALSE.equals(retValue.getReturnValue())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST); } } return true; } protected boolean canAddVm() { // Checking if a desktop with same name already exists if (VmHandler.isVmWithSameNameExistStatic(getVm().getName())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_IMPORT_VM_NAME_EXISTS); } return true; } @Override protected void executeCommand() { try { addVmToDb(); processImages(); // if there aren't tasks - we can just perform the end // vm related ops if (getReturnValue().getVdsmTaskIdList().isEmpty()) { endVmRelatedOps(); } } catch (RuntimeException e) { MacPoolManager.getInstance().freeMacs(macsAdded); throw e; } setSucceeded(true); } private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmInterfaces(); addVmStatistics(); getCompensationContext().stateChanged(); return null; } }); } private void processImages() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmImagesAndSnapshots(); updateSnapshotsFromExport(); moveOrCopyAllImageGroups(); VmDeviceUtils.addImportedDevices(getVm().getStaticData(), getParameters().isImportAsNewEntity()); VmHandler.lockVm(getVm().getId()); if (getParameters().isImportAsNewEntity()) { getParameters().setVm(getVm()); setVmId(getVm().getId()); } return null; } }); } @Override protected void moveOrCopyAllImageGroups() { moveOrCopyAllImageGroups(getVm().getId(), ImagesHandler.filterImageDisks(getVm().getDiskMap().values(), false, false)); copyAllMemoryImages(getVm().getId()); } private void copyAllMemoryImages(Guid containerId) { for (String memoryVolumes : MemoryUtils.getMemoryVolumesFromSnapshots(getVm().getSnapshots())) { List<Guid> guids = GuidUtils.getGuidListFromString(memoryVolumes); // copy the memory dump image VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryDumpImage( containerId, guids.get(0), guids.get(2), guids.get(3)), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); // copy the memory configuration (of the VM) image vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryConfImage( containerId, guids.get(0), guids.get(4), guids.get(5)), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setParentParameters(getParameters()); if (getStoragePool().getStorageType().isBlockDomain()) { params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Preallocated); params.setVolumeFormat(VolumeFormat.RAW); } return params; } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryConfImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); // This volume is always of type 'sparse' and format 'cow' so no need to convert, // and there're no snapshots for it so no reason to use copy collapse params.setUseCopyCollapse(false); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setParentParameters(getParameters()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); return params; } @Override protected void moveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { for (DiskImage disk : disks) { VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForDisk(disk, containerID), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "ImportVmCommand::MoveOrCopyAllImageGroups: Failed to copy disk!"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForDisk(DiskImage disk, Guid containerID) { Guid originalDiskId = newDiskIdForDisk.get(disk.getId()).getId(); Guid destinationDomain = imageToDestinationDomainMap.get(originalDiskId); MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, originalDiskId, newDiskIdForDisk.get(disk.getId()).getImageId(), disk.getId(), disk.getImageId(), destinationDomain, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setUseCopyCollapse(getParameters().getCopyCollapse()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setRevertDbOperationScope(ImageDbOperationScope.IMAGE); params.setQuotaId(disk.getQuotaId() != null ? disk.getQuotaId() : getParameters().getQuotaId()); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(originalDiskId)) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(originalDiskId); params.setVolumeType(diskImageBase.getVolumeType()); params.setVolumeFormat(diskImageBase.getVolumeFormat()); } params.setParentParameters(getParameters()); return params; } protected void addVmImagesAndSnapshots() { Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getVm().getImages()); if (getParameters().getCopyCollapse()) { Guid snapshotId = Guid.newGuid(); int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = ImagesHandler.getActiveVolumeDisk(diskList); disk.setParentId(VmTemplateHandler.BlankVmTemplateId); disk.setImageTemplateId(VmTemplateHandler.BlankVmTemplateId); disk.setVmSnapshotId(snapshotId); disk.setActive(true); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(disk.getId())) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(disk.getId()); disk.setvolumeFormat(diskImageBase.getVolumeFormat()); disk.setVolumeType(diskImageBase.getVolumeType()); } setDiskStorageDomainInfo(disk); if (getParameters().isImportAsNewEntity()) { generateNewDiskId(diskList, disk); } else { newDiskIdForDisk.put(disk.getId(), disk); } disk.setCreationDate(new Date()); saveImage(disk); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); saveBaseDisk(disk); saveDiskImageDynamic(disk); } Snapshot snapshot = addActiveSnapshot(snapshotId); getVm().setSnapshots(Arrays.asList(snapshot)); } else { Guid snapshotId = null; for (DiskImage disk : getVm().getImages()) { disk.setActive(false); setDiskStorageDomainInfo(disk); saveImage(disk); snapshotId = disk.getVmSnapshotId(); saveSnapshotIfNotExists(snapshotId, disk); saveDiskImageDynamic(disk); } int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = ImagesHandler.getActiveVolumeDisk(diskList); newDiskIdForDisk.put(disk.getId(), disk); snapshotId = disk.getVmSnapshotId(); disk.setActive(true); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); updateImage(disk); saveBaseDisk(disk); } // Update active snapshot's data, since it was inserted as a regular snapshot. updateActiveSnapshot(snapshotId); } } /** * Cloning a new disk with a new generated id, with the same volumes and parameters as <code>disk</code>. Also * adding the disk to <code>newDiskGuidForDisk</code> map, so we will be able to link between the new cloned disk * and the old disk id. * * @param diskList * - All the disk volumes * @param disk * - The disk which is about to be cloned */ private void generateNewDiskId(List<DiskImage> diskList, DiskImage disk) { Guid newGuidForDisk = Guid.newGuid(); // Copy the disk so it will preserve the old disk id and image id. newDiskIdForDisk.put(newGuidForDisk, DiskImage.copyOf(disk)); disk.setId(newGuidForDisk); disk.setImageId(Guid.newGuid()); for (DiskImage diskImage : diskList) { diskImage.setId(disk.getId()); } } private void setDiskStorageDomainInfo(DiskImage disk) { ArrayList<Guid> storageDomain = new ArrayList<Guid>(); storageDomain.add(imageToDestinationDomainMap.get(disk.getId())); disk.setStorageIds(storageDomain); } /** Saves the base disk object */ protected void saveBaseDisk(DiskImage disk) { getBaseDiskDao().save(disk); } /** Save the entire image, including it's storage mapping */ protected void saveImage(DiskImage disk) { BaseImagesCommand.saveImage(disk); } /** Updates an image of a disk */ protected void updateImage(DiskImage disk) { getImageDao().update(disk.getImage()); } /** * Generates and saves a {@link DiskImageDynamic} for the given {@link #disk}. * @param disk The imported disk **/ protected void saveDiskImageDynamic(DiskImage disk) { DiskImageDynamic diskDynamic = new DiskImageDynamic(); diskDynamic.setId(disk.getImageId()); diskDynamic.setactual_size(disk.getActualSizeInBytes()); getDiskImageDynamicDAO().save(diskDynamic); } /** * Saves a new active snapshot for the VM * @param snapshotId The ID to assign to the snapshot * @return The generated snapshot */ protected Snapshot addActiveSnapshot(Guid snapshotId) { return snapshotsManager.addActiveSnapshot(snapshotId, getVm(), getMemoryVolumeForNewActiveSnapshot(), getCompensationContext()); } private String getMemoryVolumeForNewActiveSnapshot() { return getParameters().isImportAsNewEntity() ? // We currently don't support using memory that was // saved when a snapshot was taken for VM with different id StringUtils.EMPTY : getMemoryVolumeFromActiveSnapshotInExportDomain(); } private String getMemoryVolumeFromActiveSnapshotInExportDomain() { for (Snapshot snapshot : getVm().getSnapshots()) { if (snapshot.getType() == SnapshotType.ACTIVE) return snapshot.getMemoryVolume(); } log.warnFormat("VM {0} doesn't have active snapshot in export domain", getVmId()); return StringUtils.EMPTY; } /** * Go over the snapshots that were read from the export data. If the snapshot exists (since it was added for the * images), it will be updated. If it doesn't exist, it will be saved. */ private void updateSnapshotsFromExport() { if (getVm().getSnapshots() == null) { return; } for (Snapshot snapshot : getVm().getSnapshots()) { if (getSnapshotDao().exists(getVm().getId(), snapshot.getId())) { getSnapshotDao().update(snapshot); } else { getSnapshotDao().save(snapshot); } } } /** * Save a snapshot if it does not exist in the database. * @param snapshotId The snapshot to save. * @param disk The disk containing the snapshot's information. */ protected void saveSnapshotIfNotExists(Guid snapshotId, DiskImage disk) { if (!getSnapshotDao().exists(getVm().getId(), snapshotId)) { getSnapshotDao().save( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.REGULAR, disk.getDescription(), disk.getLastModifiedDate(), disk.getAppList())); } } /** * Update a snapshot and make it the active snapshot. * @param snapshotId The snapshot to update. */ protected void updateActiveSnapshot(Guid snapshotId) { getSnapshotDao().update( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.ACTIVE, "Active VM snapshot", new Date(), null)); } protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BlankVmTemplateId); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); } private int computeMinAllocatedMem() { int vmMem = getVm().getMemSizeMb(); int minAllocatedMem = vmMem; if (getVm().getMinAllocatedMem() > 0) { minAllocatedMem = getVm().getMinAllocatedMem(); } else { // first get cluster memory over commit value VDSGroup vdsGroup = getVdsGroupDAO().get(getVm().getVdsGroupId()); if (vdsGroup != null && vdsGroup.getmax_vds_memory_over_commit() > 0) { minAllocatedMem = (vmMem * 100) / vdsGroup.getmax_vds_memory_over_commit(); } } return minAllocatedMem; } private void logImportEvents() { // Some values at the OVF file are used for creating events at the GUI // for the sake of providing information on the content of the VM that // was exported, // but not setting it in the imported VM VmStatic vmStaticFromOvf = getVm().getStaticData(); OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(vmStaticFromOvf); Map<String, String> aliasesValuesMap = handler.getAliasesValuesMap(); for (Map.Entry<String, String> entry : aliasesValuesMap.entrySet()) { String fieldName = entry.getKey(); String fieldValue = entry.getValue(); logField(vmStaticFromOvf, fieldName, fieldValue); } handler.resetDefaults(vmStaticForDefaultValues); } private static void logField(VmStatic vmStaticFromOvf, String fieldName, String fieldValue) { String vmName = vmStaticFromOvf.getName(); AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("FieldName", fieldName); logable.addCustomValue("VmName", vmName); logable.addCustomValue("FieldValue", fieldValue); AuditLogDirector.log(logable, AuditLogType.VM_IMPORT_INFO); } protected void addVmInterfaces() { VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(); VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(getVm().getVdsGroupId(), getStoragePoolId(), getVdsGroup().getcompatibility_version(), AuditLogType.IMPORTEXPORT_IMPORT_VM_INVALID_INTERFACES); for (VmNetworkInterface iface : getVm().getInterfaces()) { initInterface(iface); vnicProfileHelper.updateNicWithVnicProfileForUser(iface, getCurrentUser().getUserId()); vmInterfaceManager.add(iface, getCompensationContext(), getParameters().isImportAsNewEntity(), getVdsGroup().getcompatibility_version()); macsAdded.add(iface.getMacAddress()); } vnicProfileHelper.auditInvalidInterfaces(getVmName()); } private void initInterface(VmNic iface) { if (iface.getId() == null) { iface.setId(Guid.newGuid()); } fillMacAddressIfMissing(iface); iface.setVmTemplateId(null); iface.setVmId(getVmId()); } private void addVmDynamic() { VmDynamic tempVar = new VmDynamic(); tempVar.setId(getVmId()); tempVar.setStatus(VMStatus.ImageLocked); tempVar.setVmHost(""); tempVar.setVmIp(""); tempVar.setVmFQDN(""); tempVar.setAppList(getParameters().getVm().getDynamicData().getAppList()); getVmDynamicDAO().save(tempVar); getCompensationContext().snapshotNewEntity(tempVar); } private void addVmStatistics() { VmStatistics stats = new VmStatistics(); stats.setId(getVmId()); getVmStatisticsDAO().save(stats); getCompensationContext().snapshotNewEntity(stats); getCompensationContext().stateChanged(); } @Override protected void endSuccessfully() { checkTrustedService(); endImportCommand(); } private void checkTrustedService() { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("VmName", getVmName()); if (getVm().isTrustedService() && !getVdsGroup().supportsTrustedService()) { AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_TRUSTED_TO_UNTRUSTED); } else if (!getVm().isTrustedService() && getVdsGroup().supportsTrustedService()) { AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_UNTRUSTED_TO_TRUSTED); } } @Override protected void endActionOnAllImageGroups() { for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(getParameters().getTaskGroupSuccess()); getBackend().EndAction(getImagesActionType(), p); } } @Override protected void endWithFailure() { // Going to try and refresh the VM by re-loading it form DB setVm(null); if (getVm() != null) { removeVmSnapshots(); endActionOnAllImageGroups(); removeVmNetworkInterfaces(); getVmDynamicDAO().remove(getVmId()); getVmStatisticsDAO().remove(getVmId()); getVmStaticDAO().remove(getVmId()); setSucceeded(true); } else { setVm(getParameters().getVm()); // Setting VM from params, for logging purposes // No point in trying to end action again, as the imported VM does not exist in the DB. getReturnValue().setEndActionTryAgain(false); } } private void removeVmSnapshots() { Guid vmId = getVmId(); Set<String> memoryStates = snapshotsManager.removeSnapshots(vmId); for (String memoryState : memoryStates) { removeMemoryVolumes(memoryState, vmId); } } private void removeMemoryVolumes(String memoryVolume, Guid vmId) { RemoveMemoryVolumesParameters parameters = new RemoveMemoryVolumesParameters(memoryVolume, vmId); parameters.setParentCommand(getActionType()); parameters.setEntityInfo(getParameters().getEntityInfo()); parameters.setParentParameters(getParameters()); VdcReturnValueBase retVal = getBackend().runInternalAction( VdcActionType.RemoveMemoryVolumes, parameters, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!retVal.getSucceeded()) { log.errorFormat("Failed to remove memory volumes: {0}", memoryVolume); } } protected void removeVmNetworkInterfaces() { new VmInterfaceManager().removeAll(getVmId()); } protected void endImportCommand() { endActionOnAllImageGroups(); endVmRelatedOps(); setSucceeded(true); } private void endVmRelatedOps() { setVm(null); if (getVm() != null) { VmHandler.unLockVm(getVm()); } else { setCommandShouldBeLogged(false); log.warn("ImportVmCommand::EndImportCommand: Vm is null - not performing full EndAction"); } } @Override public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: return getSucceeded() ? AuditLogType.IMPORTEXPORT_STARTING_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_SUCCESS: return getSucceeded() ? AuditLogType.IMPORTEXPORT_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_FAILURE: return AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; } return super.getAuditLogTypeValue(); } @Override protected List<Class<?>> getValidationGroups() { if (getParameters().isImportAsNewEntity()) { return addValidationGroup(ImportClonedEntity.class); } return addValidationGroup(ImportEntity.class); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getVm().getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; } @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VM.name().toLowerCase(), (getVmName() == null) ? "" : getVmName()); jobProperties.put(VdcObjectType.VdsGroups.name().toLowerCase(), getVdsGroupName()); } return jobProperties; } @Override public VDSGroup getVdsGroup() { return super.getVdsGroup(); } @Override public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); for (Disk disk : getParameters().getVm().getDiskMap().values()) { //TODO: handle import more than once; if(disk instanceof DiskImage){ DiskImage diskImage = (DiskImage)disk; list.add(new QuotaStorageConsumptionParameter( diskImage.getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, imageToDestinationDomainMap.get(diskImage.getId()), (double)diskImage.getSizeInGigabytes())); } } return list; } // TaskHandlerCommand Implementation // public T getParameters() { return super.getParameters(); } public VdcActionType getActionType() { return super.getActionType(); } public VdcReturnValueBase getReturnValue() { return super.getReturnValue(); } public ExecutionContext getExecutionContext() { return super.getExecutionContext(); } public void setExecutionContext(ExecutionContext executionContext) { super.setExecutionContext(executionContext); } public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, VdcObjectType entityType, Guid... entityIds) { return super.createTaskInCurrentTransaction(taskId, asyncTaskCreationInfo, parentCommand, entityType, entityIds); } public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand) { return super.createTask(taskId, asyncTaskCreationInfo, parentCommand); } public ArrayList<Guid> getTaskIdList() { return super.getTaskIdList(); } public void preventRollback() { throw new NotImplementedException(); } public Guid persistAsyncTaskPlaceHolder() { return super.persistAsyncTaskPlaceHolder(getActionType()); } public Guid persistAsyncTaskPlaceHolder(String taskKey) { return super.persistAsyncTaskPlaceHolder(getActionType(), taskKey); } }
package org.ovirt.engine.core.bll; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import javax.inject.Inject; import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.network.cluster.NetworkHelper; import org.ovirt.engine.core.bll.numa.vm.NumaValidator; import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaSanityParameter; import org.ovirt.engine.core.bll.quota.QuotaVdsDependent; import org.ovirt.engine.core.bll.quota.QuotaVdsGroupConsumptionParameter; import org.ovirt.engine.core.bll.snapshots.SnapshotsManager; import org.ovirt.engine.core.bll.utils.IconUtils; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.IconValidator; import org.ovirt.engine.core.bll.validator.VmValidator; import org.ovirt.engine.core.bll.validator.VmWatchdogValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.GraphicsParameters; import org.ovirt.engine.core.common.action.HotSetAmountOfMemoryParameters; import org.ovirt.engine.core.common.action.HotSetNumberOfCpusParameters; import org.ovirt.engine.core.common.action.LockProperties; import org.ovirt.engine.core.common.action.LockProperties.Scope; import org.ovirt.engine.core.common.action.PlugAction; import org.ovirt.engine.core.common.action.RngDeviceParameters; import org.ovirt.engine.core.common.action.UpdateVmVersionParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.action.VmManagementParametersBase; import org.ovirt.engine.core.common.action.VmNumaNodeOperationParameters; import org.ovirt.engine.core.common.action.WatchdogParameters; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.GraphicsDevice; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.MigrationSupport; import org.ovirt.engine.core.common.businessentities.Provider; import org.ovirt.engine.core.common.businessentities.ProviderType; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmBase; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.VmDeviceId; import org.ovirt.engine.core.common.businessentities.VmNumaNode; import org.ovirt.engine.core.common.businessentities.VmPayload; import org.ovirt.engine.core.common.businessentities.VmRngDevice; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmWatchdog; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.VmNic; import org.ovirt.engine.core.common.businessentities.storage.Disk; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.errors.EngineError; import org.ovirt.engine.core.common.errors.EngineException; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.customprop.VmPropertiesUtils; import org.ovirt.engine.core.common.validation.group.UpdateVm; import org.ovirt.engine.core.compat.DateTime; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.dao.VmDeviceDao; import org.ovirt.engine.core.dao.provider.ProviderDao; public class UpdateVmCommand<T extends VmManagementParametersBase> extends VmManagementCommandBase<T> implements QuotaVdsDependent, RenamedEntityInfoProvider{ private static final Base64 BASE_64 = new Base64(0, null); @Inject private ProviderDao providerDao; private VM oldVm; private boolean quotaSanityOnly = false; private VmStatic newVmStatic; private VdcReturnValueBase setNumberOfCpusResult; private List<GraphicsDevice> cachedGraphics; private boolean isUpdateVmTemplateVersion = false; public UpdateVmCommand(T parameters) { this(parameters, null); } public UpdateVmCommand(T parameters, CommandContext commandContext) { super(parameters, commandContext); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId()); } } @Override protected void init() { super.init(); if (isVmExist()) { Version compatibilityVersion = getEffectiveCompatibilityVersion(); getVmPropertiesUtils().separateCustomPropertiesToUserAndPredefined( compatibilityVersion, getParameters().getVmStaticData()); getVmPropertiesUtils().separateCustomPropertiesToUserAndPredefined( compatibilityVersion, getVm().getStaticData()); } VmHandler.updateDefaultTimeZone(getParameters().getVmStaticData()); VmHandler.autoSelectUsbPolicy(getParameters().getVmStaticData(), getVdsGroup()); VmHandler.autoSelectDefaultDisplayType(getVmId(), getParameters().getVmStaticData(), getVdsGroup(), getParameters().getGraphicsDevices()); updateParametersVmFromInstanceType(); // we always need to verify new or existing numa nodes with the updated VM configuration if (!getParameters().isUpdateNuma()) { getParameters().getVm().setvNumaNodeList(getDbFacade().getVmNumaNodeDao().getAllVmNumaNodeByVmId (getParameters().getVmId())); } } private VmPropertiesUtils getVmPropertiesUtils() { return VmPropertiesUtils.getInstance(); } @Override protected LockProperties applyLockProperties(LockProperties lockProperties) { return lockProperties.withScope(Scope.Execution); } @Override public AuditLogType getAuditLogTypeValue() { return isInternalExecution() ? getSucceeded() ? AuditLogType.SYSTEM_UPDATE_VM : AuditLogType.SYSTEM_FAILED_UPDATE_VM : getSucceeded() ? AuditLogType.USER_UPDATE_VM : AuditLogType.USER_FAILED_UPDATE_VM; } @Override protected void executeVmCommand() { oldVm = getVm(); // needs to be here for post-actions if (isUpdateVmTemplateVersion) { updateVmTemplateVersion(); return; // template version was changed, no more work is required } if (isRunningConfigurationNeeded()) { createNextRunSnapshot(); } VmHandler.warnMemorySizeLegal(getParameters().getVm().getStaticData(), getEffectiveCompatibilityVersion()); getVmStaticDao().incrementDbGeneration(getVm().getId()); newVmStatic = getParameters().getVmStaticData(); newVmStatic.setCreationDate(oldVm.getStaticData().getCreationDate()); // save user selected value for hotplug before overriding with db values (when updating running vm) int cpuPerSocket = newVmStatic.getCpuPerSocket(); int numOfSockets = newVmStatic.getNumOfSockets(); int threadsPerCpu = newVmStatic.getThreadsPerCpu(); int memSizeMb = newVmStatic.getMemSizeMb(); if (newVmStatic.getCreationDate().equals(DateTime.getMinValue())) { newVmStatic.setCreationDate(new Date()); } if (getVm().isRunningOrPaused()) { if (!VmHandler.copyNonEditableFieldsToDestination(oldVm.getStaticData(), newVmStatic, isHotSetEnabled())) { // fail update vm if some fields could not be copied throw new EngineException(EngineError.FAILED_UPDATE_RUNNING_VM); } } updateVmNetworks(); updateVmNumaNodes(); if (isHotSetEnabled()) { hotSetCpus(cpuPerSocket, numOfSockets, threadsPerCpu); hotSetMemory(memSizeMb); } final List<Guid> oldIconIds = IconUtils.updateVmIcon( oldVm.getStaticData(), newVmStatic, getParameters().getVmLargeIcon()); getVmStaticDao().update(newVmStatic); if (getVm().isNotRunning()) { updateVmPayload(); VmDeviceUtils.updateVmDevices(getParameters(), oldVm); updateWatchdog(); updateRngDevice(); updateGraphicsDevice(); updateVmHostDevices(); } IconUtils.removeUnusedIcons(oldIconIds); VmHandler.updateVmInitToDB(getParameters().getVmStaticData()); checkTrustedService(); setSucceeded(true); } private void updateVmHostDevices() { if (isDedicatedVmForVdsChanged()) { log.info("Pinned host changed for VM: {}. Dropping configured host devices.", getVm().getName()); getVmDeviceDao().removeVmDevicesByVmIdAndType(getVmId(), VmDeviceGeneralType.HOSTDEV); } } /** * Handles a template-version update use case. * If vm is down -> updateVmVersionCommand will handle the rest and will preform the actual change. * if it's running -> a NEXT_RUN snapshot will be created and the change will take affect only on power down. * in both cases the command should end after this function as no more changes are possible. */ private void updateVmTemplateVersion() { if (getVm().getStatus() == VMStatus.Down) { VdcReturnValueBase result = runInternalActionWithTasksContext( VdcActionType.UpdateVmVersion, new UpdateVmVersionParameters(getVmId(), getParameters().getVm().getVmtGuid(), getParameters().getVm().isUseLatestVersion()), getLock() ); if (result.getSucceeded()) { getTaskIdList().addAll(result.getInternalVdsmTaskIdList()); } setSucceeded(result.getSucceeded()); setActionReturnValue(VdcActionType.UpdateVmVersion); } else { createNextRunSnapshot(); setSucceeded(true); } } private boolean updateRngDevice() { // do not update if this flag is not set if (getParameters().isUpdateRngDevice()) { VdcQueryReturnValue query = runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(getParameters().getVmId())); @SuppressWarnings("unchecked") List<VmRngDevice> rngDevs = query.getReturnValue(); VdcReturnValueBase rngCommandResult = null; if (rngDevs.isEmpty()) { if (getParameters().getRngDevice() != null) { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); rngCommandResult = runInternalAction(VdcActionType.AddRngDevice, params, cloneContextAndDetachFromParent()); } } else { if (getParameters().getRngDevice() == null) { RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), true); rngCommandResult = runInternalAction(VdcActionType.RemoveRngDevice, params, cloneContextAndDetachFromParent()); } else { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId()); rngCommandResult = runInternalAction(VdcActionType.UpdateRngDevice, params, cloneContextAndDetachFromParent()); } } if (rngCommandResult != null && !rngCommandResult.getSucceeded()) { return false; } } return true; } private void createNextRunSnapshot() { // first remove existing snapshot Snapshot runSnap = getSnapshotDao().get(getVmId(), Snapshot.SnapshotType.NEXT_RUN); if (runSnap != null) { getSnapshotDao().remove(runSnap.getId()); } VM vm = new VM(); vm.setStaticData(getParameters().getVmStaticData()); // create new snapshot with new configuration new SnapshotsManager().addSnapshot(Guid.newGuid(), "Next Run configuration snapshot", Snapshot.SnapshotStatus.OK, Snapshot.SnapshotType.NEXT_RUN, vm, true, StringUtils.EMPTY, Collections.<DiskImage> emptyList(), VmDeviceUtils.getVmDevicesForNextRun(getVm(), getParameters()), getCompensationContext()); } private void hotSetCpus(int cpuPerSocket, int newNumOfSockets, int newThreadsPerCpu) { int currentSockets = getVm().getNumOfSockets(); int currentCpuPerSocket = getVm().getCpuPerSocket(); int currentThreadsPerCpu = getVm().getThreadsPerCpu(); // try hotplug only if topology (cpuPerSocket, threadsPerCpu) hasn't changed if (getVm().getStatus() == VMStatus.Up && currentSockets != newNumOfSockets && currentCpuPerSocket == cpuPerSocket && currentThreadsPerCpu == newThreadsPerCpu) { HotSetNumberOfCpusParameters params = new HotSetNumberOfCpusParameters( newVmStatic, currentSockets < newNumOfSockets ? PlugAction.PLUG : PlugAction.UNPLUG); setNumberOfCpusResult = runInternalAction( VdcActionType.HotSetNumberOfCpus, params, cloneContextAndDetachFromParent()); newVmStatic.setNumOfSockets(setNumberOfCpusResult.getSucceeded() ? newNumOfSockets : currentSockets); auditLogHotSetCpusCandos(params); } } private void hotSetMemory(int newAmountOfMemory) { int currentMemory = getVm().getMemSizeMb(); if (getVm().getStatus() == VMStatus.Up && currentMemory != newAmountOfMemory) { HotSetAmountOfMemoryParameters params = new HotSetAmountOfMemoryParameters( newVmStatic, currentMemory < newAmountOfMemory ? PlugAction.PLUG : PlugAction.UNPLUG, // We always use node 0, auto-numa should handle the allocation 0); VdcReturnValueBase setAmountOfMemoryResult = runInternalAction( VdcActionType.HotSetAmountOfMemory, params, cloneContextAndDetachFromParent()); newVmStatic.setMemSizeMb(setAmountOfMemoryResult.getSucceeded() ? newAmountOfMemory : currentMemory); auditLogHotSetMemCandos(params, setAmountOfMemoryResult); } } /** * add audit log msg for failed hot set in case error was in CDA * otherwise internal command will audit log the result * @param params */ private void auditLogHotSetCpusCandos(HotSetNumberOfCpusParameters params) { if (!setNumberOfCpusResult.getCanDoAction()) { AuditLogableBase logable = new HotSetNumberOfCpusCommand<>(params); List<String> canDos = getBackend().getErrorsTranslator(). translateErrorText(setNumberOfCpusResult.getCanDoActionMessages()); logable.addCustomValue(HotSetNumberOfCpusCommand.LOGABLE_FIELD_ERROR_MESSAGE, StringUtils.join(canDos, ",")); auditLogDirector.log(logable, AuditLogType.FAILED_HOT_SET_NUMBER_OF_CPUS); } } /** * add audit log msg for failed hot set in case error was in CDA * otherwise internal command will audit log the result * @param params */ private void auditLogHotSetMemCandos(HotSetAmountOfMemoryParameters params, VdcReturnValueBase setAmountOfMemoryResult) { if (!setAmountOfMemoryResult.getCanDoAction()) { AuditLogableBase logable = new HotSetAmountOfMemoryCommand<>(params); List<String> canDos = getBackend().getErrorsTranslator(). translateErrorText(setAmountOfMemoryResult.getCanDoActionMessages()); logable.addCustomValue(HotSetAmountOfMemoryCommand.LOGABLE_FIELD_ERROR_MESSAGE, StringUtils.join(canDos, ",")); auditLogDirector.log(logable, AuditLogType.FAILED_HOT_SET_NUMBER_OF_CPUS); } } private void checkTrustedService() { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("VmName", getVmName()); if (getParameters().getVm().isTrustedService() && !getVdsGroup().supportsTrustedService()) { auditLogDirector.log(logable, AuditLogType.USER_UPDATE_VM_FROM_TRUSTED_TO_UNTRUSTED); } else if (!getParameters().getVm().isTrustedService() && getVdsGroup().supportsTrustedService()) { auditLogDirector.log(logable, AuditLogType.USER_UPDATE_VM_FROM_UNTRUSTED_TO_TRUSTED); } } private void updateWatchdog() { // do not update if this flag is not set if (getParameters().isUpdateWatchdog()) { VdcQueryReturnValue query = runInternalQuery(VdcQueryType.GetWatchdog, new IdQueryParameters(getParameters().getVmId())); List<VmWatchdog> watchdogs = query.getReturnValue(); if (watchdogs.isEmpty()) { if (getParameters().getWatchdog() == null) { // nothing to do, no watchdog and no watchdog to create } else { WatchdogParameters parameters = new WatchdogParameters(); parameters.setId(getParameters().getVmId()); parameters.setAction(getParameters().getWatchdog().getAction()); parameters.setModel(getParameters().getWatchdog().getModel()); runInternalAction(VdcActionType.AddWatchdog, parameters, cloneContextAndDetachFromParent()); } } else { WatchdogParameters watchdogParameters = new WatchdogParameters(); watchdogParameters.setId(getParameters().getVmId()); if (getParameters().getWatchdog() == null) { // there is a watchdog in the vm, there should not be any, so let's delete runInternalAction(VdcActionType.RemoveWatchdog, watchdogParameters, cloneContextAndDetachFromParent()); } else { // there is a watchdog in the vm, we have to update. watchdogParameters.setAction(getParameters().getWatchdog().getAction()); watchdogParameters.setModel(getParameters().getWatchdog().getModel()); runInternalAction(VdcActionType.UpdateWatchdog, watchdogParameters, cloneContextAndDetachFromParent()); } } } } private void updateGraphicsDevice() { for (GraphicsType type : getParameters().getGraphicsDevices().keySet()) { GraphicsDevice vmGraphicsDevice = getGraphicsDevOfType(type); if (vmGraphicsDevice == null) { if (getParameters().getGraphicsDevices().get(type) != null) { getParameters().getGraphicsDevices().get(type).setVmId(getVmId()); getBackend().runInternalAction(VdcActionType.AddGraphicsDevice, new GraphicsParameters(getParameters().getGraphicsDevices().get(type))); } } else { if (getParameters().getGraphicsDevices().get(type) == null) { getBackend().runInternalAction(VdcActionType.RemoveGraphicsDevice, new GraphicsParameters(vmGraphicsDevice)); } else { getParameters().getGraphicsDevices().get(type).setVmId(getVmId()); getBackend().runInternalAction(VdcActionType.UpdateGraphicsDevice, new GraphicsParameters(getParameters().getGraphicsDevices().get(type))); } } } } // first dev or null private GraphicsDevice getGraphicsDevOfType(GraphicsType type) { List<GraphicsDevice> graphicsDevices = getGraphicsDevices(); for (GraphicsDevice dev : graphicsDevices) { if (dev.getGraphicsType() == type) { return dev; } } return null; } private List<GraphicsDevice> getGraphicsDevices() { if (cachedGraphics == null) { cachedGraphics = getBackend() .runInternalQuery(VdcQueryType.GetGraphicsDevices, new IdQueryParameters(getParameters().getVmId())).getReturnValue(); } return cachedGraphics; } protected void updateVmPayload() { VmDeviceDao dao = getVmDeviceDao(); VmPayload payload = getParameters().getVmPayload(); if (payload != null || getParameters().isClearPayload()) { List<VmDevice> disks = dao.getVmDeviceByVmIdAndType(getVmId(), VmDeviceGeneralType.DISK); VmDevice oldPayload = null; for (VmDevice disk : disks) { if (VmPayload.isPayload(disk.getSpecParams())) { oldPayload = disk; break; } } if (oldPayload != null) { List<VmDeviceId> devs = new ArrayList<>(); devs.add(oldPayload.getId()); dao.removeAll(devs); } if (!getParameters().isClearPayload()) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.newGuid(), getVmId()), VmDeviceGeneralType.DISK, payload.getDeviceType(), payload.getSpecParams(), true, true); } } } private void updateVmNetworks() { // check if the cluster has changed if (!Objects.equals(getVm().getVdsGroupId(), getParameters().getVmStaticData().getVdsGroupId())) { List<Network> networks = getNetworkDao().getAllForCluster(getParameters().getVmStaticData().getVdsGroupId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getParameters().getVmStaticData().getId()); for (final VmNic iface : interfaces) { final Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId()); boolean networkFound = networks.stream().anyMatch(n -> Objects.equals(n.getId(), network.getId())); // if network not exists in cluster we remove the network from the interface if (!networkFound) { iface.setVnicProfileId(null); getVmNicDao().update(iface); } } } } private void updateVmNumaNodes() { if (!getParameters().isUpdateNuma()) { return; } List<VmNumaNode> newList = getParameters().getVmStaticData().getvNumaNodeList(); VmNumaNodeOperationParameters params = new VmNumaNodeOperationParameters(getParameters().getVm(), new ArrayList<>(newList)); addLogMessages(getBackend().runInternalAction(VdcActionType.SetVmNumaNodes, params)); } private void addLogMessages(VdcReturnValueBase returnValueBase) { if (!returnValueBase.getSucceeded()) { auditLogDirector.log(this, AuditLogType.NUMA_UPDATE_VM_NUMA_NODE_FAILED); } } @Override protected List<Class<?>> getValidationGroups() { addValidationGroup(UpdateVm.class); return super.getValidationGroups(); } @Override protected void setActionMessageParameters() { addCanDoActionMessage(EngineMessage.VAR__ACTION__UPDATE); addCanDoActionMessage(EngineMessage.VAR__TYPE__VM); } @Override protected boolean canDoAction() { if (!super.canDoAction()) { return false; } VM vmFromDB = getVm(); VM vmFromParams = getParameters().getVm(); // check if VM was changed to use latest if (vmFromDB.isUseLatestVersion() != vmFromParams.isUseLatestVersion() && vmFromParams.isUseLatestVersion()) { // check if a version change is actually required or just let the local command to update this field vmFromParams.setVmtGuid(getVmTemplateDao().getTemplateWithLatestVersionInChain(getVm().getVmtGuid()).getId()); } // pool VMs are allowed to change template id, this verifies that the change is only between template versions. if (!vmFromDB.getVmtGuid().equals(vmFromParams.getVmtGuid())) { VmTemplate origTemplate = getVmTemplateDao().get(vmFromDB.getVmtGuid()); VmTemplate newTemplate = getVmTemplateDao().get(vmFromParams.getVmtGuid()); if (newTemplate == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); } else if (origTemplate != null && !origTemplate.getBaseTemplateId().equals(newTemplate.getBaseTemplateId())) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_IS_ON_DIFFERENT_CHAIN); } else if (vmFromDB.getVmPoolId() != null) { isUpdateVmTemplateVersion = true; return true; // no more tests are needed because no more changes are allowed in this state } } if (getVdsGroup() == null) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); return false; } if (vmFromDB.getVdsGroupId() == null) { failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); return false; } if (!isVmExist()) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (!canRunActionOnNonManagedVm()) { return false; } if (StringUtils.isEmpty(vmFromParams.getName())) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NAME_MAY_NOT_BE_EMPTY); } // check that VM name is not too long boolean vmNameValidLength = isVmNameValidLength(vmFromParams); if (!vmNameValidLength) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NAME_LENGTH_IS_TOO_LONG); } // Checking if a desktop with same name already exists if (!StringUtils.equals(vmFromDB.getName(), vmFromParams.getName())) { boolean exists = isVmWithSameNameExists(vmFromParams.getName(), getStoragePoolId()); if (exists) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NAME_ALREADY_USED); } } if (!validateCustomProperties(vmFromParams.getStaticData(), getReturnValue().getCanDoActionMessages())) { return false; } if (!VmHandler.isOsTypeSupported(vmFromParams.getOs(), getVdsGroup().getArchitecture(), getReturnValue().getCanDoActionMessages())) { return false; } if (!VmHandler.isCpuSupported( vmFromParams.getVmOsId(), getEffectiveCompatibilityVersion(), getVdsGroup().getCpuName(), getReturnValue().getCanDoActionMessages())) { return false; } if (vmFromParams.getSingleQxlPci() && !VmHandler.isSingleQxlDeviceLegal(vmFromParams.getDefaultDisplayType(), vmFromParams.getOs(), getReturnValue().getCanDoActionMessages(), getEffectiveCompatibilityVersion())) { return false; } if (!areUpdatedFieldsLegal()) { return failCanDoAction(EngineMessage.VM_CANNOT_UPDATE_ILLEGAL_FIELD); } if (!vmFromDB.getVdsGroupId().equals(vmFromParams.getVdsGroupId())) { return failCanDoAction(EngineMessage.VM_CANNOT_UPDATE_CLUSTER); } if (!isDedicatedVdsExistOnSameCluster(vmFromParams.getStaticData(), getReturnValue().getCanDoActionMessages())) { return false; } if (!VmHandler.isNumOfMonitorsLegal( VmHandler.getResultingVmGraphics(VmDeviceUtils.getGraphicsTypesOfEntity(getVmId()), getParameters().getGraphicsDevices()), getParameters().getVmStaticData().getNumOfMonitors(), getReturnValue().getCanDoActionMessages())) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_NUM_OF_MONITORS); } // Check PCI and IDE limits are ok if (!isValidPciAndIdeLimit(vmFromParams)) { return false; } if (!VmTemplateCommand.isVmPriorityValueLegal(vmFromParams.getPriority(), getReturnValue().getCanDoActionMessages())) { return false; } if (vmFromDB.getVmPoolId() != null && vmFromParams.isStateless()) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_FROM_POOL_CANNOT_BE_STATELESS); } if (!AddVmCommand.checkCpuSockets( vmFromParams.getNumOfSockets(), vmFromParams.getCpuPerSocket(), vmFromParams.getThreadsPerCpu(), getEffectiveCompatibilityVersion().toString(), getReturnValue().getCanDoActionMessages())) { return false; } // check for Vm Payload if (getParameters().getVmPayload() != null) { if (!checkPayload(getParameters().getVmPayload(), vmFromParams.getIsoPath())) { return false; } // we save the content in base64 string for (Map.Entry<String, String> entry : getParameters().getVmPayload().getFiles().entrySet()) { entry.setValue(new String(BASE_64.encode(entry.getValue().getBytes()), Charset.forName(CharEncoding.UTF_8))); } } // check for Vm Watchdog Model if (getParameters().getWatchdog() != null) { if (!validate((new VmWatchdogValidator(vmFromParams.getOs(), getParameters().getWatchdog(), getEffectiveCompatibilityVersion())).isValid())) { return false; } } if (!VmHandler.isUsbPolicyLegal(vmFromParams.getUsbPolicy(), vmFromParams.getOs(), getEffectiveCompatibilityVersion(), getReturnValue().getCanDoActionMessages())) { return false; } // Check if the graphics and display from parameters are supported if (!VmHandler.isGraphicsAndDisplaySupported(vmFromParams.getOs(), VmHandler.getResultingVmGraphics(VmDeviceUtils.getGraphicsTypesOfEntity(getVmId()), getParameters().getGraphicsDevices()), vmFromParams.getDefaultDisplayType(), getReturnValue().getCanDoActionMessages(), getEffectiveCompatibilityVersion())) { return false; } if (!FeatureSupported.isMigrationSupported(getVdsGroup().getArchitecture(), getEffectiveCompatibilityVersion()) && vmFromParams.getMigrationSupport() != MigrationSupport.PINNED_TO_HOST) { return failCanDoAction(EngineMessage.VM_MIGRATION_IS_NOT_SUPPORTED); } // check cpuPinning if (!isCpuPinningValid(vmFromParams.getCpuPinning(), vmFromParams.getStaticData())) { return false; } if (!validatePinningAndMigration(getReturnValue().getCanDoActionMessages(), getParameters().getVm().getStaticData(), getParameters().getVm().getCpuPinning())) { return false; } if (vmFromParams.isUseHostCpuFlags() && vmFromParams.getMigrationSupport() != MigrationSupport.PINNED_TO_HOST) { return failCanDoAction(EngineMessage.VM_HOSTCPU_MUST_BE_PINNED_TO_HOST); } if (!isCpuSharesValid(vmFromParams)) { return failCanDoAction(EngineMessage.QOS_CPU_SHARES_OUT_OF_RANGE); } if (isVirtioScsiEnabled()) { // Verify cluster compatibility if (!FeatureSupported.virtIoScsi(getEffectiveCompatibilityVersion())) { return failCanDoAction(EngineMessage.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL); } // Verify OS compatibility if (!VmHandler.isOsTypeSupportedForVirtioScsi(vmFromParams.getOs(), getEffectiveCompatibilityVersion(), getReturnValue().getCanDoActionMessages())) { return false; } } VmValidator vmValidator = createVmValidator(vmFromParams); if (Boolean.FALSE.equals(getParameters().isVirtioScsiEnabled()) && !validate(vmValidator.canDisableVirtioScsi(null))) { return false; } if (vmFromParams.getMinAllocatedMem() > vmFromParams.getMemSizeMb()) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_MIN_MEMORY_CANNOT_EXCEED_MEMORY_SIZE); } if (!setAndValidateCpuProfile()) { return false; } if (isBalloonEnabled() && !osRepository.isBalloonEnabled(getParameters().getVmStaticData().getOsId(), getEffectiveCompatibilityVersion())) { addCanDoActionMessageVariable("clusterArch", getVdsGroup().getArchitecture()); return failCanDoAction(EngineMessage.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH); } if (isSoundDeviceEnabled() && !osRepository.isSoundDeviceEnabled(getParameters().getVmStaticData().getOsId(), getEffectiveCompatibilityVersion())) { addCanDoActionMessageVariable("clusterArch", getVdsGroup().getArchitecture()); return failCanDoAction(EngineMessage.SOUND_DEVICE_REQUESTED_ON_NOT_SUPPORTED_ARCH); } if (!validate(NumaValidator.checkVmNumaNodesIntegrity(getParameters().getVm(), getParameters().getVm().getvNumaNodeList()) )) { return false; } if (getParameters().getVmLargeIcon() != null && !validate(IconValidator.validate( IconValidator.DimensionsType.LARGE_CUSTOM_ICON, getParameters().getVmLargeIcon()))) { return false; } if (getParameters().getVmStaticData() != null && getParameters().getVmStaticData().getSmallIconId() != null && !validate(IconValidator.validateIconId(getParameters().getVmStaticData().getSmallIconId(), "Small"))) { return false; } if (getParameters().getVmStaticData() != null && getParameters().getVmStaticData().getLargeIconId() != null && !validate(IconValidator.validateIconId(getParameters().getVmStaticData().getLargeIconId(), "Large"))) { return false; } if (vmFromParams.getProviderId() != null) { Provider<?> provider = providerDao.get(vmFromParams.getProviderId()); if (provider == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_PROVIDER_DOESNT_EXIST); } if (provider.getType() != ProviderType.FOREMAN) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_HOST_PROVIDER_TYPE_MISMATCH); } } return true; } protected boolean isDedicatedVdsExistOnSameCluster(VmBase vm, ArrayList<String> canDoActionMessages) { return VmHandler.validateDedicatedVdsExistOnSameCluster(vm, canDoActionMessages); } protected boolean isValidPciAndIdeLimit(VM vmFromParams) { List<Disk> allDisks = getDbFacade().getDiskDao().getAllForVm(getVmId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getVmId()); return checkPciAndIdeLimit( vmFromParams.getOs(), getEffectiveCompatibilityVersion(), vmFromParams.getNumOfMonitors(), interfaces, allDisks, isVirtioScsiEnabled(), hasWatchdog(), isBalloonEnabled(), isSoundDeviceEnabled(), getReturnValue().getCanDoActionMessages()); } private boolean isVmExist() { return getParameters().getVmStaticData() != null && getVm() != null; } protected boolean areUpdatedFieldsLegal() { return VmHandler.isUpdateValid(getVm().getStaticData(), getParameters().getVmStaticData(), VMStatus.Down); } /** * check if we need to use running-configuration * @return true if vm is running and we change field that has @EditableOnVmStatusField annotation * or runningConfiguration already exist */ private boolean isRunningConfigurationNeeded() { return getVm().isNextRunConfigurationExists() || !VmHandler.isUpdateValid(getVm().getStaticData(), getParameters().getVmStaticData(), getVm().getStatus(), isHotSetEnabled()) || !VmHandler.isUpdateValidForVmDevices(getVmId(), getVm().getStatus(), getParameters()); } private boolean isHotSetEnabled() { return !getParameters().isApplyChangesLater(); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { final List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); if (isVmExist()) { if (!StringUtils.equals( getVm().getPredefinedProperties(), getParameters().getVmStaticData().getPredefinedProperties()) || !StringUtils.equals( getVm().getUserDefinedProperties(), getParameters().getVmStaticData().getUserDefinedProperties())) { permissionList.add(new PermissionSubject(getParameters().getVmId(), VdcObjectType.VM, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } // host-specific parameters can be changed by administration role only if (isDedicatedVmForVdsChanged() || isCpuPinningChanged()) { permissionList.add( new PermissionSubject(getParameters().getVmId(), VdcObjectType.VM, ActionGroup.EDIT_ADMIN_VM_PROPERTIES)); } } return permissionList; } private boolean isDedicatedVmForVdsChanged() { List<Guid> paramList = getParameters().getVmStaticData().getDedicatedVmForVdsList(); List<Guid> vmList = getVm().getDedicatedVmForVdsList(); if (vmList == null && paramList == null){ return false; } if (vmList == null || paramList == null){ return true; } // vmList.equals(paramList) not good enough, the lists order could change if (vmList.size() != paramList.size()){ return true; } for (Guid origGuid : vmList) { if (paramList.contains(origGuid) == false){ return true; } } return false; } private boolean isCpuPinningChanged() { return !(getVm().getCpuPinning() == null ? getParameters().getVmStaticData().getCpuPinning() == null : getVm().getCpuPinning().equals(getParameters().getVmStaticData().getCpuPinning())); } @Override public Guid getVmId() { if (super.getVmId().equals(Guid.Empty)) { super.setVmId(getParameters().getVmStaticData().getId()); } return super.getVmId(); } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { if (!StringUtils.isBlank(getParameters().getVm().getName())) { return Collections.singletonMap(getParameters().getVm().getName(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_NAME, EngineMessage.ACTION_TYPE_FAILED_VM_IS_BEING_UPDATED)); } return null; } @Override protected Map<String, Pair<String, String>> getSharedLocks() { return Collections.singletonMap( getVmId().toString(), LockMessagesMatchUtil.makeLockingPair( LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_BEING_UPDATED)); } @Override public List<QuotaConsumptionParameter> getQuotaVdsConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<>(); // The cases must be persistent with the create_functions_sp if (!getQuotaManager().isVmStatusQuotaCountable(getVm().getStatus())) { list.add(new QuotaSanityParameter(getParameters().getVmStaticData().getQuotaId(), null)); quotaSanityOnly = true; } else { if (getParameters().getVmStaticData().getQuotaId() == null || getParameters().getVmStaticData().getQuotaId().equals(Guid.Empty) || !getParameters().getVmStaticData().getQuotaId().equals(getVm().getQuotaId())) { list.add(new QuotaVdsGroupConsumptionParameter(getVm().getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.RELEASE, getVdsGroupId(), getVm().getNumOfCpus(), getVm().getMemSizeMb())); list.add(new QuotaVdsGroupConsumptionParameter(getParameters().getVmStaticData().getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, getParameters().getVmStaticData().getVdsGroupId(), getParameters().getVmStaticData().getNumOfCpus(), getParameters().getVmStaticData().getMemSizeMb())); } } return list; } @Override public String getEntityType() { return VdcObjectType.VM.getVdcObjectTranslation(); } @Override public String getEntityOldName() { return oldVm.getName(); } @Override public String getEntityNewName() { return getParameters().getVmStaticData().getName(); } @Override public void setEntityId(AuditLogableBase logable) { logable.setVmId(oldVm.getId()); } @Override public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) { // if only quota sanity is checked the user may use a quota he cannot consume // (it will be consumed only when the vm will run) if (!quotaSanityOnly) { super.addQuotaPermissionSubject(quotaPermissionList); } } protected boolean isVirtioScsiEnabled() { Boolean virtioScsiEnabled = getParameters().isVirtioScsiEnabled(); return virtioScsiEnabled != null ? virtioScsiEnabled : isVirtioScsiEnabledForVm(getVmId()); } public boolean isVirtioScsiEnabledForVm(Guid vmId) { return VmDeviceUtils.hasVirtioScsiController(vmId); } protected boolean isBalloonEnabled() { Boolean balloonEnabled = getParameters().isBalloonEnabled(); return balloonEnabled != null ? balloonEnabled : VmDeviceUtils.hasMemoryBalloon(getVmId()); } protected boolean isSoundDeviceEnabled() { Boolean soundDeviceEnabled = getParameters().isSoundDeviceEnabled(); return soundDeviceEnabled != null ? soundDeviceEnabled : VmDeviceUtils.hasSoundDevice(getVmId()); } protected boolean hasWatchdog() { return getParameters().getWatchdog() != null; } public VmValidator createVmValidator(VM vm) { return new VmValidator(vm); } }
package ch.epfl.lamp.util; import java.io.Writer; /** * This class provides methods to print XHTML document. * * @author Stephane Micheloud * @version 1.1 */ public class XHTMLPrinter extends HTMLPrinter { // // Public Constructors /** * Creates a new instance. * * @param writer * @param title * @param repr */ public XHTMLPrinter(Writer writer, String title, HTMLRepresentation repr) { super(writer, title, repr); } /** * Creates a new instance with "XHTML 1.0 Transitional" as default document type. * * @param writer * @param title * @param encoding */ public XHTMLPrinter(Writer writer, String title, String encoding) { this(writer, title, new HTMLRepresentation("XHTML 1.0 Transitional", encoding)); } /** * Creates a new instance with "utf-8" as default character encoding. * * @param writer * @param title */ public XHTMLPrinter(Writer writer, String title) { this(writer, title, "utf-8"); } // // Public Methods - Printing simple values followed by a new line /** * Prints text <code>text</code> in bold followed by a new line. * * @param text */ public HTMLPrinter printlnBold(String text) { return printlnTag("span", new XMLAttribute[]{ new XMLAttribute("style", "font-weight:bold;") }, text); } /** * Prints an horizontal line separator followed by a new line. */ public HTMLPrinter printlnHLine() { printOTag("div", new XMLAttribute[] { new XMLAttribute("style", "border:1px solid #aaaaaa; " + "margin:10px 0px 5px 0px;height:1px;") }); return printlnCTag("div"); } // // Public Methods - Printing simple values /** * Prints text <code>text</code> in bold. * * @param text */ public HTMLPrinter printBold(String text) { return printTag("span", new XMLAttribute[]{ new XMLAttribute("style", "font-weight:bold;") }, text); } /** * Prints an horizontal line separator */ public HTMLPrinter printHLine() { printOTag("div", new XMLAttribute[] { new XMLAttribute("style", "border:1px solid #aaaaaa; " + "margin:10px 0px 5px 0px;height:1px;") }); return printCTag("div"); } /** * Prints an horizontal line separator with attributes <code>attrs</code>. * * @param attrs */ public HTMLPrinter printHLine(XMLAttribute[] attrs) { return printHLine(); } /** * Prints the &lt;meta/&gt; tag with attributes <code>attrs</code> * followed by a new line. * * @param attrs */ public HTMLPrinter printlnMeta(XMLAttribute[] attrs) { return printlnSTag("meta", attrs); } /** * Prints the &lt;link&gt; tag with attributes <code>attrs</code> * followed by a new line. * * @param attrs */ public HTMLPrinter printlnLink(XMLAttribute[] attrs) { return printlnSTag("link", attrs); } // /** * Prints XHTML preamble. */ protected void printPreamble() { println("<! println("< ?xml version=\"1.0\" encoding=\"" + representation.getEncoding() + "\"?>"); println(" println("<!DOCTYPE html PUBLIC \"-//W3C//DTD " + representation.getType() + "//" + representation.getLanguage() + "\" \"http: println("<html xmlns=\"http: representation.getLanguage() + "\">").line(); } // }
package org.intermine.bio.web.displayer; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.intermine.api.InterMineAPI; import org.intermine.api.query.PathQueryExecutor; import org.intermine.api.results.ExportResultsIterator; import org.intermine.api.results.ResultElement; import org.intermine.metadata.Model; import org.intermine.model.InterMineObject; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.OrderDirection; import org.intermine.pathquery.PathQuery; import org.intermine.web.displayer.ReportDisplayer; import org.intermine.web.logic.config.ReportDisplayerConfig; import org.intermine.web.logic.results.ReportObject; import org.intermine.web.logic.session.SessionMethods; /** * * If we are mouse, fetch results straight off of us, otherwise create a PathQuery from other * organisms. * @author radek * */ public class MouseAllelesDisplayer extends ReportDisplayer { protected static final Logger LOG = Logger.getLogger(MouseAllelesDisplayer.class); /** * Construct with config and the InterMineAPI. * @param config to describe the report displayer * @param im the InterMine API */ public MouseAllelesDisplayer(ReportDisplayerConfig config, InterMineAPI im) { super(config, im); } @SuppressWarnings({ "unchecked", "unused" }) @Override public void display(HttpServletRequest request, ReportObject reportObject) { HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Model model = im.getModel(); PathQueryExecutor executor = im.getPathQueryExecutor(SessionMethods.getProfile(session)); // Counts of HLPT Names PathQuery q = new PathQuery(model); Boolean mouser = false; if (!this.isThisAMouser(reportObject)) { // to give us some homologue identifier and the actual terms to tag-cloudize q.addViews( "Gene.symbol", "Gene.primaryIdentifier", "Gene.id", "Gene.homologues.homologue.alleles.genotypes.phenotypeTerms.name"); // add this rubbish so we do not filter out the same terms q.addViews( "Gene.homologues.homologue.id", "Gene.homologues.homologue.alleles.id", "Gene.homologues.homologue.alleles.genotypes.id"); // mouse homologues only q.addConstraint(Constraints.eq("Gene.homologues.homologue.organism.shortName", "M. musculus"), "A"); // for our gene object q.addConstraint(Constraints.eq("Gene.id", reportObject.getObject().getId().toString()), "B"); // we want only those homologues that have a non-empty alleles collection q.addConstraint(Constraints.isNotNull("Gene.homologues.homologue.alleles.id")); q.setConstraintLogic("A and B"); // order by the homologue db id, just to keep the alleles in a reasonable order q.addOrderBy("Gene.homologues.homologue.id", OrderDirection.ASC); } else { mouser = true; // to give us some homologue identifier and the actual terms to tag-cloudize q.addViews( "Gene.symbol", "Gene.primaryIdentifier", "Gene.id", "Gene.alleles.genotypes.phenotypeTerms.name"); // add this rubbish so we do not filter out the same terms q.addViews( "Gene.alleles.id", "Gene.alleles.genotypes.id"); // for our gene object q.addConstraint(Constraints.eq("Gene.id", reportObject.getObject().getId().toString()), "A"); // we want only those homologues that have a non-empty alleles collection q.addConstraint(Constraints.isNotNull("Gene.alleles.id")); } ExportResultsIterator qResults = executor.execute((PathQuery) q); // traverse so we get a nice map from homologue symbol to a map of allele term names (and // some extras) HashMap<String, HashMap<String, Object>> counts = new HashMap<String, HashMap<String, Object>>(); while (qResults.hasNext()) { List<ResultElement> row = qResults.next(); String sourceGeneSymbol = getIdentifier(row); // a per source gene map HashMap<String, Integer> terms; if (!counts.containsKey(sourceGeneSymbol)) { HashMap<String, Object> wrapper = new HashMap<String, Object>(); wrapper.put("terms", terms = new LinkedHashMap<String, Integer>()); wrapper.put("homologueId", (mouser) ? row.get(2).getField().toString() : row.get(4).getField().toString()); wrapper.put("isMouser", mouser); counts.put(sourceGeneSymbol, wrapper); } else { terms = (HashMap<String, Integer>) counts.get(sourceGeneSymbol).get("terms"); } // populate the allele term with count String alleleTerm = row.get(3).getField().toString(); if (!alleleTerm.isEmpty()) { Object k = (!terms.containsKey(alleleTerm)) ? terms.put(alleleTerm, 1) : terms.put(alleleTerm, terms.get(alleleTerm) + 1); } } // Now give us a map of top 20 per homologue HashMap<String, HashMap<String, Object>> top = new HashMap<String, HashMap<String, Object>>(); for (String symbol : counts.keySet()) { HashMap<String, Object> gene = counts.get(symbol); LinkedHashMap<String, Integer> terms = (LinkedHashMap<String, Integer>) gene.get("terms"); if (terms != null) { // sorted by value TreeMap<String, Integer> sorted = new TreeMap<String, Integer>( new IntegerValueComparator(terms)); // deep copy for (String term : terms.keySet()) { sorted.put(term, (Integer) terms.get(term)); } // "mark" top 20 and order by natural order - the keys HashMap<String, Map<String, Object>> marked = new HashMap<String, Map<String, Object>>(); Integer i = 0; for (String term : sorted.keySet()) { // wrapper map HashMap<String, Object> m = new HashMap<String, Object>(); // am I top dog? Boolean topTerm = false; if (i < 20) { topTerm = true; } m.put("top", topTerm); m.put("count", (Integer) sorted.get(term)); m.put("url", getUrl((String) gene.get("homologueId"), term)); // save it marked.put(term, m); i++; } HashMap<String, Object> wrapper = new HashMap<String, Object>(); wrapper.put("terms", marked); wrapper.put("homologueId", gene.get("homologueId")); wrapper.put("isMouser", gene.get("isMouser")); top.put(symbol, wrapper); } } request.setAttribute("counts", top); } private String getUrl(String geneId, String term) { String url = "<query name=\"\" model=\"genomic\" view=\"Gene.alleles.genotypes.phenotypeTerms.name Gene.alleles.symbol Gene.alleles.primaryIdentifier Gene.alleles.genotypes.name Gene.alleles.name Gene.alleles.type Gene.alleles.genotypes.geneticBackground Gene.alleles.genotypes.zygosity Gene.alleles.organism.name\" longDescription=\"\" constraintLogic=\"B and C and A\">" + "<constraint path=\"Gene.alleles.genotypes.phenotypeTerms.name\" code=\"B\" op=\"=\" value=\"" + term + "\"/>" + "<constraint path=\"Gene.organism.species\" code=\"C\" op=\"=\" value=\"musculus\"/>" + "<constraint path=\"Gene.id\" code=\"A\" op=\"=\" value=\"" + geneId + "\"/>" + "</query>"; return url; } /** * Given columns: [symbol, primaryId, id] in a List<ResultElement> row, give us a nice * identifier back * @param row * @return */ private String getIdentifier(List<ResultElement> row) { String id = null; return (!(id = row.get(0).getField().toString()).isEmpty()) ? id : ((id = row.get(1).getField().toString()).isEmpty()) ? id : row.get(2).getField().toString(); } /** * * @return true if we are on a mouseified gene */ private Boolean isThisAMouser(ReportObject reportObject) { try { return "Mus".equals(((InterMineObject) reportObject.getObject() .getFieldValue("organism")) .getFieldValue("genus")); } catch (IllegalAccessException e) { e.printStackTrace(); } return false; } /** * Compare Maps by their integer values * @author radek * */ class IntegerValueComparator implements Comparator { Map base; /** * A constructor * @param base parameter */ public IntegerValueComparator(Map base) { this.base = base; } /** * A function * @param a parameter * @param b parameter * @return Integer */ public int compare(Object a, Object b) { Integer aV = (Integer) base.get(a); Integer bV = (Integer) base.get(b); if (aV < bV) { return 1; } else { if (aV == bV) { // Same size, need to sort by name return a.toString().compareTo(b.toString()); } } return -1; } } }
package com.github.kubatatami.judonetworking.internals; import com.github.kubatatami.judonetworking.CacheInfo; import com.github.kubatatami.judonetworking.Endpoint; import com.github.kubatatami.judonetworking.annotations.HandleException; import com.github.kubatatami.judonetworking.batches.Batch; import com.github.kubatatami.judonetworking.callbacks.AsyncResultCallback; import com.github.kubatatami.judonetworking.callbacks.CacheInfoCallback; import com.github.kubatatami.judonetworking.callbacks.Callback; import com.github.kubatatami.judonetworking.exceptions.JudoException; import com.github.kubatatami.judonetworking.internals.requests.RequestImpl; import com.github.kubatatami.judonetworking.logs.JudoLogger; import java.lang.reflect.Method; import java.util.List; public class AsyncResultSender implements Runnable { protected Callback<Object> callback; protected RequestProxy requestProxy; protected Object result = null; protected Object[] results = null; protected JudoException e = null; protected int progress = 0; protected final Type type; protected Integer methodId; protected EndpointImpl rpc; protected RequestImpl request; protected List<RequestImpl> requests; protected CacheInfo cacheInfo; enum Type { RESULT, ERROR, PROGRESS, START } public AsyncResultSender(EndpointImpl rpc, RequestProxy requestProxy) { this.requestProxy = requestProxy; this.rpc = rpc; this.type = Type.START; } public AsyncResultSender(EndpointImpl rpc, RequestProxy requestProxy, Object results[]) { this.results = results; this.requestProxy = requestProxy; this.rpc = rpc; this.type = Type.RESULT; } public AsyncResultSender(EndpointImpl rpc, RequestProxy requestProxy, int progress) { this.progress = progress; this.requestProxy = requestProxy; this.rpc = rpc; this.type = Type.PROGRESS; } public AsyncResultSender(EndpointImpl rpc, RequestProxy requestProxy, JudoException e) { this.e = e; this.requestProxy = requestProxy; this.rpc = rpc; this.type = Type.ERROR; } public AsyncResultSender(RequestImpl request, CacheInfo cacheInfo) { this.callback = request.getCallback(); this.request = request; this.rpc = request.getRpc(); this.type = Type.START; this.cacheInfo = cacheInfo; } public AsyncResultSender(RequestImpl request, Object result) { this.result = result; this.callback = request.getCallback(); this.request = request; this.rpc = request.getRpc(); this.methodId = request.getMethodId(); this.type = Type.RESULT; } public AsyncResultSender(RequestImpl request, int progress) { this.progress = progress; this.callback = request.getCallback(); this.request = request; this.rpc = request.getRpc(); this.methodId = request.getMethodId(); this.type = Type.PROGRESS; } public AsyncResultSender(List<RequestImpl> requests, int progress) { this.progress = progress; this.requests = requests; this.type = Type.PROGRESS; } public AsyncResultSender(List<RequestImpl> requests) { this.requests = requests; this.type = Type.START; this.cacheInfo = new CacheInfo(false, 0L); } public AsyncResultSender(RequestImpl request, JudoException e) { this.e = e; this.callback = request.getCallback(); this.request = request; this.rpc = request.getRpc(); this.methodId = request.getMethodId(); this.type = Type.ERROR; } protected Method findHandleMethod(Class<?> callbackClass, Class<?> exceptionClass) { Method handleMethod = null; for (; callbackClass != null; callbackClass = callbackClass.getSuperclass()) { for (Method method : callbackClass.getMethods()) { HandleException handleException = method.getAnnotation(HandleException.class); if (handleException != null && handleException.enabled()) { if (method.getParameterTypes().length != 1) { throw new RuntimeException("Method " + method.getName() + " annotated HandleException must have one parameter."); } Class<?> handleExceptionClass = method.getParameterTypes()[0]; if (handleExceptionClass.isAssignableFrom(exceptionClass)) { if (handleMethod == null || handleMethod.getParameterTypes()[0].isAssignableFrom(handleExceptionClass)) { handleMethod = method; } } } } } return handleMethod; } @Override public void run() { if (callback != null) { if (request.isCancelled()) { return; } sendRequestEvent(); } else if (requestProxy != null && requestProxy.getBatchCallback() != null) { Batch<?> transaction = requestProxy.getBatchCallback(); if (requestProxy.isCancelled()) { return; } sendBatchEvent(transaction); } else if (requests != null) { sendRequestsEvent(); } } private void cleanResources() { removeFromSingleCallMethods(); sendStopRequest(); } private void sendRequestsEvent() { for (RequestImpl batchRequest : requests) { if (batchRequest.getCallback() != null) { if (type == Type.PROGRESS) { batchRequest.getCallback().onProgress(progress); } else if (type == Type.START) { batchRequest.getCallback().onStart(cacheInfo, batchRequest); } } } } private void sendStopRequest() { if (request != null) { JudoLogger.log("Send stop request event(" + request.getName() + ":" + request.getId() + ")", JudoLogger.LogLevel.VERBOSE); rpc.getHandler().post(new Runnable() { @Override public void run() { rpc.stopRequest(request); } }); } } private void removeFromSingleCallMethods() { if (methodId != null) { synchronized (rpc.getSingleCallMethods()) { boolean result = rpc.getSingleCallMethods().remove(methodId) != null; if (result && (rpc.getDebugFlags() & Endpoint.REQUEST_LINE_DEBUG) > 0) { JudoLogger.log("Request " + request.getName() + "(" + methodId + ")" + " removed from SingleCall queue.", JudoLogger.LogLevel.VERBOSE); } } } } private void sendBatchEvent(Batch<?> transaction) { JudoLogger.log("Send batch event:" + type, JudoLogger.LogLevel.VERBOSE); switch (type) { case START: requestProxy.start(); if (callback instanceof AsyncResultCallback) { ((AsyncResultCallback) callback).setAsyncResult(request); } transaction.onStart(requestProxy); break; case RESULT: transaction.onSuccess(results); doneBatch(transaction); break; case ERROR: Method handleMethod = findHandleMethod(transaction.getClass(), e.getClass()); logError("Batch", e); if (handleMethod != null) { try { handleMethod.invoke(transaction, e); } catch (Exception invokeException) { throw new RuntimeException(invokeException); } } else { transaction.onError(e); } doneBatch(transaction); break; case PROGRESS: transaction.onProgress(progress); break; } } private void doneBatch(Batch<?> transaction) { transaction.onFinish(); requestProxy.done(); requestProxy.clearBatchCallback(); cleanResources(); } private void sendRequestEvent() { JudoLogger.log("Send request event(" + request.getName() + ":" + request.getId() + "):" + type, JudoLogger.LogLevel.VERBOSE); switch (type) { case START: request.start(); if (callback instanceof AsyncResultCallback) { ((AsyncResultCallback) callback).setAsyncResult(request); } if (callback instanceof CacheInfoCallback) { ((CacheInfoCallback) callback).setCacheInfo(cacheInfo); } callback.onStart(cacheInfo, request); break; case RESULT: callback.onSuccess(result); doneRequest(); break; case ERROR: Method handleMethod = findHandleMethod(callback.getClass(), e.getClass()); logError(request.getName(), e); if (handleMethod != null) { try { handleMethod.invoke(callback, e); } catch (Exception invokeException) { throw new RuntimeException(invokeException); } } else { callback.onError(e); } doneRequest(); break; case PROGRESS: callback.onProgress(progress); break; } } private void doneRequest() { callback.onFinish(); request.done(); cleanResources(); } protected void logError(String requestName, Exception ex) { if ((rpc.getDebugFlags() & Endpoint.ERROR_DEBUG) > 0) { if (requestName != null) { JudoLogger.log("Error on: " + requestName, JudoLogger.LogLevel.ERROR); } JudoLogger.log(ex); } } }
package org.intermine.bio.web.widget; import java.util.ArrayList; import java.util.List; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; import org.intermine.web.logic.bag.InterMineBag; import org.intermine.web.logic.query.Constraint; import org.intermine.web.logic.query.MainHelper; import org.intermine.web.logic.query.PathNode; import org.intermine.web.logic.query.PathQuery; import org.intermine.web.logic.widget.GraphCategoryURLGenerator; import org.jfree.data.category.CategoryDataset; /** * * @author Julie Sullivan */ public class ChromosomeDistributionGraphURLGenerator implements GraphCategoryURLGenerator { String bagName; /** * Creates a ChromosomeDistributionGraphURLGenerator for the chart * @param model * @param bag the bag */ public ChromosomeDistributionGraphURLGenerator(String bagName) { super(); this.bagName = bagName; } /** * {@inheritDoc} * @see org.jfree.chart.urls.CategoryURLGenerator#generateURL( * org.jfree.data.category.CategoryDataset, * int, int) */ public String generateURL(CategoryDataset dataset, @SuppressWarnings("unused") int series, int category) { StringBuffer sb = new StringBuffer("queryForGraphAction.do?bagName=" + bagName); sb.append("&category=" + dataset.getColumnKey(category)); sb.append("&series="); sb.append("&urlGen=org.intermine.bio.web.widget.ChromosomeDistributionGraphURLGenerator"); return sb.toString(); } public PathQuery generatePathQuery(ObjectStore os, InterMineBag imBag, @SuppressWarnings("unused") String series, String category) { Model model = os.getModel(); InterMineBag bag = imBag; PathQuery q = new PathQuery(model); List view = new ArrayList(); view.add(MainHelper.makePath(model, q, "Gene.identifier")); view.add(MainHelper.makePath(model, q, "Gene.organismDbId")); view.add(MainHelper.makePath(model, q, "Gene.name")); view.add(MainHelper.makePath(model, q, "Gene.organism.name")); view.add(MainHelper.makePath(model, q, "Gene.chromosome.identifier")); view.add(MainHelper.makePath(model, q, "Gene.chromosomeLocation.start")); view.add(MainHelper.makePath(model, q, "Gene.chromosomeLocation.end")); q.setView(view); String bagType = bag.getType(); ConstraintOp constraintOp = ConstraintOp.IN; String constraintValue = bag.getName(); String label = null, id = null, code = q.getUnusedConstraintCode(); Constraint c = new Constraint(constraintOp, constraintValue, false, label, code, id, null); q.addNode(bagType).getConstraints().add(c); // constrain to be specific chromosome constraintOp = ConstraintOp.EQUALS; code = q.getUnusedConstraintCode(); PathNode chromosomeNode = q.addNode("Gene.chromosome.identifier"); Constraint chromosomeConstraint = new Constraint(constraintOp, series, false, label, code, id, null); chromosomeNode.getConstraints().add(chromosomeConstraint); q.setConstraintLogic("A and B"); q.syncLogicExpression("and"); return q; } }
package org.biojava.bio.structure.align.ce; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.biojava.bio.structure.Atom; import org.biojava.bio.structure.StructureException; import org.biojava.bio.structure.StructureTools; import org.biojava.bio.structure.align.StructureAlignmentFactory; import org.biojava.bio.structure.align.ce.CeMain; import org.biojava.bio.structure.align.model.AFPChain; import org.biojava.bio.structure.align.util.AFPChainScorer; import org.biojava.bio.structure.align.util.AtomCache; import org.biojava.bio.structure.jama.Matrix; /** * A wrapper for {@link CeMain} which sets default parameters to be appropriate for finding * circular permutations. * <p> * A circular permutation consists of a single cleavage point and rearrangement * between two structures, for example: * <pre> * ABCDEFG * DEFGABC * </pre> * @author Spencer Bliven. * */ public class OptimalCECPMain extends CeMain { private static boolean debug = true; public static final String algorithmName = "jCE Optimal Circular Permutation"; public static final String version = "1.0"; protected OptimalCECPParameters params; public OptimalCECPMain() { super(); params = new OptimalCECPParameters(); } @Override public String getAlgorithmName() { return OptimalCECPMain.algorithmName; } @Override public String getVersion() { return OptimalCECPMain.version; } /** * @return an {@link OptimalCECPParameters} object */ @Override public ConfigStrucAligParams getParameters() { return params; } /** * @param params Should be an {@link OptimalCECPParameters} object specifying alignment options */ @Override public void setParameters(ConfigStrucAligParams params){ if (! (params instanceof OptimalCECPParameters )){ throw new IllegalArgumentException("provided parameter object is not of type CeParameter"); } this.params = (OptimalCECPParameters) params; } /** * Circularly permutes arr in place. * * <p>Similar to {@link Collections#rotate(List, int)} but with reversed * direction. Perhaps it would be more efficient to use the Collections version? * @param <T> * @param arr The array to be permuted * @param cp The number of residues to shift leftward, or equivalently, the index of * the first element after the permutation point. */ private static <T> void permuteArray(T[] arr, int cp) { // Allow negative cp points for convenience. if(cp == 0) { return; } if(cp < 0) { cp = arr.length+cp; } if(cp < 0 || cp >= arr.length) { throw new ArrayIndexOutOfBoundsException( "Permutation point ("+cp+") must be between -ca2.length and ca2.length-1" ); } List<T> temp = new ArrayList<T>(cp); // shift residues left for(int i=0;i<cp;i++) { temp.add(arr[i]); } for(int j=cp;j<arr.length;j++) { arr[j-cp]=arr[j]; } for(int i=0;i<cp;i++) { arr[arr.length-cp+i] = temp.get(i); } } /** * Circularly permutes arr in place. * * <p>Similar to {@link Collections#rotate(List, int)} but with reversed * direction. Perhaps it would be more efficient to use the Collections version? * @param <T> * @param arr The array to be permuted * @param cp The number of residues to shift leftward, or equivalently, the index of * the first element after the permutation point. * private static void permuteArray(int[] arr, int cp) { // Allow negative cp points for convenience. if(cp == 0) { return; } if(cp < 0) { cp = arr.length+cp; } if(cp < 0 || cp >= arr.length) { throw new ArrayIndexOutOfBoundsException( "Permutation point ("+cp+") must be between -ca2.length and ca2.length-1" ); } List<Integer> temp = new ArrayList<Integer>(cp); // shift residues left for(int i=0;i<cp;i++) { temp.add(arr[i]); } for(int j=cp;j<arr.length;j++) { arr[j-cp]=arr[j]; } for(int i=0;i<cp;i++) { arr[arr.length-cp+i] = temp.get(i); } } */ /** * Aligns ca1 with ca2 permuted by <i>cp</i> residues. * <p><strong>WARNING:</strong> Modifies ca2 during the permutation. Be sure * to make a copy before calling this method. * * @param ca1 * @param ca2 * @param param * @param cp * @return * @throws StructureException */ public AFPChain alignPermuted(Atom[] ca1, Atom[] ca2, Object param, int cp) throws StructureException { // initial permutation permuteArray(ca2,cp); // perform alignment AFPChain afpChain = super.align(ca1, ca2, param); // un-permute alignment permuteAFPChain(afpChain, -cp); if(afpChain.getName2() != null) { afpChain.setName2(afpChain.getName2()+" CP="+cp); } // Specify the permuted return afpChain; } /** * Permute the second protein of afpChain by the specified number of residues. * @param afpChain Input alignment * @param cp Amount leftwards (or rightward, if negative) to shift the * @return A new alignment equivalent to afpChain after the permutations */ private static void permuteAFPChain(AFPChain afpChain, int cp) { int ca2len = afpChain.getCa2Length(); //fix up cp to be positive if(cp == 0) { return; } if(cp < 0) { cp = ca2len+cp; } if(cp < 0 || cp >= ca2len) { throw new ArrayIndexOutOfBoundsException( "Permutation point ("+cp+") must be between -ca2.length and ca2.length-1" ); } // Fix up optAln permuteOptAln(afpChain,cp); if(afpChain.getBlockNum() > 1) afpChain.setSequentialAlignment(false); // fix up matrices // ca1 corresponds to row indices, while ca2 corresponds to column indices. afpChain.setDistanceMatrix(permuteMatrix(afpChain.getDistanceMatrix(),0,-cp)); // this is square, so permute both afpChain.setDisTable2(permuteMatrix(afpChain.getDisTable2(),-cp,-cp)); //TODO fix up other AFP parameters? } /** * Permutes <i>mat</i> by moving the rows of the matrix upwards by <i>cp</i> * rows. * @param mat The original matrix * @param cpRows Number of rows upward to move entries * @param cpCols Number of columns leftward to move entries * @return The permuted matrix */ private static Matrix permuteMatrix(Matrix mat, int cpRows, int cpCols) { //fix up cp to be positive if(cpRows == 0 && cpCols == 0) { return mat.copy(); } if(cpRows < 0) { cpRows = mat.getRowDimension()+cpRows; } if(cpRows < 0 || cpRows >= mat.getRowDimension()) { throw new ArrayIndexOutOfBoundsException( String.format( "Can't permute rows by %d: only %d rows.", cpRows, mat.getRowDimension() ) ); } if(cpCols < 0) { cpCols = mat.getColumnDimension()+cpCols; } if(cpCols < 0 || cpCols >= mat.getColumnDimension()) { throw new ArrayIndexOutOfBoundsException( String.format( "Can't permute cols by %d: only %d rows.", cpCols, mat.getColumnDimension() ) ); } int[] rows = new int[mat.getRowDimension()]; for(int i=0;i<rows.length;i++) { rows[i] = (i+cpRows)%rows.length; } int[] cols = new int[mat.getColumnDimension()]; for(int i=0;i<cols.length;i++) { cols[i] = (i+cpCols)%cols.length; } Matrix newMat = mat.getMatrix(rows, cols); assert(newMat.getRowDimension() == mat.getRowDimension()); assert(newMat.getColumnDimension() == mat.getColumnDimension()); assert(newMat.get(0, 0) == mat.get(cpRows%mat.getRowDimension(), cpCols%mat.getColumnDimension())); return newMat; } /** * Modifies the {@link AFPChain#setOptAln(int[][][]) optAln} of an AFPChain * by permuting the second protein. * * Sets residue numbers in the second protein to <i>(i-cp)%len</i> * * @param afpChain * @param cp Amount leftwards (or rightward, if negative) to shift the */ private static void permuteOptAln(AFPChain afpChain, int cp) { int ca2len = afpChain.getCa2Length(); if( ca2len <= 0) { throw new IllegalArgumentException("No Ca2Length specified in "+afpChain); } // Allow negative cp points for convenience. if(cp == 0) { return; } if(cp <= -ca2len || cp >= ca2len) { // could just take cp%ca2len, but probably its a bug if abs(cp)>=ca2len throw new ArrayIndexOutOfBoundsException( String.format( "Permutation point %d must be between %d and %d for %s", cp, 1-ca2len,ca2len-1, afpChain.getName2() ) ); } if(cp < 0) { cp = cp + ca2len; } // the unprocessed alignment int[][][] optAln = afpChain.getOptAln(); int[] optLen = afpChain.getOptLen(); // the processed alignment List<List<List<Integer>>> blocks = new ArrayList<List<List<Integer>>>(afpChain.getBlockNum()*2); //Update residue indices // newi = (oldi-cp) % N for(int block = 0; block < afpChain.getBlockNum(); block++) { if(optLen[block]<1) continue; // set up storage for the current block List<List<Integer>> currBlock = new ArrayList<List<Integer>>(2); currBlock.add( new ArrayList<Integer>()); currBlock.add( new ArrayList<Integer>()); blocks.add(currBlock); // pos = 0 case currBlock.get(0).add( optAln[block][0][0] ); currBlock.get(1).add( (optAln[block][1][0]+cp ) % ca2len); for(int pos = 1; pos < optLen[block]; pos++) { //check if we need to start a new block //this happens when the new alignment crosses the protein terminus if( optAln[block][1][pos-1]+cp<ca2len && optAln[block][1][pos]+cp >= ca2len) { currBlock = new ArrayList<List<Integer>>(2); currBlock.add( new ArrayList<Integer>()); currBlock.add( new ArrayList<Integer>()); blocks.add(currBlock); } currBlock.get(0).add( optAln[block][0][pos] ); currBlock.get(1).add( (optAln[block][1][pos]+cp ) % ca2len); } } // save permuted blocks to afpChain assignOptAln(afpChain,blocks); } /** * Sometimes it's convenient to store an alignment using java collections, * where <tt>blocks.get(blockNum).get(0).get(pos)</tt> specifies the aligned * residue at position <i>pos</i> of block <i>blockNum</i> of the first * protein. * * This method takes such a collection and stores it into the afpChain's * {@link AFPChain#setOptAln(int[][][]) optAln}, setting the associated * length variables as well. * * @param afpChain * @param blocks */ private static void assignOptAln(AFPChain afpChain, List<List<List<Integer>>> blocks) { int[][][] optAln = new int[blocks.size()][][]; int[] optLen = new int[blocks.size()]; int optLength = 0; int numBlocks = blocks.size(); for(int block = 0; block < numBlocks; block++) { // block should be 2xN rectangular assert(blocks.get(block).size() == 2); assert( blocks.get(block).get(0).size() == blocks.get(block).get(1).size()); optLen[block] = blocks.get(block).get(0).size(); optLength+=optLen[block]; optAln[block] = new int[][] { new int[optLen[block]], new int[optLen[block]] }; for(int pos = 0; pos < optLen[block]; pos++) { optAln[block][0][pos] = blocks.get(block).get(0).get(pos); optAln[block][1][pos] = blocks.get(block).get(1).get(pos); } } afpChain.setBlockNum(numBlocks); afpChain.setOptAln(optAln); afpChain.setOptLen(optLen); afpChain.setOptLength(optLength); // TODO I don't know what these do. Should they be set? //afpChain.setBlockSize(blockSize); //afpChain.setBlockResList(blockResList); //afpChain.setChainLen(chainLen); } /** * Finds the optimal alignment between two proteins allowing for a circular * permutation (CP). * * The precise algorithm is controlled by the * {@link OptimalCECPParameters parameters}. If the parameter * {@link OptimalCECPParameters#isTryAllCPs() tryAllCPs} is true, all possible * CP sites are tried and the optimal site is returned. Otherwise, the * {@link OptimalCECPParameters#getCPPoint() cpPoint} parameter is used to * determine the CP point, greatly reducing the computation required. * * @param ca1 CA atoms of the first protein * @param ca2 CA atoms of the second protein * @param param {@link CeParameters} object * @return The best-scoring alignment * @throws StructureException * * @see #alignOptimal(Atom[], Atom[], Object, AFPChain[]) */ @Override public AFPChain align(Atom[] ca1, Atom[] ca2, Object param) throws StructureException { if(params.isTryAllCPs()) { return alignOptimal(ca1,ca2,param,null); } else { int cpPoint = params.getCPPoint(); return alignPermuted(ca1, ca2, param, cpPoint); } } /** * Finds the optimal alignment between two proteins allowing for a circular * permutation (CP). * * This algorithm performs a CE alignment for each possible CP site. This is * quite slow. Use {@link #alignHeuristic(Atom[], Atom[], Object)} for a * faster algorithm. * * @param ca1 CA atoms of the first protein * @param ca2 CA atoms of the second protein * @param param {@link CeParameters} object * @param alignments If not null, should be an empty array of the same length as * ca2. This will be filled with the alignments from permuting ca2 by * 0 to n-1 residues. * @return The best-scoring alignment * @throws StructureException */ public AFPChain alignOptimal(Atom[] ca1, Atom[] ca2, Object param, AFPChain[] alignments) throws StructureException { long startTime = System.currentTimeMillis(); if(alignments.length != ca2.length) { throw new IllegalArgumentException("scores param should have same length as ca2"); } AFPChain unaligned = super.align(ca1, ca2, param); AFPChain bestAlignment = unaligned; if(debug) { // print progress bar header System.out.print("|"); for(int cp=1;cp<ca2.length-1;cp++) { System.out.print("="); } System.out.println("|"); System.out.print("."); } if(alignments != null) { alignments[0] = unaligned; } for(int cp=1;cp<ca2.length;cp++) { // clone ca2 to prevent side effects from propegating Atom[] ca2p = StructureTools.cloneCAArray(ca2); //permute one each time. Alters ca2p as a side effect AFPChain currentAlignment = alignPermuted(ca1,ca2p,param,cp); // increment progress bar if(debug) System.out.print("."); // fix up names, since cloning ca2 wipes it try { currentAlignment.setName2(ca2[0].getGroup().getChain().getParent().getName()+" CP="+cp); } catch( Exception e) { //null pointers, empty arrays, etc. } double currentScore = currentAlignment.getAlignScore(); if(alignments != null) { alignments[cp] = currentAlignment; } if(currentScore>bestAlignment.getAlignScore()) { bestAlignment = currentAlignment; } } if(debug) { long elapsedTime = System.currentTimeMillis()-startTime; System.out.println(); System.out.format("%d alignments took %.4f s (%.1f ms avg)\n", ca2.length, elapsedTime/1000., (double)elapsedTime/ca2.length); } return bestAlignment; } public static void main(String[] args){ try { String name1, name2; int[] cps= new int[] {}; //Concanavalin name1 = "2pel.A"; name2 = "3cna"; cps = new int[] {122,0,3}; //small case //name1 = "d1qdmA1"; //name1 = "1QDM.A"; //name2 = "d1nklA_"; /*cps = new int[] { //41, // CECP optimum 19,59, // unpermuted local minima in TM-score //39, // TM-score optimum 0, };*/ //1itb selfsymmetry //name1 = "1ITB.A"; //name2 = "1ITB.A"; //cps = new int[] {92}; OptimalCECPMain ce = (OptimalCECPMain) StructureAlignmentFactory.getAlgorithm(OptimalCECPMain.algorithmName); CeParameters params = (CeParameters) ce.getParameters(); ce.setParameters(params); AtomCache cache = new AtomCache(); Atom[] ca1 = cache.getAtoms(name1); Atom[] ca2 = cache.getAtoms(name2); AFPChain afpChain; // find optimal solution AFPChain[] alignments = new AFPChain[ca2.length]; afpChain = ce.alignOptimal(ca1, ca2, params, alignments); System.out.format("Optimal Score: %.2f\n", afpChain.getAlignScore()); System.out.println("Pos\tScore\tTMScore\tLen\tRMSD\tBlocks"); for(int i = 0; i< alignments.length; i++) { double tm = AFPChainScorer.getTMScore(alignments[i], ca1, ca2); System.out.format("%d\t%.2f\t%.2f\t%d\t%.2f\t%d\n", i, alignments[i].getAlignScore(), tm, alignments[i].getOptLength(), alignments[i].getTotalRmsdOpt(), alignments[i].getBlockNum() ); } //displayAlignment(afpChain,ca1,ca2); // permuted alignment for(int cp : cps) { // new copy of ca2, since alignPermuted has side effects //Atom[] ca2clone = cache.getAtoms(name2); //afpChain = ce.alignPermuted(ca1, ca2clone, params, cp); //displayAlignment(afpChain, ca1, ca2); displayAlignment(alignments[cp],ca1,ca2); } // CECP alignment CeCPMain cecp = new CeCPMain(); afpChain = cecp.align(ca1, ca2); displayAlignment(afpChain,ca1,ca2); } catch (Exception e) { e.printStackTrace(); } } private static void displayAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, StructureException { Atom[] ca1clone = StructureTools.cloneCAArray(ca1); Atom[] ca2clone = StructureTools.cloneCAArray(ca2); if (! GuiWrapper.isGuiModuleInstalled()) { System.err.println("The biojava-structure-gui and/or JmolApplet modules are not installed. Please install!"); // display alignment in console System.out.println(afpChain.toCE(ca1clone, ca2clone)); } else { Object jmol = GuiWrapper.display(afpChain,ca1clone,ca2clone); GuiWrapper.showAlignmentImage(afpChain, ca1clone,ca2clone,jmol); } } }
package io.moquette.broker.security; import org.apache.commons.codec.binary.Hex; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class DBAuthenticatorTest { private static final Logger LOG = LoggerFactory.getLogger(DBAuthenticatorTest.class); public static final String ORG_H2_DRIVER = "org.h2.Driver"; public static final String JDBC_H2_MEM_TEST = "jdbc:h2:mem:test"; public static final String SHA_256 = "SHA-256"; private Connection connection; @BeforeEach public void setup() throws ClassNotFoundException, SQLException, NoSuchAlgorithmException { Class.forName(ORG_H2_DRIVER); this.connection = DriverManager.getConnection(JDBC_H2_MEM_TEST); Statement statement = this.connection.createStatement(); try { statement.execute("DROP TABLE IF EXISTS ACCOUNT"); } catch (SQLException sqle) { LOG.info("Table not found, not dropping", sqle); } MessageDigest digest = MessageDigest.getInstance(SHA_256); String hash = new String(Hex.encodeHex(digest.digest("password".getBytes(StandardCharsets.UTF_8)))); try { if (statement.execute("CREATE TABLE ACCOUNT ( LOGIN VARCHAR(64), PASSWORD VARCHAR(256))")) { throw new SQLException("can't create USER table"); } if (statement.execute("INSERT INTO ACCOUNT ( LOGIN , PASSWORD ) VALUES ('dbuser', '" + hash + "')")) { throw new SQLException("can't insert in USER table"); } } catch (SQLException sqle) { LOG.error("Table not created, not inserted", sqle); return; } LOG.info("Table User created"); statement.close(); } @Test public void Db_verifyValid() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertTrue(dbAuthenticator.checkValid(null, "dbuser", "password".getBytes(UTF_8))); } @Test public void Db_verifyInvalidLogin() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes(UTF_8))); } @Test public void Db_verifyInvalidPassword() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser", "wrongPassword".getBytes(UTF_8))); } @AfterEach public void teardown() { try { this.connection.close(); } catch (SQLException e) { LOG.error("can't close connection", e); } } }
package com.malhartech.bufferserver.packet; import com.malhartech.bufferserver.util.Codec; import java.util.Arrays; import java.util.Collection; /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public class SubscribeRequestTuple extends RequestTuple { public static final String EMPTY_STRING = new String(); private String version; private String identifier; private int baseSeconds; private int windowId; private String type; private String upstreamIdentifier; private int mask; private int[] partitions; @Override public void parse() { parsed = true; int dataOffset = offset + 1; int limit = offset + length; /* * read the version. */ int idlen = readVarInt(dataOffset, limit); if (idlen > 0) { while (buffer[dataOffset++] < 0) { } version = new String(buffer, dataOffset, idlen); dataOffset += idlen; } else if (idlen == 0) { version = EMPTY_STRING; dataOffset++; } else { return; } /* * read the identifier. */ idlen = readVarInt(dataOffset, limit); if (idlen > 0) { while (buffer[dataOffset++] < 0) { } identifier = new String(buffer, dataOffset, idlen); dataOffset += idlen; } else if (idlen == 0) { identifier = EMPTY_STRING; dataOffset++; } else { return; } baseSeconds = readVarInt(dataOffset, limit); if (getBaseSeconds() != Integer.MIN_VALUE) { while (buffer[dataOffset++] < 0) { } } else { return; } windowId = readVarInt(dataOffset, limit); if (windowId >= 0) { while (buffer[dataOffset++] < 0) { } } else { return; } /* * read the type */ idlen = readVarInt(dataOffset, limit); if (idlen > 0) { while (buffer[dataOffset++] < 0) { } type = new String(buffer, dataOffset, idlen); dataOffset += idlen; } else if (idlen == 0) { type = EMPTY_STRING; dataOffset++; } else { return; } /* * read the upstream identifier */ idlen = readVarInt(dataOffset, limit); if (idlen > 0) { while (buffer[dataOffset++] < 0) { } upstreamIdentifier = new String(buffer, dataOffset, idlen); dataOffset += idlen; } else if (idlen == 0) { upstreamIdentifier = EMPTY_STRING; dataOffset++; } else { return; } /* * read the partition count */ int count = readVarInt(dataOffset, limit); if (count > 0) { while (buffer[dataOffset++] < 0) { } mask = readVarInt(dataOffset, limit); if (getMask() > 0) { while (buffer[dataOffset++] < 0) { } } else { /* mask cannot be zero */ return; } partitions = new int[count]; for (int i = 0; i < count; i++) { partitions[i] = readVarInt(dataOffset, limit); if (getPartitions()[i] == -1) { return; } else { while (buffer[dataOffset++] < 0) { } } } } valid = true; } public boolean isParsed() { return parsed; } public String getUpstreamType() { return type; } public SubscribeRequestTuple(byte[] array, int offset, int length) { super(array, offset, length); } @Override public int getWindowId() { return windowId; } @Override public int getBaseSeconds() { return baseSeconds; } /** * @return the version */ @Override public String getVersion() { return version; } /** * @return the identifier */ @Override public String getIdentifier() { return identifier; } /** * @return the upstreamIdentifier */ public String getUpstreamIdentifier() { return upstreamIdentifier; } /** * @return the mask */ public int getMask() { return mask; } /** * @return the partitions */ @SuppressWarnings(value = "ReturnOfCollectionOrArrayField") public int[] getPartitions() { return partitions; } public static byte[] getSerializedRequest( String id, String down_type, String upstream_id, int mask, Collection<Integer> partitions, long startingWindowId) { byte[] array = new byte[4096]; int offset = 0; /* write the type */ array[offset++] = MessageType.SUBSCRIBER_REQUEST_VALUE; /* write the version */ offset = Tuple.writeString(VERSION, array, offset); /* write the identifier */ offset = Tuple.writeString(id, array, offset); /* write the baseSeconds */ int baseSeconds = (int)(startingWindowId >> 32); offset = Codec.writeRawVarint32(baseSeconds, array, offset); /* write the windowId */ int windowId = (int)startingWindowId; offset = Codec.writeRawVarint32(windowId, array, offset); /* write the type */ offset = Tuple.writeString(down_type, array, offset); /* write upstream identifier */ offset = Tuple.writeString(upstream_id, array, offset); /* write the partitions */ if (partitions == null || partitions.isEmpty()) { offset = Codec.writeRawVarint32(0, array, offset); } else { offset = Codec.writeRawVarint32(partitions.size(), array, offset); offset = Codec.writeRawVarint32(mask, array, offset); for (int i : partitions) { offset = Codec.writeRawVarint32(i, array, offset); } } return Arrays.copyOfRange(array, 0, offset); } @Override public String toString() { return "SubscribeRequestTuple{" + "version=" + version + ", identifier=" + identifier + ", baseSeconds=" + baseSeconds + ", windowId=" + windowId + ", type=" + type + ", upstreamIdentifier=" + upstreamIdentifier + ", mask=" + mask + ", partitions=" + (partitions == null? "null": Arrays.toString(partitions)) + '}'; } }
package org.carlspring.strongbox.cron.domain; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.util.Assert; /** * @author Yougeshwar * @author Pablo Tirado */ public class CronTaskConfigurationDto implements Serializable { private String uuid; private String name; private Map<String, String> properties = new HashMap<>(); private boolean oneTimeExecution = false; private boolean immediateExecution = false; public CronTaskConfigurationDto() { } @JsonCreator public CronTaskConfigurationDto(@JsonProperty(value = "uuid", required = true) String uuid, @JsonProperty(value = "name", required = true) String name) { this.uuid = uuid; this.name = name; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public String getRequiredProperty(String key) { String value = getProperty(key); Assert.notNull(value, "No property of key '" + key + "' found"); return value; } public String getProperty(String key) { return this.properties.get(key); } public void addProperty(String key, String value) { properties.put(key, value); } public boolean contains(String key) { return properties.containsKey(key); } public boolean isOneTimeExecution() { return oneTimeExecution; } public void setOneTimeExecution(boolean oneTimeExecution) { this.oneTimeExecution = oneTimeExecution; } @JsonGetter("immediateExecution") public boolean shouldExecuteImmediately() { return immediateExecution; } public void setImmediateExecution(boolean immediateExecution) { this.immediateExecution = immediateExecution; } @Override public String toString() { final StringBuilder sb = new StringBuilder("CronTaskConfiguration{"); sb.append("uuid='").append(uuid).append('\''); sb.append("name='").append(name).append('\''); sb.append(", properties=").append(properties); sb.append(", oneTimeExecution=").append(oneTimeExecution); sb.append(", immediateExecution=").append(immediateExecution); sb.append('}'); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof CronTaskConfigurationDto)) { return false; } final CronTaskConfigurationDto that = (CronTaskConfigurationDto) o; return getUuid() != null ? getUuid().equals(that.getUuid()) : that.getUuid() == null; } @Override public int hashCode() { return getUuid() != null ? getUuid().hashCode() : 0; } }
package com.specmate.connectors.config; import java.util.Hashtable; import java.util.Map.Entry; import java.util.Set; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.log.LogService; import com.specmate.common.OSGiUtil; import com.specmate.common.SpecmateException; import com.specmate.common.SpecmateValidationException; import com.specmate.config.api.IConfigService; import com.specmate.connectors.api.Configurable; import com.specmate.connectors.api.IProjectConfigService; import com.specmate.model.base.BaseFactory; import com.specmate.model.base.Folder; import com.specmate.model.support.util.SpecmateEcoreUtil; import com.specmate.persistency.IChange; import com.specmate.persistency.IPersistencyService; import com.specmate.persistency.ITransaction; /** * Service that configures connectors, exporters and top-level library folders * based on configured projects */ @Component(immediate = true) public class ProjectConfigService implements IProjectConfigService { /** The config service */ private IConfigService configService; /** The config admin service. */ private ConfigurationAdmin configAdmin; /** The log service. */ private LogService logService; /** The persistency service to access the model data */ private IPersistencyService persistencyService; @Activate public void activate() throws SpecmateException, SpecmateValidationException { String[] projectsNames = configService.getConfigurationPropertyArray(KEY_PROJECT_NAMES); if (projectsNames == null) { return; } configureProjects(projectsNames); } @Override public void configureProjects(String[] projectsNames) throws SpecmateException, SpecmateValidationException { for (int i = 0; i < projectsNames.length; i++) { String projectName = projectsNames[i]; try { String projectPrefix = PROJECT_PREFIX + projectsNames[i]; Configurable connector = createConnector(projectPrefix); if (connector != null) { configureConfigurable(connector); } Configurable exporter = createExporter(projectPrefix); if (exporter != null) { configureConfigurable(exporter); } ensureProjectFolder(projectName); configureProject(projectName, connector, exporter); bootstrapProjectLibrary(projectName); } catch (SpecmateException | SpecmateValidationException e) { this.logService.log(LogService.LOG_ERROR, "Could not create project " + projectName, e); } } } private void ensureProjectFolder(String projectName) throws SpecmateException, SpecmateValidationException { ITransaction trans = null; try { trans = this.persistencyService.openTransaction(); EList<EObject> projects = trans.getResource().getContents(); EObject obj = SpecmateEcoreUtil.getEObjectWithId(projectName, projects); if (obj == null || !(obj instanceof Folder)) { trans.doAndCommit(() -> { Folder folder = BaseFactory.eINSTANCE.createFolder(); folder.setName(projectName); folder.setId(projectName); projects.add(folder); return null; }); } } finally { if (trans != null) { trans.close(); } } } /** * Configures a single project with a given connector and exporter * description */ private void configureProject(String projectName, Configurable connector, Configurable exporter) throws SpecmateException { String exporterFilter; if (exporter != null) { exporterFilter = "(" + KEY_EXPORTER_ID + "=" + exporter.getConfig().get(KEY_EXPORTER_ID) + ")"; } else { exporterFilter = "(" + KEY_EXPORTER_ID + "= NO_ID)"; } String connectorFilter = "(" + KEY_CONNECTOR_ID + "=" + connector.getConfig().get(KEY_CONNECTOR_ID) + ")"; Hashtable<String, Object> projectConfig = new Hashtable<String, Object>(); projectConfig.put(KEY_PROJECT_NAME, projectName); // Set the target of the 'exporter' reference in the Project. // This ensures that the right exporter will be bound to the project. projectConfig.put("exporter.target", exporterFilter); // Set the target of the 'connector' reference in the Project. // This ensures that the right connector will be bound to the project. projectConfig.put("connector.target", connectorFilter); projectConfig.put(KEY_PROJECT_NAME, projectName); OSGiUtil.configureFactory(configAdmin, PROJECT_PID, projectConfig); } /** * Creates an exporter from the config for the project given by the config * prefix. */ private Configurable createExporter(String projectPrefix) { String exporterPrefix = projectPrefix + "." + "exporter"; Configurable exporter = new Configurable(); return fillConfigurable(exporter, exporterPrefix); } /** * Creates an connector from the config for the project given by the config * prefix. */ private Configurable createConnector(String projectPrefix) { String connectorPrefix = projectPrefix + "." + "connector"; Configurable connector = new Configurable(); return fillConfigurable(connector, connectorPrefix); } /** Configures a configurable with the ConfigAdmin */ private void configureConfigurable(Configurable configurable) { try { OSGiUtil.configureFactory(configAdmin, configurable.getPid(), configurable.getConfig()); } catch (Exception e) { this.logService.log(LogService.LOG_ERROR, "Failed attempt to configure " + configurable.getPid() + " with config " + OSGiUtil.configDictionaryToString(configurable.getConfig()), e); } } /** Fills the config entries into the configurable object. */ private <T extends Configurable> T fillConfigurable(T configurable, String prefix) { Set<Entry<Object, Object>> config = configService.getConfigurationProperties(prefix); if (config == null || config.isEmpty()) { return null; } Hashtable<String, Object> configTable = new Hashtable<>(); for (Entry<Object, Object> configEntry : config) { String key = (String) configEntry.getKey(); String connectorConfigKey = key.substring(prefix.length() + 1); String pidKey = "pid"; if (connectorConfigKey.equals(pidKey)) { configurable.setPid((String) configEntry.getValue()); } else { configTable.put(connectorConfigKey, configEntry.getValue()); } } configurable.setConfig(configTable); return configurable; } /** Creates top-level library folders, if necessary */ private void bootstrapProjectLibrary(String projectName) throws SpecmateException, SpecmateValidationException { ITransaction trans = null; try { trans = this.persistencyService.openTransaction(); EList<EObject> projects = trans.getResource().getContents(); if (projects == null || projects.size() == 0) { return; } EObject obj = SpecmateEcoreUtil.getEObjectWithName(projectName, projects); if (obj == null || !(obj instanceof Folder)) { throw new SpecmateException("Expected project " + projectName + " not found in database"); } trans.doAndCommit(new LibraryFolderUpdater((Folder) obj)); } finally { if (trans != null) { trans.close(); } } } private class LibraryFolderUpdater implements IChange<Object> { private Folder projectFolder; public LibraryFolderUpdater(Folder projectFolder) { this.projectFolder = projectFolder; } @Override public Object doChange() throws SpecmateException, SpecmateValidationException { String projectName = projectFolder.getName(); String projectLibraryKey = PROJECT_PREFIX + projectName + KEY_PROJECT_LIBRARY; String[] libraryFolders = configService.getConfigurationPropertyArray(projectLibraryKey); if (libraryFolders != null) { for (int i = 0; i < libraryFolders.length; i++) { String projectLibraryId = libraryFolders[i]; String libraryName = configService.getConfigurationProperty( projectLibraryKey + "." + projectLibraryId + KEY_PROJECT_LIBRARY_NAME); String libraryDescription = configService.getConfigurationProperty( projectLibraryKey + "." + projectLibraryId + KEY_PROJECT_LIBRARY_DESCRIPTION); EObject obj = SpecmateEcoreUtil.getEObjectWithId(projectLibraryId, projectFolder.eContents()); Folder libraryFolder = null; if (obj == null) { libraryFolder = BaseFactory.eINSTANCE.createFolder(); projectFolder.getContents().add(libraryFolder); } else { assert (obj instanceof Folder); libraryFolder = (Folder) obj; } libraryFolder.setId(projectLibraryId); libraryFolder.setName(libraryName); libraryFolder.setDescription(libraryDescription); } } return null; } } @Reference public void setConfigService(IConfigService configService) { this.configService = configService; } @Reference public void setConfigurationAdmin(ConfigurationAdmin configAdmin) { this.configAdmin = configAdmin; } @Reference public void setLogService(LogService logService) { this.logService = logService; } @Reference public void setPersistencyService(IPersistencyService persistencyService) { this.persistencyService = persistencyService; } }
package com.github.yuruki.camel.scr; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @SuppressWarnings("unused") public class ScrHelper { private static Logger log = LoggerFactory.getLogger(ScrHelper.class); public static Map<String, String> getScrProperties(String componentName) throws Exception { return getScrProperties(String.format("target/classes/OSGI-INF/%s.xml", componentName), componentName); } public static Map<String, String> getScrProperties(String xmlLocation, String componentName) throws Exception { Map<String, String> result = new HashMap<>(); final Document dom = readXML(new File(xmlLocation)); final XPath xPath = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI, "com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", null).newXPath(); xPath.setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { switch (prefix) { case "scr": try { XPathExpression scrNamespace = xPath.compile("/*/namespace::*[name()='scr']"); Node node = (Node) scrNamespace.evaluate(dom, XPathConstants.NODE); return node.getNodeValue(); } catch (XPathExpressionException e) { e.printStackTrace(); } return "http: } return XMLConstants.NULL_NS_URI; } @Override public String getPrefix(String namespaceURI) { return null; } @Override public Iterator getPrefixes(String namespaceURI) { return null; } }); String propertyListExpression = String.format("/components/scr:component[@name='%s']/property", componentName); XPathExpression propertyList = xPath.compile(propertyListExpression); XPathExpression propertyName = xPath.compile("@name"); XPathExpression propertyValue = xPath.compile("@value"); NodeList nodes = (NodeList) propertyList.evaluate(dom, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); result.put((String) propertyName.evaluate(node, XPathConstants.STRING), (String) propertyValue.evaluate(node, XPathConstants.STRING)); } return result; } private static Document readXML(File xml) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); return builder.parse(xml); } }
package dhbw.ka.mwi.businesshorizon2.demo.ui; import dhbw.ka.mwi.businesshorizon2.cf.*; import dhbw.ka.mwi.businesshorizon2.demo.CFAlgo; import dhbw.ka.mwi.businesshorizon2.demo.calc.CFCalculator; import dhbw.ka.mwi.businesshorizon2.demo.models.CompanyModelProvider; import dhbw.ka.mwi.businesshorizon2.demo.saving.CsvExport; import dhbw.ka.mwi.businesshorizon2.demo.saving.CsvImport; import dhbw.ka.mwi.businesshorizon2.demo.saving.ExportListener; import javax.swing.*; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; public class MainWindow extends JFrame { private final CompanyPanel company; private final SzenarioPanel szenario; private final StochiResultPanel stochiResultPanel; private final DeterResultPanel deterResultPanel; private final HeaderPanel header; public MainWindow() { setTitle("Business Horizon Demo"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(1024, 768); setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); final JTabbedPane tab = new JTabbedPane(); add(tab); header = new HeaderPanel(); tab.addTab("Kopf",header); company = new CompanyPanel(header); tab.addTab("Unternehmenswerte", company); szenario = new SzenarioPanel(); tab.addTab("Szenario",szenario); deterResultPanel = new DeterResultPanel(); tab.addTab("Unternehmenswert", deterResultPanel); stochiResultPanel = new StochiResultPanel(); final ChangeListener yearAndPeriodenListener = e -> { company.setModel(CompanyModelProvider.getModel((Integer) header.getBasisjahr().getValue(),(Integer) header.getPerioden().getValue(), header.getCurrentMode(),company.getDetailMode())); company.setDetailModel(CompanyModelProvider.getDetailModel((Integer) header.getBasisjahr().getValue(),(Integer) header.getPerioden().getValue(), header.getCurrentMode())); }; header.getPerioden().addChangeListener(yearAndPeriodenListener); header.getBasisjahr().addChangeListener(yearAndPeriodenListener); header.getStochi().addActionListener(e -> { company.setModel(CompanyModelProvider.getModel((Integer) header.getBasisjahr().getValue(),(Integer) header.getPerioden().getValue(), header.getCurrentMode(),company.getDetailMode())); company.setDetailModel(CompanyModelProvider.getDetailModel((Integer) header.getBasisjahr().getValue(),(Integer) header.getPerioden().getValue(), header.getCurrentMode())); setTabs(tab); }); header.getDeter().addActionListener(e -> { company.setModel(CompanyModelProvider.getModel((Integer) header.getBasisjahr().getValue(),(Integer) header.getPerioden().getValue(), header.getCurrentMode(),company.getDetailMode())); company.setDetailModel(CompanyModelProvider.getDetailModel((Integer) header.getBasisjahr().getValue(),(Integer) header.getPerioden().getValue(), header.getCurrentMode())); setTabs(tab); }); header.getLoad().addActionListener(e -> { final JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter("CSV", "csv")); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { try { CsvImport.importCSV(chooser.getSelectedFile(),header,company,szenario); setTabs(tab); } catch (final Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(this, "Datei kann nicht importiert werden: " + e1.getLocalizedMessage()); } } }); header.getSave().addActionListener(new ExportListener(file -> CsvExport.export(header, szenario, company, file))); stochiResultPanel.getCalculate().addActionListener(e -> { try { final long was = System.nanoTime(); final double[] uWerts = CFCalculator.calculateStochi(company,szenario,stochiResultPanel, (CFAlgo) deterResultPanel.getAlgo().getSelectedItem()); final double uWert = CFCalculator.avg(uWerts); System.out.println("Dauer Stochi:" + (System.nanoTime() - was) / 1000000 + " ms"); stochiResultPanel.setLastResult(uWerts); stochiResultPanel.getuWert().setText(String.valueOf(uWert)); } catch (final Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(this, "Fehler bei der Berechnung: " + e1.getLocalizedMessage()); } }); deterResultPanel.getCalculate().addActionListener(e -> { try { final CFParameter parameter = CFCalculator.getParameter(company,szenario); switch ((CFAlgo) deterResultPanel.getAlgo().getSelectedItem()){ case APV: final APVResult apvResult = new APV().calculateUWert(parameter); deterResultPanel.displayAPV(apvResult,parameter.getFK()[0]); deterResultPanel.getuWert().setText(String.valueOf(apvResult.getuWert())); break; case FCF: final FCFResult fcfResult = new FCF().calculateUWert(parameter); deterResultPanel.displayFCF(fcfResult,parameter.getFK()[0]); deterResultPanel.getuWert().setText(String.valueOf(fcfResult.getuWert())); break; case FTE: final CFResult fteResult = new FTE().calculateUWert(parameter); deterResultPanel.displayFTE(fteResult); deterResultPanel.getuWert().setText(String.valueOf(fteResult.getuWert())); break; } } catch (final Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(this, "Fehler bei der Berechnung: " + e1.getLocalizedMessage()); } }); deterResultPanel.getExport().addActionListener(new ExportListener(file -> CsvExport.exportResults(file,new double[]{Double.parseDouble(deterResultPanel.getuWert().getText())}))); stochiResultPanel.getExport().addActionListener(new ExportListener(file -> CsvExport.exportResults(file,stochiResultPanel.getLastResult()))); } private void setTabs(final JTabbedPane tab) { switch (header.getCurrentMode()){ case STOCHI: tab.remove(deterResultPanel); tab.addTab("Unternehmenswert", stochiResultPanel); break; case DETER: tab.remove(stochiResultPanel); tab.addTab("Unternehmenswert", deterResultPanel); break; } } }
package com.splicemachine.derby.impl.sql.execute.operations; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.derby.catalog.types.ReferencedColumnsDescriptorImpl; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.io.FormatableBitSet; import org.apache.derby.iapi.services.loader.GeneratedMethod; import org.apache.derby.iapi.sql.Activation; import org.apache.derby.iapi.sql.execute.CursorResultSet; import org.apache.derby.iapi.sql.execute.ExecRow; import org.apache.derby.iapi.sql.execute.NoPutResultSet; import org.apache.derby.iapi.store.access.DynamicCompiledOpenConglomInfo; import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.types.RowLocation; import org.apache.derby.impl.sql.GenericPreparedStatement; import org.apache.derby.impl.sql.GenericStorablePreparedStatement; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Result; import org.apache.log4j.Logger; import com.splicemachine.derby.iapi.sql.execute.SpliceNoPutResultSet; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext; import com.splicemachine.derby.iapi.storage.RowProvider; import com.splicemachine.derby.impl.store.access.SpliceAccessManager; import com.splicemachine.derby.utils.SpliceUtils; import com.splicemachine.utils.SpliceLogUtils; /** * Maps between an Index Table and a data Table. */ public class IndexRowToBaseRowOperation extends SpliceBaseOperation implements CursorResultSet{ private static Logger LOG = Logger.getLogger(IndexRowToBaseRowOperation.class); protected int lockMode; protected int isolationLevel; // protected ExecRow candidate; protected FormatableBitSet accessedCols; protected String resultRowAllocatorMethodName; protected StaticCompiledOpenConglomInfo scoci; protected DynamicCompiledOpenConglomInfo dcoci; protected SpliceOperation source; protected String indexName; protected boolean forUpdate; protected GeneratedMethod restriction; protected String restrictionMethodName; protected FormatableBitSet accessedHeapCols; protected FormatableBitSet heapOnlyCols; protected FormatableBitSet accessedAllCols; protected int[] indexCols; protected ExecRow resultRow; protected DataValueDescriptor[] rowArray; protected int scociItem; protected long conglomId; protected int heapColRefItem; protected int allColRefItem; protected int heapOnlyColRefItem; protected int indexColMapItem; private ExecRow compactRow; RowLocation baseRowLocation = null; // FormatableBitSet accessFromTableCols; boolean copiedFromSource = false; /* * Variable here to stash pre-generated DataValue definitions for use in * getExecRowDefinition(). Save a little bit of performance by caching it * once created. */ // private ExecRow definition; private HTableInterface table; public IndexRowToBaseRowOperation () { super(); } public IndexRowToBaseRowOperation(long conglomId, int scociItem, Activation activation, NoPutResultSet source, GeneratedMethod resultRowAllocator, int resultSetNumber, String indexName, int heapColRefItem, int allColRefItem, int heapOnlyColRefItem, int indexColMapItem, GeneratedMethod restriction, boolean forUpdate, double optimizerEstimatedRowCount, double optimizerEstimatedCost) throws StandardException { super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); SpliceLogUtils.trace(LOG,"instantiate with parameters"); this.resultRowAllocatorMethodName = resultRowAllocator.getMethodName(); this.source = (SpliceOperation) source; this.indexName = indexName; this.forUpdate = forUpdate; this.scociItem = scociItem; this.conglomId = conglomId; this.heapColRefItem = heapColRefItem; this.allColRefItem = allColRefItem; this.heapOnlyColRefItem = heapOnlyColRefItem; this.indexColMapItem = indexColMapItem; this.restrictionMethodName = restriction==null? null: restriction.getMethodName(); init(SpliceOperationContext.newContext(activation)); recordConstructorTime(); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // SpliceLogUtils.trace(LOG,"readExternal"); super.readExternal(in); scociItem = in.readInt(); conglomId = in.readLong(); heapColRefItem = in.readInt(); allColRefItem = in.readInt(); heapOnlyColRefItem = in.readInt(); indexColMapItem = in.readInt(); source = (SpliceOperation) in.readObject(); accessedCols = (FormatableBitSet) in.readObject(); resultRowAllocatorMethodName = in.readUTF(); indexName = in.readUTF(); restrictionMethodName = readNullableString(in); } @Override public void writeExternal(ObjectOutput out) throws IOException { // SpliceLogUtils.trace(LOG,"writeExternal"); super.writeExternal(out); out.writeInt(scociItem); out.writeLong(conglomId); out.writeInt(heapColRefItem); out.writeInt(allColRefItem); out.writeInt(heapOnlyColRefItem); out.writeInt(indexColMapItem); out.writeObject(source); out.writeObject(accessedCols); out.writeUTF(resultRowAllocatorMethodName); out.writeUTF(indexName); writeNullableString(restrictionMethodName, out); } @Override public void init(SpliceOperationContext context) throws StandardException{ // SpliceLogUtils.trace(LOG,"init called"); super.init(context); source.init(context); try { GenericStorablePreparedStatement statement = context.getPreparedStatement(); if(restrictionMethodName !=null){ SpliceLogUtils.trace(LOG,"%s:restrictionMethodName=%s",indexName,restrictionMethodName); restriction = statement.getActivationClass().getMethod(restrictionMethodName); } GeneratedMethod generatedMethod = statement.getActivationClass().getMethod(resultRowAllocatorMethodName); final GenericPreparedStatement gp = (GenericPreparedStatement)activation.getPreparedStatement(); final Object[] saved = gp.getSavedObjects(); scoci = (StaticCompiledOpenConglomInfo)saved[scociItem]; TransactionController tc = activation.getTransactionController(); dcoci = tc.getDynamicCompiledConglomInfo(conglomId); // the saved objects, if it exists if (heapColRefItem != -1) { this.accessedHeapCols = (FormatableBitSet)saved[heapColRefItem]; } if (allColRefItem != -1) { this.accessedAllCols = (FormatableBitSet)saved[allColRefItem]; } if(heapOnlyColRefItem!=-1){ this.heapOnlyCols = (FormatableBitSet)saved[heapOnlyColRefItem]; } // retrieve the array of columns coming from the index indexCols = ((ReferencedColumnsDescriptorImpl) saved[indexColMapItem]).getReferencedColumnPositions(); /* Get the result row template */ resultRow = (ExecRow) generatedMethod.invoke(activation); compactRow = getCompactRow(activation.getLanguageConnectionContext(),resultRow, accessedAllCols, false); if (accessedHeapCols == null) { rowArray = resultRow.getRowArray(); } else { // Figure out how many columns are coming from the heap final DataValueDescriptor[] resultRowArray = resultRow.getRowArray(); final int heapOnlyLen = heapOnlyCols.getLength(); // Need a separate DataValueDescriptor array in this case rowArray = new DataValueDescriptor[heapOnlyLen]; final int minLen = Math.min(resultRowArray.length, heapOnlyLen); // Make a copy of the relevant part of rowArray for (int i = 0; i < minLen; ++i) { if (resultRowArray[i] != null && heapOnlyCols.isSet(i)) { rowArray[i] = resultRowArray[i]; } } if (indexCols != null) { for (int index = 0; index < indexCols.length; index++) { if (indexCols[index] != -1) { compactRow.setColumn(index + 1,source.getExecRowDefinition().getColumn(indexCols[index] + 1)); } } } } SpliceLogUtils.trace(LOG,"accessedAllCols=%s,accessedHeapCols=%s,heapOnlyCols=%s,accessedCols=%s",accessedAllCols,accessedHeapCols,heapOnlyCols,accessedCols); SpliceLogUtils.trace(LOG,"rowArray=%s,compactRow=%s,resultRow=%s,resultSetNumber=%d", Arrays.asList(rowArray),compactRow,resultRow,resultSetNumber); } catch (StandardException e) { SpliceLogUtils.logAndThrowRuntime(LOG, "Operation Init Failed!",e); } } @Override public NoPutResultSet executeScan() throws StandardException { SpliceLogUtils.trace(LOG,"executeScan"); final List<SpliceOperation> operationStack = getOperationStack(); SpliceLogUtils.trace(LOG,"operationStack=%s",operationStack); SpliceOperation regionOperation = operationStack.get(0); SpliceLogUtils.trace(LOG,"regionOperation=%s",regionOperation); RowProvider provider; ExecRow template = getExecRowDefinition(); if(regionOperation.getNodeTypes().contains(NodeType.REDUCE)&&this!=regionOperation){ SpliceLogUtils.trace(LOG,"Scanning temp tables"); provider = regionOperation.getReduceRowProvider(this,template); }else { SpliceLogUtils.trace(LOG,"scanning Map table"); provider = regionOperation.getMapRowProvider(this,template); } return new SpliceNoPutResultSet(activation,this, provider); } @Override public SpliceOperation getLeftOperation() { // SpliceLogUtils.trace(LOG,"getLeftOperation ",source); return this.source; } @Override public RowLocation getRowLocation() throws StandardException { return currentRowLocation; } @Override public ExecRow getCurrentRow() throws StandardException { return currentRow; } @Override public List<NodeType> getNodeTypes() { return Collections.singletonList(NodeType.SCAN); } @Override public List<SpliceOperation> getSubOperations() { SpliceLogUtils.trace(LOG,"getSubOperations"); return Collections.singletonList(source); } @Override public ExecRow getNextRowCore() throws StandardException { SpliceLogUtils.trace(LOG,"<%s> getNextRowCore",indexName); ExecRow sourceRow; ExecRow retRow; boolean restrict = false; DataValueDescriptor restrictBoolean; do{ sourceRow = source.getNextRowCore(); SpliceLogUtils.trace(LOG,"<%s> retrieved index row %s",indexName,sourceRow); if(sourceRow==null){ //No Rows remaining clearCurrentRow(); baseRowLocation= null; retRow = null; if(table!=null){ try { table.close(); } catch (IOException e) { SpliceLogUtils.warn(LOG,"Unable to close HTable"); } } break; } //we have a row, get it if(table==null) table = SpliceAccessManager.getHTable(conglomId); baseRowLocation = (RowLocation)sourceRow.getColumn(sourceRow.nColumns()); Get get = SpliceUtils.createGet(baseRowLocation, rowArray, heapOnlyCols, getTransactionID()); boolean rowExists = false; try{ Result result = table.get(get); SpliceLogUtils.trace(LOG,"<%s> rowArray=%s,accessedHeapCols=%s,heapOnlyCols=%s,baseColumnMap=%s", indexName,Arrays.toString(rowArray),accessedHeapCols,heapOnlyCols,Arrays.toString(baseColumnMap)); rowExists = result!=null && !result.isEmpty(); if(rowExists){ SpliceUtils.populate(result, compactRow.getRowArray(), accessedHeapCols,baseColumnMap); } }catch(IOException ioe){ SpliceLogUtils.logAndThrowRuntime(LOG,ioe); } SpliceLogUtils.trace(LOG,"<%s>,rowArray=%s,compactRow=%s",indexName,rowArray,compactRow); if(rowExists){ if(!copiedFromSource){ copiedFromSource=true; for(int index=0;index < indexCols.length;index++){ if(indexCols[index] != -1) { SpliceLogUtils.trace(LOG,"<%s> indexCol overwrite for value %d" ,indexName,indexCols[index]); compactRow.setColumn(index+1,sourceRow.getColumn(indexCols[index]+1)); } } } SpliceLogUtils.trace(LOG, "<%s>compactRow=%s", indexName,compactRow); setCurrentRow(compactRow); currentRowLocation = baseRowLocation; restrictBoolean = (DataValueDescriptor) ((restriction == null) ? null: restriction.invoke(activation)); restrict = (restrictBoolean ==null) || ((!restrictBoolean.isNull()) && restrictBoolean.getBoolean()); } if(!restrict || !rowExists){ clearCurrentRow(); baseRowLocation = null; currentRowLocation=null; }else{ currentRow = compactRow; } retRow = currentRow; }while(!restrict); SpliceLogUtils.trace(LOG, "emitting row %s",retRow); // setCurrentRow(retRow); return retRow; } @Override public void close() throws StandardException { SpliceLogUtils.trace(LOG, "close in IndexRowToBaseRow"); beginTime = getCurrentTimeMillis(); source.close(); super.close(); closeTime += getElapsedMillis(beginTime); } @Override public ExecRow getExecRowDefinition() { return compactRow.getClone(); } public String getIndexName() { return this.indexName; } public FormatableBitSet getAccessedHeapCols() { return this.accessedHeapCols; } public SpliceOperation getSource() { return this.source; } @Override public long getTimeSpent(int type) { long totTime = constructorTime + openTime + nextTime + closeTime; if (type == CURRENT_RESULTSET_ONLY) return totTime - source.getTimeSpent(ENTIRE_RESULTSET_TREE); else return totTime; } @Override public String toString() { return String.format("IndexRowToBaseRow {source=%s,indexName=%s,conglomId=%d,resultSetNumber=%d}", source,indexName,conglomId,resultSetNumber); } @Override public void openCore() throws StandardException { super.openCore(); if(source!=null)source.openCore(); } }
package cc.catalysts.boot.report.pdf.elements; import cc.catalysts.boot.report.pdf.config.PdfStyleSheet; import cc.catalysts.boot.report.pdf.utils.ReportAlignType; import cc.catalysts.boot.report.pdf.utils.ReportVerticalAlignType; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; /** * <p><b>IMPORTANT:</b> Although this class is publicly visible, it is subject to change and may not be implemented by clients!</p> * * @author Klaus Lehner */ public class ReportTable implements ReportElement { private static final boolean DEFAULT_BORDER = false; private static final float DEFAULT_CELL_PADDING_LEFT_RIGHT = 2; private static final float DEFAULT_CELL_PADDING_TOP_BOTTOM = 0; private static final int BORDER_Y_DELTA = 1; private final PdfStyleSheet pdfStyleSheet; private float[] cellWidths; private ReportVerticalAlignType[] cellAligns; private ReportElement[][] elements; private ReportElement[] title; private boolean border = DEFAULT_BORDER; private boolean noBottomBorder; private boolean noTopBorder; private boolean noInnerBorders = false; private boolean placeFirstBorder = true; private boolean placeLastBorder = true; private boolean enableExtraSplitting; private boolean isSplitable = true; private Collection<ReportImage.ImagePrintIntent> intents = new LinkedList<ReportImage.ImagePrintIntent>(); /** * left and right cell padding */ private float cellPaddingX = DEFAULT_CELL_PADDING_LEFT_RIGHT; private float cellPaddingY = DEFAULT_CELL_PADDING_TOP_BOTTOM; /** * @param cellWidths width of each column (the sum of elements must be 1) * @param elements elements of each cell * @param pdfStyleSheet the stylesheet to be used for this table * @param title the titles for the report (first row) */ public ReportTable(PdfStyleSheet pdfStyleSheet, float[] cellWidths, ReportElement[][] elements, ReportElement[] title) { this.pdfStyleSheet = pdfStyleSheet; if (elements == null || cellWidths == null) { throw new IllegalArgumentException("Arguments cant be null"); } if (elements.length > 0 && cellWidths.length != elements[0].length) { throw new IllegalArgumentException("The cell widths must have the same number of elements as 'elements'"); } if (title != null && title.length != cellWidths.length) { throw new IllegalArgumentException("Title must be null, or the same size as elements"); } this.cellWidths = cellWidths; this.cellAligns = new ReportVerticalAlignType[cellWidths.length]; Arrays.fill(cellAligns, ReportVerticalAlignType.TOP); this.elements = elements; this.title = title; } public void setNoInnerBorders(boolean noInnerBorders) { this.noInnerBorders = noInnerBorders; } public void setNoBottomBorder(boolean border) { this.noBottomBorder = border; } public void setNoTopBorder(boolean border) { this.noTopBorder = border; } public void setBorder(boolean border) { this.border = border; } public void setExtraSplitting(boolean enableExtraSplitting) { this.enableExtraSplitting = enableExtraSplitting; } /** * @param cellPaddingX for left and right */ public void setCellPaddingX(float cellPaddingX) { this.cellPaddingX = cellPaddingX; } /** * @param cellPaddingY for top and bottom */ public void setCellPaddingY(float cellPaddingY) { this.cellPaddingY = cellPaddingY; } public boolean getExtraSplitting() { return enableExtraSplitting; } @Override public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException { if (title != null) { throw new IllegalStateException("title not implemented!"); } float y = startY; int i = 0; float lineY = 0; for (ReportElement[] line : elements) { float lineHeight = getLineHeight(line, allowedWidth) + pdfStyleSheet.getLineDistance(); y = printLine(document, stream, pageNumber, startX, y, allowedWidth, line, lineY); placeFirstBorder = i == 0; placeLastBorder = i == elements.length - 1; placeBorders(stream, startY, y, startX, allowedWidth); i++; lineY += lineHeight; } return y; } private void placeBorders(PDPageContentStream stream, float startY, float endY, float x, float allowedWidth) throws IOException { if (border) { stream.setStrokingColor(0, 0, 0); stream.setLineWidth(0.3f); float y0 = startY - BORDER_Y_DELTA; float y1 = endY - (BORDER_Y_DELTA + 1); if (!noInnerBorders) { if (!noTopBorder || noTopBorder && !placeFirstBorder) { stream.drawLine(x, y0, x + allowedWidth, y0); } if (!noBottomBorder || noBottomBorder && !placeLastBorder) { stream.drawLine(x, y1, x + allowedWidth, y1); } } else { if (!noTopBorder && placeFirstBorder) { stream.drawLine(x, y0, x + allowedWidth, y0); } if (!noBottomBorder && placeLastBorder) { stream.drawLine(x, y1, x + allowedWidth, y1); } } float currX = x; stream.drawLine(currX, y0, currX, y1); for (float width : cellWidths) { if (!noInnerBorders) { stream.drawLine(currX, y0, currX, y1); } currX += width * allowedWidth; } stream.drawLine(currX, y0, currX, y1); } } private float calculateVerticalAlignment(ReportElement[] line, int elementIndex, float y, float allowedWidth) { float yPos = 0; float lineHeight = getLineHeight(line, allowedWidth); switch (cellAligns[elementIndex]) { case TOP: yPos = y - cellPaddingY; break; case BOTTOM: yPos = y - cellPaddingY - lineHeight + line[elementIndex].getHeight(cellWidths[elementIndex] * allowedWidth - 2 * cellPaddingX); break; case MIDDLE: yPos = y - cellPaddingY - lineHeight / 2 + line[elementIndex].getHeight(cellWidths[elementIndex] * allowedWidth - 2 * cellPaddingX) / 2; break; default: throw new IllegalArgumentException("Vertical align type " + cellAligns[elementIndex] + " not implemented for tables"); } return yPos; } private float printLine(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float y, float allowedWidth, ReportElement[] line, float previousLineHeight) throws IOException { float x = startX + cellPaddingX; float minY = y; for (int i = 0; i < cellWidths.length; i++) { if (line[i] != null) { float yi = 0; float yPos = calculateVerticalAlignment(line, i, y, allowedWidth); if (line[i] instanceof ReportImage) { ReportImage reportImage = (ReportImage) line[i]; float initialWidth = reportImage.getWidth(); reportImage.setWidth(cellWidths[i] * allowedWidth - cellPaddingX * 2); reportImage.setHeight(reportImage.getHeight() * (cellWidths[i] * allowedWidth - cellPaddingX * 2) / initialWidth); yi = line[i].print(document, stream, pageNumber, x, yPos, cellWidths[i] * allowedWidth - cellPaddingX * 2); reportImage.printImage(document, pageNumber, x, yPos); } else { yi = line[i].print(document, stream, pageNumber, x, yPos, cellWidths[i] * allowedWidth - cellPaddingX * 2); } intents.addAll(line[i].getImageIntents()); minY = Math.min(minY, yi); } x += cellWidths[i] * allowedWidth; } return minY - cellPaddingY; } @Override public float getHeight(float allowedWidth) { float[] maxes = new float[elements.length]; for (int i = 0; i < elements.length; i++) { maxes[i] = getLineHeight(elements[i], allowedWidth); } float max = 0; for (float f : maxes) { max += f; } return max; } @Override public boolean isSplitable() { return isSplitable; } public void setSplitable(boolean isSplitable) { this.isSplitable = isSplitable; } @Override public float getFirstSegmentHeight(float allowedWidth) { if (elements != null && elements.length > 0) { return border ? getFirstSegmentHeightFromLine(elements[0], allowedWidth) + BORDER_Y_DELTA : getFirstSegmentHeightFromLine(elements[0], allowedWidth); } else { return 0; } } private float getFirstSegmentHeightFromLine(ReportElement[] line, float allowedWidth) { float maxHeight = 0f; for (int i = 0; i < line.length; i++) { if (line[i] != null) maxHeight = Math.max(maxHeight, line[i].getFirstSegmentHeight(cellWidths[i] * allowedWidth - cellPaddingX * 2)); } return maxHeight + 2 * cellPaddingY; } private float getLineHeight(ReportElement[] line, float allowedWidth) { float maxHeight = 0; float currentHeight; for (int i = 0; i < line.length; i++) { if (line[i] != null) { if (line[i] instanceof ReportImage) { ReportImage lineImage = (ReportImage) line[i]; currentHeight = lineImage.getHeight() * (cellWidths[i] * allowedWidth - cellPaddingX * 2) / lineImage.getWidth(); } else { currentHeight = line[i].getHeight(cellWidths[i] * allowedWidth - cellPaddingX * 2); } maxHeight = Math.max(maxHeight, currentHeight); } } return maxHeight + 2 * cellPaddingY; } private ReportTable createNewTableWithClonedSettings(ReportElement[][] data) { ReportTable newTable = new ReportTable(pdfStyleSheet, cellWidths, data, title); newTable.setBorder(border); newTable.setCellPaddingX(cellPaddingX); newTable.setCellPaddingY(cellPaddingY); newTable.setExtraSplitting(enableExtraSplitting); return newTable; } @Override public Collection<ReportImage.ImagePrintIntent> getImageIntents() { return intents; } public ReportElement[] splitFirstCell(float allowedHeight, float allowedWidth) { ReportElement[] firstLineA = new ReportElement[elements[0].length]; ReportElement[] firstLineB = new ReportElement[elements[0].length]; boolean hasSecondPart = false; for (int i = 0; i < elements[0].length; i++) { ReportElement elem = elements[0][i]; float width = cellWidths[i] * allowedWidth - 2 * cellPaddingX; if (elem != null && elem.isSplitable()) { ReportElement[] split = elem.split(width, allowedHeight); firstLineA[i] = split[0]; firstLineB[i] = split[1]; if (firstLineB[i] != null) { hasSecondPart = true; } } else { firstLineA[i] = elem; } } if (hasSecondPart) { ReportElement[][] newMatrix = new ReportElement[elements.length][elements[0].length]; newMatrix[0] = firstLineB; for (int i = 1; i < elements.length; i++) { newMatrix[i] = elements[i]; } ReportTable firstLine = createNewTableWithClonedSettings(new ReportElement[][]{firstLineA}); ReportTable nextLines = createNewTableWithClonedSettings(newMatrix); return new ReportElement[]{firstLine, nextLines}; } else { return new ReportElement[]{this, null}; } } @Override public ReportElement[] split(float allowedWidth, float allowedHeight) { float currentHeight = 0f; int i = 0; while (i < elements.length && (currentHeight + getLineHeight(elements[i], allowedWidth)) < allowedHeight) { currentHeight += getLineHeight(elements[i], allowedWidth); i++; } if (i > 0) { //they all fit until i-1, inclusive //check if the last row can be split ReportElement[][] extraRows = new ReportElement[2][elements[0].length]; boolean splittable = false; if (enableExtraSplitting) { splittable = true; for (int j = 0; j < elements[i].length; j++) { if (!elements[i][j].isSplitable() || currentHeight + elements[i][j].getFirstSegmentHeight(cellWidths[j] * allowedWidth - cellPaddingX * 2) + 2 * cellPaddingY >= allowedHeight) { splittable = false; } } if (splittable) { for (int j = 0; j < elements[i].length; j++) { if (elements[i][j].getHeight(cellWidths[j] * allowedWidth - cellPaddingX * 2) + currentHeight < allowedHeight) { extraRows[0][j] = elements[i][j]; extraRows[1][j] = new ReportTextBox(pdfStyleSheet.getBodyText(), pdfStyleSheet.getLineDistance(), ""); } else { ReportElement[] extraSplit = elements[i][j].split(cellWidths[j] * allowedWidth - cellPaddingX * 2, allowedHeight - currentHeight - 2 * cellPaddingY); extraRows[0][j] = extraSplit[0]; extraRows[1][j] = extraSplit[1]; } } } } ReportElement[][] first = new ReportElement[splittable ? i + 1 : i][elements[0].length]; ReportElement[][] next = new ReportElement[elements.length - i][elements[0].length]; for (int j = 0; j < elements.length; j++) { if (j < i) first[j] = elements[j]; else next[j - i] = elements[j]; } if (splittable) { first[i] = extraRows[0]; next[0] = extraRows[1]; } ReportTable firstLine = createNewTableWithClonedSettings(first); ReportTable nextLines = createNewTableWithClonedSettings(next); return new ReportElement[]{firstLine, nextLines}; } else { //this means first row does not fit in the given height ReportElement[][] first = new ReportElement[1][elements[0].length]; ReportElement[][] next = new ReportElement[elements.length][elements[0].length]; for (i = 1; i < elements.length; i++) next[i] = elements[i]; for (i = 0; i < elements[0].length; i++) { ReportElement[] splits = elements[0][i].split(cellWidths[i] * allowedWidth - cellPaddingX * 2, allowedHeight - 2 * cellPaddingY); if (splits[0] != null) first[0][i] = splits[0]; else first[0][i] = new ReportTextBox(pdfStyleSheet.getBodyText(), pdfStyleSheet.getLineDistance(), ""); if (splits[1] != null) next[0][i] = splits[1]; else next[0][i] = new ReportTextBox(pdfStyleSheet.getBodyText(), pdfStyleSheet.getLineDistance(), ""); } ReportTable firstLine = createNewTableWithClonedSettings(first); ReportTable nextLines = createNewTableWithClonedSettings(next); return new ReportElement[]{firstLine, nextLines}; } } @Override public ReportElement[] split(float allowedWidth) { ReportElement[][] first = new ReportElement[][]{elements[0]}; ReportElement[][] next = Arrays.copyOfRange(elements, 1, elements.length); ReportTable firstLine = createNewTableWithClonedSettings(first); ReportTable nextLines = createNewTableWithClonedSettings(next); return new ReportElement[]{firstLine, nextLines}; } public void setTextAlignInColumn(int column, ReportAlignType alignType, boolean excludeHeader) { for (int i = excludeHeader ? 1 : 0; i < elements.length; i++) { ReportElement[] element = elements[i]; if (element[column] instanceof ReportTextBox) { ((ReportTextBox) element[column]).setAlign(alignType); } } } public void setVerticalAlignInColumn(int column, ReportVerticalAlignType alignType) { cellAligns[column] = alignType; } public ReportElement[][] getElements() { return elements; } public ReportElement[] getTitle() { return title; } public float[] getCellWidths() { return cellWidths; } public PdfStyleSheet getPdfStyleSheet() { return pdfStyleSheet; } }
package org.apereo.cas.oidc.web; import org.apereo.cas.oidc.AbstractOidcTests; import org.apereo.cas.support.oauth.OAuth20Constants; import lombok.val; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.pac4j.cas.client.CasClient; import org.pac4j.cas.config.CasConfiguration; import org.pac4j.core.http.callback.CallbackUrlResolver; import org.pac4j.core.http.url.UrlResolver; import org.pac4j.jee.context.JEEContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; /** * This is {@link OidcCasClientRedirectActionBuilderTests}. * * @author Misagh Moayyed * @since 6.2.0 */ @Tag("OIDC") public class OidcCasClientRedirectActionBuilderTests extends AbstractOidcTests { @Test public void verifyPromptNone() { verifyBuild("=none"); } @Test public void verifyPromptLogin() { verifyBuild("=login"); } private void verifyBuild(final String prompt) { val request = new MockHttpServletRequest(); request.setRequestURI("https://cas.org/something"); request.setQueryString(OAuth20Constants.PROMPT + prompt); val response = new MockHttpServletResponse(); val context = new JEEContext(request, response); val casClient = new CasClient(new CasConfiguration("https://caslogin.com")); casClient.setCallbackUrl("https://caslogin.com"); val callback = mock(CallbackUrlResolver.class); when(callback.compute(any(), any(), anyString(), any())).thenReturn("https://caslogin.com"); casClient.setCallbackUrlResolver(callback); casClient.setUrlResolver(mock(UrlResolver.class)); val result = oauthCasClientRedirectActionBuilder.build(casClient, context); assertTrue(result.isPresent()); } }
package org.openscience.cdk.app; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.simolecule.centres.BaseMol; import com.simolecule.centres.CdkLabeller; import com.simolecule.centres.Descriptor; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.depict.Abbreviations; import org.openscience.cdk.depict.Depiction; import org.openscience.cdk.depict.DepictionGenerator; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.exception.InvalidSmilesException; import org.openscience.cdk.geometry.GeometryUtil; import org.openscience.cdk.graph.ConnectedComponents; import org.openscience.cdk.graph.Cycles; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IChemObjectBuilder; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.interfaces.IStereoElement; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.layout.StructureDiagramGenerator; import org.openscience.cdk.renderer.RendererModel; import org.openscience.cdk.renderer.SymbolVisibility; import org.openscience.cdk.renderer.color.CDK2DAtomColors; import org.openscience.cdk.renderer.color.IAtomColorer; import org.openscience.cdk.renderer.color.UniColor; import org.openscience.cdk.renderer.generators.standard.StandardGenerator; import org.openscience.cdk.renderer.generators.standard.StandardGenerator.Visibility; import org.openscience.cdk.sgroup.Sgroup; import org.openscience.cdk.sgroup.SgroupKey; import org.openscience.cdk.sgroup.SgroupType; import org.openscience.cdk.silent.SilentChemObjectBuilder; import org.openscience.cdk.smiles.SmilesParser; import org.openscience.cdk.smarts.SmartsPattern; import org.openscience.cdk.stereo.ExtendedTetrahedral; import org.openscience.cdk.stereo.TetrahedralChirality; import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; import org.openscience.cdk.tools.manipulator.ReactionManipulator; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.request.WebRequest; import javax.imageio.ImageIO; import javax.vecmath.Point2d; import java.awt.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Chemical structure depiction controller. */ @CrossOrigin @Controller public class DepictController { private final Object lock = new Object(); private Color[] COLORS = new Color[]{ new Color(0xe6194b), new Color(0x3cb44b), new Color(0xffe119), new Color(0x0082c8), new Color(0xf58231), new Color(0x911eb4), new Color(0x46f0f0), new Color(0xf032e6), new Color(0xd2f53c), new Color(0xfabebe), new Color(0x008080), new Color(0xe6beff), new Color(0xaa6e28), new Color(0xfffac8), new Color(0x800000), new Color(0xaaffc3), new Color(0x808000), new Color(0xffd8b1), new Color(0x000080), new Color(0x808080), new Color(0xE3E3E3), new Color(0x000000) }; private final ExecutorService smartsExecutor = Executors.newFixedThreadPool(4); // chem object builder to create objects with private final IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance(); // we make are raster depictions slightly smalled by default (40px bond length) private final DepictionGenerator generator = new DepictionGenerator(); private SmilesParser smipar = new SmilesParser(builder); private final Abbreviations abbreviations = new Abbreviations(); private final Abbreviations reagents = new Abbreviations(); private enum Param { // match highlighting SMARTSHITLIM("smalim", 100), SMARTSQUERY("sma", ""), // model options HDISPLAY("hdisp", false), ALIGNRXNMAP("alignrxnmap", true), ANON("anon", false), SUPRESSH("suppressh", true), ANNOTATE("annotate", "none"), ABBREVIATE("abbr", "reagents"), // rendering param BGCOLOR("bgcolor", "default"), FGCOLOR("fgcolor", "default"), SHOWTITLE("showtitle", false), ZOOM("zoom", 1.3), ROTATE("r", 0), FLIP("f", false), WIDTH("w", -1), HEIGHT("h", -1), SVGUNITS("svgunits", "mm"); private final String name; private final Object defaultValue; Param(String name, Object defaultValue) { this.name = name; this.defaultValue = defaultValue; } } public DepictController() throws IOException { this.abbreviations.loadFromFile("/org/openscience/cdk/app/abbreviations.smi"); this.abbreviations.loadFromFile("/org/openscience/cdk/app/reagents.smi"); this.reagents.loadFromFile("/org/openscience/cdk/app/reagents.smi"); this.reagents.setContractToSingleLabel(true); abbreviations.setContractOnHetero(false); } private String getString(Param param, Map<String, String> params) { String value = params.get(param.name); if (value != null) return value; return param.defaultValue != null ? param.defaultValue.toString() : ""; } private double getDouble(Param param, Map<String, String> params) { String value = getString(param, params); if (value.isEmpty()) { if (param.defaultValue != null) return (double) param.defaultValue; throw new IllegalArgumentException(param.name + " not provided and no default!"); } return Double.parseDouble(value); } private int getInt(Param param, Map<String, String> params) { String value = getString(param, params); if (value.isEmpty()) { if (param.defaultValue != null) return (int) param.defaultValue; throw new IllegalArgumentException(param.name + " not provided and no default!"); } return Integer.parseInt(value); } private boolean getBoolean(Param param, Map<String, String> params) { String value = params.get(param.name); if (value != null) { switch (value.toLowerCase(Locale.ROOT)) { case "f": case "false": case "off": case "0": return false; case "t": case "true": case "on": case "1": return true; default: throw new IllegalArgumentException("Can not interpret boolean string param: " + value); } } return param.defaultValue != null && (boolean) param.defaultValue; } static Color getColor(String color) { int vals[] = new int[]{0, 0, 0, 255}; // r,g,b,a int pos = 0; int beg = 0; if (color.startsWith("0x")) beg = 2; else if (color.startsWith(" beg = 1; for (; pos < 4 && beg + 1 < color.length(); beg += 2) { vals[pos++] = Integer.parseInt(color.substring(beg, beg + 2), 16); } return new Color(vals[0], vals[1], vals[2], vals[3]); } private HydrogenDisplayType getHydrogenDisplay(Map<String, String> params) { if (!getBoolean(Param.SUPRESSH, params)) { return HydrogenDisplayType.Provided; } else { switch (getString(Param.HDISPLAY, params)) { case "suppressed": return HydrogenDisplayType.Minimal; case "provided": return HydrogenDisplayType.Provided; case "stereo": return HydrogenDisplayType.Stereo; case "bridgeheadtetrahedral": case "bridgehead": case "default": case "smart": return HydrogenDisplayType.Smart; default: return HydrogenDisplayType.Smart; } } } /** * Restful entry point. * * @param smi SMILES to depict * @param fmt output format * @param style preset style COW (Color-on-white), COB, BOW, COW * @return the depicted structure * @throws CDKException something not okay with input * @throws IOException problem reading/writing request */ @RequestMapping("depict/{style}/{fmt}") public HttpEntity<?> depict(@RequestParam("smi") String smi, @PathVariable("fmt") String fmt, @PathVariable("style") String style, @RequestParam Map<String, String> extra) throws CDKException, IOException { String abbr = getString(Param.ABBREVIATE, extra); String annotate = getString(Param.ANNOTATE, extra); HydrogenDisplayType hDisplayType = getHydrogenDisplay(extra); // Note: DepictionGenerator is immutable DepictionGenerator myGenerator = generator.withSize(getDouble(Param.WIDTH, extra), getDouble(Param.HEIGHT, extra)) .withZoom(getDouble(Param.ZOOM, extra)); // Configure style preset myGenerator = withStyle(myGenerator, style); myGenerator = withBgFgColors(extra, myGenerator); myGenerator = myGenerator.withAnnotationScale(0.7) .withAnnotationColor(Color.RED); if (getBoolean(Param.ANON, extra)) { myGenerator = myGenerator.withParam(Visibility.class, new SymbolVisibility() { @Override public boolean visible(IAtom iAtom, List<IBond> list, RendererModel rendererModel) { return list.isEmpty(); } }); } final boolean isRxn = !smi.contains("V2000") && isRxnSmi(smi); final boolean isRgp = smi.contains("RG:"); IReaction rxn = null; IAtomContainer mol = null; List<IAtomContainer> mols = null; Set<IChemObject> highlight; StructureDiagramGenerator sdg = new StructureDiagramGenerator(); sdg.setAlignMappedReaction(getBoolean(Param.ALIGNRXNMAP, extra)); if (isRxn) { rxn = smipar.parseReactionSmiles(smi); highlight = findHits(getString(Param.SMARTSQUERY, extra), rxn, mol, getInt(Param.SMARTSHITLIM, extra)); abbreviate(rxn, abbr, annotate); for (IAtomContainer component : rxn.getReactants().atomContainers()) { setHydrogenDisplay(component, hDisplayType); MolOp.perceiveRadicals(component); MolOp.perceiveDativeBonds(component); } for (IAtomContainer component : rxn.getProducts().atomContainers()) { setHydrogenDisplay(component, hDisplayType); MolOp.perceiveRadicals(component); MolOp.perceiveDativeBonds(component); } for (IAtomContainer component : rxn.getAgents().atomContainers()) { setHydrogenDisplay(component, hDisplayType); MolOp.perceiveRadicals(component); MolOp.perceiveDativeBonds(component); } sdg.generateCoordinates(rxn); } else { mol = loadMol(smi); setHydrogenDisplay(mol, hDisplayType); highlight = findHits(getString(Param.SMARTSQUERY, extra), rxn, mol, getInt(Param.SMARTSHITLIM, extra)); abbreviate(mol, abbr, annotate); MolOp.perceiveRadicals(mol); MolOp.perceiveDativeBonds(mol); sdg.generateCoordinates(mol); } // Add annotations switch (annotate) { case "number": myGenerator = myGenerator.withAtomNumbers(); abbr = "false"; break; case "mapidx": myGenerator = myGenerator.withAtomMapNumbers(); break; case "atomvalue": myGenerator = myGenerator.withAtomValues(); break; case "colmap": if (isRxn) { myGenerator = myGenerator.withAtomMapHighlight(new Color[]{new Color(169, 199, 255), new Color(185, 255, 180), new Color(255, 162, 162), new Color(253, 139, 255), new Color(255, 206, 86), new Color(227, 227, 227)}) .withOuterGlowHighlight(6d); } else { myGenerator = myGenerator.withOuterGlowHighlight(); myGenerator = myGenerator.withParam(StandardGenerator.Visibility.class, SymbolVisibility.iupacRecommendationsWithoutTerminalCarbon()); for (IAtom atom : mol.atoms()) { Integer mapidx = atom.getProperty(CDKConstants.ATOM_ATOM_MAPPING); if (mapidx != null && mapidx < COLORS.length) atom.setProperty(StandardGenerator.HIGHLIGHT_COLOR, COLORS[mapidx]); } } break; case "cip": if (isRxn) { for (IAtomContainer part : ReactionManipulator.getAllAtomContainers(rxn)) { annotateCip(part); } } else { annotateCip(mol); } break; } // add highlight from atom/bonds hit by the provided SMARTS switch (style) { case "nob": myGenerator = myGenerator.withHighlight(highlight, new Color(0xffaaaa)); break; case "bow": case "wob": case "bot": myGenerator = myGenerator.withHighlight(highlight, new Color(0xff0000)); break; default: myGenerator = myGenerator.withHighlight(highlight, new Color(0xaaffaa)); break; } if (getBoolean(Param.SHOWTITLE, extra)) { if (isRxn) myGenerator = myGenerator.withRxnTitle(); else myGenerator = myGenerator.withMolTitle(); } // reactions are laid out in the main depiction gen if (getBoolean(Param.FLIP, extra)) { if (isRxn) { for (IAtomContainer part : ReactionManipulator.getAllAtomContainers(rxn)) flip(part); } else flip(mol); } int rotate = getInt(Param.ROTATE, extra); if (rotate != 0) { if (isRxn) { for (IAtomContainer part : ReactionManipulator.getAllAtomContainers(rxn)) rotate(part, rotate); } else { rotate(mol, rotate); } } final String fmtlc = fmt.toLowerCase(Locale.ROOT); // pre-render the depiction final Depiction depiction = isRxn ? myGenerator.depict(rxn) : isRgp ? myGenerator.depict(mols, mols.size(), 1) : myGenerator.depict(mol); switch (fmtlc) { case Depiction.SVG_FMT: return makeResponse(depiction.toSvgStr(getString(Param.SVGUNITS, extra)) .getBytes(), "image/svg+xml"); case Depiction.PDF_FMT: return makeResponse(depiction.toPdfStr().getBytes(), "application/pdf"); case Depiction.PNG_FMT: case Depiction.JPG_FMT: case Depiction.GIF_FMT: ByteArrayOutputStream bao = new ByteArrayOutputStream(); ImageIO.write(depiction.toImg(), fmtlc, bao); return makeResponse(bao.toByteArray(), "image/" + fmtlc); } throw new IllegalArgumentException("Unsupported format."); } private void rotate(IAtomContainer mol, int rotate) { Point2d c = GeometryUtil.get2DCenter(mol); GeometryUtil.rotate(mol, c, Math.toRadians(rotate)); } private void flip(IAtomContainer mol) { for (IAtom atom : mol.atoms()) atom.getPoint2d().x = -atom.getPoint2d().x; } private DepictionGenerator withBgFgColors( @RequestParam Map<String, String> extra, DepictionGenerator myGenerator) { final String bgcolor = getString(Param.BGCOLOR, extra); switch (bgcolor) { case "clear": case "transparent": case "null": myGenerator = myGenerator.withBackgroundColor(new Color(0, 0, 0, 0)); break; case "default": // do nothing break; default: myGenerator = myGenerator.withBackgroundColor(getColor(bgcolor)); break; } final String fgcolor = getString(Param.FGCOLOR, extra); switch (fgcolor) { case "cpk": case "cdk": myGenerator = myGenerator.withAtomColors(new CDK2DAtomColors()); break; case "default": // do nothing break; default: myGenerator = myGenerator.withAtomColors(new UniColor(getColor(fgcolor))); break; } return myGenerator; } private void annotateCip(IAtomContainer part) { CdkLabeller.label(part); // update to label appropriately for racmic and relative stereochemistry for (IStereoElement<?,?> se : part.stereoElements()) { if (se.getConfigClass() == IStereoElement.TH && se.getGroupInfo() != 0) { IAtom focus = (IAtom)se.getFocus(); Object label = focus.getProperty(BaseMol.CIP_LABEL_KEY); if (label instanceof Descriptor && label != Descriptor.ns && label != Descriptor.Unknown) { if ((se.getGroupInfo() & IStereoElement.GRP_RAC) != 0) { Descriptor inv = null; switch ((Descriptor)label) { case R: inv = Descriptor.S; break; case S: inv = Descriptor.R; break; case r: inv = Descriptor.s; break; case s: inv = Descriptor.r; break; } if (inv != null) focus.setProperty(BaseMol.CIP_LABEL_KEY, label.toString() + inv.name()); } else if ((se.getGroupInfo() & IStereoElement.GRP_REL) != 0) { focus.setProperty(BaseMol.CIP_LABEL_KEY, label.toString() + "*"); } } } } for (IAtom atom : part.atoms()) { if (atom.getProperty(BaseMol.CONF_INDEX) != null) atom.setProperty(StandardGenerator.ANNOTATION_LABEL, StandardGenerator.ITALIC_DISPLAY_PREFIX + atom.getProperty(BaseMol.CONF_INDEX)); else if (atom.getProperty(BaseMol.CIP_LABEL_KEY) != null) atom.setProperty(StandardGenerator.ANNOTATION_LABEL, StandardGenerator.ITALIC_DISPLAY_PREFIX + atom.getProperty(BaseMol.CIP_LABEL_KEY)); } for (IBond bond : part.bonds()) { if (bond.getProperty(BaseMol.CIP_LABEL_KEY) != null) bond.setProperty(StandardGenerator.ANNOTATION_LABEL, StandardGenerator.ITALIC_DISPLAY_PREFIX + bond.getProperty(BaseMol.CIP_LABEL_KEY)); } } private void setHydrogenDisplay(IAtomContainer mol, HydrogenDisplayType hDisplayType) { switch (hDisplayType) { case Minimal: AtomContainerManipulator.suppressHydrogens(mol); break; case Stereo: { AtomContainerManipulator.suppressHydrogens(mol); List<IStereoElement> ses = new ArrayList<>(); for (IStereoElement se : mol.stereoElements()) { switch (se.getConfigClass()) { case IStereoElement.Tetrahedral: { IAtom focus = (IAtom) se.getFocus(); if (focus.getImplicitHydrogenCount() == 1) { focus.setImplicitHydrogenCount(0); IAtom hydrogen = sproutHydrogen(mol, focus); IStereoElement tmp = se.map(Collections.singletonMap(focus, hydrogen)); // need to keep focus same TetrahedralChirality e = new TetrahedralChirality(focus, (IAtom[]) tmp.getCarriers().toArray(new IAtom[4]), tmp.getConfig()); e.setGroupInfo(se.getGroupInfo()); ses.add(e); } else { ses.add(se); } } break; case IStereoElement.CisTrans: { IBond focus = (IBond) se.getFocus(); IAtom beg = focus.getBegin(); IAtom end = focus.getEnd(); if (beg.getImplicitHydrogenCount() == 1) { beg.setImplicitHydrogenCount(0); sproutHydrogen(mol, beg); } if (end.getImplicitHydrogenCount() == 1) { end.setImplicitHydrogenCount(0); sproutHydrogen(mol, end); } // don't need to update stereo element ses.add(se); } break; default: ses.add(se); break; } } mol.setStereoElements(ses); } break; case Smart: { AtomContainerManipulator.suppressHydrogens(mol); Cycles.markRingAtomsAndBonds(mol); List<IStereoElement> ses = new ArrayList<>(); for (IStereoElement se : mol.stereoElements()) { switch (se.getConfigClass()) { case IStereoElement.Tetrahedral: { IAtom focus = (IAtom) se.getFocus(); if (focus.getImplicitHydrogenCount() == 1 && shouldAddH(mol, focus, mol.getConnectedBondsList(focus))) { focus.setImplicitHydrogenCount(0); IAtom hydrogen = sproutHydrogen(mol, focus); IStereoElement tmp = se.map(Collections.singletonMap(focus, hydrogen)); // need to keep focus same TetrahedralChirality e = new TetrahedralChirality(focus, (IAtom[]) tmp.getCarriers().toArray(new IAtom[4]), tmp.getConfig()); e.setGroupInfo(se.getGroupInfo()); ses.add(e); } else { ses.add(se); } } break; case IStereoElement.CisTrans: { IBond focus = (IBond) se.getFocus(); IAtom begin = focus.getBegin(); IAtom end = focus.getEnd(); IAtom hydrogenBegin = null; IAtom hydrogenEnd = null; if (begin.getImplicitHydrogenCount() == 1 && shouldAddH(mol, begin, mol.getConnectedBondsList(begin))) { begin.setImplicitHydrogenCount(0); hydrogenBegin = sproutHydrogen(mol, begin); } if (end.getImplicitHydrogenCount() == 1 && shouldAddH(mol, end, mol.getConnectedBondsList(end))) { end.setImplicitHydrogenCount(0); hydrogenEnd = sproutHydrogen(mol, end); } if (hydrogenBegin != null || hydrogenEnd != null) { Map<IAtom, IAtom> map = new HashMap<>(); map.put(begin, hydrogenBegin); map.put(end, hydrogenEnd); ses.add(se.map(map)); } else { ses.add(se); } } break; case IStereoElement.Allenal: { IAtom focus = (IAtom) se.getFocus(); IAtom[] terminals = ExtendedTetrahedral.findTerminalAtoms(mol, focus); IAtom hydrogen1 = null; IAtom hydrogen2 = null; if (terminals[0].getImplicitHydrogenCount() == 1) { terminals[0].setImplicitHydrogenCount(0); hydrogen1 = sproutHydrogen(mol, terminals[0]); } if (terminals[1].getImplicitHydrogenCount() == 1) { terminals[1].setImplicitHydrogenCount(0); hydrogen2 = sproutHydrogen(mol, terminals[1]); } if (hydrogen1 != null || hydrogen2 != null) { Map<IAtom, IAtom> map = new HashMap<>(); if (hydrogen1 != null) map.put(terminals[0], hydrogen1); if (hydrogen2 != null) map.put(terminals[1], hydrogen2); // find as focus is not one of the terminals IStereoElement<IAtom, IAtom> tmp = se.map(map); ses.add(tmp); } else { ses.add(se); } } break; default: ses.add(se); break; } } mol.setStereoElements(ses); } break; case Provided: default: break; } } private boolean shouldAddH(IAtomContainer mol, IAtom atom, Iterable<IBond> bonds) { int count = 0; for (IBond bond : bonds) { IAtom nbr = bond.getOther(atom); if (bond.isInRing()) { ++count; } else { for (IStereoElement se : mol.stereoElements()) { if (se.getConfigClass() == IStereoElement.TH && se.getFocus().equals(nbr)) { count++; } } } // hydrogen isotope if (nbr.getAtomicNumber() == 1 && nbr.getMassNumber() != null) return true; } return count == 3; } private IAtom sproutHydrogen(IAtomContainer mol, IAtom focus) { IAtom hydrogen = mol.getBuilder().newAtom(); hydrogen.setAtomicNumber(1); hydrogen.setSymbol("H"); hydrogen.setImplicitHydrogenCount(0); mol.addAtom(hydrogen); mol.addBond(mol.indexOf(focus), mol.getAtomCount() - 1, IBond.Order.SINGLE); return mol.getAtom(mol.getAtomCount() - 1); } private void contractHydrates(IAtomContainer mol) { Set<IAtom> hydrate = new HashSet<>(); for (IAtom atom : mol.atoms()) { if (atom.getAtomicNumber() == 8 && atom.getImplicitHydrogenCount() == 2 && mol.getConnectedAtomsList(atom).size() == 0) hydrate.add(atom); } if (hydrate.size() < 2) return; @SuppressWarnings("unchecked") List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS, List.class); if (sgroups == null) mol.setProperty(CDKConstants.CTAB_SGROUPS, sgroups = new ArrayList<>()); else sgroups = new ArrayList<>(sgroups); if (sgroups.size() == 1 && sgroups.get(0).getType() == SgroupType.CtabAbbreviation) { Sgroup sgrp = sgroups.get(0); boolean okay = true; Set<IAtom> atoms = sgrp.getAtoms(); for (IAtom a : hydrate) { if (atoms.contains(a)) { okay = false; break; } } if (okay && sgrp.getAtoms().size() + hydrate.size() == mol.getAtomCount()) { for (IAtom a : hydrate) sgrp.addAtom(a); sgrp.setSubscript(sgrp.getSubscript() + '·' + hydrate.size() + "H2O"); } } else { Sgroup sgrp = new Sgroup(); for (IAtom atom : hydrate) sgrp.addAtom(atom); sgrp.putValue(SgroupKey.CtabParentAtomList, Collections.singleton(hydrate.iterator().next())); sgrp.setType(SgroupType.CtabMultipleGroup); sgrp.setSubscript(Integer.toString(hydrate.size())); sgroups.add(sgrp); } } private boolean add(Set<IAtom> set, Set<IAtom> atomsToAdd) { boolean res = true; for (IAtom atom : atomsToAdd) { if (!set.add(atom)) res = false; } return res; } private void abbreviate(IReaction rxn, String mode, String annotate) { Multimap<IAtomContainer, Sgroup> sgroupmap = ArrayListMultimap.create(); switch (mode.toLowerCase()) { case "true": case "on": case "yes": for (IAtomContainer mol : rxn.getReactants().atomContainers()) { Set<IAtom> atoms = new HashSet<>(); List<Sgroup> newSgroups = new ArrayList<>(); for (Sgroup sgroup : abbreviations.generate(mol)) { if (add(atoms, sgroup.getAtoms())) newSgroups.add(sgroup); } contractHydrates(mol); sgroupmap.putAll(mol, newSgroups); } for (IAtomContainer mol : rxn.getProducts().atomContainers()) { Set<IAtom> atoms = new HashSet<>(); List<Sgroup> newSgroups = new ArrayList<>(); for (Sgroup sgroup : abbreviations.generate(mol)) { if (add(atoms, sgroup.getAtoms())) newSgroups.add(sgroup); } contractHydrates(mol); sgroupmap.putAll(mol, newSgroups); } for (IAtomContainer mol : rxn.getAgents().atomContainers()) { reagents.apply(mol); abbreviations.apply(mol); contractHydrates(mol); } break; case "groups": for (IAtomContainer mol : rxn.getAgents().atomContainers()) { abbreviations.apply(mol); contractHydrates(mol); } break; case "reagents": for (IAtomContainer mol : rxn.getAgents().atomContainers()) { reagents.apply(mol); contractHydrates(mol); } break; } Set<String> include = new HashSet<>(); for (Map.Entry<IAtomContainer, Sgroup> e : sgroupmap.entries()) { final IAtomContainer mol = e.getKey(); final Sgroup abbrv = e.getValue(); int numAtoms = mol.getAtomCount(); if (abbrv.getBonds().isEmpty()) { include.add(abbrv.getSubscript()); } else { int numAbbr = abbrv.getAtoms().size(); double f = numAbbr / (double) numAtoms; if (numAtoms - numAbbr > 1 && f <= 0.4) { include.add(abbrv.getSubscript()); } } } for (Map.Entry<IAtomContainer, Collection<Sgroup>> e : sgroupmap.asMap().entrySet()) { final IAtomContainer mol = e.getKey(); List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS); if (sgroups == null) sgroups = new ArrayList<>(); else sgroups = new ArrayList<>(sgroups); mol.setProperty(CDKConstants.CTAB_SGROUPS, sgroups); for (Sgroup abbrv : e.getValue()) { if (include.contains(abbrv.getSubscript())) sgroups.add(abbrv); } } } private void abbreviate(IAtomContainer mol, String mode, String annotate) { switch (mode.toLowerCase()) { case "true": case "on": case "yes": case "groups": contractHydrates(mol); abbreviations.apply(mol); break; case "reagents": contractHydrates(mol); break; } // remove abbreviations of mapped atoms if ("mapidx".equals(annotate)) { List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS); List<Sgroup> filtered = new ArrayList<>(); if (sgroups != null) { for (Sgroup sgroup : sgroups) { // turn off display short-cuts if (sgroup.getType() == SgroupType.CtabAbbreviation || sgroup.getType() == SgroupType.CtabMultipleGroup) { boolean okay = true; for (IAtom atom : sgroup.getAtoms()) { if (atom.getProperty(CDKConstants.ATOM_ATOM_MAPPING) != null) { okay = false; break; } } if (okay) filtered.add(sgroup); } else { filtered.add(sgroup); } } mol.setProperty(CDKConstants.CTAB_SGROUPS, filtered); } } } private boolean isRxnSmi(String smi) { return smi.split(" ")[0].contains(">"); } private IAtomContainer loadMol(String str) throws CDKException { if (str.contains("V2000")) { try (MDLV2000Reader mdlr = new MDLV2000Reader(new StringReader(str))) { return mdlr.read(SilentChemObjectBuilder.getInstance().newAtomContainer()); } catch (CDKException | IOException e3) { throw new CDKException("Could not parse input"); } } else { try { return smipar.parseSmiles(str); } catch (CDKException ex) { SmilesParser smipar2 = new SmilesParser(builder); smipar2.kekulise(false); return smipar2.parseSmiles(str); } } } private HttpEntity<byte[]> makeResponse(byte[] bytes, String contentType) { HttpHeaders header = new HttpHeaders(); String type = contentType.substring(0, contentType.indexOf('/')); String subtype = contentType.substring(contentType.indexOf('/') + 1, contentType.length()); header.setContentType(new MediaType(type, subtype)); header.add("Access-Control-Allow-Origin", "*"); // header.set(HttpHeaders.CACHE_CONTROL, "public, max-age=31536000"); header.setContentLength(bytes.length); return new HttpEntity<>(bytes, header); } /** * Set the depiction style. * * @param generator the generator * @param style style type * @return configured depiction generator */ private static DepictionGenerator withStyle(DepictionGenerator generator, String style) { switch (style) { case "cow": generator = generator.withAtomColors(new CDK2DAtomColors()) .withBackgroundColor(Color.WHITE) .withOuterGlowHighlight(); break; case "cot": generator = generator.withAtomColors(new CDK2DAtomColors()) .withBackgroundColor(new Color(0, 0, 0, 0)) .withOuterGlowHighlight(); break; case "bow": generator = generator.withAtomColors(new UniColor(Color.BLACK)) .withBackgroundColor(Color.WHITE); break; case "bot": generator = generator.withAtomColors(new UniColor(Color.BLACK)) .withBackgroundColor(new Color(0, 0, 0, 0)); break; case "wob": generator = generator.withAtomColors(new UniColor(Color.WHITE)) .withBackgroundColor(Color.BLACK); break; case "wot": generator = generator.withAtomColors(new UniColor(Color.WHITE)) .withBackgroundColor(new Color(0, 0, 0, 0)); break; case "cob": generator = generator.withAtomColors(new CobColorer()) .withBackgroundColor(Color.BLACK) .withOuterGlowHighlight(); break; case "nob": generator = generator.withAtomColors(new NobColorer()) .withBackgroundColor(Color.BLACK) .withOuterGlowHighlight(); break; } return generator; } /** * Color-on-black atom colors. */ private static final class CobColorer implements IAtomColorer { private final CDK2DAtomColors colors = new CDK2DAtomColors(); @Override public Color getAtomColor(IAtom atom) { Color res = colors.getAtomColor(atom); if (res.equals(Color.BLACK)) return Color.WHITE; else return res; } @Override public Color getAtomColor(IAtom atom, Color color) { Color res = colors.getAtomColor(atom); if (res.equals(Color.BLACK)) return Color.WHITE; else return res; } } /** * Neon-on-black atom colors. */ private static final class NobColorer implements IAtomColorer { private final CDK2DAtomColors colors = new CDK2DAtomColors(); private final Color NEON = new Color(0x00FF0E); @Override public Color getAtomColor(IAtom atom) { Color res = colors.getAtomColor(atom); if (res.equals(Color.BLACK)) return NEON; else return res; } @Override public Color getAtomColor(IAtom atom, Color color) { Color res = colors.getAtomColor(atom, color); if (res.equals(Color.BLACK)) return NEON; else return res; } } /** * Find matching atoms and bonds in the reaction or molecule. * * @param sma SMARTS pattern * @param rxn reaction * @param mol molecule * @return set of matched atoms and bonds */ private Set<IChemObject> findHits(final String sma, final IReaction rxn, final IAtomContainer mol, final int limit) { Set<IChemObject> highlight = new HashSet<>(); if (!sma.isEmpty()) { SmartsPattern smartsPattern; try { smartsPattern = SmartsPattern.create(sma, null); } catch (Exception | Error e) { return Collections.emptySet(); } if (mol != null) { for (Map<IChemObject, IChemObject> m : smartsPattern.matchAll(mol) .limit(limit) .uniqueAtoms() .toAtomBondMap()) { for (Map.Entry<IChemObject, IChemObject> e : m.entrySet()) { highlight.add(e.getValue()); } } } else if (rxn != null) { for (Map<IChemObject, IChemObject> m : smartsPattern.matchAll(rxn) .limit(limit) .uniqueAtoms() .toAtomBondMap()) { for (Map.Entry<IChemObject, IChemObject> e : m.entrySet()) { highlight.add(e.getValue()); } } } } return highlight; } @ExceptionHandler({Exception.class, InvalidSmilesException.class}) public static ResponseEntity<Object> handleException(Exception ex, WebRequest request) { if (ex instanceof InvalidSmilesException) { InvalidSmilesException ise = (InvalidSmilesException) ex; String mesg = ise.getMessage(); String disp = ""; if (mesg.endsWith("^")) { int i = mesg.indexOf(":\n"); if (i >= 0) { disp = mesg.substring(i + 2); mesg = mesg.substring(0, i); } } return new ResponseEntity<>("<!DOCTYPE html><html>" + "<title>400 - Invalid SMILES</title>" + "<body><div>" + "<h1>Invalid SMILES</h1>" + mesg + "<pre>" + disp + "</pre>" + "</div></body>" + "</html>", new HttpHeaders(), HttpStatus.BAD_REQUEST); } else { return new ResponseEntity<>("<!DOCTYPE html><html><title>500 - Internal Server Error</title><body><div>" + "<h1>" + ex.getClass().getSimpleName() + "</h1>" + ex.getMessage() + "</div></body></html>", new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } }
package org.apereo.cas.support.saml.mdui; import org.apereo.cas.services.RegisteredService; import org.opensaml.core.xml.schema.XSString; import org.opensaml.core.xml.schema.XSURI; import org.opensaml.saml.ext.saml2mdui.Logo; import org.opensaml.saml.ext.saml2mdui.UIInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import javax.annotation.Nullable; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * This is {@link SimpleMetadataUIInfo}. * * @author Misagh Moayyed * @since 4.1.0 */ public class SimpleMetadataUIInfo implements Serializable { private static final Logger LOGGER = LoggerFactory.getLogger(SimpleMetadataUIInfo.class); private static final int DEFAULT_IMAGE_SIZE = 32; private static final long serialVersionUID = -1434801982864628179L; private transient UIInfo uiInfo; private transient RegisteredService registeredService; /** * Instantiates a new Simple metadata uI info. * * @param registeredService the registered service */ public SimpleMetadataUIInfo(final RegisteredService registeredService) { this(null, registeredService); } /** * Instantiates a new Simple mdui info. * * @param uiInfo the ui info * @param registeredService the registered service */ public SimpleMetadataUIInfo(@Nullable final UIInfo uiInfo, final RegisteredService registeredService) { this.uiInfo = uiInfo; this.registeredService = registeredService; } /** * Gets description. * * @return the description */ public String getDescription() { final Collection<String> items = getDescriptions(); if (items.isEmpty()) { return this.registeredService.getDescription(); } return StringUtils.collectionToDelimitedString(items, "."); } /** * Gets descriptions. * * @return the descriptions */ public Collection<String> getDescriptions() { if (this.uiInfo != null) { return getStringValues(this.uiInfo.getDescriptions()); } return new ArrayList<>(); } /** * Gets display name. * * @return the display name */ public String getDisplayName() { final Collection<String> items = getDisplayNames(); if (items.isEmpty()) { return this.registeredService.getName(); } return StringUtils.collectionToDelimitedString(items, "."); } /** * Gets display names. * * @return the display names */ public Collection<String> getDisplayNames() { if (this.uiInfo != null) { return getStringValues(this.uiInfo.getDisplayNames()); } return new ArrayList<>(); } /** * Gets information uRL. * * @return the information uRL */ public String getInformationURL() { final Collection<String> items = getInformationURLs(); return StringUtils.collectionToDelimitedString(items, "."); } /** * Gets information uR ls. * * @return the information uR ls */ public Collection<String> getInformationURLs() { if (this.uiInfo != null) { return getStringValues(this.uiInfo.getInformationURLs()); } return new ArrayList<>(); } /** * Gets privacy statement uRL. * * @return the privacy statement uRL */ public String getPrivacyStatementURL() { final Collection<String> items = getPrivacyStatementURLs(); return StringUtils.collectionToDelimitedString(items, "."); } /** * Gets privacy statement uR ls. * * @return the privacy statement uR ls */ public Collection<String> getPrivacyStatementURLs() { if (this.uiInfo != null) { return getStringValues(this.uiInfo.getPrivacyStatementURLs()); } return new ArrayList<>(); } /** * Gets logo height. * * @return the logo url */ public long getLogoWidth() { try { final Collection<Logo> items = getLogoUrls(); if (!items.isEmpty()) { return items.iterator().next().getWidth(); } } catch (final Exception e) { LOGGER.debug(e.getMessage(), e); } return DEFAULT_IMAGE_SIZE; } /** * Gets logo height. * * @return the logo url */ public long getLogoHeight() { try { final Collection<Logo> items = getLogoUrls(); if (!items.isEmpty()) { return items.iterator().next().getHeight(); } } catch (final Exception e) { LOGGER.debug(e.getMessage(), e); } return DEFAULT_IMAGE_SIZE; } /** * Gets logo url. * * @return the logo url */ public URL getLogoUrl() { try { final Collection<Logo> items = getLogoUrls(); if (!items.isEmpty()) { return new URL(items.iterator().next().getURL()); } } catch (final Exception e) { LOGGER.debug(e.getMessage(), e); } return this.registeredService.getLogo(); } /** * Gets logo urls. * * @return the logo urls */ public Collection<Logo> getLogoUrls() { final List<Logo> list = new ArrayList<>(); if (this.uiInfo != null) { list.addAll(this.uiInfo.getLogos().stream().collect(Collectors.toList())); } return list; } /** * Gets string values from the list of mdui objects. * * @param items the items * @return the string values */ private static Collection<String> getStringValues(final List<?> items) { final List<String> list = new ArrayList<>(); for (final Object d : items) { if (d instanceof XSURI) { list.add(((XSURI) d).getValue()); } else if (d instanceof XSString) { list.add(((XSString) d).getValue()); } } return list; } public void setUIInfo(final UIInfo uiInfo) { this.uiInfo = uiInfo; } }
package com.telefonica.claudia.slm.lifecyclemanager; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InvalidClassException; import java.io.PrintWriter; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; 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.dmtf.schemas.ovf.envelope._1.VirtualSystemType; import org.json.JSONException; import com.telefonica.claudia.configmanager.ConfiguratorFactory; import com.telefonica.claudia.configmanager.lb.LoadBalancerConfigurator; import com.telefonica.claudia.slm.common.DbManager; import com.telefonica.claudia.slm.common.SMConfiguration; import com.telefonica.claudia.slm.deployment.Customer; import com.telefonica.claudia.slm.deployment.Rule; import com.telefonica.claudia.slm.deployment.ServiceApplication; import com.telefonica.claudia.slm.deployment.ServiceKPI; import com.telefonica.claudia.slm.deployment.VEE; import com.telefonica.claudia.slm.deployment.VEEReplica; import com.telefonica.claudia.slm.deployment.hwItems.CPU; import com.telefonica.claudia.slm.deployment.hwItems.Disk; import com.telefonica.claudia.slm.deployment.hwItems.DiskConf; import com.telefonica.claudia.slm.deployment.hwItems.NIC; import com.telefonica.claudia.slm.deployment.hwItems.NICConf; import com.telefonica.claudia.slm.deployment.hwItems.Network; import com.telefonica.claudia.slm.deployment.paas.Product; import com.telefonica.claudia.slm.eventsBus.events.SMControlEvent; import com.telefonica.claudia.slm.maniParser.ManiParserException; import com.telefonica.claudia.slm.maniParser.Parser; import com.telefonica.claudia.slm.monitoring.MonitoringRestBusConnector; import com.telefonica.claudia.slm.monitoring.WasupHierarchy; import com.telefonica.claudia.slm.naming.FQN; import com.telefonica.claudia.slm.naming.ReservoirDirectory; import com.telefonica.claudia.slm.paas.PaasUtils; import com.telefonica.claudia.slm.paas.vmiHandler.MonitoringClient; import com.telefonica.claudia.slm.paas.vmiHandler.RECManagerClient; import com.telefonica.claudia.slm.rulesEngine.RulesEngine; import com.telefonica.claudia.slm.serviceconfiganalyzer.ServiceConfigurationAnalyzer; import com.telefonica.claudia.slm.vmiHandler.TCloudClient; import com.telefonica.claudia.slm.vmiHandler.VEEReplicaAllocationResult; import com.telefonica.claudia.slm.vmiHandler.VEEReplicaUpdateResult; import com.telefonica.claudia.slm.vmiHandler.VMIHandler; import com.telefonica.claudia.slm.vmiHandler.VMIHandler.SubmissionModelType; import com.telefonica.claudia.slm.vmiHandler.exceptions.AccessDeniedException; import com.telefonica.claudia.slm.vmiHandler.exceptions.CommunicationErrorException; import com.telefonica.claudia.slm.vmiHandler.exceptions.NotEnoughResourcesException; import com.telefonica.claudia.slm.vmiHandler.exceptions.VEEReplicaDescriptionMalformedException; /** * The FSM (Finite State Machine) manages the lifecycle of a single service. FSM * is a runnable class, that is started by the LCC. * * The service lifecycle, represented by the run() method, consists of an * event-consuming loop. Each service has a matching event queue in the LCC, * where all the control events are enqueued. In each step of the lifecycle, a * new event is pulled out of the queue and treated in the getNextState() * method. This method will transition the FSM to the appropiate state after any * completed action. * * When a service is created, first of all the init() method is called (INIT * state). In this method, all the needed clients are created and the OVF * descriptor is parsed so all the information about the service is translated * into a class hierarchy of classes in the deployment package. Once it is * parsed, the Service transitions to the SPECIFIED state where the service will * be really deployed. */ public class FSM extends Thread implements Serializable { private static final long serialVersionUID = -8902978852760714189L; private static Logger logger = Logger.getLogger("Service"); // Internal state information @SuppressWarnings("unused") private long monitFreq = 1000; /** * This flag should be set for this situations that causa a non-recoverable * error. It leads the machine automatically to the ERROR state. */ private boolean abort = false; /** * This message will be printed in the abort message of the FSM to be able * to recognize the problem that lead the FSM to abort its execution. */ private String abortMessage = null; /** * Determines whether the Finite state machine should continue its execution * or not. */ private boolean finishExecution = false; /** * Whenever an elasticity rule is fired (and so a creation or removement of * a replica), the timestamps of the beginning and ending of this action are * stored in this interval (the beginning in the first member of the array, * the ending in the last one) for each vee. If an event is recieved to * create or deploy a replica, the timestamp of the event is checked against * the interval for this veee, so to avoid creating more than one replica * due to the same load increment (this situation will happen whenever the * monitoring period is greater than the time needed to make one of those * actions). */ public Map<VEE, long[]> lastElasticityInterval = new HashMap<VEE, long[]>(); /** * Margin under and over the elasticity interval, to prevent events out of * order to fire actions supposed to be prevented by the elasticity interval * (the interval is calculated with the timestamp of the event firing the * action), and to let the deployed or removed replica affect the real load * of the service before reevaluating the need of doing some action. */ private final static long ELASTICITY_MARGIN = 30 * 1000; // State-related information private int currentState, nextState;; public static final int numStates = 6; public static final int NONE = 0; public static final int INIT = 1; public static final int RUNNING = 2; public static final int ERROR = 3; public static final int RECONFIGURED = 4; public static final int FINISHED = 5; /** * Determines the polling frequency the FSM will use to check the event * buffer. */ private static final long POLLING_PERIOD = 1000; // Service related information /** * Service application the FSM manages. */ public ServiceApplication sap; /** * URL of the OVF Descriptor used to deploy the service. */ private String xmlFile = ""; /** * Scale up and down factors. */ public float scaleUpPercentage; public float scaleDownPercentage; /** * Lazy scale down time. */ public int lazyScaleDownTime; // VEE Related information /** * Array containing the vees. Is exactly the same information we have in * vees. * * TODO: Is this synchronized with the hashset? */ private VEE[] veeArray; /** * Set with the currently deployed replicas. */ private Set<VEEReplica> veesRollBack = new HashSet<VEEReplica>(); /** * Set of nics used to deploy the service. It will be used to properly * undeploy them once the service has finished. */ Set<Network> nicsToDeploy; // Internal references to other blocks of the SM /** * Reference to the Lifecycle Controller that created the FSM (also the one * who have the evente queue). */ private LifecycleController lcc; private RulesEngine rle; /** * OVF Parser. The parser is used for two kinds of actions: it is used first * time the service is deployed to create the class hierarchy of the service * components; and its also used to generate the OVF environment for each * replica once it is deployed (whether it is the first deployement or a * elasticity action). */ public Parser parser; /** * VMI client used to comunicate with the underlying layer in order to * deploy replicas and other resources. */ public VMIHandler vmi = null; // Deployment information private static final String repositoryDir = "./repository"; private static final String customImagesDir = repositoryDir + SMConfiguration.getInstance().getImagesServerPath(); private static final String protocol = "http: /** * Monitoring client for the service. It holds the hierarchy of measurement * types for this service and also acts as the client for client * interactions with Wasup (whenever a measurement reaches de SM it is * redirected to Wasup for data mining). */ private WasupHierarchy wasupClient; private boolean setSwap = false; /** * Property map defining the customization info for the vees. * * TODO: it seems strange to have the same customization information for all * the types of vees. TODO: this seems more appropiate as a local attribute * in the getNextState method. */ private HashMap<String, String> replicaCustomInfo; private LoadBalancerConfigurator lbConfigurator; /** * Determines the kind of events permitted in each of the different FSM * states. The key of the map represents the state and the value is a list * of the accepted events. */ private static Map<Integer, List<Integer>> stateEventMatrix = new HashMap<Integer, List<Integer>>(); static { stateEventMatrix.put(NONE, new ArrayList<Integer>()); stateEventMatrix.put(INIT, new ArrayList<Integer>()); stateEventMatrix.get(INIT).add(SMControlEvent.START_SERVICE); stateEventMatrix.put(RUNNING, new ArrayList<Integer>()); stateEventMatrix.get(RUNNING).add( SMControlEvent.ELASTICITY_RULE_VIOLATION); stateEventMatrix.get(RUNNING).add(SMControlEvent.NEW_RULE_ADDED); stateEventMatrix.get(RUNNING).add(SMControlEvent.RULE_CHANGED); stateEventMatrix.get(RUNNING).add(SMControlEvent.UNDEPLOY_SERVICE); stateEventMatrix.get(RUNNING).add(SMControlEvent.GET_MONITORING_DATA); stateEventMatrix.put(ERROR, new ArrayList<Integer>()); stateEventMatrix.put(RECONFIGURED, new ArrayList<Integer>()); stateEventMatrix.put(FINISHED, new ArrayList<Integer>()); } public FSM(LifecycleController lcc, String endPoint) { this.lcc = lcc; currentState = NONE; nextState = currentState; try { this.lbConfigurator = ConfiguratorFactory.getInstance() .createConfigManager(LoadBalancerConfigurator.class); } catch (InvalidClassException e) { logger.fatal("Invalid Configurator", e); } } public FSM() { try { this.lbConfigurator = ConfiguratorFactory.getInstance() .createConfigManager(LoadBalancerConfigurator.class); } catch (InvalidClassException e) { logger.fatal("Invalid Configurator", e); } } public int getCurrentState() { return this.currentState; } public String getStateText() { switch (currentState) { case NONE: return "NONE"; case INIT: return "INIT"; case RUNNING: return "RUNNING"; case ERROR: return "ERROR"; case RECONFIGURED: return "RECONFIGURED"; case FINISHED: return "FINISHED"; default: return "UNKNOWN"; } } public void loadManifest(String mani) { this.xmlFile = mani; } public void loadRuleEngine(RulesEngine rulesEngine) { rle = rulesEngine; } /** * Method for the LCC to set the monitoring frequency upon SP request. */ protected void setMonFreq(long freq) { monitFreq = freq; } @SuppressWarnings("unchecked") private void registerInDirectory() { VEE vee; Rule rule; ServiceKPI kpi; logger.info("Service Application: " + sap.getSerAppName()); Set<VEE> veeVector = sap.getVEEs(); Set<Rule> ruleVector = sap.getServiceRules(); Set<ServiceKPI> kpiVector = sap.getServiceKPIs(); // Register ServiceApp ReservoirDirectory.getInstance().registerObject(sap.getFQN(), sap); // add VEEs to Service Iterator veeIterator = veeVector.iterator(); if (!veeIterator.hasNext()) logger.info("No VEEs defined"); while (veeIterator.hasNext()) { vee = (VEE) veeIterator.next(); logger.info("VEE " + vee.getVEEName()); ReservoirDirectory.getInstance().registerObject(vee.getFQN(), vee); } // add KPIs Iterator kpiIterator = kpiVector.iterator(); if (!kpiIterator.hasNext()) logger.info("No KPIs defined"); while (kpiIterator.hasNext()) { kpi = (ServiceKPI) kpiIterator.next(); logger.info("KPI " + kpi.getKPIName()); ReservoirDirectory.getInstance().registerObject(kpi.getFQN(), kpi); } // add Rules Iterator ruleIterator = ruleVector.iterator(); if (!ruleIterator.hasNext()) logger.info("No Rules defined"); while (ruleIterator.hasNext()) { rule = (Rule) ruleIterator.next(); logger.info("Rule " + rule.getName()); rule.configure((ServiceKPI) ReservoirDirectory.getInstance() .getObject(new FQN(rule.getKPIName()))); ReservoirDirectory.getInstance() .registerObject(rule.getFQN(), rule); } } /** * Initializes all the structures needed by the FSM to begin the service * lifecycle. * * @param serviceName * Name of the service to be created. */ @SuppressWarnings("unchecked") public void init(String serviceName, String customerName) { logger.info("Initiating FSM for service defined in file " + xmlFile + " , customer " + customerName); Customer client; // Check if customer already present in directory. FQN customerFQN = new Customer(customerName).getFQN(); if (ReservoirDirectory.getInstance().isNameRegistered(customerFQN)) { logger.info("Customer already present: " + customerFQN.toString()); client = (Customer) ReservoirDirectory.getInstance().getObject( customerFQN); } else { logger.info("New customer: " + customerFQN.toString() + ", registering in directory"); client = new Customer(customerName); ReservoirDirectory.getInstance().registerObject(client.getFQN(), client); DbManager.getDbManager().save(client); } try { parser = new Parser(xmlFile, client, serviceName); parser.parse(); } catch (ManiParserException ex) { logger.error( "ManiParserException when trying to parse manifest file " + xmlFile, ex); throw new Error( "ManiParserException when trying to parse manifest file " + xmlFile, ex); } logger.info("Manifest file successfully parsed"); sap = parser.getServiceApplication(); client.registerService(sap); registerInDirectory(); // inform its lcc that the service FSM has been created logger .info("Reporting to Lifecycle Controler the FSM has been created for Service Application"); lcc.registerFSM(sap.getFQN(), this); this.lcc.addCustomer(client); rle.configure(this); rle.claudiaRules2Drools(); boolean callSCA = false; if (callSCA) { try { ServiceConfigurationAnalyzer sca = new ServiceConfigurationAnalyzer(); logger.info("Calling Service Config Analyzer, client " + client.getCustomerName()); sap = sca.refineService(sap); } catch (Exception ex) { logger.error( "Exception caught when calling to Service Config Analyzer, message: " + ex.getMessage(), ex); } } else logger.info("Skipping SCA call..."); URL oneURL = null; try { oneURL = new URL("http", SMConfiguration.getInstance() .getVEEMHost(), SMConfiguration.getInstance().getVEEMPort(), "/"); logger.info("VEEM listening on URL " + oneURL); } catch (MalformedURLException ex) { } vmi = new TCloudClient(oneURL.toString()); // Initialize the WASUP client. if (SMConfiguration.getInstance().isWasupActive()) { try { wasupClient = WasupHierarchy.getWasupHierarchy(); } catch (Exception e) { logger.error("Error login to the WASUP: " + e.getMessage()); } catch (Throwable e) { logger.error("Unknow error connecting to WASUP: " + e.getMessage(), e); } } // Initialize the lastElasticityInterval Map for (VEE veeItr : sap.getVEEs()) lastElasticityInterval.put(veeItr, new long[2]); if (SMConfiguration.getInstance().isACDActive()) { try { vmi.sendACD(sap); } catch (Throwable t) { logger .error("The ACD could not be sent due to the following exception: " + t.getMessage()); } } DbManager.getDbManager().save(sap); currentState = INIT; nextState = currentState; } public void loadService(ServiceApplication sap) { logger.info("Loading service into the FSM: " + sap.getSerAppName()); this.sap = sap; try { parser = new Parser(sap.getXmlFile(), sap.getCustomer(), sap .getSerAppName()); } catch (ManiParserException ex) { logger.error( "ManiParserException when trying to parse manifest file " + xmlFile, ex); throw new Error( "ManiParserException when trying to parse manifest file " + xmlFile, ex); } parser.setServiceApplication(sap); registerInDirectory(); logger .info("Reporting to Lifecycle Controler the FSM has been created for Service Application"); lcc.registerFSM(sap.getFQN(), this); rle.configure(this); rle.claudiaRules2Drools(); URL oneURL = null; try { oneURL = new URL("http", SMConfiguration.getInstance() .getVEEMHost(), SMConfiguration.getInstance().getVEEMPort(), SMConfiguration.getInstance().getVEEMPath()); logger.info("VEEM listening on URL " + oneURL); } catch (MalformedURLException ex) { } vmi = new TCloudClient(oneURL.toString()); // Initialize the WASUP client. if (SMConfiguration.getInstance().isWasupActive()) { try { wasupClient = WasupHierarchy.getWasupHierarchy(); } catch (Exception e) { logger.error("Error login to the WASUP: " + e.getMessage()); } catch (Throwable e) { logger.error("Unknow error connecting to WASUP: " + e.getMessage(), e); } } // Initialize the lastElasticityInterval Map for (VEE veeItr : sap.getVEEs()) lastElasticityInterval.put(veeItr, new long[2]); // Recreate the array with the NICS to be undeployed nicsToDeploy = sap.getNetworks(); veesRollBack.addAll(DbManager.getDbManager().getList(VEEReplica.class)); rle.run(); currentState = RUNNING; nextState = currentState; } /** * Main process of the FSM. The main loop consists of two actions: consuming * an event from the Lifecycle, and transitioning to the next state, using * the information on that event. * * Two conditions finish the execution of the FSM: the abort flag, that is * set if the abort() method is called during the SPECIFIED state, makes the * service finish with an error log; the finishExecution is set when the * Service is done (it has received the undeploy message). * */ public void run() { while (!finishExecution) { currentState = nextState; try { // wait for the arrival of the order to deploy the service Thread.sleep(POLLING_PERIOD); this.interrupt(); if (abort) { logger .error("Service lifecycle execution aborted for service [" + sap.getFQN() + "], due to the following reason: " + abortMessage); break; } } catch (InterruptedException e) { try { // ask whether is there any message nextState = getNextState(lcc.deliver(sap.getFQN()), currentState); } catch (InterruptedException ex) { logger.error("InterruptedException caught ", ex); } catch (MalformedURLException ex) { logger.error("MalformedURLException caught", ex); } } } // Remove the FSM from the Lifecycle controller lcc.deregisterFSM(this.getServiceFQN()); if (finishExecution) logger.info("Service lifecycle finished cleanly"); } public FQN getServiceFQN() { return (sap.getFQN()); } public ServiceApplication getServiceApplication() { return this.sap; } /** * Used to check whether an action should be discarded due to the elasticity * interval. Used to prevent the FSM to execute out of date actions. * * @param vee * VEE that is being the target of the action. There is a * different elasticity interval for each vee. * * @param time * Time when the event was generated. * * @return <i>true</i> if the action can proceed. <i>false</i> if the action * should be discarded. * */ private boolean checkElasticityInterval(VEE vee, long time) { long[] interval = lastElasticityInterval.get(vee); if (interval[0] == 0 || interval[1] == 0) return true; if (time < interval[0] || time > interval[1]) return true; return false; } public boolean startService() { // in this case we use an Array so as to sort it properly int g = 0; veeArray = new VEE[sap.getVEEs().size()]; for (Iterator<VEE> veeIt = sap.getVEEs().iterator(); veeIt.hasNext();) { veeArray[g] = veeIt.next(); g++; } // rearrange the array according to the order field in the VEE // object // VEE implements Comparable Arrays.sort(veeArray); // First of all, check the needed networks have been created. if (SMConfiguration.getInstance().getIpManagement()) { if (!checkAndDeployNetworks()) { abort("Network creation error"); return false; } } // for each VEE, get the required replicas for (int j = 0; j < veeArray.length; j++) { logger.info("Deployment step " + (j + 1) + ", VEE: " + veeArray[j].getVEEName() + " with " + veeArray[j].getInitReplicas() + " replicas"); // get the required number of replicas. Set<VEEReplica> replicas = createReplica(veeArray[j], veeArray[j].getInitReplicas()); if (replicas == null) { abort("Replicas could not be created for vee [" + veeArray[j].getFQN() + "]"); return false; } if (SMConfiguration.getInstance().isPaaSAware()) { RECManagerClient rec = new RECManagerClient(SMConfiguration.getInstance().getSdcUrl()); PaasUtils paas = new PaasUtils(); try { rec.installProductsInService (veeArray[j]); } catch (AccessDeniedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CommunicationErrorException e1) { // TODO Auto-generated catch block logger.error("Error to install the product " + e1.getMessage()); abortServiceAlreadyDeployed("Error to install the product " + e1.getMessage()+ ". Replicas could not be created for vee [" + veeArray[j].getFQN() + "]"); return false; } for (VEEReplica replica: replicas) { if (paas.isPaaSAware(veeArray[j])) { // if it is paas aware, we have to install the software..... String xml = paas.getVEE(replica); String ip = paas.getVeePaaSIpFromXML (xml); logger.info("IP for "+ veeArray[j].getVEEName() + " " + ip); String [] result = paas.getVeePaaSUserNamePaaswordFromXML(xml); System.out.println ("username " + result[0] + " pass " + result[1]); // veeArray[j].setUserName(result[0]); // veeArray[j].setPassword(result[1]); try { rec.installProductsInVm (veeArray[j], ip, result[0], result[1]); } catch (Exception e1) { // TODO Auto-generated catch block logger.error("Error to install the product " + e1.getMessage()); abortServiceAlreadyDeployed("Error to install the product " + e1.getMessage()+ ". Error to configure the VM]"); return false; } for (Product product: veeArray[j].getProducts()) { try { paas.installProduct(SMConfiguration.getInstance().getSdcUrl(),product, ip); } catch (Exception e) { // TODO Auto-generated catch block logger.error("Error to install the product " + e.getMessage()); abortServiceAlreadyDeployed("Error to install the product " + e.getMessage()+ ". Replicas could not be created for vee [" + veeArray[j].getFQN() + "]"); return false; } } } } } } rle.run(); logger.info("DONE with ALL replicas and ALL VEEs "); // Once all the VEES are working, it's time to replicate its structure // WASUP if (SMConfiguration.getInstance().isMonitoringEnabled()) { try { MonitoringClient client = new MonitoringClient (SMConfiguration.getInstance().getMonitoringUrl()); wasupClient.createWasupHierarchy(getServiceApplication()); } catch (IOException e) { logger .error("Error creating the WASUP monitorization hierarchy: " + e.getMessage()); } catch (JSONException e) { logger.error("Error parsing the response of a WASUP request: " + e.getMessage()); } catch (Throwable e) { logger.error("Unknow error connecting to WASUP: " + e.getMessage(), e); } } if (SMConfiguration.getInstance().isWasupActive()) { try { wasupClient.createWasupHierarchy(getServiceApplication()); } catch (IOException e) { logger .error("Error creating the WASUP monitorization hierarchy: " + e.getMessage()); } catch (JSONException e) { logger.error("Error parsing the response of a WASUP request: " + e.getMessage()); } catch (Throwable e) { logger.error("Unknow error connecting to WASUP: " + e.getMessage(), e); } } return true; } public boolean elasticityCreateReplica(String veeType, int replicaNumber, long initialTime, boolean checkinterval) { VEE vee2Replicate = (VEE) ReservoirDirectory.getInstance().getObject( new FQN(veeType)); if (!checkElasticityInterval(vee2Replicate, initialTime) && checkinterval==true) { logger.warn("Action discarded due to the Elasticity Interval."); return false; } // Save the beginning of the interval lastElasticityInterval.get(vee2Replicate)[0] = initialTime - ELASTICITY_MARGIN; // check that the current number of replicas does not // exceed the maximum int currentReplicas = vee2Replicate.getCurrentReplicas(); if (currentReplicas < vee2Replicate.getMaxReplicas()) { if (createReplica(vee2Replicate, replicaNumber) == null) logger.error("Replica could not be created."); else logger.info("Replica created successfully"); } else { logger .warn("Replica was not created, for the VEE already have the maximum number of replicas"); } // Save the ending part of the interval lastElasticityInterval.get(vee2Replicate)[1] = System .currentTimeMillis() + ELASTICITY_MARGIN; return true; } public boolean elasticityRemoveReplica(String veeType, long initialTime, boolean checkinterval) { VEE vee2Plicate = (VEE) ReservoirDirectory.getInstance().getObject( new FQN(veeType)); if (!checkElasticityInterval(vee2Plicate, initialTime) && checkinterval==true) { logger.warn("Action discarded due to the Elasticity Interval."); return false; } // Save the beginning of the interval lastElasticityInterval.get(vee2Plicate)[0] = initialTime - ELASTICITY_MARGIN; // check that the current number of replicas is not going to be // under the minimum if (vee2Plicate.getCurrentReplicas() > vee2Plicate.getMinReplicas()) { Set<VEEReplica> replicas = vee2Plicate.getVEEReplicas(); // assume all the replicas can equally be removed /* int maxreplica = 0; Set<VEEReplica> plicateSet = new HashSet<VEEReplica>(); VEEReplica removeCandidate = null; for (Iterator<VEEReplica> removeIt = replicas.iterator(); removeIt .hasNext();) { VEEReplica plicate = (VEEReplica) removeIt.next(); if ((plicate.getId()) > maxreplica) { maxreplica = plicate.getId(); removeCandidate = plicate; } }*/ Set<VEEReplica> plicateSet = getReplicaCandiates (replicas); if (plicateSet == null) { logger.error("No replicas to delete "); return true; } for (VEEReplica removeCandidate: plicateSet) { Set<VEEReplica> aux = new HashSet<VEEReplica>(); aux.add(removeCandidate); // invoke the appropriate VMI methods if (shutdown(aux)) { // Remove it from wasup /* if (SMConfiguration.getInstance().isWasupActive()) { try { wasupClient.removeNode(removeCandidate); } catch (IOException e) { logger .error("The replica could not be removed from WASUP: " + e.getMessage()); } catch (Throwable e) { logger.error( "Unknow error connecting to WASUP: " + e.getMessage(), e); } }*/ FQN fqn = removeCandidate.getFQN(); ReservoirDirectory.getInstance().removeMatchingNames(fqn); // update the data model by removing a new // replica and increasing the number of // current replicas //vee2Plicate.getVEEReplicas().remove(plicate); vee2Plicate.unregisterVEEReplica(removeCandidate); vee2Plicate.removeCurrentReplicas(); veesRollBack.remove(removeCandidate); if (vee2Plicate.isVEEReplicaRegistered(removeCandidate)){ logger.error("The replIca HAS NOT BEEN REMOVED"); } logger.info("" +"AFTER SCALING DOWN THERE ARE " + vee2Plicate.getCurrentReplicas()); return true; } else { logger.error("FAILURE WHILE REMOVING THE REPLICA!!!!!!"); } } // Save the ending part of the interval lastElasticityInterval.get(vee2Plicate)[1] = System.currentTimeMillis() + ELASTICITY_MARGIN; } return false; } private Set<VEEReplica> getReplicaCandiates(Set<VEEReplica> replicas) { for (VEEReplica replica : replicas) { VEE balancerVEE = replica.getVEE().getBalancedBy(); logger.info("Is a replica balanced por" + replica.getVEE().getBalancedBy()); if (balancerVEE!= null) { return getReplicaCandiatesLoadBalancer ( replicas); } else return getReplicaCandiatesLastElement (replicas); } return null; } private Set<VEEReplica> getReplicaCandiatesLastElement (Set<VEEReplica> replicas) { logger.info("Last element"); // assume all the replicas can equally be removed int maxreplica = 0; Set<VEEReplica> plicateSet = new HashSet<VEEReplica>(); VEEReplica removeCandidate = null; for (Iterator<VEEReplica> removeIt = replicas.iterator(); removeIt .hasNext();) { VEEReplica plicate = (VEEReplica) removeIt.next(); if ((plicate.getId()) > maxreplica) { maxreplica = plicate.getId(); removeCandidate = plicate; } } plicateSet.add(removeCandidate); return plicateSet; } private Set<VEEReplica> getReplicaCandiatesLoadBalancer (Set<VEEReplica> replicas) { logger.info("Obtain replicas to delete from balancer"); if (replicas.size()==0) return null; Set<VEEReplica> plicateSet = new HashSet<VEEReplica>(); VEE balancerVEE = null; String ipbalancer = null; for (VEEReplica balancer : replicas) { balancerVEE = balancer.getVEE().getBalancedBy(); for (VEEReplica veebalancer: balancerVEE.getVEEReplicas()) { for (NIC nic : veebalancer.getNICs() ) { if (!nic.getNICConf().getNetwork().getPrivateNet()) ipbalancer = nic.getIPAddresses().get(0); } } /* if (balancerVEE!=null) { for (NIC nic: balancerVEE.get) } veeReplica.getNICs() veeReplica.getNICs() balancerVEE.get for (NICConf nic : balancerVEE.getNICsConf()) { if (!nic.getNetwork().getPrivateNet()) { String[] addresses = nic.getNetwork().getNetworkAddresses(); ipbalancer = nic.addIPAddress } }*/ } String[] ipreplica = null; try { logger.info("IP balancer " + ipbalancer+ " " + balancerVEE .getLbManagementPort()); ipreplica = this.lbConfigurator.getNodeRemove(ipbalancer, balancerVEE .getLbManagementPort(), 1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } for (int i=0; i<ipreplica.length; i++) { System.out.println (ipreplica[i]); VEEReplica replica = getReplicaByIp (replicas, ipreplica[i] ); if (replica== null) { logger.error("No replica for IP " + ipreplica[i]); continue; } plicateSet.add(replica); } return plicateSet; } private VEEReplica getReplicaByIp (Set<VEEReplica> replicas, String Ip) { for (VEEReplica replica : replicas) { for (NIC nic : replica.getNICs()) { if (!nic.getNICConf().getNetwork().getPrivateNet()) { logger.info("Looking for ip " + Ip + " ip found " + nic.getIPAddresses().get(0)); if (nic.getIPAddresses().get(0).equals(Ip)) { return replica; } } } } return null; } private int dispatchEvent(SMControlEvent cntrlEvent) throws MalformedURLException { int retorno = 0; // Check there is really an event. if (cntrlEvent == null) return currentState; // Check the event is acceptable in the actual state boolean accepted = false; for (Integer eventId : stateEventMatrix.get(currentState)) if (cntrlEvent.getControlEventType() == eventId) accepted = true; if (!accepted) { logger.error("Event discarded: not acceptable in this state."); return currentState; } if (!cntrlEvent.getServiceFQN().equals(sap.getFQN().toString())) { logger .error("¡The FQNs of service and event doesn't match.\nService FQN: " + sap.getFQN().toString() + "\nEvent FQN: " + cntrlEvent.getServiceFQN()); } logger.info("\n\n* Dispatching event of type: " + cntrlEvent.getControlEventType()); switch (cntrlEvent.getControlEventType()) { case SMControlEvent.ELASTICITY_RULE_VIOLATION: logger .info("\n* FSM Processing Control Event: ELASTICITY_RULE_VIOLATION\n"); // this method is triggered by the RuleEngine on the // LifecycleController. Get rule action and execute it String action = cntrlEvent.getSuggestedAction(); logger.info(SMControlEvent.ELASTICITY_RULE_VIOLATION + ", action: " + action); // check the action grammar and perform the needed VMI // actions if (action.contains("createReplica")) { int scaleUpNumber = getCreateReplicaInfo(action); // By default always checkinterval boolean checkinterval = true; for (int scaleup = 0; scaleup < scaleUpNumber; scaleup++) { // get the action parameters int initIndex = action.indexOf("("); int endIndex = action.lastIndexOf(")"); String veeType = action.substring(initIndex + 1, endIndex); String[] parameters = veeType.split(","); // set to true the elasticity checkinterval return boolean reply = true; // only check interval for the first replica of a group in case of multiple scaling up if (scaleup > 0) checkinterval = false; else checkinterval = true; if (parameters.length < 2) { reply = elasticityCreateReplica(parameters[0], 1, cntrlEvent .getInitialTime(),checkinterval); } else { reply = elasticityCreateReplica(parameters[0], Integer .parseInt(parameters[1]), cntrlEvent .getInitialTime(),checkinterval); } // in case of chack interval reply false, don't increase the scaleup variable and try again if (reply==false && scaleUpNumber !=1 && scaleup > 0) { scaleup } } retorno = FSM.RUNNING; logger.info("FSM RUNNING"); } else if (action.contains("removeReplica")) { int scaleDownNumber = getRemoveReplicaInfo(action); // By default always checkinterval boolean checkinterval = true; for (int scaledown = 0; scaledown < scaleDownNumber; scaledown++) { // get the action parameters int initIndex = action.indexOf("("); int endIndex = action.lastIndexOf(")"); String veeType = action.substring(initIndex + 1, endIndex); // set to true the elasticity checkinterval return boolean reply = true; // only check interval for the first replica of a group in case of multiple scaling up if (scaledown > 0) checkinterval = false; else checkinterval = true; reply = elasticityRemoveReplica(veeType, cntrlEvent.getInitialTime(),checkinterval); // in case of chackinterval reply false, don't increase the scaledown variable and try again if (reply==false && scaleDownNumber !=1 && scaledown > 0) { scaledown } //Check if there's more replicas to remove if (((scaledown+1) < scaleDownNumber) && reply==true){ //Lazy Scale down, wait for the next replica to be removed try { logger.info("Lazy Scale Down: waiting " + lazyScaleDownTime +" seconds to remove next replica"); Thread.sleep(lazyScaleDownTime*1000); } catch(InterruptedException e) { e.printStackTrace(); } } } retorno = FSM.RUNNING; logger.info("FSM RUNNING"); } else { // or return an error if they weren't retorno = FSM.ERROR; } break; case SMControlEvent.NEW_RULE_ADDED: logger.info("\n* FSM Processing Control Event: NEW_RULE_ADDED\n"); rle.addRule(cntrlEvent.getSuggestedAction()); retorno = FSM.RECONFIGURED; break; case SMControlEvent.RULE_CHANGED: logger.info("\n* FSM Processing Control Event: RULE_CHANGED\n"); retorno = FSM.RECONFIGURED; break; case SMControlEvent.UNDEPLOY_SERVICE: logger.info("\n* FSM Processing Control Event: UNDEPLOY_SERVICE\n"); // issue the appropriate VMI Events to undeploy the service, shutdown(veesRollBack); if (nicsToDeploy==null) nicsToDeploy =new HashSet<Network>(); removeNetworks(); sap.getCustomer().unregisterService(sap); DbManager.getDbManager().save(sap.getCustomer()); FQN fqnService = sap.getFQN(); DbManager.getDbManager().remove(sap); DbManager.getDbManager().remove(fqnService); retorno = FSM.FINISHED; break; case SMControlEvent.START_SERVICE: if (startService()) retorno = FSM.RUNNING; else retorno = FSM.ERROR; break; default: retorno = FSM.ERROR; break; } return retorno; } private void removeNetworks() { try { vmi.deleteNetwork(nicsToDeploy); } catch (AccessDeniedException e) { logger.error("Access denied accessing the VMI: " + e.getMessage()); } catch (CommunicationErrorException e) { logger .error("Couldn't connect to the VMI to undeploy the networks: " + e.getMessage()); } } /** * Analyzes the event in the queue to determine the next state in the FSM * * @param cntrlEvent * @param currentState */ private int getNextState(SMControlEvent cntrlEvent, int currentState) throws InterruptedException, MalformedURLException { int retorno = currentState; switch (currentState) { case INIT: logger.info("\n\n\n\n* Processing State: INIT"); retorno = dispatchEvent(cntrlEvent); break; case RUNNING: if (!(cntrlEvent == null)) { retorno = dispatchEvent(cntrlEvent); } break; case RECONFIGURED: logger.info("\n\n\n\n* Processing State: RECONFIGURED"); retorno = FSM.RUNNING; break; case FINISHED: try { finishExecution = true; } catch (Throwable ex) { } break; case ERROR: logger.info("\n\n\n\n* Processing State: ERROR"); shutdown(veesRollBack); retorno = FSM.FINISHED; break; } if (abort) retorno = FSM.ERROR; return (retorno); } /** * Read the SA configuration to find out the FQN of the required networks. * Calculate its required size, deploy them and save a reference in the FSM * network repository. * * The size is calculated after the sum of the maximum number of replicas * for each VEE using the network. * * @throws CommunicationErrorException * @throws AccessDeniedException * */ private int getCreateReplicaInfo(String action){ int scaleUpNumber; // Decide how many replicas can be created with the percentage property int initIndexTemp = action.indexOf("("); int endIndexTemp = action.lastIndexOf(")"); String veeTypeTemp = action.substring(initIndexTemp + 1, endIndexTemp); String[] parametersTemp = veeTypeTemp.split(","); VEE vee2ReplicateTemp = (VEE) ReservoirDirectory.getInstance().getObject( new FQN(parametersTemp[0])); try { int currentReplicasTemp = vee2ReplicateTemp.getCurrentReplicas(); logger.info("Current number of replicas:" + currentReplicasTemp); logger.info("Scale Up Percentage:" + scaleUpPercentage); scaleUpNumber = Math.round((scaleUpPercentage/100)*currentReplicasTemp); } catch (NullPointerException npe) { logger.error("problem getting number of replicas"); scaleUpNumber = 1; } //Always scale 1 at minimum if (scaleUpNumber < 1) { scaleUpNumber = 1; } logger.info("Scaling up " + scaleUpNumber +" more replicas if possible"); return scaleUpNumber; } private int getRemoveReplicaInfo(String action){ int scaleDownNumber; // Decide how many replicas can be removed with the percentage property int initIndexTemp = action.indexOf("("); int endIndexTemp = action.lastIndexOf(")"); String veeTypeTemp = action.substring(initIndexTemp + 1, endIndexTemp); String[] parametersTemp = veeTypeTemp.split(","); VEE vee2PlicateTemp = (VEE) ReservoirDirectory.getInstance().getObject( new FQN(veeTypeTemp)); try { int currentReplicasTemp = vee2PlicateTemp.getCurrentReplicas(); logger.info("Current number of replicas:" + currentReplicasTemp); logger.info("Scale Down Percentage:" + scaleDownPercentage); scaleDownNumber = Math.round((scaleDownPercentage/100)*currentReplicasTemp); } catch (NullPointerException npe) { logger.error("problem getting number of replicas"); scaleDownNumber = 1; } //Always scale 1 at minimum if (scaleDownNumber < 1) { scaleDownNumber = 1; } logger.info("Scaling Down " + scaleDownNumber +" more replicas if possible"); return scaleDownNumber; } private boolean checkAndDeployNetworks() { logger.info("Checking and deploying networks"); nicsToDeploy = new HashSet<Network>(); // Calculate network sizes Map<Network, Integer> networkMaximumSizes = new HashMap<Network, Integer>(); for (VEE vee : sap.getVEEs()) { HashMap<String, Integer> ipsNeeded = parser .getNumberOfIpsPerNetwork(vee.getFQN().contexts()[vee .getFQN().contexts().length - 1]); for (NICConf nic : vee.getNICsConf()) { Integer numberOfIps = ipsNeeded.get(nic.getNetwork().getName()); if (numberOfIps == null || numberOfIps == 0) numberOfIps = 1; logger.info(numberOfIps + "(" + vee.getMaxReplicas() * numberOfIps + ")" + " IPs required for vee " + vee.getVEEName() + " on network " + nic.getNetwork().getName()); if (networkMaximumSizes.containsKey(nic.getNetwork())) { networkMaximumSizes.put(nic.getNetwork(), networkMaximumSizes.get(nic.getNetwork()) + vee.getMaxReplicas() * numberOfIps); } else { networkMaximumSizes.put(nic.getNetwork(), vee .getMaxReplicas()); } } } for (Network net : networkMaximumSizes.keySet()) { // Update the network size, based on the minumum number of bits // needed to represent the size net.setSize(networkMaximumSizes.get(net)); if (net.getSize() > 1) net.setSize(net.getSize() + 2); logger.info("Asking for a " + ((net.getPrivateNet()) ? "private" : "public") + " network with " + net.getSize() + " IPs"); String[] address = lcc.getNetworkAddress(net.getSize(), !net .getPrivateNet()); if (address == null) { logger .error("The lifecycle manager was unable to give enough IPs. It's impossible to deploy all the needed networks. Aborting."); return false; } net.setNetworkAddresses(address); nicsToDeploy.add(net); } try { vmi.allocateNetwork(nicsToDeploy); return true; } catch (AccessDeniedException e) { logger.error("Access denied when allocating a new network: " + e.getMessage() + ". Aborting."); } catch (CommunicationErrorException e) { logger.error("Communication error when allocating a new network: " + e.getMessage() + ". Aborting."); } catch (NotEnoughResourcesException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.info("Networks for Service Application " + sap.getFQN().toString() + " checked and deployed"); return false; } /** * Method to shutdown a set of running replicas * * @param rollBack * * @return */ private boolean shutdown(Set<VEEReplica> rollBack) { Map<VEEReplica, VEEReplicaUpdateResult> updateResults = null; try { updateResults = vmi.shutdownReplica(rollBack); } catch (CommunicationErrorException ex) { logger.error("Comunication error waiting for Replica shutdown: " + ex.getMessage()); return false; } catch (AccessDeniedException e) { logger.error("Access error waiting for Replica shutdown: " + e.getMessage()); return false; } Iterator<VEEReplica> rollIt = rollBack.iterator(); while (rollIt.hasNext()) { VEEReplica veeReplica = rollIt.next(); logger.info("Shutting down replic: " + veeReplica.getFQN()); // Shutdown the replica VEEReplicaUpdateResult updateResult = updateResults.get(veeReplica); if (!updateResult.isSuccess()) { logger.error("Update failed: " + updateResult.getMessage()); return false; } // If replica is loadbalanced, balancer should be notified VEE balancerVEE = veeReplica.getVEE().getBalancedBy(); if (balancerVEE!= null) removeReplicaFromLoadBalancer(veeReplica, balancerVEE); // Release the ip addres leased to the replica. for (NIC nic : veeReplica.getNICs()) for (String ipAddress : nic.getIPAddresses()) lcc.releaseHostAddress(ipAddress, nic.getNICConf() .getNetwork().getNetworkAddresses()[0]); // Once the replica is finished, it should be removed from the // storage system. // But first, it has to be unlinked from the VEE if (veeReplica.getVEE().isVEEReplicaRegistered(veeReplica)) { veeReplica.getVEE().unregisterVEEReplica(veeReplica); } /* List<VEEReplica> sas = DbManager.getDbManager().getList (VEEReplica.class); System.out.println ("ANTES"); for (VEEReplica s: sas) { System.out.println (s.getFQN()); }*/ FQN fqnReplica = veeReplica.getFQN(); DbManager.getDbManager().remove(veeReplica); DbManager.getDbManager().remove(fqnReplica); DbManager.getDbManager().save(veeReplica.getVEE()); /* sas = DbManager.getDbManager().getList (VEEReplica.class); System.out.println ("DESPUES"); for (VEEReplica s: sas) { System.out.println (s.getFQN()); }*/ } return true; } /** * Method to deploy a replica into the underlying infrastructure * * @param veeReplica * @return */ private boolean deployReplica(Set<VEEReplica> veeReplicasConfs) { Map<VEEReplica, VEEReplicaAllocationResult> allocResults = null; try { allocResults = vmi.allocateVEEReplicas(veeReplicasConfs, SubmissionModelType.BESTEFFORT); } catch (NotEnoughResourcesException ex) { abort("NotEnoughResourcesException exception caught " + ex.getMessage()); return false; } catch (AccessDeniedException ex) { abort("AccessDeniedException exception caught " + ex.getMessage()); return false; } catch (VEEReplicaDescriptionMalformedException ex) { abort("VEEReplicaDescriptionMalformedException exception caught " + ex.getMessage()); return false; } catch (CommunicationErrorException ex) { abort("CommunicationErrorException exception caught " + ex.getMessage()); return false; } for (VEEReplica veeReplica: veeReplicasConfs) { logger.info("**** Reviewing replica " + veeReplica.getFQN()); VEEReplicaAllocationResult allocResult = allocResults.get(veeReplica); if (!allocResult.isSuccess()) { abort("VIM reports error: "+ allocResult.getMessage()); return false; } // If replica is loadbalanced, balancer should be notified VEE balancerVEE = veeReplica.getVEE().getBalancedBy(); if (balancerVEE!=null){ logger.info("Adding replica to LB"); addReplicaToLoadBalancer(veeReplica, balancerVEE); } else { logger.info(veeReplica.getFQN() + " is not balanced"); } } // The allocation was successful and the replica is UP and Running // update the rollback veesRollBack.addAll(veeReplicasConfs); return true; } /** * @param veeReplica * @param balancerVEE */ private void addReplicaToLoadBalancer(VEEReplica veeReplica, VEE balancerVEE) { addRegularReplicaToBalancer(veeReplica, balancerVEE); } /** * Creates a customization image for the VEEReplica passed as a parameter, * containing only one file, called ovf-env.xml, with all the customization * data needed to initialize the Replica. * * Returns an URL to access the replica. * * @param veeReplica * @param createISOImage * @return */ private String createCustomizationFile(VEEReplica veeReplica) { String customizationDirName = customImagesDir + "/" + veeReplica.getFQN().toString(); File customizationDir = new File(customizationDirName); customizationDir.mkdirs(); String customizationFileName = customizationDirName + "/ovf-env.xml"; File customizationFile = new File(customizationFileName); logger.info("Creating customization file in " + customizationFile.getPath()); String customizationDirURLPath = SMConfiguration.getInstance() .getImagesServerPath() + "/" + veeReplica.getFQN().toString(); PrintWriter out = null; try { out = new PrintWriter(new FileWriter(customizationFile)); } catch (IOException ex) { java.util.logging.Logger.getLogger(FSM.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); return ex.getMessage(); } out.write(veeReplica.getOVFEnvironment() + "\n"); out.close(); String urlToCustomFile = protocol + SMConfiguration.getInstance().getImagesServerHost() + ":" + SMConfiguration.getInstance().getImagesServerPort() + customizationDirURLPath + "/ovf-env.xml"; logger.info("URL to customization file: " + urlToCustomFile); return urlToCustomFile; } /** * Returns the number of replicas for the indicated VEE FQN, if the FQN * belongs to this service. * * @param veeFqn * FQN of the VEE whose replica number want to be retrieved. * * @return The actual number of replicas if the VEE is part of the current * service or 0 otherwise. */ public int getAmount(String veeFqn) { VEE vee = (VEE) ReservoirDirectory.getInstance().getObject( new FQN(veeFqn)); if (vee != null) { logger.info("VEE " + vee + " current replicas: " + vee.getCurrentReplicas()); return vee.getCurrentReplicas(); } logger.error("Not VEE registered with FQN " + veeFqn); return 0; } /** * Abort the current action if the service was deployed successfully or * abort the whole execution of the service if the abort signal is generated * during the SPECIFIED state. * * @param reason * Textual reason to send the abort signal. It will end up in the * logs. */ private void abort(String reason) { if (currentState == INIT) { logger.error("Aborting the FSM due to the following reason: " + reason); abort = true; this.abortMessage = reason; } else { logger.error("Action discarded due to the following reason: " + reason); } } private void abortServiceAlreadyDeployed (String reason) { if (currentState == INIT) { logger.error("Aborting the FSM due to the following reason: " + reason); abort = true; this.abortMessage = reason; } else { logger.error("Action discarded due to the following reason: " + reason); } shutdown(veesRollBack); if (nicsToDeploy == null) nicsToDeploy = new HashSet<Network>(); removeNetworks(); sap.getCustomer().unregisterService(sap); DbManager.getDbManager().save(sap.getCustomer()); FQN fqnService = sap.getFQN(); DbManager.getDbManager().remove(sap); DbManager.getDbManager().remove(fqnService); } @SuppressWarnings("unchecked") private Set<VEEReplica> createReplica(VEE originalVEE, int replicaNumber) { /* * Set<VEEReplica> replicas = new HashSet<VEEReplica>(); * * for (int q=0; q < replicaNumber;q++) { * * VEEReplica veeReplica = new VEEReplica(originalVEE); * * replicaCustomInfo = new HashMap<String, String>(); * * logger.info("Deploying replica: "+ veeReplica.getFQN()); * veeReplica.registerHwElementsInResDir(); * * ReservoirDirectory.getInstance().registerObject(veeReplica.getFQN(), * veeReplica); * * MonitoringRestBusConnector restBusConnector = * MonitoringRestBusConnector.getInstance(); List<String> restEndPoints * = restBusConnector.getRestEndPoints(); * * if ((restEndPoints != null) && (restEndPoints.size() > 0)) { * logger.info("KPIMonitorEndPoint customization value: " + * restBusConnector.getRestEndPoints().get(0)); * replicaCustomInfo.put("KPIMonitorEndPoint", * restBusConnector.getRestEndPoints().get(0)); } * * replicaCustomInfo.put("KPIQualifier", sap.getFQN().toString() + * ".kpis"); replicaCustomInfo.put("ReplicaName", * veeReplica.getFQN().toString()); replicaCustomInfo.put("VEEid", * String .valueOf(veeReplica.getId())); * replicaCustomInfo.put("ReplicaName", veeReplica.getFQN().toString()); * * // call parser to complete the hashTable and update the // * CustomizationInformation String in the VEEReplica // object * logger.info("Customizing replica " + veeReplica.getId() + " del VEE " * + originalVEE.getVEEName()); if (replicaCustomInfo.isEmpty()) * logger.info("Empty custom information"); else { Iterator keyIter = * replicaCustomInfo.keySet().iterator(); * * while (keyIter.hasNext()) { String key = (String) keyIter.next(); * logger.info("Key: " + key + "; Value: "+ replicaCustomInfo.get(key)); * } } * * // Get the networks for the VM Environment HashMap<String,String> * masks = new HashMap<String,String>(); * HashMap<String,ArrayList<String>> ips = new * HashMap<String,ArrayList<String>>(); HashMap<String,String> dnss = * new HashMap<String, String> (); HashMap<String,String> gateways = new * HashMap<String, String> (); * * HashMap<String, Integer> ipsNeeded = * parser.getNumberOfIpsPerNetwork(originalVEE.getVEEName()); * * for (Network net: sap.getNetworks()) { masks.put(net.getName(), * net.getNetworkAddresses()[1]); dnss.put(net.getName(), * net.getNetworkAddresses()[2]); gateways.put(net.getName(), * net.getNetworkAddresses()[3]); } * * for (NIC nic: veeReplica.getNICs()) { String networkName = * nic.getNICConf().getNetwork().getName(); * * if (ips.get(networkName)==null) ips.put(networkName, new * ArrayList<String>()); * * Integer iterations = ipsNeeded.get(networkName); * * if (iterations == null || iterations == 0) iterations = 1; * * for (int i=0; i < iterations; i++) { String replicaIP = * lcc.getHostAddress * (nic.getNICConf().getNetwork().getNetworkAddresses()[0]); * * if (replicaIP==null) { abort("Lack of ip addresses"); return null; } * * // Put the IP in the entrypoint map for this network. Map<String, * String> entryPoint = nic.getNICConf().getNetwork().getEntryPoints(); * * if (entryPoint.containsKey(originalVEE.getVEEName())) { String * ipList= entryPoint.get(originalVEE.getVEEName()); * entryPoint.put(originalVEE.getVEEName(), ipList + " " + replicaIP); } * else { entryPoint.put(originalVEE.getVEEName(), replicaIP); } * * nic.addIPAddress(replicaIP); * * ips.get(networkName).add(replicaIP); } } */ if (this.abort) { this.logger .error("Unable to deploy replicas. Service already aborted"); return null; } Set<VEEReplica> replicas = new HashSet<VEEReplica>(); for (int q = 0; q < replicaNumber; q++) { VEEReplica veeReplica = new VEEReplica(originalVEE); replicaCustomInfo = new HashMap<String, String>(); logger.info("Deploying replica: " + veeReplica.getFQN()); veeReplica.registerHwElementsInResDir(); ReservoirDirectory.getInstance().registerObject( veeReplica.getFQN(), veeReplica); ReservoirDirectory.getInstance().registerObject( veeReplica.getMemory().getFQN(), veeReplica.getMemory()); logger.info("PONG Memory FQN: " + veeReplica.getMemory()); Iterator iter = veeReplica.getDisks().iterator(); while (iter.hasNext()) { Disk disc = (Disk) iter.next(); ReservoirDirectory.getInstance().registerObject(disc.getFQN(), disc); logger.info("PONG DISK FQN: " + disc.getFQN()); } iter = veeReplica.getCPUs().iterator(); while (iter.hasNext()) { CPU cpu = (CPU) iter.next(); ReservoirDirectory.getInstance().registerObject(cpu.getFQN(), cpu); logger.info("PONG CPU FQN: " + cpu.getFQN()); } iter = veeReplica.getNICs().iterator(); while (iter.hasNext()) { NIC nic = (NIC) iter.next(); ReservoirDirectory.getInstance().registerObject(nic.getFQN(), nic); logger.info("PONG NIC FQN: " + nic.getFQN()); } MonitoringRestBusConnector restBusConnector = MonitoringRestBusConnector .getInstance(); List<String> restEndPoints = restBusConnector.getRestEndPoints(); if ((restEndPoints != null) && (restEndPoints.size() > 0)) { logger.info("KPIMonitorEndPoint customization value: " + restBusConnector.getRestEndPoints().get(0)); replicaCustomInfo.put("KPIMonitorEndPoint", restBusConnector .getRestEndPoints().get(0)); } replicaCustomInfo.put("KPIQualifier", sap.getFQN().toString() + ".kpis"); replicaCustomInfo .put("ReplicaName", veeReplica.getFQN().toString()); replicaCustomInfo.put("VEEid", String.valueOf(veeReplica.getId())); replicaCustomInfo .put("ReplicaName", veeReplica.getFQN().toString()); // call parser to complete the hashTable and update the // CustomizationInformation String in the VEEReplica // object logger.info("Customizing replica " + veeReplica.getId() + " del VEE " + originalVEE.getVEEName()); if (replicaCustomInfo.isEmpty()) logger.info("Empty custom information"); else { Iterator keyIter = replicaCustomInfo.keySet().iterator(); while (keyIter.hasNext()) { String key = (String) keyIter.next(); logger.info("Key: " + key + "; Value: " + replicaCustomInfo.get(key)); } } // Get the networks for the VM Environment HashMap<String, String> masks = new HashMap<String, String>(); HashMap<String, ArrayList<String>> ips = new HashMap<String, ArrayList<String>>(); HashMap<String, String> dnss = new HashMap<String, String>(); HashMap<String, String> gateways = new HashMap<String, String>(); HashMap<String, Integer> ipsNeeded = parser .getNumberOfIpsPerNetwork(originalVEE.getVEEName()); for (Network net : sap.getNetworks()) { if (net.getNetworkAddresses()!=null && net.getNetworkAddresses()[1]!=null) masks.put(net.getName(), net.getNetworkAddresses()[1]); if (net.getNetworkAddresses()!=null &&net.getNetworkAddresses().length>2) dnss.put(net.getName(), net.getNetworkAddresses()[2]); if (net.getNetworkAddresses()!=null &&net.getNetworkAddresses().length>3) gateways.put(net.getName(), net.getNetworkAddresses()[3]); } if (SMConfiguration.getInstance().getIpManagement()) { for (NIC nic : veeReplica.getNICs()) { String networkName = nic.getNICConf().getNetwork().getName(); if (ips.get(networkName) == null) ips.put(networkName, new ArrayList<String>()); Integer iterations = ipsNeeded.get(networkName); if (iterations == null || iterations == 0) iterations = 1; String staticIpProp = parser.getStaticIpProperty(originalVEE.getVEEName()); scaleUpPercentage = parser.getScaleUpPercentage(originalVEE.getVEEName()); scaleDownPercentage = parser.getScaleDownPercentage(originalVEE.getVEEName()); lazyScaleDownTime = parser.getScaleDownTime(originalVEE.getVEEName()); for (int i = 0; i < iterations; i++) { logger.info("PONG static ip property: "+ staticIpProp); String replicaIP = lcc.getHostAddress(nic.getNICConf() .getNetwork().getNetworkAddresses()[0],staticIpProp); staticIpProp=null; if (replicaIP == null) { abort("Lack of ip addresses"); return null; } // Put the IP in the entrypoint map for this network. Map<String, String> entryPoint = nic.getNICConf() .getNetwork().getEntryPoints(); if (entryPoint.containsKey(originalVEE.getVEEName())) { String ipList = entryPoint .get(originalVEE.getVEEName()); entryPoint.put(originalVEE.getVEEName(), ipList + " " + replicaIP); } else { entryPoint.put(originalVEE.getVEEName(), replicaIP); } nic.addIPAddress(replicaIP); ips.get(networkName).add(replicaIP); } } } HashMap<String, HashMap<String, String>> entryPoints = new HashMap<String, HashMap<String, String>>(); for (Network net : sap.getNetworks()) entryPoints.put(net.getName(), net.getEntryPoints()); try { veeReplica.setOvfRepresentation(parser .inEnvolopeMacroReplacement(originalVEE .getOvfRepresentation(), veeReplica.getId(), SMConfiguration.getInstance().getDomainName(), sap.getFQN().toString(), SMConfiguration .getInstance().getMonitoringAddress(), ips, masks, dnss, gateways, entryPoints)); } catch (IOException e) { abort("Unable to create environment file: " + e.getMessage()); } catch (IllegalArgumentException iae) { abort("Some data could not be calculated for the OVF environment: " + iae.getMessage()); } // XXXXXXXXXXXXXXXXXXXXXXXXXX // to be added to OVF: How is a swap disk defined? // XXXXXXXXXXXXXXXXXXXXXXXXXX if (setSwap) { DiskConf swap = new DiskConf(256, null, null); swap.setType("swap"); veeReplica.getVEE().addDiskConf(swap); } else logger.info("Skipping swap disk"); // generate additional image @SuppressWarnings("unused") String pathToCustomizationFile = createCustomizationFile(veeReplica); replicas.add(veeReplica); } // deploy the Replica with the newly generated logger.info("Deploying replicas..."); if (deployReplica(replicas)) { for (VEEReplica veeReplica : replicas) { originalVEE.registerVEEReplica(veeReplica); originalVEE.addCurrentReplicas(); try { DbManager.getDbManager().save(veeReplica); } catch (Throwable e) { abort("Error updating the model in the DB: " + e.getMessage()); } } } else return null; return replicas; } private void addRegularReplicaToBalancer(VEEReplica veeReplica, VEE balancerVEE) { logger.info("Adding regular replica to load balancer"); logger.info("Configuring loadbalancer for " + veeReplica.getVEE().getFQN() + " "); String replicaIP = veeReplica.getNICs().iterator().next() .getIPAddresses().iterator().next(); logger.info("Replica IP " + replicaIP); Set<VEEReplica> balancerReplicas = balancerVEE.getVEEReplicas(); if (balancerVEE == null) { logger.error("There is not any balancer"); return; } logger.info("Number of replicas balanced " + balancerReplicas.size()); for (VEEReplica balancer : balancerReplicas) { Set<NIC> nics = balancer.getNICs(); for (NIC nic : nics) { if (!nic.getNICConf().getNetwork().getPrivateNet()) { List<String> addresses = nic.getIPAddresses(); for (String ip : addresses) { if (balancerVEE.getLbManagementPort()==0) { logger.error("No management port for the balancer"); return; } try { int result = this.lbConfigurator.addNode(ip, balancerVEE.getLbManagementPort(), veeReplica.getFQN() .toString(), replicaIP); } catch (Exception e) { logger.error("It was impossible to send the load balancer " + balancerVEE.getVEEName() + " " + ip+" : "+balancerVEE.getLbManagementPort()+" the IP information " + replicaIP); } } } } } } private void removeReplicaFromLoadBalancer(VEEReplica veeReplica, VEE balancerVEE) { logger.info("Removing replica from load balancer: " + veeReplica.getFQN()); if (balancerVEE==null) return; Set<VEEReplica> balancerReplicas = balancerVEE.getVEEReplicas(); for (VEEReplica balancer : balancerReplicas) { Set<NIC> nics = balancer.getNICs(); for (NIC nic : nics) { if (!nic.getNICConf().getNetwork().getPrivateNet()) { List<String> addresses = nic.getIPAddresses(); for (String ip : addresses) { this.lbConfigurator.removeNode(ip, balancerVEE .getLbManagementPort(), veeReplica.getFQN() .toString()); } } } } } }
package com.xpn.xwiki.plugin.mailsender; import java.io.IOException; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.xwiki.mail.MailSenderConfiguration; import org.xwiki.test.junit5.mockito.MockComponent; import com.icegreen.greenmail.store.FolderException; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.ServerSetup; import com.icegreen.greenmail.util.ServerSetupTest; import com.xpn.xwiki.test.MockitoOldcore; import com.xpn.xwiki.test.junit5.mockito.InjectMockitoOldcore; import com.xpn.xwiki.test.junit5.mockito.OldcoreTest; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; /** * Integration tests for {@link com.xpn.xwiki.plugin.mailsender.Mail}. */ @OldcoreTest public class MailSenderApiTest { @MockComponent private MailSenderConfiguration mockConfiguration; @InjectMockitoOldcore private MockitoOldcore oldcore; private MailSenderPluginApi api; private static GreenMail mailserver; @BeforeAll public static void beforeAll() { // Increase startup timeout (default is 1s, which can be too fast on slow CI agents). ServerSetup newSetup = ServerSetupTest.SMTP.createCopy(); newSetup.setServerStartupTimeout(5000L); mailserver = new GreenMail(newSetup); mailserver.start(); } @AfterAll public static void afterAll() { mailserver.stop(); } @BeforeEach public void beforeEach() throws Exception { when(this.mockConfiguration.getHost()).thenReturn(mailserver.getSmtp().getBindTo()); when(this.mockConfiguration.getPort()).thenReturn(mailserver.getSmtp().getPort()); when(this.mockConfiguration.getAdditionalProperties()).thenReturn(new Properties()); MailSenderPlugin plugin = new MailSenderPlugin("dummy", "dummy", this.oldcore.getXWikiContext()); this.api = new MailSenderPluginApi(plugin, this.oldcore.getXWikiContext()); } @AfterEach public void afterEach() throws FolderException { mailserver.purgeEmailFromAllMailboxes(); } @Test public void testSendMail() throws Exception { Mail mail = this.api.createMail(); mail.setFrom("john@acme.org"); mail.setTo("peter@acme.org"); mail.setSubject("Test subject"); mail.setTextPart("Text content"); mail.setHeader("header", "value"); assertEquals(0, this.api.sendMail(mail)); // Verify that the email was received MimeMessage[] receivedEmails = mailserver.getReceivedMessages(); assertEquals(1, receivedEmails.length); MimeMessage message = receivedEmails[0]; assertEquals("Test subject", message.getSubject()); assertEquals("john@acme.org", ((InternetAddress) message.getFrom()[0]).getAddress()); assertEquals("value", message.getHeader("header")[0]); } @Test public void testSendMailWithCustomConfiguration() throws Exception { Mail mail = this.api.createMail(); mail.setFrom("john@acme.org"); mail.setTo("peter@acme.org"); mail.setSubject("Test subject"); mail.setTextPart("Text content"); MailConfiguration config = this.api.createMailConfiguration( new com.xpn.xwiki.api.XWiki(this.oldcore.getSpyXWiki(), this.oldcore.getXWikiContext())); assertEquals(mailserver.getSmtp().getPort(), config.getPort()); assertEquals(mailserver.getSmtp().getBindTo(), config.getHost()); assertNull(config.getFrom()); // Modify the SMTP From value config.setFrom("jason@acme.org"); assertEquals(0, this.api.sendMail(mail, config)); // TODO: Find a way to ensure that the SMTP From value has been used. } @Test public void testSendRawMessage() throws MessagingException, IOException { assertEquals(0, this.api.sendRawMessage("john@acme.org", "peter@acme.org", "Subject:Test subject\nFrom:steve@acme.org\nCc:adam@acme.org\nheader:value\n\nTest content")); MimeMessage[] receivedEmails = mailserver.getReceivedMessages(); assertEquals(2, receivedEmails.length); MimeMessage johnMessage = receivedEmails[0]; assertEquals("Test subject", johnMessage.getSubject()); assertEquals("steve@acme.org", johnMessage.getFrom()[0].toString()); assertEquals("Test content", johnMessage.getContent()); assertEquals("value", johnMessage.getHeader("header")[0]); MimeMessage peterMessage = receivedEmails[0]; assertEquals("Test subject", peterMessage.getSubject()); assertEquals("steve@acme.org", peterMessage.getFrom()[0].toString()); assertEquals("Test content", peterMessage.getContent()); assertEquals("value", peterMessage.getHeader("header")[0]); } }
import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.topology.base.BaseWindowedBolt; import org.apache.storm.tuple.Fields; import speed.storm.spout.PookaKafkaSpout; import java.util.Properties; import java.util.concurrent.TimeUnit; public class TestMain { public static void main(String[] args) throws InterruptedException { Config conf = new Config(); conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1); conf.setDebug(true); Properties p = new Properties(); p.put("zkConnString", "localhost:2181"); p.put("topic", "test"); p.put("zkNamespace", "test_kafka"); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("kafka-spout", new PookaKafkaSpout(p).getSpout()); builder.setBolt("word-spitter", new SplitBolt()).shuffleGrouping("kafka-spout"); builder.setBolt("word-counter", new CountViewsPerCategory() .withTumblingWindow(new BaseWindowedBolt.Duration(10, TimeUnit.SECONDS))) .shuffleGrouping("word-spitter"); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("KafkaStormSample", conf, builder.createTopology()); Thread.sleep(100000); cluster.killTopology("KafkaStormSample"); cluster.shutdown(); } }
package com.xpn.xwiki.internal.template; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.VelocityContext; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.configuration.ConfigurationSource; import org.xwiki.environment.Environment; import org.xwiki.filter.input.InputSource; import org.xwiki.filter.input.InputStreamInputSource; import org.xwiki.filter.input.ReaderInputSource; import org.xwiki.filter.internal.input.DefaultInputStreamInputSource; import org.xwiki.filter.internal.input.StringInputSource; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.LocalDocumentReference; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.GroupBlock; import org.xwiki.rendering.block.RawBlock; import org.xwiki.rendering.block.VerbatimBlock; import org.xwiki.rendering.block.WordBlock; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.internal.parser.MissingParserException; import org.xwiki.rendering.parser.ContentParser; import org.xwiki.rendering.parser.ParseException; import org.xwiki.rendering.renderer.BlockRenderer; import org.xwiki.rendering.renderer.printer.WikiPrinter; import org.xwiki.rendering.renderer.printer.WriterWikiPrinter; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.rendering.syntax.SyntaxFactory; import org.xwiki.rendering.transformation.RenderingContext; import org.xwiki.rendering.transformation.TransformationContext; import org.xwiki.rendering.transformation.TransformationManager; import org.xwiki.velocity.VelocityEngine; import org.xwiki.velocity.VelocityManager; import org.xwiki.velocity.XWikiVelocityException; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; /** * Internal toolkit to experiment on wiki bases templates. * * @version $Id$ * @since 6.1M1 */ @Component(roles = WikiTemplateRenderer.class) @Singleton public class WikiTemplateRenderer { private static final Pattern FIRSTLINE = Pattern.compile("^##(source|raw)\\.syntax=(.*)$\r?\n?", Pattern.MULTILINE); private static final LocalDocumentReference SKINCLASS_REFERENCE = new LocalDocumentReference("XWiki", "XWikiSkins"); @Inject private Environment environment; @Inject private ContentParser parser; @Inject private SyntaxFactory syntaxFactory; @Inject private VelocityManager velocityManager; /** * Used to execute transformations. */ @Inject private TransformationManager transformationManager; @Inject @Named("context") private Provider<ComponentManager> componentManagerProvider; @Inject private RenderingContext renderingContext; @Inject @Named("plain/1.0") private BlockRenderer plainRenderer; @Inject private Provider<XWikiContext> xcontextProvider; @Inject @Named("xwikicfg") private ConfigurationSource xwikicfg; @Inject @Named("currentmixed") private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver; @Inject private Logger logger; private class StringContent { public String content; public Syntax sourceSyntax; public Syntax rawSyntax; public StringContent(String content, Syntax sourceSyntax, Syntax rawSyntax) { this.content = content; this.sourceSyntax = sourceSyntax; this.rawSyntax = rawSyntax; } } // TODO: put that in some SkinContext component private String getSkin() { String skin; XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext != null) { // Try to get it from context skin = (String) xcontext.get("skin"); if (StringUtils.isNotEmpty(skin)) { return skin; } else { skin = null; } // Try to get it from URL if (xcontext.getRequest() != null) { skin = xcontext.getRequest().getParameter("skin"); if (StringUtils.isNotEmpty(skin)) { return skin; } else { skin = null; } } // Try to get it from user preferences skin = getSkinFromUser(); if (skin != null) { return skin; } } // Try to get it from xwiki.cfg skin = this.xwikicfg.getProperty("xwiki.defaultskin", "colibri"); return StringUtils.isNotEmpty(skin) ? skin : null; } private String getSkinFromUser() { XWikiContext xcontext = this.xcontextProvider.get(); XWiki xwiki = xcontext.getWiki(); if (xwiki != null && xwiki.getStore() != null) { String skin = xwiki.getUserPreference("skin", xcontext); if (StringUtils.isEmpty(skin)) { return null; } } return null; } // TODO: put that in some SkinContext component private String getBaseSkin() { String baseskin; XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext != null) { // Try to get it from context baseskin = (String) xcontext.get("baseskin"); if (StringUtils.isNotEmpty(baseskin)) { return baseskin; } else { baseskin = null; } // Try to get it from the skin String skin = getSkin(); if (skin != null) { BaseObject skinObject = getSkinObject(skin); if (skinObject != null) { baseskin = skinObject.getStringValue("baseskin"); if (StringUtils.isNotEmpty(baseskin)) { return baseskin; } } } } // Try to get it from xwiki.cfg baseskin = this.xwikicfg.getProperty("xwiki.defaultbaseskin", "colibri"); return StringUtils.isNotEmpty(baseskin) ? baseskin : null; } private XWikiDocument getSkinDocument(String skin) { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext != null) { DocumentReference skinReference = this.currentMixedDocumentReferenceResolver.resolve(skin); XWiki xwiki = xcontext.getWiki(); if (xwiki != null && xwiki.getStore() != null) { XWikiDocument doc; try { doc = xwiki.getDocument(skinReference, xcontext); } catch (XWikiException e) { this.logger.error("Faied to get document [{}]", skinReference, e); return null; } if (!doc.isNew()) { return doc; } } } return null; } private BaseObject getSkinObject(String skin) { XWikiDocument skinDocument = getSkinDocument(skin); return skinDocument != null ? skinDocument.getXObject(SKINCLASS_REFERENCE) : null; } @SuppressWarnings("resource") private InputSource getTemplateStreamFromSkin(String skin, String template) { InputSource source = null; // Try from wiki pages source = getTemplateStreamFromDocumentSkin(skin, template); // Try from filesystem skins if (skin != null) { InputStream stream = this.environment.getResourceAsStream("/skins/" + skin + "/" + template); if (stream != null) { return new DefaultInputStreamInputSource(stream, true); } } return source; } private InputSource getTemplateStreamFromDocumentSkin(String skin, String template) { XWikiDocument skinDocument = getSkinDocument(skin); if (skinDocument != null) { // Try parsing the object property BaseObject skinObject = skinDocument.getXObject(SKINCLASS_REFERENCE); if (skinObject != null) { String escapedTemplateName = template.replaceAll("/", "."); BaseProperty templateProperty = (BaseProperty) skinObject.safeget(escapedTemplateName); if (templateProperty != null) { Object value = templateProperty.getValue(); if (value instanceof String && StringUtils.isNotEmpty((String) value)) { return new StringInputSource((String) value); } } } // Try parsing a document attachment XWikiAttachment attachment = skinDocument.getAttachment(template); if (attachment != null) { // It's impossible to know the real attachment encoding, but let's assume that they respect the // standard and use UTF-8 (which is required for the files located on the filesystem) try { return new DefaultInputStreamInputSource(attachment.getContentInputStream(this.xcontextProvider .get()), true); } catch (XWikiException e) { this.logger.error("Faied to get attachment content [{}]", skinDocument.getDocumentReference(), e); } } } return null; } @SuppressWarnings("resource") private InputSource getTemplateStream(String template) { InputSource source = null; // Try from skin String skin = getSkin(); if (skin != null) { source = getTemplateStreamFromSkin(skin, template); } // Try from base skin if (source == null) { String baseSkin = getBaseSkin(); if (baseSkin != null) { source = getTemplateStreamFromSkin(baseSkin, template); } } // Try from /template/ resources if (source == null) { String templatePath = "/templates/" + template; // Prevent inclusion of templates from other directories String normalizedTemplate = URI.create(templatePath).normalize().toString(); if (!normalizedTemplate.startsWith("/templates/")) { this.logger.warn("Direct access to template file [{}] refused. Possible break-in attempt!", normalizedTemplate); return null; } InputStream inputStream = this.environment.getResourceAsStream(templatePath); if (inputStream != null) { source = new DefaultInputStreamInputSource(inputStream, true); } } return source; } private StringContent getStringContent(String template) throws IOException, ParseException { InputSource source = getTemplateStream(template); if (source == null) { return null; } String content; try { if (source instanceof StringInputSource) { content = source.toString(); } else if (source instanceof ReaderInputSource) { content = IOUtils.toString(((ReaderInputSource) source).getReader()); } else if (source instanceof InputStreamInputSource) { content = IOUtils.toString(((InputStreamInputSource) source).getInputStream(), "UTF-8"); } else { // Unsupported type return null; } } finally { source.close(); } Matcher matcher = FIRSTLINE.matcher(content); if (matcher.find()) { content = content.substring(matcher.end()); String syntaxString = matcher.group(2); Syntax syntax = this.syntaxFactory.createSyntaxFromIdString(syntaxString); String mode = matcher.group(1); switch (mode) { case "source": return new StringContent(content, syntax, null); case "raw": return new StringContent(content, null, syntax); default: break; } } // The default is xhtml to support old templates return new StringContent(content, null, Syntax.XHTML_1_0); } private void renderError(Throwable throwable, Writer writer) { XDOM xdom = generateError(throwable); render(xdom, writer); } private XDOM generateError(Throwable throwable) { List<Block> errorBlocks = new ArrayList<Block>(); // Add short message Map<String, String> errorBlockParams = Collections.singletonMap("class", "xwikirenderingerror"); errorBlocks.add(new GroupBlock(Arrays.<Block> asList(new WordBlock("Failed to render step content")), errorBlockParams)); // Add complete error StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); Block descriptionBlock = new VerbatimBlock(writer.toString(), false); Map<String, String> errorDescriptionBlockParams = Collections.singletonMap("class", "xwikirenderingerrordescription hidden"); errorBlocks.add(new GroupBlock(Arrays.asList(descriptionBlock), errorDescriptionBlockParams)); return new XDOM(errorBlocks); } private void transform(Block block) { TransformationContext txContext = new TransformationContext(block instanceof XDOM ? (XDOM) block : new XDOM(Arrays.asList(block)), this.renderingContext.getDefaultSyntax(), this.renderingContext.isRestricted()); txContext.setId(this.renderingContext.getTransformationId()); txContext.setTargetSyntax(getTargetSyntax()); try { this.transformationManager.performTransformations(block, txContext); } catch (Exception e) { throw new RuntimeException(e); } } /** * @param template the template to parse * @return the result of the template parsing */ public XDOM getXDOMNoException(String template) { XDOM xdom; try { xdom = getXDOM(template); } catch (Throwable e) { xdom = generateError(e); } return xdom; } private XDOM getXDOM(StringContent content) throws ParseException, MissingParserException, XWikiVelocityException { XDOM xdom; if (content != null) { if (content.sourceSyntax != null) { xdom = this.parser.parse(content.content, content.sourceSyntax); } else { String result = evaluateString(content.content); xdom = new XDOM(Arrays.asList(new RawBlock(result, content.rawSyntax))); } } else { xdom = new XDOM(Collections.<Block> emptyList()); } return xdom; } public XDOM getXDOM(String template) throws IOException, ParseException, MissingParserException, XWikiVelocityException { StringContent content = getStringContent(template); return getXDOM(content); } public String renderNoException(String template) { Writer writer = new StringWriter(); renderNoException(template, writer); return writer.toString(); } public void renderNoException(String template, Writer writer) { try { render(template, writer); } catch (Exception e) { renderError(e, writer); } } public String render(String template) throws IOException, ParseException, MissingParserException, XWikiVelocityException { Writer writer = new StringWriter(); render(template, writer); return writer.toString(); } public void render(String template, Writer writer) throws IOException, ParseException, MissingParserException, XWikiVelocityException { StringContent content = getStringContent(template); if (content != null) { if (content.sourceSyntax != null) { XDOM xdom = execute(content); render(xdom, writer); } else { evaluateString(content.content, writer); } } } private void render(XDOM xdom, Writer writer) { WikiPrinter printer = new WriterWikiPrinter(writer); BlockRenderer blockRenderer; try { blockRenderer = this.componentManagerProvider.get().getInstance(BlockRenderer.class, getTargetSyntax().toIdString()); } catch (ComponentLookupException e) { blockRenderer = this.plainRenderer; } blockRenderer.render(xdom, printer); } public XDOM executeNoException(String template) { XDOM xdom; try { xdom = execute(template); } catch (Throwable e) { xdom = generateError(e); } return xdom; } private XDOM execute(StringContent content) throws ParseException, MissingParserException, XWikiVelocityException { XDOM xdom = getXDOM(content); transform(xdom); return xdom; } public XDOM execute(String template) throws IOException, ParseException, MissingParserException, XWikiVelocityException { StringContent content = getStringContent(template); return execute(content); } private String evaluateString(String content) throws XWikiVelocityException { Writer writer = new StringWriter(); evaluateString(content, writer); return writer.toString(); } private void evaluateString(String content, Writer writer) throws XWikiVelocityException { VelocityContext velocityContext = this.velocityManager.getVelocityContext(); // Use the Transformation id as the name passed to the Velocity Engine. This name is used internally // by Velocity as a cache index key for caching macros. String namespace = this.renderingContext.getTransformationId(); if (namespace == null) { namespace = "unknown namespace"; } VelocityEngine velocityEngine = this.velocityManager.getVelocityEngine(); velocityEngine.startedUsingMacroNamespace(namespace); try { velocityEngine.evaluate(velocityContext, writer, namespace, content); } finally { velocityEngine.stoppedUsingMacroNamespace(namespace); } } private Syntax getTargetSyntax() { Syntax targetSyntax = this.renderingContext.getTargetSyntax(); return targetSyntax != null ? targetSyntax : Syntax.PLAIN_1_0; } }
package com.wirelust.cfmock; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.security.spec.InvalidKeySpecException; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import javax.validation.constraints.NotNull; import com.amazonaws.services.cloudfront.CloudFrontCookieSigner; import com.amazonaws.services.cloudfront.CloudFrontUrlSigner; import com.amazonaws.services.identitymanagement.model.Statement; import com.wirelust.cfmock.exceptions.CFMockException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SignatureValidator { private static final Logger LOGGER = LoggerFactory.getLogger(SignatureValidator.class); public static final String PARAM_EXPIRES = "Expires"; public static final String PARAM_KEY_PAIR_ID = "Key-Pair-Id"; public static final String COOKIE_EXPIRES = "CloudFront-Expires"; public static final String COOKIE_SIGNATURE = "CloudFront-Signature"; public static final String COOKIE_POLICY = "CloudFront-Policy"; public static final String COOKIE_KEY_PAIR_ID = "CloudFront-Key-Pair-Id"; public static final String PROTOCOL_HTTP = "http"; public static final String PROTOCOL_HTTPS = "https"; private SignatureValidator() { // static only class } /** * validate a signed URL * @param keyFile the key used to sign the url * @param resource the full signed URL * @return true if signature is valid and not expired */ public static boolean validateSignedUrl(File keyFile, String resource) { URL url; try { url = new URL(resource); } catch (MalformedURLException e) { throw new CFMockException(e); } Map<String, String> queryParams = splitQuery(url.getQuery()); Date expires = new Date(Long.parseLong(queryParams.get(PARAM_EXPIRES))*1000); Date now = new Date(); if (now.getTime() > expires.getTime()) { throw new CFMockException("Signature is expired"); } String port = getPort(url); String urlToCheck = url.getProtocol() + "://" + url.getHost() + port + url.getPath(); LOGGER.debug("checking URL:{}", urlToCheck); String keyPairId = queryParams.get(PARAM_KEY_PAIR_ID); String signedUrl; try { signedUrl = CloudFrontUrlSigner.getSignedURLWithCannedPolicy( null, null, keyFile, urlToCheck, keyPairId, expires); } catch (InvalidKeySpecException | IOException e) { throw new CFMockException(e); } return resource.equals(signedUrl); } /** * * @param keyFile pem key file * @param keyId id of the key * @param expires date when the signature expires * @param signature signature * @return true if the signature is valid */ public static boolean validateSignature(@NotNull final String url, @NotNull final File keyFile, @NotNull final String keyId, @NotNull final Date expires, @NotNull final String signature) { try { CloudFrontCookieSigner.CookiesForCannedPolicy cookiesForCannedPolicy = CloudFrontCookieSigner.getCookiesForCannedPolicy(null, null, keyFile, url, keyId, expires); return signature.equals(cookiesForCannedPolicy.getSignature().getValue()); } catch (InvalidKeySpecException | IOException e) { throw new CFMockException("unable to validate cookie", e); } } public static boolean validateSignature(@NotNull final String url, @NotNull final File keyFile, @NotNull final String keyId, @NotNull final CFPolicy policy, @NotNull final String signature) { try { if (policy.getStatements() == null || policy.getStatements().size() > 1) { throw new CFMockException("Only one policy statement supported at this time"); } CFPolicyStatement statement = policy.getStatements().get(0); CloudFrontCookieSigner.CookiesForCustomPolicy cookiesForCustomPolicy = CloudFrontCookieSigner.getCookiesForCustomPolicy(null, null, keyFile, statement.getResource(), keyId, statement.dateLessThan, statement.getDateGreaterThan(), null); return signature.equals(cookiesForCustomPolicy.getSignature().getValue()); } catch (InvalidKeySpecException | IOException e) { throw new CFMockException("unable to validate cookie", e); } } public static boolean validateSignature(@NotNull final SignedRequest signedRequest) { checkForNulls(signedRequest); if (signedRequest.getType() == SignedRequest.Type.REQUEST) { return validateSignedUrl(signedRequest.getKeyFile(), signedRequest.getUrl()); } else { if (signedRequest.getPolicy() == null) { return validateSignature(signedRequest.getUrl(), signedRequest.getKeyFile(), signedRequest.getKeyId(), signedRequest.getExpires(), signedRequest.getSignature()); } else { return validateSignature(signedRequest.getUrl(), signedRequest.getKeyFile(), signedRequest.getKeyId(), signedRequest.getPolicy(), signedRequest.getSignature()); } } } private static void checkForNulls(@NotNull final SignedRequest signedRequest) { if (signedRequest.getKeyFile() == null) { throw new CFMockException("key file cannot be null"); } if (signedRequest.getUrl() == null) { throw new CFMockException("url cannot be null"); } if (signedRequest.getType() == SignedRequest.Type.COOKIE) { checkForCookieNulls(signedRequest); } } private static void checkForCookieNulls(@NotNull final SignedRequest signedRequest) { if (signedRequest.getKeyId() == null) { throw new CFMockException("key id cannot be null for cookie based signatures"); } if (signedRequest.getExpires() == null && signedRequest.getPolicy() == null) { throw new CFMockException("either expires or policy must be set for cookie based signatures"); } if (signedRequest.getSignature() == null) { throw new CFMockException("signature cannot be null for cookie based signatures"); } } public static Map<String, String> splitQuery(final String query) { return splitQuery(query, Constants.DEFAULT_ENCODING); } public static Map<String, String> splitQuery(final String query, final String encoding) { Map<String, String> queryPairs = new LinkedHashMap<>(); String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf('='); try { queryPairs.put(URLDecoder.decode(pair.substring(0, idx), encoding), URLDecoder.decode(pair.substring(idx + 1), encoding)); } catch (UnsupportedEncodingException e) { throw new CFMockException(e); } } return queryPairs; } private static String getPort(URL url) { if (url.getPort() == -1) { return ""; } String port = ""; if (url.getProtocol().equalsIgnoreCase(PROTOCOL_HTTP) && url.getPort() != 80 || url.getProtocol().equalsIgnoreCase(PROTOCOL_HTTPS) && url.getPort() != 443) { port = ":" + url.getPort(); } return port; } }
package com.xpn.xwiki.store.hibernate.query; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.hibernate.Session; import org.xwiki.bridge.DocumentAccessBridge; import org.xwiki.component.annotation.Component; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.context.Execution; import org.xwiki.query.Query; import org.xwiki.query.QueryException; import org.xwiki.query.QueryExecutor; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback; import com.xpn.xwiki.store.XWikiHibernateStore; import com.xpn.xwiki.store.hibernate.HibernateSessionFactory; import com.xpn.xwiki.util.Util; import org.xwiki.query.QueryFilter; /** * QueryExecutor implementation for Hibernate Store. * * @version $Id$ * @since 1.6M1 */ @Component @Named("hql") @Singleton public class HqlQueryExecutor implements QueryExecutor, Initializable { /** * Session factory needed for register named queries mapping. */ @Inject private HibernateSessionFactory sessionFactory; /** * Path to hibernate mapping with named queries. Configured via component manager. */ private String mappingPath = "queries.hbm.xml"; /** * Used for access to XWikiContext. */ @Inject private Execution execution; /** * The bridge to the old XWiki core API, used to access user preferences. */ @Inject private DocumentAccessBridge documentAccessBridge; @Override public void initialize() throws InitializationException { this.sessionFactory.getConfiguration().addInputStream(Util.getResourceAsStream(this.mappingPath)); } @Override public <T> List<T> execute(final Query query) throws QueryException { String olddatabase = getContext().getDatabase(); try { if (query.getWiki() != null) { getContext().setDatabase(query.getWiki()); } return getStore().executeRead(getContext(), new HibernateCallback<List<T>>() { @SuppressWarnings("unchecked") @Override public List<T> doInHibernate(Session session) { org.hibernate.Query hquery = createHibernateQuery(session, query); populateParameters(hquery, query); if (query.getFilters() != null && !query.getFilters().isEmpty()) { List results = hquery.list(); for (QueryFilter filter : query.getFilters()) { results = filter.filterResults(results); } return (List<T>) results; } else { return hquery.list(); } } }); } catch (XWikiException e) { throw new QueryException("Exception while execute query", query, e); } finally { getContext().setDatabase(olddatabase); } } /** * Append the required select clause to HQL short query statements. Short statements are the only way for users * without programming rights to perform queries. Such statements can be for example: * <ul> * <li><code>, BaseObject obj where doc.fullName=obj.name and obj.className='XWiki.MyClass'</code></li> * <li><code>where doc.creationDate > '2008-01-01'</code></li> * </ul> * * @param statement the statement to complete if required. * @return the complete statement if it had to be completed, the original one otherwise. */ protected String completeShortFormStatement(String statement) { String lcStatement = statement.toLowerCase().trim(); if (lcStatement.startsWith("where") || lcStatement.startsWith(",") || lcStatement.startsWith("order")) { return "select doc.fullName from XWikiDocument doc " + statement.trim(); } return statement; } /** * @param session hibernate session * @param query Query object * @return hibernate query */ protected org.hibernate.Query createHibernateQuery(Session session, Query query) { org.hibernate.Query hquery; String statement = query.getStatement(); if (!query.isNamed()) { // handle short queries statement = completeShortFormStatement(statement); // Handle query filters if (query.getFilters() != null) { for (QueryFilter filter : query.getFilters()) { statement = filter.filterStatement(statement, Query.HQL); } } hquery = session.createQuery(statement); } else { hquery = session.getNamedQuery(query.getStatement()); if (query.getFilters() != null && !query.getFilters().isEmpty()) { // Since we can't modify the hibernate query statement at this point we need to create a new one to // apply the query filter. This comes with a performance cost, we could fix it by handling named queries // ourselves and not delegate them to hibernate. This way we would always get a statement that we can // transform before the execution. statement = hquery.getQueryString(); for (QueryFilter filter : query.getFilters()) { statement = filter.filterStatement(statement, Query.HQL); } hquery = session.createQuery(statement); } } return hquery; } /** * @param hquery query to populate parameters * @param query query from to populate. */ protected void populateParameters(org.hibernate.Query hquery, Query query) { if (query.getOffset() > 0) { hquery.setFirstResult(query.getOffset()); } if (query.getLimit() > 0) { hquery.setMaxResults(query.getLimit()); } for (Entry<String, Object> e : query.getNamedParameters().entrySet()) { hquery.setParameter(e.getKey(), e.getValue()); } if (query.getPositionalParameters().size() > 0) { int start = Collections.min(query.getPositionalParameters().keySet()); if (start == 0) { // jdbc-style positional parameters. "?" for (Entry<Integer, Object> e : query.getPositionalParameters().entrySet()) { hquery.setParameter(e.getKey(), e.getValue()); } } else { // jpql-style. "?index" for (Entry<Integer, Object> e : query.getPositionalParameters().entrySet()) { // hack. hibernate assume "?1" is named parameter, so use string "1". hquery.setParameter("" + e.getKey(), e.getValue()); } } } } /** * @return Store component */ protected XWikiHibernateStore getStore() { return getContext().getWiki().getHibernateStore(); } /** * @return XWiki Context */ protected XWikiContext getContext() { return (XWikiContext) this.execution.getContext().getProperty("xwikicontext"); } }
package com.intellij.codeInsight.template.impl; import com.intellij.codeInsight.template.Expression; import com.intellij.codeInsight.template.Template; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class TemplateImpl implements Template { private String myKey; private String myString = null; private String myDescription; private String myGroupName; private char myShortcutChar = TemplateSettings.DEFAULT_CHAR; private ArrayList<Variable> myVariables = new ArrayList<Variable>(); private ArrayList<Segment> mySegments = null; private String myTemplateText = null; public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TemplateImpl)) return false; final TemplateImpl template = (TemplateImpl) o; if (isToReformat != template.isToReformat) return false; if (isToShortenLongNames != template.isToShortenLongNames) return false; if (myShortcutChar != template.myShortcutChar) return false; if (myDescription != null ? !myDescription.equals(template.myDescription) : template.myDescription != null) return false; if (myGroupName != null ? !myGroupName.equals(template.myGroupName) : template.myGroupName != null) return false; if (myKey != null ? !myKey.equals(template.myKey) : template.myKey != null) return false; if (myString != null ? !myString.equals(template.myString) : template.myString != null) return false; if (myTemplateText != null ? !myTemplateText.equals(template.myTemplateText) : template.myTemplateText != null) return false; if (myVariables == null && template.myVariables == null) return true; if (myVariables == null || template.myVariables == null) return false; if (myVariables.size() != template.myVariables.size()) return false; for (Variable variable : myVariables) { if (template.myVariables.indexOf(variable) < 0) return false; } return true; } public int hashCode() { int result; result = myKey.hashCode(); result = 29 * result + myString.hashCode(); result = 29 * result + myGroupName.hashCode(); return result; } private boolean isToReformat = false; private boolean isToShortenLongNames = true; private boolean toParseSegments = true; private TemplateContext myTemplateContext = new TemplateContext(); public static final @NonNls String END = "END"; public static final @NonNls String SELECTION = "SELECTION"; public static final @NonNls String SELECTION_START = "SELECTION_START"; public static final @NonNls String SELECTION_END = "SELECTION_END"; public static final Set<String> INTERNAL_VARS_SET = new HashSet<String>(Arrays.asList( END, SELECTION, SELECTION_START, SELECTION_END)); private boolean isDeactivated = false; public boolean isInline() { return myIsInline; } private boolean isToIndent = true; public void setInline(boolean isInline) { myIsInline = isInline; } private boolean myIsInline = false; public TemplateImpl(String key, String group) { toParseSegments = false; myKey = key; myGroupName = group; myTemplateText = ""; mySegments = new ArrayList<Segment>(); } public void addTextSegment(String text) { text = StringUtil.convertLineSeparators(text, "\n"); myTemplateText = myTemplateText + text; } public void addVariableSegment (String name) { mySegments.add(new Segment(name, myTemplateText.length())); } public void addVariable(String name, Expression expression, Expression defaultValueExpression, boolean isAlwaysStopAt) { if (mySegments != null) { Segment segment = new Segment(name, myTemplateText.length()); mySegments.add(segment); } Variable variable = new Variable(name, expression, defaultValueExpression, isAlwaysStopAt); myVariables.add(variable); } public void addEndVariable() { Segment segment = new Segment(END, myTemplateText.length()); mySegments.add(segment); } public void addSelectionStartVariable() { Segment segment = new Segment(SELECTION_START, myTemplateText.length()); mySegments.add(segment); } public void addSelectionEndVariable() { Segment segment = new Segment(SELECTION_END, myTemplateText.length()); mySegments.add(segment); } public TemplateImpl(String key, String string, String group) { myKey = key; myString = string; myGroupName = group; } public TemplateImpl copy() { TemplateImpl template = new TemplateImpl(myKey, myString, myGroupName); template.myDescription = myDescription; template.myShortcutChar = myShortcutChar; template.isToReformat = isToReformat; template.isToShortenLongNames = isToShortenLongNames; template.myIsInline = myIsInline; template.myTemplateContext = (TemplateContext)myTemplateContext.clone(); template.isDeactivated = isDeactivated; for (Variable variable : myVariables) { template.addVariable(variable.getName(), variable.getExpressionString(), variable.getDefaultValueString(), variable.isAlwaysStopAt()); } return template; } public boolean isToReformat() { return isToReformat; } public void setToReformat(boolean toReformat) { isToReformat = toReformat; } public void setToIndent(boolean toIndent) { isToIndent = toIndent; } public boolean isToIndent() { return isToIndent; } public boolean isToShortenLongNames() { return isToShortenLongNames; } public void setToShortenLongNames(boolean toShortenLongNames) { isToShortenLongNames = toShortenLongNames; } public void setDeactivated(boolean isDeactivated) { this.isDeactivated = isDeactivated; } public boolean isDeactivated() { return isDeactivated; } public TemplateContext getTemplateContext() { return myTemplateContext; } public int getEndSegmentNumber() { return getVariableSegmentNumber(END); } public int getSelectionStartSegmentNumber() { return getVariableSegmentNumber(SELECTION_START); } public int getSelectionEndSegmentNumber() { return getVariableSegmentNumber(SELECTION_END); } public int getVariableSegmentNumber(String variableName) { parseSegments(); for (int i = 0; i < mySegments.size(); i++) { Segment segment = mySegments.get(i); if (segment.name.equals(variableName)) { return i; } } return -1; } public String getTemplateText() { parseSegments(); return myTemplateText; } public String getSegmentName(int i) { parseSegments(); return mySegments.get(i).name; } public int getSegmentOffset(int i) { parseSegments(); return mySegments.get(i).offset; } public int getSegmentsCount() { parseSegments(); return mySegments.size(); } public void parseSegments() { if(!toParseSegments) { return; } if(mySegments != null) { return; } if (myString == null) myString = ""; myString = StringUtil.convertLineSeparators(myString, "\n"); mySegments = new ArrayList<Segment>(); StringBuffer buffer = new StringBuffer(""); TemplateTextLexer lexer = new TemplateTextLexer(); lexer.start(myString.toCharArray()); while(true){ IElementType tokenType = lexer.getTokenType(); if (tokenType == null) break; int start = lexer.getTokenStart(); int end = lexer.getTokenEnd(); String token = myString.substring(start, end); if (tokenType == TemplateTokenType.VARIABLE){ String name = token.substring(1, token.length() - 1); Segment segment = new Segment(name, buffer.length()); mySegments.add(segment); } else if (tokenType == TemplateTokenType.ESCAPE_DOLLAR){ buffer.append("$"); } else{ buffer.append(token); } lexer.advance(); } myTemplateText = buffer.toString(); } public void removeAllParsed() { myVariables.clear(); mySegments = null; } public void addVariable(String name, String expression, String defaultValue, boolean isAlwaysStopAt) { Variable variable = new Variable(name, expression, defaultValue, isAlwaysStopAt); myVariables.add(variable); } public int getVariableCount() { return myVariables.size(); } public String getVariableNameAt(int i) { return myVariables.get(i).getName(); } public String getExpressionStringAt(int i) { return myVariables.get(i).getExpressionString(); } public Expression getExpressionAt(int i) { return myVariables.get(i).getExpression(); } public String getDefaultValueStringAt(int i) { return myVariables.get(i).getDefaultValueString(); } public Expression getDefaultValueAt(int i) { return myVariables.get(i).getDefaultValueExpression(); } public boolean isAlwaysStopAt(int i) { return myVariables.get(i).isAlwaysStopAt(); } public String getKey() { return myKey; } public void setKey(String key) { myKey = key; } public String getString() { parseSegments(); return myString; } public void setString(String string) { myString = string; } public String getDescription() { return myDescription; } public void setDescription(String description) { myDescription = description; } public char getShortcutChar() { return myShortcutChar; } public void setShortcutChar(char shortcutChar) { myShortcutChar = shortcutChar; } public String getGroupName() { return myGroupName; } public void setGroupName(String groupName) { myGroupName = groupName; } public boolean isSelectionTemplate() { for (Variable v : myVariables) { if (v.getName().equals(SELECTION)) return true; } return false; } private static class Segment { public String name; public int offset; public Segment(String name, int offset) { this.name = name; this.offset = offset; } } }
package net.sourceforge.javydreamercsw.validation.manager.web; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.fieldgroup.BeanFieldGroup; import com.vaadin.data.fieldgroup.FieldGroup; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.data.util.HierarchicalContainer; import com.vaadin.data.util.converter.Converter; import com.vaadin.event.ItemClickEvent; import com.vaadin.event.Transferable; import com.vaadin.event.dd.DragAndDropEvent; import com.vaadin.event.dd.DropHandler; import com.vaadin.event.dd.acceptcriteria.AcceptCriterion; import com.vaadin.icons.VaadinIcons; import com.vaadin.server.Page; import com.vaadin.server.ThemeResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.shared.MouseEventDetails.MouseButton; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.shared.ui.dd.VerticalDropLocation; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.Field; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.HorizontalSplitPanel; import com.vaadin.ui.Image; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Notification; import com.vaadin.ui.Panel; import com.vaadin.ui.PopupDateField; import com.vaadin.ui.TabSheet; import com.vaadin.ui.TabSheet.Tab; import com.vaadin.ui.TextArea; import com.vaadin.ui.Tree; import com.vaadin.ui.Tree.TreeDragMode; import com.vaadin.ui.Tree.TreeDropCriterion; import com.vaadin.ui.Tree.TreeTargetDetails; import com.vaadin.ui.TwinColSelect; import com.vaadin.ui.UI; import com.vaadin.ui.Upload; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.VerticalSplitPanel; import com.vaadin.ui.Window; import com.vaadin.ui.themes.ValoTheme; import com.validation.manager.core.DataBaseManager; import com.validation.manager.core.DemoBuilder; import com.validation.manager.core.db.Project; import com.validation.manager.core.db.Requirement; import com.validation.manager.core.db.RequirementSpec; import com.validation.manager.core.db.RequirementSpecNode; import com.validation.manager.core.db.RequirementSpecPK; import com.validation.manager.core.db.SpecLevel; import com.validation.manager.core.db.Step; import com.validation.manager.core.db.TestCase; import com.validation.manager.core.db.TestPlan; import com.validation.manager.core.db.TestProject; import com.validation.manager.core.db.controller.ProjectJpaController; import com.validation.manager.core.db.controller.RequirementJpaController; import com.validation.manager.core.db.controller.RequirementSpecJpaController; import com.validation.manager.core.db.controller.RequirementSpecNodeJpaController; import com.validation.manager.core.db.controller.SpecLevelJpaController; import com.validation.manager.core.db.controller.StepJpaController; import com.validation.manager.core.db.controller.TestCaseJpaController; import com.validation.manager.core.db.controller.TestPlanJpaController; import com.validation.manager.core.db.controller.TestProjectJpaController; import com.validation.manager.core.db.controller.VmUserJpaController; import com.validation.manager.core.db.controller.exceptions.NonexistentEntityException; import com.validation.manager.core.server.core.ProjectServer; import com.validation.manager.core.server.core.TestCaseServer; import com.validation.manager.core.server.core.VMUserServer; import com.validation.manager.core.tool.MD5; import com.validation.manager.core.tool.requirement.importer.RequirementImportException; import com.validation.manager.core.tool.requirement.importer.RequirementImporter; import com.validation.manager.core.tool.step.importer.StepImporter; import com.validation.manager.core.tool.step.importer.TestCaseImportException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.annotation.WebServlet; import net.sourceforge.javydreamercsw.validation.manager.web.importer.FileUploader; import org.openide.util.Exceptions; import org.vaadin.peter.contextmenu.ContextMenu; import org.vaadin.peter.contextmenu.ContextMenu.ContextMenuOpenedListener; import org.vaadin.peter.contextmenu.ContextMenu.ContextMenuOpenedOnTreeItemEvent; @Theme("vmtheme") @SuppressWarnings("serial") public class ValidationManagerUI extends UI { private static final ThreadLocal<ValidationManagerUI> THREAD_LOCAL = new ThreadLocal<>(); private final ThemeResource logo = new ThemeResource("vm_logo.png"), small = new ThemeResource("VMSmall.png"); private VMUserServer user = null; private static final Logger LOG = Logger.getLogger(ValidationManagerUI.class.getSimpleName()); private static VMDemoResetThread reset = null; private LoginDialog subwindow = null; private final String projTreeRoot = "Available Projects"; private Component left; private final TabSheet right = new TabSheet(); private final List<Project> projects = new ArrayList<>(); private final VaadinIcons projectIcon = VaadinIcons.RECORDS; private final VaadinIcons specIcon = VaadinIcons.BOOK; private final VaadinIcons requirementIcon = VaadinIcons.PIN; private final VaadinIcons testSuiteIcon = VaadinIcons.FILE_TREE; private final VaadinIcons testPlanIcon = VaadinIcons.FILE_TREE_SMALL; private final VaadinIcons testIcon = VaadinIcons.FILE_TEXT; private final VaadinIcons stepIcon = VaadinIcons.FILE_TREE_SUB; private final VaadinIcons importIcon = VaadinIcons.ARROW_CIRCLE_UP_O; private Tree tree; private Tab admin, tester, designer, demo; private final List<String> roles = new ArrayList<>(); /** * @return the user */ protected VMUserServer getUser() { return user; } /** * @param user the user to set */ protected void setUser(VMUserServer user) { this.user = user; updateScreen(); } private void displayRequirementSpecNode(RequirementSpecNode rsn) { displayRequirementSpecNode(rsn, false); } private void displayRequirementSpecNode(RequirementSpecNode rsn, boolean edit) { Panel form = new Panel("Requirement Specification Node Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(rsn.getClass()); binder.setItemDataSource(rsn); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field desc = binder.buildAndBind("Description", "description", TextArea.class); desc.setStyleName(ValoTheme.TEXTAREA_LARGE); desc.setSizeFull(); layout.addComponent(desc); Field<?> scope = binder.buildAndBind("Scope", "scope"); layout.addComponent(scope); if (edit) { if (rsn.getRequirementSpecNodePK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { rsn.setName(name.getValue().toString()); rsn.setDescription(desc.getValue().toString()); rsn.setScope(scope.getValue().toString()); rsn.setRequirementSpec((RequirementSpec) tree.getValue()); new RequirementSpecNodeJpaController(DataBaseManager .getEntityManagerFactory()).create(rsn); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(rsn); displayRequirementSpecNode(rsn, true); updateScreen(); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { rsn.setName(name.getValue().toString()); rsn.setDescription(desc.getValue().toString()); rsn.setScope(scope.getValue().toString()); new RequirementSpecNodeJpaController(DataBaseManager .getEntityManagerFactory()).edit(rsn); displayRequirementSpecNode(rsn, true); } catch (FieldGroup.CommitException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } private void setTabContent(Tab target, Component content) { Layout l = (Layout) right.getTab(right.getTabPosition(target)) .getComponent(); l.removeAllComponents(); l.addComponent(content); } private void displayStep(Step s) { displayStep(s, false); } private void displayStep(Step s, boolean edit) { Panel form = new Panel("Step Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(s.getClass()); binder.setItemDataSource(s); Field<?> sequence = binder.buildAndBind("Sequence", "stepSequence"); layout.addComponent(sequence); TextArea text = new TextArea("Text"); text.setConverter(new ByteToStringConverter()); binder.bind(text, "text"); layout.addComponent(text); TextArea result = new TextArea("Expected Result"); result.setConverter(new ByteToStringConverter()); binder.bind(result, "expectedResult"); layout.addComponent(result); Field<?> notes = binder.buildAndBind("Notes", "notes"); layout.addComponent(notes); tree.select(s); Project p = getParentProject(); List<Requirement> reqs = ProjectServer.getRequirements(p); Collections.sort(reqs, (Requirement o1, Requirement o2) -> o1.getUniqueId().compareTo(o2.getUniqueId())); BeanItemContainer<Requirement> requirementContainer = new BeanItemContainer<>(Requirement.class, reqs); TwinColSelect requirements = new TwinColSelect("Linked Requirements"); requirements.setItemCaptionPropertyId("uniqueId"); requirements.setContainerDataSource(requirementContainer); requirements.setRows(5); requirements.setLeftColumnCaption("Available Requirements"); requirements.setRightColumnCaption("Linked Requirements"); if (s.getRequirementList() != null) { s.getRequirementList().forEach((r) -> { requirements.select(r); }); } requirements.setEnabled(edit); layout.addComponent(requirements); if (edit) { if (s.getStepPK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { s.setExpectedResult(result.getValue() .getBytes("UTF-8")); s.setNotes(notes.getValue() == null ? "null" : notes.getValue().toString()); s.setStepSequence(Integer.parseInt(sequence .getValue().toString())); s.setTestCase((TestCase) tree.getValue()); s.setText(text.getValue().getBytes("UTF-8")); if (s.getRequirementList() == null) { s.setRequirementList(new ArrayList<>()); } s.getRequirementList().clear(); ((Set<Requirement>) requirements.getValue()).forEach((r) -> { s.getRequirementList().add(r); }); new StepJpaController(DataBaseManager .getEntityManagerFactory()).create(s); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); displayStep(s); buildProjectTree(s); updateScreen(); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { s.setExpectedResult(result.getValue() .getBytes("UTF-8")); s.setNotes(notes.getValue().toString()); s.setStepSequence(Integer.parseInt(sequence.getValue().toString())); s.setText(text.getValue().getBytes("UTF-8")); if (s.getRequirementList() == null) { s.setRequirementList(new ArrayList<>()); } s.getRequirementList().clear(); ((Set<Requirement>) requirements.getValue()).forEach((r) -> { s.getRequirementList().add(r); }); new StepJpaController(DataBaseManager .getEntityManagerFactory()).edit(s); displayStep(s, true); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } private void displayTestCase(TestCase t) { displayTestCase(t, false); } private void displayTestCase(TestCase t, boolean edit) { Panel form = new Panel("Test Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(t.getClass()); binder.setItemDataSource(t); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); TextArea summary = new TextArea("Summary"); summary.setConverter(new ByteToStringConverter()); binder.bind(summary, "summary"); layout.addComponent(summary); PopupDateField creation = new PopupDateField("Created on"); creation.setResolution(Resolution.SECOND); creation.setDateFormat("MM-dd-yyyy hh:hh:ss"); binder.bind(creation, "creationDate"); layout.addComponent(creation); Field<?> active = binder.buildAndBind("Active", "active"); layout.addComponent(active); Field<?> open = binder.buildAndBind("Open", "isOpen"); layout.addComponent(open); if (edit) { if (t.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { t.setName(name.getValue().toString()); t.setSummary(summary.getValue().getBytes("UTF-8")); t.setCreationDate((Date) creation.getValue()); t.setActive((Boolean) active.getValue()); t.setIsOpen((Boolean) open.getValue()); new TestCaseJpaController(DataBaseManager .getEntityManagerFactory()).create(t); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(t); displayTestCase(t, false); updateScreen(); } catch (UnsupportedEncodingException ex) { Exceptions.printStackTrace(ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { t.setName(name.getValue().toString()); t.setSummary(summary.getValue().getBytes("UTF-8")); t.setCreationDate((Date) creation.getValue()); t.setActive((Boolean) active.getValue()); t.setIsOpen((Boolean) open.getValue()); new TestCaseJpaController(DataBaseManager .getEntityManagerFactory()).edit(t); displayTestCase(t, true); } catch (FieldGroup.CommitException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setReadOnly(!edit); creation.setEnabled(false); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } private void displayTestPlan(TestPlan tp) { displayTestPlan(tp, false); } private void displayTestPlan(TestPlan tp, boolean edit) { Panel form = new Panel("Test Plan Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(tp.getClass()); binder.setItemDataSource(tp); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field<?> notes = binder.buildAndBind("Notes", "notes"); layout.addComponent(notes); Field<?> active = binder.buildAndBind("Active", "active"); layout.addComponent(active); Field<?> open = binder.buildAndBind("Open", "isOpen"); layout.addComponent(open); if (edit) { if (tp.getTestPlanPK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) active.getValue()); tp.setIsOpen((Boolean) open.getValue()); new TestPlanJpaController(DataBaseManager .getEntityManagerFactory()).create(tp); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(tp); displayTestPlan(tp, false); updateScreen(); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) open.getValue()); tp.setIsOpen((Boolean) open.getValue()); new TestPlanJpaController(DataBaseManager .getEntityManagerFactory()).edit(tp); displayTestPlan(tp, true); } catch (FieldGroup.CommitException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } private void displayTestProject(TestProject tp) { displayTestProject(tp, false); } private void displayTestProject(TestProject tp, boolean edit) { Panel form = new Panel("Test Project Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(tp.getClass()); binder.setItemDataSource(tp); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field<?> notes = binder.buildAndBind("Notes", "notes"); layout.addComponent(notes); Field<?> active = binder.buildAndBind("Active", "active"); layout.addComponent(active); if (edit) { if (tp.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) active.getValue()); new TestProjectJpaController(DataBaseManager .getEntityManagerFactory()).create(tp); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(tp); displayTestProject(tp, false); updateScreen(); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) active.getValue()); new TestProjectJpaController(DataBaseManager .getEntityManagerFactory()).edit(tp); displayTestProject(tp, true); } catch (FieldGroup.CommitException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } private void displayRequirementSpec(RequirementSpec rs) { displayRequirementSpec(rs, false); } private void displayRequirementSpec(RequirementSpec rs, boolean edit) { Panel form = new Panel("Requirement Specification Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(rs.getClass()); binder.setItemDataSource(rs); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field desc = binder.buildAndBind("Description", "description", TextArea.class); desc.setSizeFull(); layout.addComponent(desc); Field<?> date = binder.buildAndBind("Modification Date", "modificationDate"); layout.addComponent(date); date.setEnabled(false); SpecLevelJpaController controller = new SpecLevelJpaController(DataBaseManager .getEntityManagerFactory()); List<SpecLevel> levels = controller.findSpecLevelEntities(); BeanItemContainer<SpecLevel> specLevelContainer = new BeanItemContainer<>(SpecLevel.class, levels); ComboBox level = new ComboBox("Spec Level"); level.setItemCaptionPropertyId("name"); level.setContainerDataSource(specLevelContainer); binder.bind(level, "specLevel"); layout.addComponent(level); if (edit) { if (rs.getRequirementSpecPK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { rs.setName(name.getValue().toString()); rs.setModificationDate(new Date()); rs.setSpecLevel((SpecLevel) level.getValue()); rs.setProject(((Project) tree.getValue())); rs.setRequirementSpecPK(new RequirementSpecPK( rs.getProject().getId(), rs.getSpecLevel().getId())); new RequirementSpecJpaController(DataBaseManager .getEntityManagerFactory()).create(rs); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(rs); displayRequirementSpec(rs, false); updateScreen(); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { rs.setName(name.getValue().toString()); rs.setModificationDate(new Date()); rs.setSpecLevel((SpecLevel) level.getValue()); new RequirementSpecJpaController(DataBaseManager .getEntityManagerFactory()).edit(rs); displayRequirementSpec(rs, true); } catch (FieldGroup.CommitException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } private void displayRequirement(Requirement req) { displayRequirement(req, false); } private void displayRequirement(Requirement req, boolean edit) { Panel form = new Panel("Requirement Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(req.getClass()); binder.setItemDataSource(req); Field<?> id = binder.buildAndBind("Requirement ID", "uniqueId"); layout.addComponent(id); Field desc = binder.buildAndBind("Description", "description", TextArea.class); desc.setStyleName(ValoTheme.TEXTAREA_LARGE); desc.setSizeFull(); layout.addComponent(desc); layout.addComponent(binder.buildAndBind("Notes", "notes")); if (edit) { if (req.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { req.setUniqueId(id.getValue().toString()); req.setDescription(desc.getValue().toString()); new RequirementJpaController(DataBaseManager .getEntityManagerFactory()).create(req); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(req); displayRequirement(req, false); updateScreen(); }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { binder.commit(); } catch (FieldGroup.CommitException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setBuffered(true); binder.setReadOnly(!edit); binder.bindMemberFields(form); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } // @return the current application instance public static ValidationManagerUI getInstance() { return THREAD_LOCAL.get(); } // Set the current application instance public static void setInstance(ValidationManagerUI application) { THREAD_LOCAL.set(application); } private static void buildDemoTree() { try { DemoBuilder.buildDemoProject(); } catch (NonexistentEntityException ex) { Exceptions.printStackTrace(ex); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } private void buildProjectTree() { buildProjectTree(null); } private void buildProjectTree(Object item) { tree.removeAllItems(); tree.addItem(projTreeRoot); projects.forEach((p) -> { if (p.getParentProjectId() == null) { addProject(p, tree); } }); if (item == null) { tree.expandItem(projTreeRoot); } else { tree.select(item); Object parent = tree.getParent(item); while (parent != null) { tree.expandItem(parent); parent = tree.getParent(parent); } } } private void createRootMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Project", projectIcon); create.setEnabled(checkRight("product.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayProject(new Project(), true); }); } private void createTestPlanMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Test Case", specIcon); create.setEnabled(checkRight("testplan.planning")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Test Plan", specIcon); edit.setEnabled(checkRight("testplan.planning")); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestPlan((TestPlan) tree.getValue(), true); }); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestCase tc = new TestCase(); tc.setTestPlanList(new ArrayList<>()); tc.getTestPlanList().add((TestPlan) tree.getValue()); tc.setCreationDate(new Date()); displayTestCase(tc, true); }); } private void createProjectMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Sub Project", projectIcon); create.setEnabled(checkRight("requirement.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { Project project = new Project(); project.setParentProjectId((Project) tree.getValue()); displayProject(project, true); }); ContextMenu.ContextMenuItem createSpec = menu.addItem("Create Requirement Spec", specIcon); createSpec.setEnabled(checkRight("requirement.modify")); createSpec.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { RequirementSpec rs = new RequirementSpec(); rs.setProject((Project) tree.getValue()); displayRequirementSpec(rs, true); }); ContextMenu.ContextMenuItem createTest = menu.addItem("Create Test Suite", testSuiteIcon); createTest.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Project", VaadinIcons.EDIT); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayProject((Project) tree.getValue(), true); }); edit.setEnabled(checkRight("product.modify")); createTest.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestProject tp = new TestProject(); tp.setProjectList(new ArrayList<>()); tp.getProjectList().add((Project) tree.getValue()); displayTestProject(tp, true); }); } private void createRequirementMenu(ContextMenu menu) { ContextMenu.ContextMenuItem edit = menu.addItem("Edit Requirement", VaadinIcons.EDIT); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayRequirement((Requirement) tree.getValue(), true); }); edit.setEnabled(checkRight("requirement.modify")); } private void createRequirementSpecMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Requirement Spec Node", specIcon); create.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Requirement Spec", specIcon); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayRequirementSpec((RequirementSpec) tree.getValue(), true); }); edit.setEnabled(checkRight("requirement.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { RequirementSpecNode rs = new RequirementSpecNode(); rs.setRequirementSpec((RequirementSpec) tree.getValue()); displayRequirementSpecNode(rs, true); }); } private void createRequirementSpecNodeMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Requirement Spec", VaadinIcons.PLUS); create.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Requirement Spec Node", VaadinIcons.EDIT); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayRequirementSpecNode((RequirementSpecNode) tree.getValue(), true); }); edit.setEnabled(checkRight("requirement.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { Requirement r = new Requirement(); r.setRequirementSpecNode((RequirementSpecNode) tree.getValue()); displayRequirement(r, true); }); ContextMenu.ContextMenuItem importRequirement = menu.addItem("Import Requirements", importIcon); importRequirement.setEnabled(checkRight("requirement.modify")); importRequirement.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { // Create a sub-window and set the content Window subWindow = new Window("Import Requirements"); VerticalLayout subContent = new VerticalLayout(); subWindow.setContent(subContent); //Add a checkbox to know if file has headers or not CheckBox cb = new CheckBox("File has header row?"); FileUploader receiver = new FileUploader(); Upload upload = new Upload("Upload Excel Spreadsheet here", receiver); upload.addSucceededListener((Upload.SucceededEvent event1) -> { try { subWindow.close(); //TODO: Display the excel file (partially), map columns and import //Process the file RequirementImporter importer = new RequirementImporter(receiver.getFile(), (RequirementSpecNode) tree.getValue()); importer.importFile(cb.getValue()); importer.processImport(); buildProjectTree(tree.getValue()); updateScreen(); } catch (RequirementImportException ex) { LOG.log(Level.SEVERE, "Error processing import!", ex); Notification.show("Importing unsuccessful!", Notification.Type.ERROR_MESSAGE); } }); upload.addFailedListener((Upload.FailedEvent event1) -> { LOG.log(Level.SEVERE, "Upload unsuccessful!\n{0}", event1.getReason()); Notification.show("Upload unsuccessful!", Notification.Type.ERROR_MESSAGE); subWindow.close(); }); subContent.addComponent(cb); subContent.addComponent(upload); // Center it in the browser window subWindow.center(); // Open it in the UI addWindow(subWindow); }); } private void createTestCaseMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Step", VaadinIcons.PLUS); create.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Test Case", VaadinIcons.EDIT); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestCase((TestCase) tree.getValue(), true); }); edit.setEnabled(checkRight("testcase.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestCase tc = (TestCase) tree.getValue(); Step s = new Step(); s.setStepSequence(tc.getStepList().size() + 1); s.setTestCase(tc); displayStep(s, true); }); ContextMenu.ContextMenuItem importSteps = menu.addItem("Import Steps", importIcon); importSteps.setEnabled(checkRight("requirement.modify")); importSteps.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { // Create a sub-window and set the content Window subWindow = new Window("Import Test Case Steps"); VerticalLayout subContent = new VerticalLayout(); subWindow.setContent(subContent); //Add a checkbox to know if file has headers or not CheckBox cb = new CheckBox("File has header row?"); FileUploader receiver = new FileUploader(); Upload upload = new Upload("Upload Excel Spreadsheet here", receiver); upload.addSucceededListener((Upload.SucceededEvent event1) -> { try { subWindow.close(); //TODO: Display the excel file (partially), map columns and import //Process the file TestCase tc = (TestCase) tree.getValue(); StepImporter importer = new StepImporter(receiver.getFile(), tc); importer.importFile(cb.getValue()); importer.processImport(); SortedMap<Integer, Step> map = new TreeMap<>(); tc.getStepList().forEach((s) -> { map.put(s.getStepSequence(), s); }); //Now update the sequence numbers int count = 0; for (Entry<Integer, Step> entry : map.entrySet()) { entry.getValue().setStepSequence(++count); try { new StepJpaController(DataBaseManager .getEntityManagerFactory()) .edit(entry.getValue()); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } buildProjectTree(new TestCaseServer(tc.getId()).getEntity()); updateScreen(); } catch (TestCaseImportException ex) { LOG.log(Level.SEVERE, "Error processing import!", ex); Notification.show("Importing unsuccessful!", Notification.Type.ERROR_MESSAGE); } }); upload.addFailedListener((Upload.FailedEvent event1) -> { LOG.log(Level.SEVERE, "Upload unsuccessful!\n{0}", event1.getReason()); Notification.show("Upload unsuccessful!", Notification.Type.ERROR_MESSAGE); subWindow.close(); }); subContent.addComponent(cb); subContent.addComponent(upload); // Center it in the browser window subWindow.center(); // Open it in the UI addWindow(subWindow); }); } private void createStepMenu(ContextMenu menu) { ContextMenu.ContextMenuItem edit = menu.addItem("Edit Step", VaadinIcons.EDIT); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayStep((Step) tree.getValue(), true); }); edit.setEnabled(checkRight("testcase.modify")); } private void createTestProjectMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Test Plan", VaadinIcons.PLUS); create.setEnabled(checkRight("testplan.planning")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Test Project", VaadinIcons.EDIT); edit.setEnabled(checkRight("testplan.planning")); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestProject((TestProject) tree.getValue(), true); }); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestPlan tp = new TestPlan(); tp.setTestProject((TestProject) tree.getValue()); displayTestPlan(tp, true); }); } private Component getContentComponent() { HorizontalSplitPanel hsplit = new HorizontalSplitPanel(); hsplit.setLocked(true); if (left != null) { if (!(left instanceof Panel)) { left = new Panel(left); } if (user != null) { hsplit.setFirstComponent(left); } } //Build the right component if (right != null) { //This is a tabbed pane. Enable/Disable the panes based on role TabSheet tab = (TabSheet) right; if (getUser() != null) { roles.clear(); user.update();//Get any recent changes user.getRoleList().forEach((r) -> { roles.add(r.getRoleName()); }); } if (demo == null && DataBaseManager.isDemo()) { VerticalLayout layout = new VerticalLayout(); VmUserJpaController controller = new VmUserJpaController(DataBaseManager .getEntityManagerFactory()); layout.addComponent(new Label("<h1>Welcome to " + "Validation Manager Demo instance</h1>", ContentMode.HTML)); layout.addComponent(new Label("Below you can find the " + "various accounts that exist in the demo so " + "you can explore.")); StringBuilder sb = new StringBuilder("<ul>"); controller.findVmUserEntities().stream().filter((u) -> (u.getId() < 1000)).forEachOrdered((u) -> { try { //Default accounts if (u.getPassword().equals(MD5 .encrypt(u.getUsername()))) { sb.append("<li><b>User name:</b> ") .append(u.getUsername()) .append(", <b>Password:</b> ") .append(u.getUsername()) .append(" <b>Role</b>: ") .append(u.getRoleList().get(0) .getDescription()) .append("</li>"); } } catch (Exception ex) { Exceptions.printStackTrace(ex); } }); sb.append("</ul>"); layout.addComponent(new Label(sb.toString(), ContentMode.HTML)); demo = tab.addTab(layout, "Demo"); } if (admin == null) { admin = tab.addTab(new VerticalLayout(), "Admin"); } if (tester == null) { tester = tab.addTab(new VerticalLayout(), "Tester"); } if (designer == null) { designer = tab.addTab(new VerticalLayout(), "Test Designer"); } admin.setVisible(checkRight("system.configuration")); tester.setVisible(checkRight("testplan.execute")); designer.setVisible(checkRight("testplan.planning")); hsplit.setSecondComponent(right); } hsplit.setSplitPosition(25, Unit.PERCENTAGE); return hsplit; } private Component getMenu() { HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(new Image("", logo)); return hl; } private void updateScreen() { //Set up a menu header on top and the content below VerticalSplitPanel vs = new VerticalSplitPanel(); vs.setSplitPosition(20, Unit.PERCENTAGE); //Set up top menu panel vs.setFirstComponent(getMenu()); //Add the content vs.setSecondComponent(getContentComponent()); setContent(vs); if (getUser() == null) { showLoginDialog(); } } private void displayProject(Project p) { displayProject(p, false); } private void displayProject(Project p, boolean edit) { // Bind it to a component Panel form = new Panel("Project Detail"); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); FormLayout layout = new FormLayout(); form.setContent(layout); BeanFieldGroup binder = new BeanFieldGroup(p.getClass()); binder.setItemDataSource(p); Field<?> name = binder.buildAndBind("Name", "name"); Field<?> notes = binder.buildAndBind("Notes", "notes"); layout.addComponent(name); layout.addComponent(notes); if (edit) { if (p.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { p.setName(name.getValue().toString()); p.setNotes(notes.getValue().toString()); new ProjectJpaController(DataBaseManager .getEntityManagerFactory()).create(p); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(p); displayProject(p, false); updateScreen(); }); layout.addComponent(save); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { binder.commit(); } catch (FieldGroup.CommitException ex) { Exceptions.printStackTrace(ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); layout.addComponent(update); } } binder.setBuffered(true); binder.setReadOnly(!edit); binder.bindMemberFields(form); form.setSizeFull(); setTabContent(admin, form); updateScreen(); } private void addRequirementSpec(RequirementSpec rs, Tree tree) { // Add the item as a regular item. tree.addItem(rs); tree.setItemCaption(rs, rs.getName()); tree.setItemIcon(rs, specIcon); // Set it to be a child. tree.setParent(rs, rs.getProject()); if (rs.getRequirementSpecNodeList().isEmpty()) { //No children tree.setChildrenAllowed(rs, false); } else { rs.getRequirementSpecNodeList().forEach((rsn) -> { addRequirementSpecsNode(rsn, tree); }); } } private void addRequirementSpecsNode(RequirementSpecNode rsn, Tree tree) { // Add the item as a regular item. tree.addItem(rsn); tree.setItemCaption(rsn, rsn.getName()); tree.setItemIcon(rsn, specIcon); // Set it to be a child. tree.setParent(rsn, rsn.getRequirementSpec()); if (rsn.getRequirementList().isEmpty()) { //No children tree.setChildrenAllowed(rsn, false); } else { ArrayList<Requirement> list = new ArrayList<>(rsn.getRequirementList()); Collections.sort(list, (Requirement o1, Requirement o2) -> o1.getUniqueId().compareTo(o2.getUniqueId())); list.forEach((req) -> { addRequirement(req, tree); }); } } private void addTestProject(TestProject tp, Tree tree) { tree.addItem(tp); tree.setItemCaption(tp, tp.getName()); tree.setItemIcon(tp, testSuiteIcon); tree.setParent(tp, tp.getProjectList().get(0)); boolean children = false; if (!tp.getTestPlanList().isEmpty()) { tp.getTestPlanList().forEach((plan) -> { addTestPlan(plan, tree); }); children = true; } tree.setChildrenAllowed(tp, children); } private void addTestPlan(TestPlan tp, Tree tree) { tree.addItem(tp); tree.setItemCaption(tp, tp.getName()); tree.setItemIcon(tp, testPlanIcon); tree.setParent(tp, tp.getTestProject()); if (!tp.getTestCaseList().isEmpty()) { tp.getTestCaseList().forEach((tc) -> { addTestCase(tc, tp, tree); }); } } private void addTestCase(TestCase t, TestPlan plan, Tree tree) { tree.addItem(t); tree.setItemCaption(t, t.getName()); tree.setItemIcon(t, testIcon); tree.setParent(t, plan); List<Step> stepList = t.getStepList(); Collections.sort(stepList, (Step o1, Step o2) -> o1.getStepSequence() - o2.getStepSequence()); stepList.forEach((s) -> { addStep(s, tree); }); } private void addStep(Step s, Tree tree) { tree.addItem(s); tree.setItemCaption(s, "Step # " + s.getStepSequence()); tree.setItemIcon(s, stepIcon); tree.setParent(s, s.getTestCase()); tree.setChildrenAllowed(s, false); } private void addRequirement(Requirement req, Tree tree) { // Add the item as a regular item. tree.addItem(req); tree.setItemCaption(req, req.getUniqueId()); tree.setItemIcon(req, requirementIcon); tree.setParent(req, req.getRequirementSpecNode()); //No children tree.setChildrenAllowed(req, false); } public void addProject(Project p, Tree tree) { tree.addItem(p); tree.setItemCaption(p, p.getName()); tree.setParent(p, p.getParentProjectId() == null ? projTreeRoot : p.getParentProjectId()); tree.setItemIcon(p, projectIcon); boolean children = false; if (!p.getProjectList().isEmpty()) { p.getProjectList().forEach((sp) -> { addProject(sp, tree); }); children = true; } if (!p.getRequirementSpecList().isEmpty()) { p.getRequirementSpecList().forEach((rs) -> { addRequirementSpec(rs, tree); }); children = true; } if (!p.getTestProjectList().isEmpty()) { p.getTestProjectList().forEach((tp) -> { addTestProject(tp, tree); }); children = true; } if (!children) { // No subprojects tree.setChildrenAllowed(p, false); } } @Override protected void init(VaadinRequest request) { //Connect to the database defined in context.xml DataBaseManager.setPersistenceUnitName("VMPUJNDI"); setInstance(this); ProjectJpaController controller = new ProjectJpaController(DataBaseManager .getEntityManagerFactory()); if (DataBaseManager.isDemo() && controller.findProjectEntities().isEmpty()) { buildDemoTree(); } tree = new Tree(); // Set the tree in drag source mode tree.setDragMode(TreeDragMode.NODE); // Allow the tree to receive drag drops and handle them tree.setDropHandler(new DropHandler() { @Override public AcceptCriterion getAcceptCriterion() { TreeDropCriterion criterion = new TreeDropCriterion() { @Override protected Set<Object> getAllowedItemIds( DragAndDropEvent dragEvent, Tree tree) { HashSet<Object> allowed = new HashSet<>(); tree.getItemIds().stream().filter((itemId) -> (itemId instanceof Step)).forEachOrdered((itemId) -> { allowed.add(itemId); }); return allowed; } }; return criterion; } @Override public void drop(DragAndDropEvent event) { // Wrapper for the object that is dragged Transferable t = event.getTransferable(); // Make sure the drag source is the same tree if (t.getSourceComponent() != tree) { return; } TreeTargetDetails target = (TreeTargetDetails) event.getTargetDetails(); // Get ids of the dragged item and the target item Object sourceItemId = t.getData("itemId"); Object targetItemId = target.getItemIdOver(); LOG.log(Level.INFO, "Source: {0}", sourceItemId); LOG.log(Level.INFO, "Target: {0}", targetItemId); // On which side of the target the item was dropped VerticalDropLocation location = target.getDropLocation(); HierarchicalContainer container = (HierarchicalContainer) tree.getContainerDataSource(); if (null != location) // Drop right on an item -> make it a child { switch (location) { case MIDDLE: if (tree.areChildrenAllowed(targetItemId)) { tree.setParent(sourceItemId, targetItemId); } break; case TOP: { //for Steps we need to update the sequence number if (sourceItemId instanceof Step && targetItemId instanceof Step) { Step targetItem = (Step) targetItemId; Step sourceItem = (Step) sourceItemId; StepJpaController stepController = new StepJpaController(DataBaseManager.getEntityManagerFactory()); // TestCaseJpaController tcController // = new TestCaseJpaController(DataBaseManager.getEntityManagerFactory()); boolean valid = false; if (targetItem.getTestCase().equals(sourceItem.getTestCase())) { //Same Test Case, just re-arrange LOG.info("Same Test Case!"); SortedMap<Integer, Step> map = new TreeMap<>(); targetItem.getTestCase().getStepList().forEach((s) -> { map.put(s.getStepSequence(), s); }); //Now swap the two that switched swapValues(map, sourceItem.getStepSequence(), targetItem.getStepSequence()); //Now update the sequence numbers int count = 0; for (Entry<Integer, Step> entry : map.entrySet()) { entry.getValue().setStepSequence(++count); try { stepController.edit(entry.getValue()); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } valid = true; } else { //Diferent Test Case LOG.info("Different Test Case!"); // //Remove from source test case // SortedMap<Integer, Step> map = new TreeMap<>(); // sourceItem.getTestCase().getStepList().forEach((s) -> { // map.put(s.getStepSequence(), s); // //Now swap the two that switched // //First we remove the one from the source Test Case // Step removed = map.remove(sourceItem.getStepSequence() - 1); // sourceItem.getTestCase().getStepList().remove(removed); // removed.setTestCase(targetItem.getTestCase()); // try { // stepController.edit(removed); // tcController.edit(sourceItem.getTestCase()); // } catch (NonexistentEntityException ex) { // Exceptions.printStackTrace(ex); // } catch (Exception ex) { // Exceptions.printStackTrace(ex); // //Now update the sequence numbers // int count = 0; // for (Entry<Integer, Step> entry : map.entrySet()) { // entry.getValue().setStepSequence(++count); // try { // stepController.edit(entry.getValue()); // } catch (Exception ex) { // Exceptions.printStackTrace(ex); // //And add it to the target test Case // SortedMap<Integer, Step> map2 = new TreeMap<>(); // targetItem.getTestCase().getStepList().forEach((s) -> { // map2.put(s.getStepSequence(), s); // map2.put(targetItem.getStepSequence() - 1, removed); // count = 0; // for (Entry<Integer, Step> entry : map2.entrySet()) { // entry.getValue().setStepSequence(++count); // try { // stepController.edit(entry.getValue()); // } catch (Exception ex) { // Exceptions.printStackTrace(ex); // //Add it to the Test Case // targetItem.getTestCase().getStepList().add(removed); } if (valid) { // Drop at the top of a subtree -> make it previous Object parentId = container.getParent(targetItemId); container.setParent(sourceItemId, parentId); container.moveAfterSibling(sourceItemId, targetItemId); container.moveAfterSibling(targetItemId, sourceItemId); buildProjectTree(targetItem); updateScreen(); } } break; } case BOTTOM: { // Drop below another item -> make it next Object parentId = container.getParent(targetItemId); container.setParent(sourceItemId, parentId); container.moveAfterSibling(sourceItemId, targetItemId); break; } default: break; } } } }); tree.addValueChangeListener((Property.ValueChangeEvent event) -> { if (tree.getValue() instanceof Project) { Project p = (Project) tree.getValue(); LOG.log(Level.FINE, "Selected: {0}", p.getName()); displayProject(p); } else if (tree.getValue() instanceof Requirement) { Requirement req = (Requirement) tree.getValue(); LOG.log(Level.FINE, "Selected: {0}", req.getUniqueId()); displayRequirement(req); } else if (tree.getValue() instanceof RequirementSpec) { RequirementSpec rs = (RequirementSpec) tree.getValue(); LOG.log(Level.FINE, "Selected: {0}", rs.getName()); displayRequirementSpec(rs); } else if (tree.getValue() instanceof RequirementSpecNode) { RequirementSpecNode rsn = (RequirementSpecNode) tree.getValue(); LOG.log(Level.FINE, "Selected: {0}", rsn.getName()); displayRequirementSpecNode(rsn); } else if (tree.getValue() instanceof TestProject) { TestProject tp = (TestProject) tree.getValue(); LOG.log(Level.FINE, "Selected: {0}", tp.getName()); displayTestProject(tp); } else if (tree.getValue() instanceof TestPlan) { TestPlan tp = (TestPlan) tree.getValue(); LOG.log(Level.FINE, "Selected: {0}", tp.getName()); displayTestPlan(tp); } else if (tree.getValue() instanceof TestCase) { TestCase tc = (TestCase) tree.getValue(); LOG.log(Level.FINE, "Selected: {0}", tc.getName()); displayTestCase(tc); } else if (tree.getValue() instanceof Step) { Step step = (Step) tree.getValue(); LOG.log(Level.FINE, "Selected: Step step.getStepSequence()); displayStep(step); } }); //Select item on right click as well tree.addItemClickListener((ItemClickEvent event) -> { if (event.getSource() == tree && event.getButton() == MouseButton.RIGHT) { if (event.getItem() != null) { Item clicked = event.getItem(); tree.select(event.getItemId()); } } }); ContextMenu contextMenu = new ContextMenu(); contextMenu.setAsContextMenuOf(tree); ContextMenuOpenedListener.TreeListener treeItemListener = (ContextMenuOpenedOnTreeItemEvent event) -> { contextMenu.removeAllItems(); if (tree.getValue() instanceof Project) { createProjectMenu(contextMenu); } else if (tree.getValue() instanceof Requirement) { createRequirementMenu(contextMenu); } else if (tree.getValue() instanceof RequirementSpec) { createRequirementSpecMenu(contextMenu); } else if (tree.getValue() instanceof RequirementSpecNode) { createRequirementSpecNodeMenu(contextMenu); } else if (tree.getValue() instanceof TestProject) { createTestProjectMenu(contextMenu); } else if (tree.getValue() instanceof Step) { createStepMenu(contextMenu); } else if (tree.getValue() instanceof TestCase) { createTestCaseMenu(contextMenu); } else if (tree.getValue() instanceof String) { //We are at the root createRootMenu(contextMenu); } else if (tree.getValue() instanceof TestPlan) { createTestPlanMenu(contextMenu); } }; contextMenu.addContextMenuTreeListener(treeItemListener); tree.setImmediate(true); tree.expandItem(projTreeRoot); tree.setSizeFull(); updateProjectList(); updateScreen(); Page.getCurrent().setTitle("Validation Manager"); } private static <V> void swapValues(SortedMap m, int i0, int i1) { Object first = m.get(i0); Object second = m.get(i1); m.put(i0, second); m.put(i1, first); } private void updateProjectList() { ProjectJpaController controller = new ProjectJpaController(DataBaseManager .getEntityManagerFactory()); if (DataBaseManager.isDemo() && controller.findProjectEntities().isEmpty()) { buildDemoTree(); } List<Project> all = controller.findProjectEntities(); projects.clear(); all.stream().filter((p) -> (p.getParentProjectId() == null)).forEachOrdered((p) -> { projects.add(p); }); buildProjectTree(); left = new HorizontalLayout(tree); LOG.log(Level.FINE, "Found {0} root projects!", projects.size()); } private void showLoginDialog() { if (subwindow == null) { subwindow = new LoginDialog(this, small); subwindow.setVisible(true); subwindow.setClosable(false); subwindow.setResizable(false); subwindow.center(); subwindow.setWidth(25, Unit.PERCENTAGE); subwindow.setHeight(25, Unit.PERCENTAGE); addWindow(subwindow); } else { subwindow.setVisible(true); } } private Project getParentProject() { Object current = tree.getValue(); Project result = null; while (current != null && !(current instanceof Project)) { current = tree.getParent(current); } if (current instanceof Project) { result = (Project) current; } return result; } private boolean checkAnyRights(List<String> rights) { boolean result = false; if (rights.stream().anyMatch((r) -> (checkRight(r)))) { return true; } return result; } private boolean checkAllRights(List<String> rights) { boolean result = true; for (String r : rights) { if (!checkRight(r)) { result = false; break; } } return result; } private boolean checkRight(String right) { if (user != null) { user.update(); return user.getRoleList().stream().anyMatch((r) -> (r.getUserRightList().stream().anyMatch((ur) -> (ur.getDescription().equals(right))))); } return false; }
package openiss.utils; import openiss.Kinect; import openiss.ws.soap.endpoint.ServicePublisher; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.nio.file.Files; public class OpenISSImageDriver { private static String colorFileName = "src/api/java/openiss/ws/soap/service/color_example.jpg"; private static String depthFileName = "src/api/java/openiss/ws/soap/service/depth_example.jpg"; static String FAKENECT_PATH = System.getenv("FAKENECT_PATH"); static Kinect kinect; static { kinect = new Kinect(); kinect.initVideo(); kinect.initDepth(); } /** * Retrives a frame from either a real Kinect or fakenect * @param type * @return jpeg image as a byte array */ public byte[] getFrame(String type) { byte[] imageInBytes = new byte[0]; byte[] jpgImageInByte = new byte[0]; try { BufferedImage image; ByteArrayOutputStream baos = new ByteArrayOutputStream(); // validity checks if (!type.equals("color") && !type.equals("depth")) { throw new IllegalArgumentException("Bad type for getFrame: " + type); } if (ServicePublisher.USE_FREENECT) { if (type.equals("color")) { image = kinect.getVideoImage(); } else { image = kinect.getDepthImage(); } } else { if (type.equals("color")) { image = ImageIO.read(new File(colorFileName)); } else { image = ImageIO.read(new File(depthFileName)); } } ImageIO.write(image, "jpg", baos); baos.flush(); jpgImageInByte = baos.toByteArray(); baos.close(); } catch (IOException e) { e.printStackTrace(); } return jpgImageInByte; } /** * Mixes a jpg image with one from the kinect/fakenect * @param image jpg byte array from the client * @param type color or depth * @param op operand (only single operand handled as of now) * @return jpg image as a byte array */ public byte[] mixFrame(byte[] image, String type, String op) { System.out.println("Mixing frame, type=" + type + ", op="+op); // check validity if (!type.equals("color") && !type.equals("depth")) { throw new IllegalArgumentException("Bad type for getFrame: " + type); } // weight for bleding, 0.5 = 50% of both images double weight = 0.5; // init images byte[] imageInBytes; BufferedImage image_1 = null; BufferedImage image_2 = null; InputStream bain = new ByteArrayInputStream(image); // convert client image to BufferedImage image_1 try { image_1 = ImageIO.read(bain); } catch (IOException e) { e.printStackTrace(); } // convert kinect/fakenect image to BufferedImage image_2 try { if (ServicePublisher.USE_FREENECT) { if (type.equals("color")) { image_2 = kinect.getVideoImage(); } else { image_2 = kinect.getDepthImage(); } } else { if (type.equals("color")) { image_2 = ImageIO.read(new File(colorFileName)); } else { image_2 = ImageIO.read(new File(depthFileName)); } } } catch (IOException e) { e.printStackTrace(); } // check height and width int width = image_1.getWidth(); int height = image_2.getHeight(); // check equal size if(width != image_2.getWidth() || height != image_2.getHeight()) { throw new IllegalArgumentException("dimensions are not equal."); } // create new mixed image and alpha weight BufferedImage mixed_image = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = mixed_image.createGraphics(); float alpha = (float)(1.0 - weight); // mix both images into a third one g.drawImage (image_1, null, 0, 0); g.setComposite (AlphaComposite.getInstance (AlphaComposite.SRC_OVER, alpha)); g.drawImage (image_2, null, 0, 0); g.dispose(); // transform mixed image in jpeg byte array byte[] imageInByte = new byte[0]; try { // convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(mixed_image, "jpg", baos); baos.flush(); imageInByte = baos.toByteArray(); baos.close(); // fromByteToJpg(imageInByte); } catch (IOException e) { e.printStackTrace(); } System.out.println("Frame mixed. Sending jpg result to client"); return imageInByte; } public String getFileName(String type) { if(type.equalsIgnoreCase("color")){ return colorFileName; } else { return depthFileName; } } public void setColorFileName(String fileName) { colorFileName = fileName; } public void setDepthFileName(String fileName) { depthFileName = fileName; } }
package net.sourceforge.javydreamercsw.validation.manager.web; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.fieldgroup.BeanFieldGroup; import com.vaadin.data.fieldgroup.FieldGroup; import com.vaadin.data.fieldgroup.FieldGroupFieldFactory; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.data.util.HierarchicalContainer; import com.vaadin.event.Action; import com.vaadin.event.ItemClickEvent; import com.vaadin.event.Transferable; import com.vaadin.event.dd.DragAndDropEvent; import com.vaadin.event.dd.DropHandler; import com.vaadin.event.dd.acceptcriteria.AcceptCriterion; import com.vaadin.icons.VaadinIcons; import com.vaadin.server.Page; import com.vaadin.server.ThemeResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.shared.MouseEventDetails.MouseButton; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.shared.ui.dd.VerticalDropLocation; import com.vaadin.shared.ui.grid.HeightMode; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.Field; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Grid; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.HorizontalSplitPanel; import com.vaadin.ui.Image; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Notification; import com.vaadin.ui.Panel; import com.vaadin.ui.PopupDateField; import com.vaadin.ui.TabSheet; import com.vaadin.ui.TabSheet.Tab; import com.vaadin.ui.Table; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.Tree; import com.vaadin.ui.Tree.TreeDragMode; import com.vaadin.ui.Tree.TreeDropCriterion; import com.vaadin.ui.Tree.TreeTargetDetails; import com.vaadin.ui.TreeTable; import com.vaadin.ui.TwinColSelect; import com.vaadin.ui.UI; import com.vaadin.ui.Upload; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.VerticalSplitPanel; import com.vaadin.ui.Window; import com.vaadin.ui.renderers.ButtonRenderer; import com.vaadin.ui.themes.ValoTheme; import com.validation.manager.core.DataBaseManager; import com.validation.manager.core.DemoBuilder; import com.validation.manager.core.db.ExecutionResult; import com.validation.manager.core.db.ExecutionStep; import com.validation.manager.core.db.ExecutionStepPK; import com.validation.manager.core.db.Project; import com.validation.manager.core.db.Requirement; import com.validation.manager.core.db.RequirementSpec; import com.validation.manager.core.db.RequirementSpecNode; import com.validation.manager.core.db.RequirementSpecPK; import com.validation.manager.core.db.SpecLevel; import com.validation.manager.core.db.Step; import com.validation.manager.core.db.TestCase; import com.validation.manager.core.db.TestCaseExecution; import com.validation.manager.core.db.TestPlan; import com.validation.manager.core.db.TestProject; import com.validation.manager.core.db.VmSetting; import com.validation.manager.core.db.VmUser; import com.validation.manager.core.db.controller.ProjectJpaController; import com.validation.manager.core.db.controller.RequirementJpaController; import com.validation.manager.core.db.controller.RequirementSpecJpaController; import com.validation.manager.core.db.controller.RequirementSpecNodeJpaController; import com.validation.manager.core.db.controller.SpecLevelJpaController; import com.validation.manager.core.db.controller.StepJpaController; import com.validation.manager.core.db.controller.TestCaseJpaController; import com.validation.manager.core.db.controller.TestPlanJpaController; import com.validation.manager.core.db.controller.TestProjectJpaController; import com.validation.manager.core.db.controller.VmUserJpaController; import com.validation.manager.core.db.controller.exceptions.NonexistentEntityException; import com.validation.manager.core.server.core.ExecutionResultServer; import com.validation.manager.core.server.core.ExecutionStepServer; import com.validation.manager.core.server.core.ProjectServer; import com.validation.manager.core.server.core.TestCaseExecutionServer; import com.validation.manager.core.server.core.TestCaseServer; import com.validation.manager.core.server.core.VMSettingServer; import com.validation.manager.core.server.core.VMUserServer; import com.validation.manager.core.tool.MD5; import com.validation.manager.core.tool.requirement.importer.RequirementImportException; import com.validation.manager.core.tool.requirement.importer.RequirementImporter; import com.validation.manager.core.tool.step.importer.StepImporter; import com.validation.manager.core.tool.step.importer.TestCaseImportException; import java.io.UnsupportedEncodingException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.annotation.WebServlet; import net.sourceforge.javydreamercsw.validation.manager.web.execution.ExecutionWindow; import net.sourceforge.javydreamercsw.validation.manager.web.importer.FileUploader; import net.sourceforge.javydreamercsw.validation.manager.web.wizard.assign.AssignUserStep; import net.sourceforge.javydreamercsw.validation.manager.web.wizard.plan.DetailStep; import net.sourceforge.javydreamercsw.validation.manager.web.wizard.plan.SelectTestCasesStep; import org.vaadin.peter.contextmenu.ContextMenu; import org.vaadin.peter.contextmenu.ContextMenu.ContextMenuOpenedListener; import org.vaadin.peter.contextmenu.ContextMenu.ContextMenuOpenedOnTreeItemEvent; import org.vaadin.teemu.wizards.Wizard; import org.vaadin.teemu.wizards.event.WizardCancelledEvent; import org.vaadin.teemu.wizards.event.WizardCompletedEvent; import org.vaadin.teemu.wizards.event.WizardProgressListener; import org.vaadin.teemu.wizards.event.WizardStepActivationEvent; import org.vaadin.teemu.wizards.event.WizardStepSetChangedEvent; @Theme("vmtheme") @SuppressWarnings("serial") public class ValidationManagerUI extends UI { private static final ThreadLocal<ValidationManagerUI> THREAD_LOCAL = new ThreadLocal<>(); private final ThemeResource logo = new ThemeResource("vm_logo.png"); private VMUserServer user = null; private static final Logger LOG = Logger.getLogger(ValidationManagerUI.class.getSimpleName()); private static VMDemoResetThread reset = null; private LoginDialog loginWindow = null; private ExecutionWindow executionWindow = null; private final String projTreeRoot = "Available Projects"; private Component left; private final TabSheet tabSheet = new TabSheet(); private final List<Project> projects = new ArrayList<>(); public static final VaadinIcons PROJECT_ICON = VaadinIcons.RECORDS; public static final VaadinIcons SPEC_ICON = VaadinIcons.BOOK; public static final VaadinIcons REQUIREMENT_ICON = VaadinIcons.PIN; public static final VaadinIcons TEST_SUITE_ICON = VaadinIcons.FILE_TREE; public static final VaadinIcons TEST_PLAN_ICON = VaadinIcons.FILE_TREE_SMALL; public static final VaadinIcons TEST_ICON = VaadinIcons.FILE_TEXT; public static final VaadinIcons STEP_ICON = VaadinIcons.FILE_TREE_SUB; public static final VaadinIcons IMPORT_ICON = VaadinIcons.ARROW_CIRCLE_UP_O; public static final VaadinIcons PLAN_ICON = VaadinIcons.BULLETS; public static final VaadinIcons EDIT_ICON = VaadinIcons.EDIT; public static final VaadinIcons EXECUTIONS_ICON = VaadinIcons.COGS; public static final VaadinIcons EXECUTION_ICON = VaadinIcons.COG; public static final VaadinIcons ASSIGN_ICON = VaadinIcons.USER_CLOCK; private Tree tree; private Tab main, tester, designer, demo, admin; private final List<String> roles = new ArrayList<>(); private static final ResourceBundle RB = ResourceBundle.getBundle( "com.validation.manager.resources.VMMessages"); /** * @return the user */ public VMUserServer getUser() { return user; } /** * @param user the user to set */ protected void setUser(VMUserServer user) { this.user = user; updateScreen(); } private void displayRequirementSpecNode(RequirementSpecNode rsn, boolean edit) { Panel form = new Panel("Requirement Specification Node Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(rsn.getClass()); binder.setItemDataSource(rsn); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field desc = binder.buildAndBind("Description", "description", TextArea.class); desc.setStyleName(ValoTheme.TEXTAREA_LARGE); desc.setSizeFull(); layout.addComponent(desc); Field<?> scope = binder.buildAndBind("Scope", "scope"); layout.addComponent(scope); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (rsn.getRequirementSpecNodePK() == null) { displayObject(rsn.getRequirementSpec()); } else { displayObject(rsn, false); } }); if (edit) { if (rsn.getRequirementSpecNodePK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { rsn.setName(name.getValue().toString()); rsn.setDescription(desc.getValue().toString()); rsn.setScope(scope.getValue().toString()); rsn.setRequirementSpec((RequirementSpec) tree.getValue()); new RequirementSpecNodeJpaController(DataBaseManager .getEntityManagerFactory()).create(rsn); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(rsn); displayObject(rsn, true); updateScreen(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { rsn.setName(name.getValue().toString()); rsn.setDescription(desc.getValue().toString()); rsn.setScope(scope.getValue().toString()); new RequirementSpecNodeJpaController(DataBaseManager .getEntityManagerFactory()).edit(rsn); displayRequirementSpecNode(rsn, true); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "requirement.view"); } private void setTabContent(Tab target, Component content, String permission) { Layout l = (Layout) target.getComponent(); l.removeAllComponents(); if (content != null) { l.addComponent(content); } if (permission != null && !permission.isEmpty()) { boolean viewable = checkRight(permission); if (viewable != target.isVisible()) { target.setVisible(viewable); } } tabSheet.setSelectedTab(target); } private void setTabContent(Tab target, Component content) { setTabContent(target, content, null); } private void displayTestCaseExecution(TestCaseExecution tce, boolean edit) { Panel form = new Panel("Test Case Execution Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(tce.getClass()); binder.setItemDataSource(tce); Field<?> scope = binder.buildAndBind("Scope", "scope"); layout.addComponent(scope); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); TextArea conclusion = new TextArea("Conclusion"); binder.bind(conclusion, "conclusion"); layout.addComponent(conclusion); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (tce.getId() == null) { displayObject(tree.getValue()); } else { displayObject(tce, false); } }); if (edit) { TestCaseExecutionServer tces = new TestCaseExecutionServer(tce); if (tce.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { tces.setConclusion(conclusion.getValue()); tces.setScope(scope.getValue().toString()); tces.setName(name.getValue().toString()); try { tces.write2DB(); tces.update(tce, tces.getEntity()); displayObject(tce); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { tces.setConclusion(conclusion.getValue()); tces.setScope(scope.getValue().toString()); tces.setName(name.getValue().toString()); try { tces.write2DB(); tces.update(tce, tces.getEntity()); displayObject(tce); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "testcase.view"); } private void displayExecutionStep(ExecutionStep es, boolean edit) { Panel form = new Panel("Execution Step Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(es.getClass()); binder.setItemDataSource(es); FieldGroupFieldFactory defaultFactory = binder.getFieldFactory(); binder.setFieldFactory(new FieldGroupFieldFactory() { @Override public <T extends Field> T createField(Class<?> dataType, Class<T> fieldType) { if (dataType.isAssignableFrom(VmUser.class)) { BeanItemContainer<VmUser> userEntityContainer = new BeanItemContainer<>(VmUser.class); userEntityContainer.addBean(es.getAssignee()); Field field = new TextField(es.getAssignee() == null ? "N/A" : es.getAssignee().getFirstName() + " " + es.getAssignee().getLastName()); return fieldType.cast(field); } return defaultFactory.createField(dataType, fieldType); } }); BeanItemContainer stepContainer = new BeanItemContainer<>(Step.class); stepContainer.addBean(es.getStep()); Grid grid = new Grid(stepContainer); grid.setCaption("Step Details"); grid.setContainerDataSource(stepContainer); grid.setColumns("text", "expectedResult", "notes"); grid.setHeightMode(HeightMode.ROW); grid.setHeightByRows(1); Grid.Column textColumn = grid.getColumn("text"); textColumn.setHeaderCaption("Text"); textColumn.setConverter(new ByteToStringConverter()); Grid.Column resultColumn = grid.getColumn("expectedResult"); resultColumn.setHeaderCaption("Expected Result"); resultColumn.setConverter(new ByteToStringConverter()); Grid.Column notesColumn = grid.getColumn("notes"); notesColumn.setHeaderCaption("Notes"); grid.setSizeFull(); layout.addComponent(grid); if (es.getResultId() != null) { Field<?> result = binder.buildAndBind("Result", "resultId.resultName"); layout.addComponent(result); } if (es.getComment() != null) { TextArea comment = new TextArea("Comment"); binder.bind(comment, "comment"); layout.addComponent(comment); } if (es.getAssignee() != null) { TextField assignee = new TextField("Assignee"); assignee.setConverter(new UserToStringConverter()); binder.bind(assignee, "vmUserId"); layout.addComponent(assignee); } if (es.getExecutionStart() != null) { Field<?> start = binder.buildAndBind("Execution Start", "executionStart"); layout.addComponent(start); } if (es.getExecutionEnd() != null) { Field<?> end = binder.buildAndBind("Execution End", "executionEnd"); layout.addComponent(end); } if (es.getExecutionTime() > 0) { Field<?> time = binder.buildAndBind("Execution Time", "executionTime"); layout.addComponent(time); } if (es.getStep().getRequirementList() != null && !es.getStep().getRequirementList().isEmpty()) { BeanItemContainer reqContainer = new BeanItemContainer<>(Requirement.class); reqContainer.addAll(es.getStep().getRequirementList()); Grid reqGrid = new Grid(reqContainer); reqGrid.setCaption("Related Requirements"); reqGrid.setColumns("uniqueId"); Grid.Column reqColumn = reqGrid.getColumn("uniqueId"); reqColumn.setHeaderCaption("Requirement ID"); reqColumn.setRenderer(new ButtonRenderer(e -> { //Show the requirement details in a window VerticalLayout l = new VerticalLayout(); Window subWindow = new VMWindow( ((Requirement) e.getItemId()).getUniqueId() + " Details"); BeanFieldGroup<Requirement> b = new BeanFieldGroup<>(Requirement.class); b.setItemDataSource((Requirement) e.getItemId()); b.setReadOnly(true); Field<?> id = b.buildAndBind("Requirement ID", "uniqueId"); id.setReadOnly(true); //Read only flag set to true !!! l.addComponent(id); Field<?> desc = b.buildAndBind("Description", "description", TextArea.class); desc.setReadOnly(true); //Read only flag set to true !!! l.addComponent(desc); Field<?> notes = b.buildAndBind("Notes", "notes", TextArea.class); notes.setReadOnly(true); //Read only flag set to true !!! l.addComponent(notes); subWindow.setContent(l); subWindow.setModal(true); subWindow.center(); // Open it in the UI addWindow(subWindow); })); layout.addComponent(reqGrid); } Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (es.getExecutionStepPK() == null) { displayObject(tree.getValue()); } else { displayObject(es, false); } }); if (edit) { if (es.getExecutionStepPK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "testcase.view"); } private void displayStep(Step s, boolean edit) { Panel form = new Panel("Step Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(s.getClass()); binder.setItemDataSource(s); Field<?> sequence = binder.buildAndBind("Sequence", "stepSequence"); layout.addComponent(sequence); TextArea text = new TextArea("Text"); text.setConverter(new ByteToStringConverter()); binder.bind(text, "text"); layout.addComponent(text); TextArea result = new TextArea("Expected Result"); result.setConverter(new ByteToStringConverter()); binder.bind(result, "expectedResult"); layout.addComponent(result); Field notes = binder.buildAndBind("Notes", "notes", TextArea.class); notes.setStyleName(ValoTheme.TEXTAREA_LARGE); notes.setSizeFull(); layout.addComponent(notes); tree.select(s); Project p = getParentProject(); List<Requirement> reqs = ProjectServer.getRequirements(p); Collections.sort(reqs, (Requirement o1, Requirement o2) -> o1.getUniqueId().compareTo(o2.getUniqueId())); BeanItemContainer<Requirement> requirementContainer = new BeanItemContainer<>(Requirement.class, reqs); TwinColSelect requirements = new TwinColSelect("Linked Requirements"); requirements.setItemCaptionPropertyId("uniqueId"); requirements.setContainerDataSource(requirementContainer); requirements.setRows(5); requirements.setLeftColumnCaption("Available Requirements"); requirements.setRightColumnCaption("Linked Requirements"); if (s.getRequirementList() != null) { s.getRequirementList().forEach((r) -> { requirements.select(r); }); } requirements.setEnabled(edit); layout.addComponent(requirements); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (s.getStepPK() == null) { displayObject(tree.getValue()); } else { displayObject(s, false); } }); if (edit) { if (s.getStepPK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { s.setExpectedResult(((TextArea) result).getValue() .getBytes("UTF-8")); s.setNotes(notes.getValue() == null ? "null" : notes.getValue().toString()); s.setStepSequence(Integer.parseInt(sequence .getValue().toString())); s.setTestCase((TestCase) tree.getValue()); s.setText(text.getValue().getBytes("UTF-8")); if (s.getRequirementList() == null) { s.setRequirementList(new ArrayList<>()); } s.getRequirementList().clear(); ((Set<Requirement>) requirements.getValue()).forEach((r) -> { s.getRequirementList().add(r); }); new StepJpaController(DataBaseManager .getEntityManagerFactory()).create(s); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); displayObject(s); buildProjectTree(s); updateScreen(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { s.setExpectedResult(((TextArea) result).getValue() .getBytes("UTF-8")); s.setNotes(notes.getValue().toString()); s.setStepSequence(Integer.parseInt(sequence.getValue().toString())); s.setText(text.getValue().getBytes("UTF-8")); if (s.getRequirementList() == null) { s.setRequirementList(new ArrayList<>()); } s.getRequirementList().clear(); ((Set<Requirement>) requirements.getValue()).forEach((r) -> { s.getRequirementList().add(r); }); new StepJpaController(DataBaseManager .getEntityManagerFactory()).edit(s); displayStep(s, true); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "testcase.view"); } private void displayTestCase(TestCase t, boolean edit) { Panel form = new Panel("Test Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(t.getClass()); binder.setItemDataSource(t); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); TextArea summary = new TextArea("Summary"); summary.setConverter(new ByteToStringConverter()); binder.bind(summary, "summary"); layout.addComponent(summary); PopupDateField creation = new PopupDateField("Created on"); creation.setResolution(Resolution.SECOND); creation.setDateFormat("MM-dd-yyyy hh:hh:ss"); binder.bind(creation, "creationDate"); layout.addComponent(creation); Field<?> active = binder.buildAndBind("Active", "active"); layout.addComponent(active); Field<?> open = binder.buildAndBind("Open", "isOpen"); layout.addComponent(open); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (t.getId() == null) { displayObject(tree.getValue()); } else { displayObject(t, false); } }); if (edit) { if (t.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { t.setName(name.getValue().toString()); t.setSummary(summary.getValue().getBytes("UTF-8")); t.setCreationDate((Date) creation.getValue()); t.setActive((Boolean) active.getValue()); t.setIsOpen((Boolean) open.getValue()); t.getTestPlanList().add((TestPlan) tree.getValue()); new TestCaseJpaController(DataBaseManager .getEntityManagerFactory()).create(t); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(t); displayTestCase(t, false); updateScreen(); } catch (UnsupportedEncodingException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { t.setName(name.getValue().toString()); t.setSummary(summary.getValue().getBytes("UTF-8")); t.setCreationDate((Date) creation.getValue()); t.setActive((Boolean) active.getValue()); t.setIsOpen((Boolean) open.getValue()); new TestCaseJpaController(DataBaseManager .getEntityManagerFactory()).edit(t); displayTestCase(t, true); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); creation.setEnabled(false); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "testcase.view"); } private void displayTestPlan(TestPlan tp, boolean edit) { Panel form = new Panel("Test Plan Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(tp.getClass()); binder.setItemDataSource(tp); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field notes = binder.buildAndBind("Notes", "notes", TextArea.class); notes.setStyleName(ValoTheme.TEXTAREA_LARGE); notes.setSizeFull(); layout.addComponent(notes); Field<?> active = binder.buildAndBind("Active", "active"); layout.addComponent(active); Field<?> open = binder.buildAndBind("Open", "isOpen"); layout.addComponent(open); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (tp.getTestPlanPK() == null) { displayObject(tree.getValue()); } else { displayObject(tp, false); } }); if (edit) { if (tp.getTestPlanPK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) active.getValue()); tp.setIsOpen((Boolean) open.getValue()); new TestPlanJpaController(DataBaseManager .getEntityManagerFactory()).create(tp); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(tp); displayTestPlan(tp, false); updateScreen(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) open.getValue()); tp.setIsOpen((Boolean) open.getValue()); new TestPlanJpaController(DataBaseManager .getEntityManagerFactory()).edit(tp); displayTestPlan(tp, true); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "testcase.view"); } private void displayTestProject(TestProject tp, boolean edit) { Panel form = new Panel("Test Project Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(tp.getClass()); binder.setItemDataSource(tp); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field notes = binder.buildAndBind("Notes", "notes", TextArea.class); notes.setStyleName(ValoTheme.TEXTAREA_LARGE); notes.setSizeFull(); layout.addComponent(notes); Field<?> active = binder.buildAndBind("Active", "active"); layout.addComponent(active); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (tp.getId() == null) { displayObject(tree.getValue()); } else { displayObject(tp, false); } }); if (edit) { if (tp.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) active.getValue()); new TestProjectJpaController(DataBaseManager .getEntityManagerFactory()).create(tp); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(tp); displayTestProject(tp, false); updateScreen(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { tp.setName(name.getValue().toString()); tp.setNotes(notes.getValue().toString()); tp.setActive((Boolean) active.getValue()); new TestProjectJpaController(DataBaseManager .getEntityManagerFactory()).edit(tp); displayTestProject(tp, true); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "testcase.view"); } private void displayRequirementSpec(RequirementSpec rs, boolean edit) { Panel form = new Panel("Requirement Specification Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(rs.getClass()); binder.setItemDataSource(rs); Field<?> name = binder.buildAndBind("Name", "name"); layout.addComponent(name); Field desc = binder.buildAndBind("Description", "description", TextArea.class); desc.setSizeFull(); layout.addComponent(desc); Field<?> date = binder.buildAndBind("Modification Date", "modificationDate"); layout.addComponent(date); date.setEnabled(false); SpecLevelJpaController controller = new SpecLevelJpaController(DataBaseManager .getEntityManagerFactory()); List<SpecLevel> levels = controller.findSpecLevelEntities(); BeanItemContainer<SpecLevel> specLevelContainer = new BeanItemContainer<>(SpecLevel.class, levels); ComboBox level = new ComboBox("Spec Level"); level.setItemCaptionPropertyId("name"); level.setContainerDataSource(specLevelContainer); binder.bind(level, "specLevel"); layout.addComponent(level); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (rs.getRequirementSpecPK() == null) { displayObject(rs.getProject()); } else { displayObject(rs, false); } }); if (edit) { if (rs.getRequirementSpecPK() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { try { rs.setName(name.getValue().toString()); rs.setModificationDate(new Date()); rs.setSpecLevel((SpecLevel) level.getValue()); rs.setProject(((Project) tree.getValue())); rs.setRequirementSpecPK(new RequirementSpecPK( rs.getProject().getId(), rs.getSpecLevel().getId())); new RequirementSpecJpaController(DataBaseManager .getEntityManagerFactory()).create(rs); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(rs); displayObject(rs, true); updateScreen(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error creating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { rs.setName(name.getValue().toString()); rs.setModificationDate(new Date()); rs.setSpecLevel((SpecLevel) level.getValue()); new RequirementSpecJpaController(DataBaseManager .getEntityManagerFactory()).edit(rs); displayRequirementSpec(rs, true); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (NonexistentEntityException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setReadOnly(!edit); binder.bindMemberFields(form); layout.setSizeFull(); form.setSizeFull(); setTabContent(main, form, "requirement.view"); } private void displayObject(Object item) { displayObject(item, false); } public void displayObject(Object item, boolean edit) { if (item instanceof Project) { Project p = (Project) item; LOG.log(Level.FINE, "Selected: {0}", p.getName()); displayProject(p, edit); } else if (item instanceof Requirement) { Requirement req = (Requirement) item; LOG.log(Level.FINE, "Selected: {0}", req.getUniqueId()); displayRequirement(req, edit); } else if (item instanceof RequirementSpec) { RequirementSpec rs = (RequirementSpec) item; LOG.log(Level.FINE, "Selected: {0}", rs.getName()); displayRequirementSpec(rs, edit); } else if (item instanceof RequirementSpecNode) { RequirementSpecNode rsn = (RequirementSpecNode) item; LOG.log(Level.FINE, "Selected: {0}", rsn.getName()); displayRequirementSpecNode(rsn, edit); } else if (item instanceof TestProject) { TestProject tp = (TestProject) item; LOG.log(Level.FINE, "Selected: {0}", tp.getName()); displayTestProject(tp, edit); } else if (item instanceof TestPlan) { TestPlan tp = (TestPlan) item; LOG.log(Level.FINE, "Selected: {0}", tp.getName()); displayTestPlan(tp, edit); } else if (item instanceof TestCase) { TestCase tc = (TestCase) item; LOG.log(Level.FINE, "Selected: {0}", tc.getName()); displayTestCase(tc, edit); } else if (item instanceof Step) { Step step = (Step) item; LOG.log(Level.FINE, "Selected: Step step.getStepSequence()); displayStep(step, edit); } else if (item instanceof TestCaseExecution) { TestCaseExecution tce = (TestCaseExecution) item; LOG.log(Level.FINE, "Selected: Test Case Execution tce.getId()); displayTestCaseExecution(tce, edit); } else if (item instanceof ExecutionStep) { ExecutionStep es = (ExecutionStep) item; LOG.log(Level.FINE, "Selected: Test Case Execution es.getExecutionStepPK()); displayExecutionStep(es, edit); } } private Component displaySetting(VmSetting s) { Panel form = new Panel("Setting Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(s.getClass()); binder.setItemDataSource(s); Field<?> id = binder.buildAndBind("Setting", "setting"); layout.addComponent(id); Field bool = binder.buildAndBind("Boolean Value", "boolVal"); bool.setSizeFull(); layout.addComponent(bool); Field integerVal = binder.buildAndBind("Integer Value", "intVal"); integerVal.setSizeFull(); layout.addComponent(integerVal); Field longVal = binder.buildAndBind("Long Value", "longVal"); longVal.setSizeFull(); layout.addComponent(longVal); Field stringVal = binder.buildAndBind("String Value", "stringVal", TextArea.class); stringVal.setStyleName(ValoTheme.TEXTAREA_LARGE); stringVal.setSizeFull(); layout.addComponent(stringVal); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); }); //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { binder.commit(); displaySetting(s); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); boolean blocked = !s.getSetting().startsWith("version."); if (blocked) { HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } binder.setBuffered(true); binder.setReadOnly(false); binder.bindMemberFields(form); //The version settigns are not modifiable from the GUI binder.setEnabled(blocked); //Id is always blocked. id.setEnabled(false); form.setSizeFull(); return form; } private void displayRequirement(Requirement req, boolean edit) { Panel form = new Panel("Requirement Detail"); FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(req.getClass()); binder.setItemDataSource(req); Field<?> id = binder.buildAndBind("Requirement ID", "uniqueId"); layout.addComponent(id); Field desc = binder.buildAndBind("Description", "description", TextArea.class); desc.setStyleName(ValoTheme.TEXTAREA_LARGE); desc.setSizeFull(); layout.addComponent(desc); Field notes = binder.buildAndBind("Notes", "notes", TextArea.class); notes.setStyleName(ValoTheme.TEXTAREA_LARGE); notes.setSizeFull(); layout.addComponent(notes); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (req.getId() == null) { displayObject(req.getRequirementSpecNode()); } else { displayRequirement(req, false); } }); if (edit) { if (req.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { req.setUniqueId(id.getValue().toString()); req.setDescription(notes.getValue().toString()); req.setRequirementSpecNode((RequirementSpecNode) tree.getValue()); new RequirementJpaController(DataBaseManager .getEntityManagerFactory()).create(req); form.setVisible(false); //Recreate the tree to show the addition buildProjectTree(req); displayObject(req, true); }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { binder.commit(); //Recreate the tree to show the addition buildProjectTree(req); displayRequirement(req, false); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setBuffered(true); binder.setReadOnly(!edit); binder.bindMemberFields(form); form.setSizeFull(); setTabContent(main, form, "requirement.view"); } // @return the current application instance public static ValidationManagerUI getInstance() { return THREAD_LOCAL.get(); } // Set the current application instance public static void setInstance(ValidationManagerUI application) { THREAD_LOCAL.set(application); } private static void buildDemoTree() { try { DemoBuilder.buildDemoProject(); } catch (NonexistentEntityException ex) { LOG.log(Level.SEVERE, null, ex); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } public void buildProjectTree() { buildProjectTree(null); } public void buildProjectTree(Object item) { tree.removeAllItems(); tree.addItem(projTreeRoot); projects.forEach((p) -> { if (p.getParentProjectId() == null) { addProject(p, tree); } }); showItemInTree(item); } private void showItemInTree(Object item) { if (item == null) { tree.expandItem(projTreeRoot); } else { tree.select(item); Object parent = tree.getParent(item); while (parent != null) { tree.expandItem(parent); parent = tree.getParent(parent); } } } private void addTestCaseAssignment(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Assign Test Case Execution", ASSIGN_ICON); create.setEnabled(checkRight("testplan.planning")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { Wizard w = new Wizard(); Window sw = new VMWindow(); w.addStep(new AssignUserStep(this, tree.getValue())); w.addListener(new WizardProgressListener() { @Override public void activeStepChanged(WizardStepActivationEvent event) { //Do nothing } @Override public void stepSetChanged(WizardStepSetChangedEvent event) { //Do nothing } @Override public void wizardCompleted(WizardCompletedEvent event) { removeWindow(sw); } @Override public void wizardCancelled(WizardCancelledEvent event) { removeWindow(sw); } }); sw.setContent(w); sw.center(); sw.setModal(true); sw.setSizeFull(); addWindow(sw); }); } private void createTestExecutionMenu(ContextMenu menu) { addTestCaseAssignment(menu); } private void createRootMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Execution", PROJECT_ICON); create.setEnabled(checkRight("product.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayProject(new Project(), true); }); } private void createTestCaseExecutionPlanMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Execution Step", SPEC_ICON); create.setEnabled(checkRight("testplan.planning")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Execution", EXECUTION_ICON); edit.setEnabled(checkRight("testplan.planning")); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestCaseExecution((TestCaseExecution) tree.getValue(), true); }); addTestCaseAssignment(menu); } private void createTestPlanMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Test Case", SPEC_ICON); create.setEnabled(checkRight("testplan.planning")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Test Plan", SPEC_ICON); edit.setEnabled(checkRight("testplan.planning")); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestPlan((TestPlan) tree.getValue(), true); }); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestCase tc = new TestCase(); tc.setTestPlanList(new ArrayList<>()); tc.getTestPlanList().add((TestPlan) tree.getValue()); tc.setCreationDate(new Date()); displayTestCase(tc, true); }); } private void createProjectMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Sub Project", PROJECT_ICON); create.setEnabled(checkRight("requirement.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { Project project = new Project(); project.setParentProjectId((Project) tree.getValue()); displayProject(project, true); }); ContextMenu.ContextMenuItem createSpec = menu.addItem("Create Requirement Spec", SPEC_ICON); createSpec.setEnabled(checkRight("requirement.modify")); createSpec.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { RequirementSpec rs = new RequirementSpec(); rs.setProject((Project) tree.getValue()); displayRequirementSpec(rs, true); }); ContextMenu.ContextMenuItem createTest = menu.addItem("Create Test Suite", TEST_SUITE_ICON); createTest.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Project", EDIT_ICON); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayProject((Project) tree.getValue(), true); }); edit.setEnabled(checkRight("product.modify")); createTest.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestProject tp = new TestProject(); tp.setProjectList(new ArrayList<>()); tp.getProjectList().add((Project) tree.getValue()); displayTestProject(tp, true); }); ContextMenu.ContextMenuItem plan = menu.addItem("Plan Testing", PLAN_ICON); plan.setEnabled(checkRight("testplan.planning")); plan.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestPlanning((Project) tree.getValue()); }); } private void createRequirementMenu(ContextMenu menu) { ContextMenu.ContextMenuItem edit = menu.addItem("Edit Requirement", EDIT_ICON); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayRequirement((Requirement) tree.getValue(), true); }); edit.setEnabled(checkRight("requirement.modify")); } private void createRequirementSpecMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Requirement Spec Node", SPEC_ICON); create.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Requirement Spec", SPEC_ICON); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayRequirementSpec((RequirementSpec) tree.getValue(), true); }); edit.setEnabled(checkRight("requirement.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { RequirementSpecNode rs = new RequirementSpecNode(); rs.setRequirementSpec((RequirementSpec) tree.getValue()); displayRequirementSpecNode(rs, true); }); } private void createRequirementSpecNodeMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Requirement Spec", VaadinIcons.PLUS); create.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Requirement Spec Node", EDIT_ICON); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayRequirementSpecNode((RequirementSpecNode) tree.getValue(), true); }); edit.setEnabled(checkRight("requirement.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { Requirement r = new Requirement(); r.setRequirementSpecNode((RequirementSpecNode) tree.getValue()); displayRequirement(r, true); }); ContextMenu.ContextMenuItem importRequirement = menu.addItem("Import Requirements", IMPORT_ICON); importRequirement.setEnabled(checkRight("requirement.modify")); importRequirement.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { // Create a sub-window and set the content Window subWindow = new VMWindow("Import Requirements"); VerticalLayout subContent = new VerticalLayout(); subWindow.setContent(subContent); //Add a checkbox to know if file has headers or not CheckBox cb = new CheckBox("File has header row?"); FileUploader receiver = new FileUploader(); Upload upload = new Upload("Upload Excel Spreadsheet here", receiver); upload.addSucceededListener((Upload.SucceededEvent event1) -> { try { subWindow.close(); //TODO: Display the excel file (partially), map columns and import //Process the file RequirementImporter importer = new RequirementImporter(receiver.getFile(), (RequirementSpecNode) tree.getValue()); importer.importFile(cb.getValue()); importer.processImport(); buildProjectTree(tree.getValue()); updateScreen(); } catch (RequirementImportException ex) { LOG.log(Level.SEVERE, "Error processing import!", ex); Notification.show("Importing unsuccessful!", Notification.Type.ERROR_MESSAGE); } }); upload.addFailedListener((Upload.FailedEvent event1) -> { LOG.log(Level.SEVERE, "Upload unsuccessful!\n{0}", event1.getReason()); Notification.show("Upload unsuccessful!", Notification.Type.ERROR_MESSAGE); subWindow.close(); }); subContent.addComponent(cb); subContent.addComponent(upload); // Center it in the browser window subWindow.center(); // Open it in the UI addWindow(subWindow); }); } private void createTestCaseMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Step", VaadinIcons.PLUS); create.setEnabled(checkRight("requirement.modify")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Test Case", EDIT_ICON); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestCase((TestCase) tree.getValue(), true); }); edit.setEnabled(checkRight("testcase.modify")); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestCase tc = (TestCase) tree.getValue(); Step s = new Step(); s.setStepSequence(tc.getStepList().size() + 1); s.setTestCase(tc); displayStep(s, true); }); ContextMenu.ContextMenuItem importSteps = menu.addItem("Import Steps", IMPORT_ICON); importSteps.setEnabled(checkRight("requirement.modify")); importSteps.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { // Create a sub-window and set the content Window subWindow = new VMWindow("Import Test Case Steps"); VerticalLayout subContent = new VerticalLayout(); subWindow.setContent(subContent); //Add a checkbox to know if file has headers or not CheckBox cb = new CheckBox("File has header row?"); FileUploader receiver = new FileUploader(); Upload upload = new Upload("Upload Excel Spreadsheet here", receiver); upload.addSucceededListener((Upload.SucceededEvent event1) -> { try { subWindow.close(); //TODO: Display the excel file (partially), map columns and import //Process the file TestCase tc = (TestCase) tree.getValue(); StepImporter importer = new StepImporter(receiver.getFile(), tc); importer.importFile(cb.getValue()); importer.processImport(); SortedMap<Integer, Step> map = new TreeMap<>(); tc.getStepList().forEach((s) -> { map.put(s.getStepSequence(), s); }); //Now update the sequence numbers int count = 0; for (Entry<Integer, Step> entry : map.entrySet()) { entry.getValue().setStepSequence(++count); try { new StepJpaController(DataBaseManager .getEntityManagerFactory()) .edit(entry.getValue()); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } buildProjectTree(new TestCaseServer(tc.getId()).getEntity()); updateScreen(); } catch (TestCaseImportException ex) { LOG.log(Level.SEVERE, "Error processing import!", ex); Notification.show("Importing unsuccessful!", Notification.Type.ERROR_MESSAGE); } }); upload.addFailedListener((Upload.FailedEvent event1) -> { LOG.log(Level.SEVERE, "Upload unsuccessful!\n{0}", event1.getReason()); Notification.show("Upload unsuccessful!", Notification.Type.ERROR_MESSAGE); subWindow.close(); }); subContent.addComponent(cb); subContent.addComponent(upload); // Center it in the browser window subWindow.center(); // Open it in the UI addWindow(subWindow); }); } private void createStepMenu(ContextMenu menu) { ContextMenu.ContextMenuItem edit = menu.addItem("Edit Step", EDIT_ICON); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayStep((Step) tree.getValue(), true); }); edit.setEnabled(checkRight("testcase.modify")); } private void createTestProjectMenu(ContextMenu menu) { ContextMenu.ContextMenuItem create = menu.addItem("Create Test Plan", VaadinIcons.PLUS); create.setEnabled(checkRight("testplan.planning")); ContextMenu.ContextMenuItem edit = menu.addItem("Edit Test Project", EDIT_ICON); edit.setEnabled(checkRight("testplan.planning")); edit.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { displayTestProject((TestProject) tree.getValue(), true); }); create.addItemClickListener( (ContextMenu.ContextMenuItemClickEvent event) -> { TestPlan tp = new TestPlan(); tp.setTestProject((TestProject) tree.getValue()); displayTestPlan(tp, true); }); } public String translate(String mess) { return RB.containsKey(mess) ? RB.getString(mess) : mess; } private Component getContentComponent() { HorizontalSplitPanel hsplit = new HorizontalSplitPanel(); hsplit.setLocked(true); if (left != null) { if (!(left instanceof Panel)) { left = new Panel(left); } if (user != null) { hsplit.setFirstComponent(left); } } //Build the right component if (hsplit.getSecondComponent() == null) { if (main == null) { main = tabSheet.addTab(new VerticalLayout(), "Main"); } if (tester == null) { VerticalLayout vl = new VerticalLayout(); if (getUser() != null && !getUser().getExecutionStepList().isEmpty()) { TreeTable testCaseTree = new TreeTable("Available Tests"); testCaseTree.setAnimationsEnabled(true); testCaseTree.addContainerProperty("Name", String.class, ""); testCaseTree.addGeneratedColumn("Status", (Table source, Object itemId, Object columnId) -> { if (columnId.equals("Status") && itemId instanceof String && ((String) itemId).startsWith("es")) { Button label = new Button(); label.addStyleName(ValoTheme.BUTTON_BORDERLESS + " labelButton"); ExecutionStepServer ess = new ExecutionStepServer(extractExecutionStepPK((String) itemId)); String message; if (ess.getResultId() == null) { ExecutionResult result = ExecutionResultServer.getResult("result.pending"); message = result.getResultName(); } else { message = ess.getResultId().getResultName(); } label.setCaption(translate(message)); if (ess.getExecutionStart() != null && ess.getExecutionEnd() == null) { //In progress label.setIcon(VaadinIcons.AUTOMATION); } else if (ess.getExecutionStart() == null && ess.getExecutionEnd() == null) { //Not started label.setIcon(VaadinIcons.CLOCK); } else if (ess.getExecutionStart() != null && ess.getExecutionEnd() != null) { //Completed. Now check result switch (ess.getResultId().getId()) { case 1: label.setIcon(VaadinIcons.CHECK); break; case 2: label.setIcon(VaadinIcons.CLOSE); break; case 3: label.setIcon(VaadinIcons.PAUSE); break; default: label.setIcon(VaadinIcons.CLOCK); break; } } return label; } return new Label(); }); testCaseTree.addContainerProperty("Summary", String.class, ""); testCaseTree.addContainerProperty("Assignment Date", String.class, ""); testCaseTree.setVisibleColumns(new Object[]{"Name", "Status", "Summary", "Assignment Date"}); testCaseTree.addActionHandler(new Action.Handler() { @Override public Action[] getActions(Object target, Object sender) { List<Action> actions = new ArrayList<>(); if (target instanceof String && ((String) target).startsWith("es")) { actions.add(new Action("Execute")); } return actions.toArray(new Action[actions.size()]); } @Override public void handleAction(Action action, Object sender, Object target) { //Parse the information to get the exact Execution Step List<TestCaseExecutionServer> executions = new ArrayList<>(); executions.add(new TestCaseExecutionServer(new ExecutionStepServer(extractExecutionStepPK((String) target)).getTestCaseExecution().getId())); showExecutionScreen(executions); } }); ProjectServer.getProjects().forEach(p -> { if (p.getParentProjectId() == null) { testCaseTree.addItem(new Object[]{p.getName(), "", "",}, "p" + p.getId()); testCaseTree.setItemIcon("p" + p.getId(), PROJECT_ICON); p.getProjectList().forEach(sp -> { //Add subprojects testCaseTree.addItem(new Object[]{sp.getName(), "", "",}, "p" + sp.getId()); testCaseTree.setParent("p" + sp.getId(), "p" + p.getId()); testCaseTree.setItemIcon("p" + sp.getId(), PROJECT_ICON); //Add applicable Executions Map<Integer, ExecutionStep> tests = new HashMap<>(); sp.getTestProjectList().forEach(test -> { test.getTestPlanList().forEach(tp -> { tp.getTestCaseList().forEach(testCase -> { List<Integer> tcids = new ArrayList<>(); testCase.getStepList().forEach(s -> { s.getExecutionStepList().forEach(es -> { TestCaseExecution tce = es.getTestCaseExecution(); testCaseTree.addItem(new Object[]{tce.getName(), "", "",}, "tce" + tce.getId()); testCaseTree.setParent("tce" + tce.getId(), "p" + sp.getId()); testCaseTree.setItemIcon("tce" + tce.getId(), EXECUTION_ICON); if (es.getAssignee().getId().equals(getUser().getId())) { TestCase tc = es.getStep().getTestCase(); if (!tcids.contains(tc.getId())) { tcids.add(tc.getId()); DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a"); LocalDateTime time = LocalDateTime.ofInstant(es.getAssignedTime() .toInstant(), ZoneId.systemDefault()); String key = "es" + es.getExecutionStepPK().getTestCaseExecutionId() + "-" + es.getStep().getStepPK().getId() + "-" + tc.getId(); testCaseTree.addItem(new Object[]{tc.getName(), tc.getSummary(), format.format(time),}, key); testCaseTree.setParent(key, "tce" + tce.getId()); testCaseTree.setItemIcon(key, TEST_ICON); testCaseTree.setChildrenAllowed(key, false); } } }); }); tcids.clear(); }); }); }); testCaseTree.setSizeFull(); vl.addComponent(testCaseTree); tester = tabSheet.addTab(vl, "Tester"); }); } }); //Make columns autofit for (Object id : testCaseTree.getVisibleColumns()) { LOG.log(Level.INFO, "{0}", id); testCaseTree.setColumnExpandRatio(id, 1.0f); } } } if (designer == null) { designer = tabSheet.addTab(new VerticalLayout(), "Test Designer"); } if (admin == null) { TabSheet adminSheet = new TabSheet(); VerticalLayout layout = new VerticalLayout(); //Build setting tab VerticalLayout sl = new VerticalLayout(); HorizontalSplitPanel split = new HorizontalSplitPanel(); sl.addComponent(split); //Build left side Tree sTree = new Tree("Settings"); adminSheet.addTab(sl, "Settings"); VMSettingServer.getSettings().stream().map((s) -> { sTree.addItem(s); sTree.setChildrenAllowed(s, false); return s; }).forEachOrdered((s) -> { sTree.setItemCaption(s, translate(s.getSetting())); }); split.setFirstComponent(sTree); layout.addComponent(adminSheet); admin = tabSheet.addTab(layout, "Admin"); sTree.addValueChangeListener((Property.ValueChangeEvent event) -> { if (sTree.getValue() instanceof VmSetting) { split.setSecondComponent( displaySetting((VmSetting) sTree.getValue())); } }); } if (demo == null && DataBaseManager.isDemo()) { VerticalLayout layout = new VerticalLayout(); VmUserJpaController controller = new VmUserJpaController(DataBaseManager .getEntityManagerFactory()); layout.addComponent(new Label("<h1>Welcome to " + "Validation Manager Demo instance</h1>", ContentMode.HTML)); layout.addComponent(new Label("Below you can find the " + "various accounts that exist in the demo so " + "you can explore.")); StringBuilder sb = new StringBuilder("<ul>"); controller.findVmUserEntities().stream().filter((u) -> (u.getId() < 1000)).forEachOrdered((u) -> { try { //Default accounts if (u.getPassword() != null && u.getPassword().equals(MD5 .encrypt(u.getUsername()))) { sb.append("<li><b>User name:</b> ") .append(u.getUsername()) .append(", <b>Password:</b> ") .append(u.getUsername()) .append(" <b>Role</b>: ") .append(u.getRoleList().get(0) .getDescription()) .append("</li>"); } } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } }); sb.append("</ul>"); layout.addComponent(new Label(sb.toString(), ContentMode.HTML)); demo = tabSheet.addTab(layout, "Demo"); } hsplit.setSecondComponent(tabSheet); } //This is a tabbed pane. Enable/Disable the panes based on role if (getUser() != null) { roles.clear(); user.update();//Get any recent changes user.getRoleList().forEach((r) -> { roles.add(r.getRoleName()); }); } if (main != null) { main.setVisible(user != null); } if (tester != null) { tester.setVisible(((Layout) tester.getComponent()) .getComponentCount() > 0 && checkRight("testplan.execute")); } if (designer != null) { designer.setVisible(((Layout) designer.getComponent()) .getComponentCount() > 0 && checkRight("testplan.planning")); } if (admin != null) { admin.setVisible(checkRight("system.configuration")); } tabSheet.setTabPosition(demo, tabSheet.getComponentCount() - 1); hsplit.setSplitPosition(25, Unit.PERCENTAGE); return hsplit; } private Component getMenu() { GridLayout gl = new GridLayout(3, 3); gl.addComponent(new Image("", logo), 0, 0); if (getUser() != null) { //Logout button Button logout = new Button("Log out"); logout.addClickListener((Button.ClickEvent event) -> { try { user.write2DB(); user = null; main = null; tester = null; designer = null; demo = null; admin = null; updateScreen(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } }); gl.addComponent(logout, 2, 2); } gl.setSizeFull(); return gl; } public void updateScreen() { //Set up a menu header on top and the content below VerticalSplitPanel vs = new VerticalSplitPanel(); vs.setSplitPosition(25, Unit.PERCENTAGE); //Set up top menu panel vs.setFirstComponent(getMenu()); setContent(vs); if (getUser() == null) { showLoginDialog(); } else { //Process any notifications //Check for assigned test getUser().update(); for (ExecutionStep es : getUser().getExecutionStepList()) { if (es.getExecutionStart() == null) { //It has been assigned but not started Notification.show("Test Pending", "You have test case(s) pending execution.", Notification.Type.TRAY_NOTIFICATION); break; } } } //Add the content vs.setSecondComponent(getContentComponent()); } private void displayProject(Project p, boolean edit) { // Bind it to a component Panel form = new Panel("Project Detail"); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); FormLayout layout = new FormLayout(); form.setContent(layout); BeanFieldGroup binder = new BeanFieldGroup(p.getClass()); binder.setItemDataSource(p); Field<?> name = binder.buildAndBind("Name", "name"); Field notes = binder.buildAndBind("Notes", "notes", TextArea.class); notes.setStyleName(ValoTheme.TEXTAREA_LARGE); notes.setSizeFull(); layout.addComponent(notes); layout.addComponent(name); layout.addComponent(notes); Button cancel = new Button("Cancel"); cancel.addClickListener((Button.ClickEvent event) -> { binder.discard(); if (p.getId() == null) { displayObject(tree.getValue()); } else { displayObject(p, false); } }); if (edit) { if (p.getId() == null) { //Creating a new one Button save = new Button("Save"); save.addClickListener((Button.ClickEvent event) -> { p.setName(name.getValue().toString()); p.setNotes(notes.getValue().toString()); new ProjectJpaController(DataBaseManager .getEntityManagerFactory()).create(p); form.setVisible(false); //Recreate the tree to show the addition updateProjectList(); buildProjectTree(p); displayProject(p, false); updateScreen(); }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(save); hl.addComponent(cancel); layout.addComponent(hl); } else { //Editing existing one Button update = new Button("Update"); update.addClickListener((Button.ClickEvent event) -> { try { binder.commit(); } catch (FieldGroup.CommitException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show("Error updating record!", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); } }); HorizontalLayout hl = new HorizontalLayout(); hl.addComponent(update); hl.addComponent(cancel); layout.addComponent(hl); } } binder.setBuffered(true); binder.setReadOnly(!edit); binder.bindMemberFields(form); form.setSizeFull(); setTabContent(main, form, "project.viewer"); } private void addRequirementSpec(RequirementSpec rs, Tree tree) { // Add the item as a regular item. tree.addItem(rs); tree.setItemCaption(rs, rs.getName()); tree.setItemIcon(rs, SPEC_ICON); // Set it to be a child. tree.setParent(rs, rs.getProject()); if (rs.getRequirementSpecNodeList().isEmpty()) { //No children tree.setChildrenAllowed(rs, false); } else { rs.getRequirementSpecNodeList().forEach((rsn) -> { addRequirementSpecsNode(rsn, tree); }); } } private void addRequirementSpecsNode(RequirementSpecNode rsn, Tree tree) { // Add the item as a regular item. tree.addItem(rsn); tree.setItemCaption(rsn, rsn.getName()); tree.setItemIcon(rsn, SPEC_ICON); // Set it to be a child. tree.setParent(rsn, rsn.getRequirementSpec()); if (rsn.getRequirementList().isEmpty()) { //No children tree.setChildrenAllowed(rsn, false); } else { ArrayList<Requirement> list = new ArrayList<>(rsn.getRequirementList()); Collections.sort(list, (Requirement o1, Requirement o2) -> o1.getUniqueId().compareTo(o2.getUniqueId())); list.forEach((req) -> { addRequirement(req, tree); }); } } private void addTestProject(TestProject tp, Tree tree) { tree.addItem(tp); tree.setItemCaption(tp, tp.getName()); tree.setItemIcon(tp, TEST_SUITE_ICON); tree.setParent(tp, tp.getProjectList().get(0)); boolean children = false; if (!tp.getTestPlanList().isEmpty()) { tp.getTestPlanList().forEach((plan) -> { addTestPlan(plan, tree); }); children = true; } tree.setChildrenAllowed(tp, children); } private void addTestPlan(TestPlan tp, Tree tree) { tree.addItem(tp); tree.setItemCaption(tp, tp.getName()); tree.setItemIcon(tp, TEST_PLAN_ICON); tree.setParent(tp, tp.getTestProject()); if (!tp.getTestCaseList().isEmpty()) { tp.getTestCaseList().forEach((tc) -> { addTestCase(tc, tp, tree); }); } } private void addTestCase(TestCase t, TestPlan plan, Tree tree) { tree.addItem(t); tree.setItemCaption(t, t.getName()); tree.setItemIcon(t, TEST_ICON); tree.setParent(t, plan); List<Step> stepList = t.getStepList(); Collections.sort(stepList, (Step o1, Step o2) -> o1.getStepSequence() - o2.getStepSequence()); stepList.forEach((s) -> { addStep(s, tree); }); } private void addStep(Step s, Tree tree) { addStep(s, tree, null); } private void addStep(Step s, Tree tree, String parent) { tree.addItem(s); tree.setItemCaption(s, "Step # " + s.getStepSequence()); tree.setItemIcon(s, STEP_ICON); Object parentId = s.getTestCase(); if (parent != null) { parentId = parent; } tree.setParent(s, parentId); tree.setChildrenAllowed(s, false); } private void addRequirement(Requirement req, Tree tree) { // Add the item as a regular item. tree.addItem(req); tree.setItemCaption(req, req.getUniqueId()); tree.setItemIcon(req, REQUIREMENT_ICON); tree.setParent(req, req.getRequirementSpecNode()); //No children tree.setChildrenAllowed(req, false); } private void addTestCaseExecutions(String parent, TestCaseExecution tce, Tree tree) { tree.addItem(tce); tree.setItemCaption(tce, tce.getName()); tree.setItemIcon(tce, EXECUTION_ICON); tree.setParent(tce, parent); for (ExecutionStep es : tce.getExecutionStepList()) { //Group under the Test Case TestCase tc = es.getStep().getTestCase(); Collection<?> children = tree.getChildren(tce); String node = "tce-" + tce.getId() + "-" + tc.getId(); boolean add = true; if (children != null) { //Check if already added as children for (Object o : children) { if (o.equals(node)) { add = false; break; } } } if (add) { //Add Test Case if not there tree.addItem(node); tree.setItemCaption(node, tc.getName()); tree.setItemIcon(node, TEST_ICON); tree.setParent(node, tce); } tree.addItem(es); tree.setItemCaption(es, "Step #" + es.getStep().getStepSequence()); //Use icon based on result of step tree.setItemIcon(es, STEP_ICON); tree.setParent(es, node); tree.setChildrenAllowed(es, false); } } public void addProject(Project p, Tree tree) { tree.addItem(p); tree.setItemCaption(p, p.getName()); tree.setParent(p, p.getParentProjectId() == null ? projTreeRoot : p.getParentProjectId()); tree.setItemIcon(p, PROJECT_ICON); boolean children = false; if (!p.getProjectList().isEmpty()) { p.getProjectList().forEach((sp) -> { addProject(sp, tree); }); children = true; } if (!p.getRequirementSpecList().isEmpty()) { p.getRequirementSpecList().forEach((rs) -> { addRequirementSpec(rs, tree); }); children = true; } if (!p.getTestProjectList().isEmpty()) { p.getTestProjectList().forEach((tp) -> { addTestProject(tp, tree); }); children = true; } List<TestCaseExecution> executions = TestCaseExecutionServer.getExecutions(p); if (!executions.isEmpty()) { String id = "executions" + p.getId(); tree.addItem(id); tree.setItemCaption(id, "Executions"); tree.setItemIcon(id, EXECUTIONS_ICON); tree.setParent(id, p); executions.forEach((tce) -> { addTestCaseExecutions(id, tce, tree); }); children = true; } if (!children) { // No subprojects tree.setChildrenAllowed(p, false); } } @Override protected void init(VaadinRequest request) { //Connect to the database defined in context.xml try { DataBaseManager.setPersistenceUnitName("VMPUJNDI"); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } setInstance(this); ProjectJpaController controller = new ProjectJpaController(DataBaseManager .getEntityManagerFactory()); if (DataBaseManager.isDemo() && controller.findProjectEntities().isEmpty()) { buildDemoTree(); } tree = new Tree(); // Set the tree in drag source mode tree.setDragMode(TreeDragMode.NODE); // Allow the tree to receive drag drops and handle them tree.setDropHandler(new DropHandler() { @Override public AcceptCriterion getAcceptCriterion() { TreeDropCriterion criterion = new TreeDropCriterion() { @Override protected Set<Object> getAllowedItemIds( DragAndDropEvent dragEvent, Tree tree) { HashSet<Object> allowed = new HashSet<>(); tree.getItemIds().stream().filter((itemId) -> (itemId instanceof Step)).forEachOrdered((itemId) -> { allowed.add(itemId); }); return allowed; } }; return criterion; } @Override public void drop(DragAndDropEvent event) { // Wrapper for the object that is dragged Transferable t = event.getTransferable(); // Make sure the drag source is the same tree if (t.getSourceComponent() != tree) { return; } TreeTargetDetails target = (TreeTargetDetails) event.getTargetDetails(); // Get ids of the dragged item and the target item Object sourceItemId = t.getData("itemId"); Object targetItemId = target.getItemIdOver(); LOG.log(Level.INFO, "Source: {0}", sourceItemId); LOG.log(Level.INFO, "Target: {0}", targetItemId); // On which side of the target the item was dropped VerticalDropLocation location = target.getDropLocation(); HierarchicalContainer container = (HierarchicalContainer) tree.getContainerDataSource(); if (null != location) // Drop right on an item -> make it a child { switch (location) { case MIDDLE: if (tree.areChildrenAllowed(targetItemId)) { tree.setParent(sourceItemId, targetItemId); } break; case TOP: { //for Steps we need to update the sequence number if (sourceItemId instanceof Step && targetItemId instanceof Step) { Step targetItem = (Step) targetItemId; Step sourceItem = (Step) sourceItemId; StepJpaController stepController = new StepJpaController(DataBaseManager.getEntityManagerFactory()); // TestCaseJpaController tcController // = new TestCaseJpaController(DataBaseManager.getEntityManagerFactory()); boolean valid = false; if (targetItem.getTestCase().equals(sourceItem.getTestCase())) { //Same Test Case, just re-arrange LOG.info("Same Test Case!"); SortedMap<Integer, Step> map = new TreeMap<>(); targetItem.getTestCase().getStepList().forEach((s) -> { map.put(s.getStepSequence(), s); }); //Now swap the two that switched swapValues(map, sourceItem.getStepSequence(), targetItem.getStepSequence()); //Now update the sequence numbers int count = 0; for (Entry<Integer, Step> entry : map.entrySet()) { entry.getValue().setStepSequence(++count); try { stepController.edit(entry.getValue()); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } valid = true; } else { //Diferent Test Case LOG.info("Different Test Case!"); // //Remove from source test case // SortedMap<Integer, Step> map = new TreeMap<>(); // sourceItem.getTestCase().getStepList().forEach((s) -> { // map.put(s.getStepSequence(), s); // //Now swap the two that switched // //First we remove the one from the source Test Case // Step removed = map.remove(sourceItem.getStepSequence() - 1); // sourceItem.getTestCase().getStepList().remove(removed); // removed.setTestCase(targetItem.getTestCase()); // try { // stepController.edit(removed); // tcController.edit(sourceItem.getTestCase()); // } catch (NonexistentEntityException ex) { // LOG.log(Level.SEVERE, null, ex); // } catch (Exception ex) { // LOG.log(Level.SEVERE, null, ex); // //Now update the sequence numbers // int count = 0; // for (Entry<Integer, Step> entry : map.entrySet()) { // entry.getValue().setStepSequence(++count); // try { // stepController.edit(entry.getValue()); // } catch (Exception ex) { // LOG.log(Level.SEVERE, null, ex); // //And add it to the target test Case // SortedMap<Integer, Step> map2 = new TreeMap<>(); // targetItem.getTestCase().getStepList().forEach((s) -> { // map2.put(s.getStepSequence(), s); // map2.put(targetItem.getStepSequence() - 1, removed); // count = 0; // for (Entry<Integer, Step> entry : map2.entrySet()) { // entry.getValue().setStepSequence(++count); // try { // stepController.edit(entry.getValue()); // } catch (Exception ex) { // LOG.log(Level.SEVERE, null, ex); // //Add it to the Test Case // targetItem.getTestCase().getStepList().add(removed); } if (valid) { // Drop at the top of a subtree -> make it previous Object parentId = container.getParent(targetItemId); container.setParent(sourceItemId, parentId); container.moveAfterSibling(sourceItemId, targetItemId); container.moveAfterSibling(targetItemId, sourceItemId); buildProjectTree(targetItem); updateScreen(); } } break; } case BOTTOM: { // Drop below another item -> make it next Object parentId = container.getParent(targetItemId); container.setParent(sourceItemId, parentId); container.moveAfterSibling(sourceItemId, targetItemId); break; } default: break; } } } }); tree.addValueChangeListener((Property.ValueChangeEvent event) -> { displayObject(tree.getValue()); }); //Select item on right click as well tree.addItemClickListener((ItemClickEvent event) -> { if (event.getSource() == tree && event.getButton() == MouseButton.RIGHT) { if (event.getItem() != null) { Item clicked = event.getItem(); tree.select(event.getItemId()); } } }); ContextMenu contextMenu = new ContextMenu(); contextMenu.setAsContextMenuOf(tree); ContextMenuOpenedListener.TreeListener treeItemListener = (ContextMenuOpenedOnTreeItemEvent event) -> { contextMenu.removeAllItems(); if (tree.getValue() instanceof Project) { createProjectMenu(contextMenu); } else if (tree.getValue() instanceof Requirement) { createRequirementMenu(contextMenu); } else if (tree.getValue() instanceof RequirementSpec) { createRequirementSpecMenu(contextMenu); } else if (tree.getValue() instanceof RequirementSpecNode) { createRequirementSpecNodeMenu(contextMenu); } else if (tree.getValue() instanceof TestProject) { createTestProjectMenu(contextMenu); } else if (tree.getValue() instanceof Step) { createStepMenu(contextMenu); } else if (tree.getValue() instanceof TestCase) { createTestCaseMenu(contextMenu); } else if (tree.getValue() instanceof String) { String val = (String) tree.getValue(); if (val.startsWith("tce")) { createTestExecutionMenu(contextMenu); } else { //We are at the root createRootMenu(contextMenu); } } else if (tree.getValue() instanceof TestPlan) { createTestPlanMenu(contextMenu); } else if (tree.getValue() instanceof TestCaseExecution) { createTestCaseExecutionPlanMenu(contextMenu); } }; contextMenu.addContextMenuTreeListener(treeItemListener); tree.setImmediate(true); tree.expandItem(projTreeRoot); tree.setSizeFull(); updateProjectList(); updateScreen(); Page.getCurrent().setTitle("Validation Manager"); } private static <V> void swapValues(SortedMap m, int i0, int i1) { Object first = m.get(i0); Object second = m.get(i1); m.put(i0, second); m.put(i1, first); } public void updateProjectList() { ProjectJpaController controller = new ProjectJpaController(DataBaseManager .getEntityManagerFactory()); if (DataBaseManager.isDemo() && controller.findProjectEntities().isEmpty()) { buildDemoTree(); } List<Project> all = controller.findProjectEntities(); projects.clear(); all.stream().filter((p) -> (p.getParentProjectId() == null)).forEachOrdered((p) -> { projects.add(p); }); buildProjectTree(); left = new HorizontalLayout(tree); LOG.log(Level.FINE, "Found {0} root projects!", projects.size()); } private void showLoginDialog() { if (loginWindow == null) { loginWindow = new LoginDialog(this); loginWindow.setVisible(true); loginWindow.setClosable(false); loginWindow.setResizable(false); loginWindow.center(); loginWindow.setWidth(35, Unit.PERCENTAGE); loginWindow.setHeight(35, Unit.PERCENTAGE); } else { loginWindow.clear(); } if (!getWindows().contains(loginWindow)) { addWindow(loginWindow); } } private Project getParentProject() { Object current = tree.getValue(); Project result = null; while (current != null && !(current instanceof Project)) { current = tree.getParent(current); } if (current instanceof Project) { result = (Project) current; } return result; } private boolean checkAnyRights(List<String> rights) { boolean result = false; if (rights.stream().anyMatch((r) -> (checkRight(r)))) { return true; } return result; } private boolean checkAllRights(List<String> rights) { boolean result = true; for (String r : rights) { if (!checkRight(r)) { result = false; break; } } return result; } private boolean checkRight(String right) { if (user != null) { user.update(); if (user.getRoleList().stream().anyMatch((r) -> (r.getUserRightList().stream().anyMatch((ur) -> (ur.getDescription().equals(right)))))) { return true; } } return false; } private void displayTestPlanning(Project p) { Wizard w = new Wizard(); w.addStep(new SelectTestCasesStep(w, p)); w.addStep(new DetailStep(ValidationManagerUI.this, p)); w.addListener(new WizardProgressListener() { @Override public void activeStepChanged(WizardStepActivationEvent event) { //Do nothing } @Override public void stepSetChanged(WizardStepSetChangedEvent event) { //Do nothing } @Override public void wizardCompleted(WizardCompletedEvent event) { setTabContent(designer, null, "testplan.planning"); } @Override public void wizardCancelled(WizardCancelledEvent event) { setTabContent(designer, null, "testplan.planning"); } }); setTabContent(designer, w, "testplan.planning"); } public Object getSelectdValue() { return tree.getValue(); } private ExecutionStepPK extractExecutionStepPK(String itemId) { String id = itemId.substring(2);//Remove es int esId, sId, tcId; StringTokenizer st = new StringTokenizer(id, "-"); esId = Integer.parseInt(st.nextToken()); sId = Integer.parseInt(st.nextToken()); tcId = Integer.parseInt(st.nextToken()); return new ExecutionStepPK(esId, sId, tcId); }
package com.reprezen.swagedit.editor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.dadacoalition.yedit.YEditLog; import org.dadacoalition.yedit.editor.IDocumentIdleListener; import org.dadacoalition.yedit.editor.YEdit; import org.dadacoalition.yedit.editor.YEditSourceViewerConfiguration; import org.dadacoalition.yedit.preferences.PreferenceConstants; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.text.source.projection.ProjectionAnnotation; import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; import org.eclipse.jface.text.source.projection.ProjectionSupport; import org.eclipse.jface.text.source.projection.ProjectionViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.yaml.snakeyaml.error.YAMLException; import com.fasterxml.jackson.core.JsonParseException; import com.reprezen.swagedit.Activator; import com.reprezen.swagedit.validation.SwaggerError; import com.reprezen.swagedit.validation.Validator; /** * SwagEdit editor. * */ public class SwaggerEditor extends YEdit { public static final String ID = "com.reprezen.swagedit.editor"; private final Validator validator = new Validator(); private ProjectionSupport projectionSupport; private Annotation[] oldAnnotations; private ProjectionAnnotationModel annotationModel; private Composite topPanel; private SwaggerSourceViewerConfiguration sourceViewerConfiguration; private final IDocumentListener changeListener = new IDocumentListener() { @Override public void documentAboutToBeChanged(DocumentEvent event) { } @Override public void documentChanged(DocumentEvent event) { if (event.getDocument() instanceof SwaggerDocument) { final SwaggerDocument document = (SwaggerDocument) event.getDocument(); Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { document.onChange(); runValidate(false); } }); } } }; /* * This listener is added to the preference store when the editor is initialized. It listens to changes to color * preferences. Once a color change happens, the editor is re-initialize. */ private final IPropertyChangeListener preferenceChangeListener = new IPropertyChangeListener() { private final List<String> preferenceKeys = new ArrayList<>(); { preferenceKeys.add(PreferenceConstants.COLOR_COMMENT); preferenceKeys.add(PreferenceConstants.BOLD_COMMENT); preferenceKeys.add(PreferenceConstants.ITALIC_COMMENT); preferenceKeys.add(PreferenceConstants.UNDERLINE_COMMENT); preferenceKeys.add(PreferenceConstants.COLOR_KEY); preferenceKeys.add(PreferenceConstants.BOLD_KEY); preferenceKeys.add(PreferenceConstants.ITALIC_KEY); preferenceKeys.add(PreferenceConstants.UNDERLINE_KEY); preferenceKeys.add(PreferenceConstants.COLOR_SCALAR); preferenceKeys.add(PreferenceConstants.BOLD_SCALAR); preferenceKeys.add(PreferenceConstants.ITALIC_SCALAR); preferenceKeys.add(PreferenceConstants.UNDERLINE_SCALAR); preferenceKeys.add(PreferenceConstants.COLOR_DEFAULT); preferenceKeys.add(PreferenceConstants.BOLD_DEFAULT); preferenceKeys.add(PreferenceConstants.ITALIC_DEFAULT); preferenceKeys.add(PreferenceConstants.UNDERLINE_DEFAULT); preferenceKeys.add(PreferenceConstants.COLOR_DOCUMENT); preferenceKeys.add(PreferenceConstants.BOLD_DOCUMENT); preferenceKeys.add(PreferenceConstants.ITALIC_DOCUMENT); preferenceKeys.add(PreferenceConstants.UNDERLINE_DOCUMENT); preferenceKeys.add(PreferenceConstants.COLOR_ANCHOR); preferenceKeys.add(PreferenceConstants.BOLD_ANCHOR); preferenceKeys.add(PreferenceConstants.ITALIC_ANCHOR); preferenceKeys.add(PreferenceConstants.UNDERLINE_ANCHOR); preferenceKeys.add(PreferenceConstants.COLOR_ALIAS); preferenceKeys.add(PreferenceConstants.BOLD_ALIAS); preferenceKeys.add(PreferenceConstants.ITALIC_ALIAS); preferenceKeys.add(PreferenceConstants.UNDERLINE_ALIAS); preferenceKeys.add(PreferenceConstants.COLOR_TAG_PROPERTY); preferenceKeys.add(PreferenceConstants.BOLD_TAG_PROPERTY); preferenceKeys.add(PreferenceConstants.ITALIC_TAG_PROPERTY); preferenceKeys.add(PreferenceConstants.UNDERLINE_TAG_PROPERTY); preferenceKeys.add(PreferenceConstants.COLOR_INDICATOR_CHARACTER); preferenceKeys.add(PreferenceConstants.BOLD_INDICATOR_CHARACTER); preferenceKeys.add(PreferenceConstants.ITALIC_INDICATOR_CHARACTER); preferenceKeys.add(PreferenceConstants.UNDERLINE_INDICATOR_CHARACTER); preferenceKeys.add(PreferenceConstants.COLOR_CONSTANT); preferenceKeys.add(PreferenceConstants.BOLD_CONSTANT); preferenceKeys.add(PreferenceConstants.ITALIC_CONSTANT); preferenceKeys.add(PreferenceConstants.UNDERLINE_CONSTANT); } @Override public void propertyChange(PropertyChangeEvent event) { if (preferenceKeys.contains(event.getProperty())) { if (getSourceViewer() instanceof SourceViewer) { ((SourceViewer) getSourceViewer()).unconfigure(); initializeEditor(); getSourceViewer().configure(sourceViewerConfiguration); } } } }; public SwaggerEditor() { super(); setDocumentProvider(new SwaggerDocumentProvider()); } @Override protected YEditSourceViewerConfiguration createSourceViewerConfiguration() { sourceViewerConfiguration = new SwaggerSourceViewerConfiguration(); sourceViewerConfiguration.setEditor(this); return sourceViewerConfiguration; } @Override protected void doSetInput(IEditorInput input) throws CoreException { if (input != null) { super.doSetInput(input); IDocument document = getDocumentProvider().getDocument(getEditorInput()); if (document != null) { document.addDocumentListener(changeListener); // validate content before editor opens runValidate(true); } } } public ProjectionViewer getProjectionViewer() { return (ProjectionViewer) getSourceViewer(); } @Override public void createPartControl(Composite parent) { super.createPartControl(parent); ProjectionViewer viewer = getProjectionViewer(); projectionSupport = new ProjectionSupport(viewer, getAnnotationAccess(), getSharedColors()); projectionSupport.install(); // turn projection mode on viewer.doOperation(ProjectionViewer.TOGGLE); annotationModel = viewer.getProjectionAnnotationModel(); Activator.getDefault().getPreferenceStore().addPropertyChangeListener(preferenceChangeListener); } @Override public void dispose() { super.dispose(); Activator.getDefault().getPreferenceStore().removePropertyChangeListener(preferenceChangeListener); } @Override protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { Composite composite = new Composite(parent, SWT.NONE); GridLayout compositeLayout = new GridLayout(1, false); compositeLayout.marginHeight = 0; compositeLayout.marginWidth = 0; compositeLayout.horizontalSpacing = 0; compositeLayout.verticalSpacing = 0; composite.setLayout(compositeLayout); topPanel = new Composite(composite, SWT.NONE); topPanel.setLayout(new StackLayout()); topPanel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); Composite editorComposite = new Composite(composite, SWT.NONE); editorComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); FillLayout fillLayout = new FillLayout(SWT.VERTICAL); fillLayout.marginHeight = 0; fillLayout.marginWidth = 0; fillLayout.spacing = 0; editorComposite.setLayout(fillLayout); ISourceViewer result = doCreateSourceViewer(editorComposite, ruler, styles); return result; } /** * SwaggerEditor provides additional hidden panel on top of the source viewer, where external integrations can put * their UI. * <p/> * The panel is only a placeholder, that is: * <ul> * <li>it is not visible by default</li> * <li>it has a {@link StackLayout} and expect single composite to be created per contribution</li> * <li>if there are more than one contributors, it is their responsibility to manage {@link StackLayout#topControl} * </li> * </ul> */ public Composite getTopPanel() { return topPanel; } protected ISourceViewer doCreateSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { ISourceViewer viewer = new ProjectionViewer(parent, ruler, getOverviewRuler(), isOverviewRulerVisible(), styles); getSourceViewerDecorationSupport(viewer); return viewer; } public void updateFoldingStructure(List<Position> positions) { final Map<Annotation, Position> newAnnotations = new HashMap<Annotation, Position>(); for (Position position : positions) { newAnnotations.put(new ProjectionAnnotation(), position); } annotationModel.modifyAnnotations(oldAnnotations, newAnnotations, null); oldAnnotations = newAnnotations.keySet().toArray(new Annotation[0]); } @Override public void doSave(IProgressMonitor monitor) { // batch all marker changes into a single delta for ZEN-2736 Refresh live views on swagedit error changes new WorkspaceJob("Do save") { @Override public IStatus runInWorkspace(final IProgressMonitor jobMonitor) throws CoreException { // need to run it in UI thread because AbstractTextEditor.doSave needs it in TextViewer.setEditable() Shell shell = getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().syncExec(new Runnable() { @Override public void run() { SwaggerEditor.super.doSave(jobMonitor); } }); } validate(); return Status.OK_STATUS; } }.schedule(); } @Override public void doSaveAs() { // batch all marker changes into a single delta for ZEN-2736 Refresh live views on swagedit error changes new WorkspaceJob("Do save as") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { // AbstractDecoratedTextEditor.performSaveAs() invoked by doSaveAs() needs to be executed in SWT thread Shell shell = getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().syncExec(new Runnable() { @Override public void run() { SwaggerEditor.super.doSaveAs(); } }); } return Status.OK_STATUS; } }.schedule(); validate(); } protected void validate() { validate(false); } protected void runValidate(final boolean onOpen) { new WorkspaceJob("Update SwagEdit validation markers") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { validate(onOpen); return Status.OK_STATUS; } }.schedule(); } private void validate(boolean onOpen) { IEditorInput editorInput = getEditorInput(); final IDocument document = getDocumentProvider().getDocument(getEditorInput()); // if the file is not part of a workspace it does not seems that it is a // IFileEditorInput // but instead a FileStoreEditorInput. Unclear if markers are valid for // such files. if (!(editorInput instanceof IFileEditorInput)) { YEditLog.logError("Marking errors not supported for files outside of a project."); YEditLog.logger.info("editorInput is not a part of a project."); return; } if (document instanceof SwaggerDocument) { final IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput; final IFile file = fileEditorInput.getFile(); if (onOpen) { // force parsing of yaml to init parsing errors ((SwaggerDocument) document).onChange(); } clearMarkers(file); validateYaml(file, (SwaggerDocument) document); validateSwagger(file, (SwaggerDocument) document, fileEditorInput); } } protected void clearMarkers(IFile file) { int depth = IResource.DEPTH_INFINITE; try { file.deleteMarkers(IMarker.PROBLEM, true, depth); } catch (CoreException e) { YEditLog.logException(e); YEditLog.logger.warning("Failed to delete markers:\n" + e.toString()); } } protected void validateYaml(IFile file, SwaggerDocument document) { if (document.getYamlError() instanceof YAMLException) { addMarker(new SwaggerError((YAMLException) document.getYamlError()), file, document); } if (document.getJsonError() instanceof JsonParseException) { addMarker(new SwaggerError((JsonParseException) document.getJsonError()), file, document); } } protected void validateSwagger(IFile file, SwaggerDocument document, IFileEditorInput editorInput) { final Set<SwaggerError> errors = validator.validate(document, editorInput); for (SwaggerError error : errors) { addMarker(error, file, document); } } private IMarker addMarker(SwaggerError error, IFile target, IDocument document) { IMarker marker = null; try { marker = target.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.SEVERITY, error.getLevel()); marker.setAttribute(IMarker.MESSAGE, error.getMessage()); marker.setAttribute(IMarker.LINE_NUMBER, error.getLine()); } catch (CoreException e) { YEditLog.logException(e); YEditLog.logger.warning("Failed to create marker for syntax error: \n" + e.toString()); } return marker; } public void redrawViewer() { Display.getDefault().asyncExec(new Runnable() { public void run() { if (getSourceViewer() != null) { getSourceViewer().getTextWidget().redraw(); } } }); } @Override public void addDocumentIdleListener(IDocumentIdleListener listener) { super.addDocumentIdleListener(listener); } }
package net.i2p.router; import net.i2p.data.Hash; import net.i2p.router.client.ClientManagerFacadeImpl; import net.i2p.router.transport.OutboundMessageRegistry; import net.i2p.router.networkdb.kademlia.KademliaNetworkDatabaseFacade; import net.i2p.router.transport.CommSystemFacadeImpl; import net.i2p.router.transport.BandwidthLimiter; import net.i2p.router.transport.TrivialBandwidthLimiter; import net.i2p.router.tunnelmanager.PoolingTunnelManagerFacade; import net.i2p.router.peermanager.ProfileOrganizer; import net.i2p.router.peermanager.PeerManagerFacadeImpl; import net.i2p.router.peermanager.ProfileManagerImpl; import net.i2p.router.peermanager.Calculator; import net.i2p.router.peermanager.IsFailingCalculator; import net.i2p.router.peermanager.ReliabilityCalculator; import net.i2p.router.peermanager.SpeedCalculator; import net.i2p.router.peermanager.IntegrationCalculator; import net.i2p.I2PAppContext; import java.util.Properties; /** * Build off the core I2P context to provide a root for a router instance to * coordinate its resources. Router instances themselves should be sure to have * their own RouterContext, and rooting off of it will allow multiple routers to * operate in the same JVM without conflict (e.g. sessionTags wont get * intermingled, nor will their netDbs, jobQueues, or bandwidth limiters). * */ public class RouterContext extends I2PAppContext { private Router _router; private ClientManagerFacade _clientManagerFacade; private ClientMessagePool _clientMessagePool; private JobQueue _jobQueue; private InNetMessagePool _inNetMessagePool; private OutNetMessagePool _outNetMessagePool; private MessageHistory _messageHistory; private OutboundMessageRegistry _messageRegistry; private NetworkDatabaseFacade _netDb; private KeyManager _keyManager; private CommSystemFacade _commSystem; private ProfileOrganizer _profileOrganizer; private PeerManagerFacade _peerManagerFacade; private ProfileManager _profileManager; private BandwidthLimiter _bandwidthLimiter; private TunnelManagerFacade _tunnelManager; private StatisticsManager _statPublisher; private Shitlist _shitlist; private MessageValidator _messageValidator; private Calculator _isFailingCalc; private Calculator _integrationCalc; private Calculator _speedCalc; private Calculator _reliabilityCalc; public RouterContext(Router router) { this(router, null); } public RouterContext(Router router, Properties envProps) { super(envProps); _router = router; initAll(); } private void initAll() { _clientManagerFacade = new ClientManagerFacadeImpl(this); _clientMessagePool = new ClientMessagePool(this); _jobQueue = new JobQueue(this); _inNetMessagePool = new InNetMessagePool(this); _outNetMessagePool = new OutNetMessagePool(this); _messageHistory = new MessageHistory(this); _messageRegistry = new OutboundMessageRegistry(this); _netDb = new KademliaNetworkDatabaseFacade(this); _keyManager = new KeyManager(this); _commSystem = new CommSystemFacadeImpl(this); _profileOrganizer = new ProfileOrganizer(this); _peerManagerFacade = new PeerManagerFacadeImpl(this); _profileManager = new ProfileManagerImpl(this); _bandwidthLimiter = new TrivialBandwidthLimiter(this); _tunnelManager = new PoolingTunnelManagerFacade(this); _statPublisher = new StatisticsManager(this); _shitlist = new Shitlist(this); _messageValidator = new MessageValidator(this); _isFailingCalc = new IsFailingCalculator(this); _integrationCalc = new IntegrationCalculator(this); _speedCalc = new SpeedCalculator(this); _reliabilityCalc = new ReliabilityCalculator(this); } /** what router is this context working for? */ public Router router() { return _router; } /** convenience method for querying the router's ident */ public Hash routerHash() { return _router.getRouterInfo().getIdentity().getHash(); } /** * How are we coordinating clients for the router? */ public ClientManagerFacade clientManager() { return _clientManagerFacade; } /** * Where do we toss messages for the clients (and where do we get client messages * to forward on from)? */ public ClientMessagePool clientMessagePool() { return _clientMessagePool; } /** * Where do we get network messages from (aka where does the comm system dump what * it reads)? */ public InNetMessagePool inNetMessagePool() { return _inNetMessagePool; } /** * Where do we put messages that the router wants to forwards onto the network? */ public OutNetMessagePool outNetMessagePool() { return _outNetMessagePool; } /** * Tracker component for monitoring what messages are wrapped in what containers * and how they proceed through the network. This is fully for debugging, as when * a large portion of the network tracks their messages through this messageHistory * and submits their logs, we can correlate them and watch as messages flow from * hop to hop. */ public MessageHistory messageHistory() { return _messageHistory; } /** * The registry is used by outbound messages to wait for replies. */ public OutboundMessageRegistry messageRegistry() { return _messageRegistry; } /** * Our db cache */ public NetworkDatabaseFacade netDb() { return _netDb; } /** * The actual driver of the router, where all jobs are enqueued and processed. */ public JobQueue jobQueue() { return _jobQueue; } /** * Coordinates the router's ElGamal and DSA keys, as well as any keys given * to it by clients as part of a LeaseSet. */ public KeyManager keyManager() { return _keyManager; } /** * How do we pass messages from our outNetMessagePool to another router */ public CommSystemFacade commSystem() { return _commSystem; } /** * Organize the peers we know about into various tiers, profiling their * performance and sorting them accordingly. */ public ProfileOrganizer profileOrganizer() { return _profileOrganizer; } /** * Minimal interface for selecting peers for various tasks based on given * criteria. This is kept seperate from the profile organizer since this * logic is independent of how the peers are organized (or profiled even). */ public PeerManagerFacade peerManager() { return _peerManagerFacade; } /** * Expose a simple API for various router components to take note of * particular events that a peer enacts (sends us a message, agrees to * participate in a tunnel, etc). */ public ProfileManager profileManager() { return _profileManager; } /** * Coordinate this router's bandwidth limits */ public BandwidthLimiter bandwidthLimiter() { return _bandwidthLimiter; } /** * Coordinate this router's tunnels (its pools, participation, backup, etc). * Any configuration for the tunnels is rooted from the context's properties */ public TunnelManagerFacade tunnelManager() { return _tunnelManager; } /** * If the router is configured to, gather up some particularly tasty morsels * regarding the stats managed and offer to publish them into the routerInfo. */ public StatisticsManager statPublisher() { return _statPublisher; } /** * who does this peer hate? */ public Shitlist shitlist() { return _shitlist; } /** * The router keeps track of messages it receives to prevent duplicates, as * well as other criteria for "validity". */ public MessageValidator messageValidator() { return _messageValidator; } /** how do we rank the failure of profiles? */ public Calculator isFailingCalculator() { return _isFailingCalc; } /** how do we rank the integration of profiles? */ public Calculator integrationCalculator() { return _integrationCalc; } /** how do we rank the speed of profiles? */ public Calculator speedCalculator() { return _speedCalc; } /** how do we rank the reliability of profiles? */ public Calculator reliabilityCalculator() { return _reliabilityCalc; } }
package com.tapad.sample; import java.net.URLEncoder; import java.util.List; import org.json.JSONObject; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTabHost; import android.view.Menu; import android.view.MenuItem; import com.tapad.tapestry.Logging; import com.tapad.tapestry.R; import com.tapad.tapestry.TapestryService; import com.tapad.tapestry.deviceidentification.TypedIdentifier; public class MainActivity extends FragmentActivity { private MenuItem bridgeEmailItem; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.menu_tabs); FragmentTabHost host = (FragmentTabHost) findViewById(android.R.id.tabhost); host.setup(this, getSupportFragmentManager(), R.id.realtabcontent); host.addTab(host.newTabSpec("demo").setIndicator("Demo"), CarExampleFragment.class, null); host.addTab(host.newTabSpec("debug").setIndicator("Debug"), DebugFragment.class, null); } @Override public boolean onCreateOptionsMenu(Menu menu) { bridgeEmailItem = menu.add("Compose Bridge Email"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item == bridgeEmailItem) { composeBridgeEmail(); return true; } else return super.onOptionsItemSelected(item); } private void composeBridgeEmail() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/html"); intent.putExtra(Intent.EXTRA_SUBJECT, "TapAd Bridge: " + Build.MODEL); intent.putExtra(Intent.EXTRA_TEXT, "Pleaes open this URL in your desktop's browser to bridge " + Build.MODEL + ":\n\n" + buildURL()); startActivity(Intent.createChooser(intent, "Select Email App")); } private String buildURL() { JSONObject bridge = new JSONObject(); List<TypedIdentifier> deviceIDs = TapestryService.client().getDeviceIDs(); try { for (TypedIdentifier id : deviceIDs) { bridge.put(id.getType(), id.getValue()); } Logging.d("Added device ids:\n" + bridge.toString()); StringBuilder stringBuilder = new StringBuilder(TapestryService.client().getURL()); stringBuilder.append("?ta_partner_id="); stringBuilder.append(TapestryService.client().getPartnerID()); stringBuilder.append("&ta_bridge="); stringBuilder.append(URLEncoder.encode(bridge.toString(), "UTF-8")); stringBuilder.append("&ta_redirect="); stringBuilder.append(URLEncoder.encode("http://tapestry-demo-test.dev.tapad.com/content_optimization", "UTF-8")); return stringBuilder.toString(); } catch (Exception e) { Logging.e("Some error occured while making URL for bridging", e); return "error!"; } } }
package hypergraph.storage; public class Schema { /** * The values in this class will be used as 'prefixes' within an IID in the * of every object database, and must not overlap with each other. * * The size of a prefix is 1 byte; i.e. min-value = 0 and max-value = 255. */ private static class Prefix { private static final int INDEX_TYPE = 0; private static final int INDEX_VALUE = 5; private static final int VERTEX_ENTITY_TYPE = 20; private static final int VERTEX_RELATION_TYPE = 30; private static final int VERTEX_ROLE_TYPE = 40; private static final int VERTEX_ATTRIBUTE_TYPE = 50; private static final int VERTEX_ENTITY = 60; private static final int VERTEX_RELATION = 70; private static final int VERTEX_ROLE = 80; private static final int VERTEX_ATTRIBUTE = 90; private static final int VERTEX_VALUE = 100; private static final int VERTEX_RULE = 110; } /** * The values in this class will be used as 'infixes' between two IIDs of * two objects in the database, and must not overlap with each other. * * The size of a prefix is 1 byte; i.e. min-value = 0 and max-value = 255. */ private static class Infix { private static final int PROPERTY_ABSTRACT = 0; private static final int PROPERTY_DATATYPE = 1; private static final int PROPERTY_REGEX = 2; private static final int PROPERTY_VALUE = 3; private static final int PROPERTY_VALUE_REF = 4; private static final int PROPERTY_WHEN = 5; private static final int PROPERTY_THEN = 6; private static final int EDGE_SUB_OUT = 20; private static final int EDGE_SUB_IN = 25; private static final int EDGE_ISA_OUT = 30; private static final int EDGE_ISA_IN = 35; private static final int EDGE_KEY_OUT = 40; private static final int EDGE_KEY_IN = 45; private static final int EDGE_HAS_OUT = 50; private static final int EDGE_HAS_IN = 55; private static final int EDGE_PLAYS_OUT = 60; private static final int EDGE_PLAYS_IN = 65; private static final int EDGE_RELATES_OUT = 70; private static final int EDGE_RELATES_IN = 75; private static final int EDGE_OPT_ROLE_OUT = 100; private static final int EDGE_OPT_ROLE_IN = 105; private static final int EDGE_OPT_RELATION_OUT = 110; } public enum IndexType { TYPE(Prefix.INDEX_TYPE), VALUE(Prefix.INDEX_VALUE); private final byte key; IndexType(int key) { this.key = (byte) key; } } public enum VertexType { ENTITY_TYPE(Prefix.VERTEX_ENTITY_TYPE), RELATION_TYPE(Prefix.VERTEX_RELATION_TYPE), ROLE_TYPE(Prefix.VERTEX_ROLE_TYPE), ATTRIBUTE_TYPE(Prefix.VERTEX_ATTRIBUTE_TYPE), ENTITY(Prefix.VERTEX_ENTITY), RELATION(Prefix.VERTEX_RELATION), ROLE(Prefix.VERTEX_ROLE), ATTRIBUTE(Prefix.VERTEX_ATTRIBUTE), VALUE(Prefix.VERTEX_VALUE), RULE(Prefix.VERTEX_RULE); private final byte key; VertexType(int key) { this.key = (byte) key; } } public enum PropertyType { ABSTRACT(Infix.PROPERTY_ABSTRACT), DATATYPE(Infix.PROPERTY_DATATYPE), REGEX(Infix.PROPERTY_REGEX), VALUE(Infix.PROPERTY_VALUE), VALUE_REF(Infix.PROPERTY_VALUE_REF), WHEN(Infix.PROPERTY_WHEN), THEN(Infix.PROPERTY_THEN); private final byte key; PropertyType(int key) { this.key = (byte) key; } } public enum DataType { LONG(0), DOUBLE(2), STRING(4), BOOLEAN(6), DATE(8); private final byte key; DataType(int key) { this.key = (byte) key; } } public enum EdgeType { SUB_OUT(Infix.EDGE_SUB_OUT), SUB_IN(Infix.EDGE_SUB_IN), ISA_OUT(Infix.EDGE_ISA_OUT), ISA_IN(Infix.EDGE_ISA_IN), KEY_OUT(Infix.EDGE_KEY_OUT), KEY_IN(Infix.EDGE_KEY_IN), HAS_OUT(Infix.EDGE_HAS_OUT), HAS_IN(Infix.EDGE_HAS_IN), PLAYS_OUT(Infix.EDGE_PLAYS_OUT), PLAYS_IN(Infix.EDGE_PLAYS_IN), RELATES_OUT(Infix.EDGE_RELATES_OUT), RELATES_IN(Infix.EDGE_RELATES_IN), OPT_ROLE_OUT(Infix.EDGE_OPT_ROLE_OUT), OPT_ROLE_IN(Infix.EDGE_OPT_ROLE_IN), OPT_RELATION_OUT(Infix.EDGE_OPT_RELATION_OUT); private final byte key; EdgeType(int key) { this.key = (byte) key; } } }
package graph; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.Properties; import java.util.Scanner; import java.util.concurrent.locks.ReentrantLock; import java.util.prefs.Preferences; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.metal.MetalButtonUI; import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import lpn.parser.LhpnFile; import main.Gui; import main.Log; import main.util.Utility; import main.util.dataparser.DTSDParser; import main.util.dataparser.DataParser; import main.util.dataparser.TSDParser; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.StandardChartTheme; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.StandardTickUnitSource; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.GradientBarPainter; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.title.LegendTitle; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jibble.epsgraphics.EpsGraphics2D; import org.sbml.libsbml.ListOf; import org.sbml.libsbml.Model; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.w3c.dom.DOMImplementation; import analysis.AnalysisView; import biomodel.parser.BioModel; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.DefaultFontMapper; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private XYSeriesCollection curData; // Data in the current graph private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private Gui biomodelsim; // tstubd gui private JButton save, run, saveAs; private JButton export, refresh; // buttons // private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg, // exportCsv; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private LinkedList<GraphProbs> probGraphed; private JCheckBox resize; private JComboBox XVariable; private JCheckBox LogX, LogY; private JCheckBox visibleLegend; private LegendTitle legend; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JButton> colorsButtons; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; private String separator; private boolean change; private boolean timeSeries; private boolean topLevel; private ArrayList<String> graphProbs; private JTree tree; private IconNode node, simDir; private AnalysisView reb2sac; // reb2sac options private ArrayList<String> learnSpecs; private boolean warn; private ArrayList<String> averageOrder; private JPopupMenu popup; // popup menu private ArrayList<String> directories; private JPanel specPanel; private JScrollPane scrollpane; private JPanel all; private JPanel titlePanel; private JScrollPane scroll; private boolean updateXNumber; private final ReentrantLock lock, lock2; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(AnalysisView reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim, String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) { lock = new ReentrantLock(true); lock2 = new ReentrantLock(true); this.reb2sac = reb2sac; averageOrder = null; popup = new JPopupMenu(); warn = false; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // initializes member variables this.log = log; this.timeSeries = timeSeries; if (graphName != null) { this.graphName = graphName; topLevel = true; } else { if (timeSeries) { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf"; } else { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb"; } topLevel = false; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data = new XYSeriesCollection(); if (learnGraph) { updateSpecies(); } else { learnSpecs = null; } // graph the output data if (timeSeries) { setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, data, time); if (open != null) { open(open); } } else { setUpShapesAndColors(); probGraphed = new LinkedList<GraphProbs>(); selected = ""; lastSelected = ""; probGraph(label); if (open != null) { open(open); } } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); applyChartTheme(chart); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.addProgressListener(this); legend = chart.getLegend(); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); setChange(false); // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XVariable = new JComboBox(); Dimension dim = new Dimension(1,1); XVariable.setPreferredSize(dim); updateXNumber = false; XVariable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (updateXNumber && node != null) { String curDir = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName(); } else if (directories.contains(((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent()).getName(); } else { curDir = ""; } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(curDir)) { graphed.get(i).setXNumber(XVariable.getSelectedIndex()); } } } } }); LogX = new JCheckBox("LogX"); LogX.setSelected(false); LogY = new JCheckBox("LogY"); LogY.setSelected(false); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (file.contains(".dtsd")) graphSpecies = (new DTSDParser(file)).getSpecies(); else graphSpecies = new TSDParser(file, true).getSpecies(); Gui.frame.setCursor(null); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); i } } } } /** * This public helper method parses the output file of ODE, monte carlo, and * markov abstractions. */ public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) { warn = warning; String[] s = file.split(separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance")) || (label.contains("deviation") && file.contains("standard_deviation"))) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } if (label.contains("average") || label.contains("variance") || label.contains("deviation")) { ArrayList<String> runs = new ArrayList<String>(); if (directory == null) { String[] files = new File(outDir).list(); for (String f : files) { if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(f); } } } else { String[] files = new File(outDir + separator + directory).list(); for (String f : files) { if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(f); } } } boolean outputFile; if (directory == null) { outputFile = !(new File(outDir + separator + "running").exists()); } else { outputFile = !(new File(outDir + separator + directory + separator + "running").exists()); } if (label.contains("average")) { if (directory == null) { outputFile = outputFile && !(new File(outDir + separator + "mean.tsd").exists()); } else { outputFile = outputFile && !(new File(outDir + separator + directory + separator + "mean.tsd").exists()); } return calculateAverageVarianceDeviation(runs, 0, directory, warn, outputFile); } else if (label.contains("variance")) { if (directory == null) { outputFile = outputFile && !(new File(outDir + separator + "variance.tsd").exists()); } else { outputFile = outputFile && !(new File(outDir + separator + directory + separator + "variance.tsd").exists()); } return calculateAverageVarianceDeviation(runs, 1, directory, warn, outputFile); } else { if (directory == null) { outputFile = outputFile && !(new File(outDir + separator + "standard_deviation.tsd").exists()); } else { outputFile = outputFile && !(new File(outDir + separator + directory + separator + "standard_deviation.tsd") .exists()); } return calculateAverageVarianceDeviation(runs, 2, directory, warn, outputFile); } } //if it's not a stats file else { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); DTSDParser dtsdParser; TSDParser p; ArrayList<ArrayList<Double>> data; if (file.contains(".dtsd")) { dtsdParser = new DTSDParser(file); Gui.frame.setCursor(null); warn = false; graphSpecies = dtsdParser.getSpecies(); data = dtsdParser.getData(); } else { p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); data = p.getData(); } if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == run) { reb2sac.getRunButton().doClick(); } if (e.getSource() == save) { save(); } // if the save as button is clicked if (e.getSource() == saveAs) { saveAs(); } // if the export button is clicked else if (e.getSource() == export) { export(); } else if (e.getSource() == refresh) { refresh(); } else if (e.getActionCommand().equals("rename")) { String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { boolean write = true; if (rename.equals(node.getName())) { write = false; } else if (new File(outDir + separator + rename).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(outDir + separator + rename); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) { simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(rename)) { graphed.remove(i); i } } } else { write = false; } } if (write) { String getFile = node.getName(); IconNode s = node; while (s.getParent().getParent() != null) { getFile = s.getName() + separator + getFile; s = (IconNode) s.getParent(); } getFile = outDir + separator + getFile; new File(getFile).renameTo(new File(outDir + separator + rename)); for (GraphSpecies spec : graphed) { if (spec.getDirectory().equals(node.getName())) { spec.setDirectory(rename); } } directories.remove(node.getName()); directories.add(rename); node.setUserObject(rename); node.setName(rename); simDir.remove(node); int i; for (i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) { simDir.insert(node, i); break; } } else { break; } } simDir.insert(node, i); ArrayList<String> rows = new ArrayList<String>(); for (i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); int select = 0; for (i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } if (rename.equals(node.getName())) { select = i; } } tree.removeTreeSelectionListener(t); addTreeListener(); tree.setSelectionRow(select); } } } else if (e.getActionCommand().equals("recalculate")) { TreePath select = tree.getSelectionPath(); String[] files; if (((IconNode) select.getLastPathComponent()).getParent() != null) { files = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()).list(); } else { files = new File(outDir).list(); } ArrayList<String> runs = new ArrayList<String>(); for (String file : files) { if (file.contains("run-") && file.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(file); } } if (((IconNode) select.getLastPathComponent()).getParent() != null) { calculateAverageVarianceDeviation(runs, 0, ((IconNode) select.getLastPathComponent()).getName(), warn, true); } else { calculateAverageVarianceDeviation(runs, 0, null, warn, true); } } else if (e.getActionCommand().equals("delete")) { TreePath[] selected = tree.getSelectionPaths(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) { tree.removeTreeSelectionListener(listen); } tree.addTreeSelectionListener(t); for (TreePath select : selected) { tree.setSelectionPath(select); if (((IconNode) select.getLastPathComponent()).getParent() != null) { for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } directories.remove(((IconNode) select.getLastPathComponent()).getName()); for (int j = 0; j < graphed.size(); j++) { if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) { graphed.remove(j); j } } } else { String name = ((IconNode) select.getLastPathComponent()).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; simDir.remove(i); } else if (name.equals("Termination Time")) { name = "term-time"; simDir.remove(i); } else if (name.equals("Constraint Termination")) { name = "sim-rep"; simDir.remove(i); } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; simDir.remove(i); } else { simDir.remove(i); } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } int count = 0; boolean m = false; if (new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { m = true; } boolean v = false; if (new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { v = true; } boolean d = false; if (new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { d = true; } for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(j)).getName().contains("run-")) { count++; } } } if (count == 0) { for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(j)).getName().contains("Average") && !m) { simDir.remove(j); j } else if (((IconNode) simDir.getChildAt(j)).getName().contains("Variance") && !v) { simDir.remove(j); j } else if (((IconNode) simDir.getChildAt(j)).getName().contains("Deviation") && !d) { simDir.remove(j); j } } } } } } else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) { if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) { String name = ((IconNode) select.getLastPathComponent()).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; ((IconNode) simDir.getChildAt(i)).remove(j); } else if (name.equals("Termination Time")) { name = "term-time"; ((IconNode) simDir.getChildAt(i)).remove(j); } else if (name.equals("Constraint Termination")) { name = "sim-rep"; ((IconNode) simDir.getChildAt(i)).remove(j); } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; ((IconNode) simDir.getChildAt(i)).remove(j); } else { ((IconNode) simDir.getChildAt(i)).remove(j); } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } boolean checked = false; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { ((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon()); ((IconNode) simDir.getChildAt(i)).setIconName(""); } int count = 0; boolean m = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { m = true; } boolean v = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { v = true; } boolean d = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { d = true; } for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("run-")) { count++; } } } if (count == 0) { for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Average") && !m) { ((IconNode) simDir.getChildAt(i)).remove(k); k } else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Variance") && !v) { ((IconNode) simDir.getChildAt(i)).remove(k); k } else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Deviation") && !d) { ((IconNode) simDir.getChildAt(i)).remove(k); k } } } } } } } } } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete runs")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { String name = ((IconNode) simDir.getChildAt(i)).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; } else if (name.equals("Termination Time")) { name = "term-time"; } else if (name.equals("Constraint Termination")) { name = "sim-rep"; } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete all")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { String name = ((IconNode) simDir.getChildAt(i)).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; } else if (name.equals("Termination Time")) { name = "term-time"; } else if (name.equals("Constraint Termination")) { name = "sim-rep"; } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } else { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } // // if the export as jpeg button is clicked // else if (e.getSource() == exportJPeg) { // export(0); // // if the export as png button is clicked // else if (e.getSource() == exportPng) { // export(1); // // if the export as pdf button is clicked // else if (e.getSource() == exportPdf) { // export(2); // // if the export as eps button is clicked // else if (e.getSource() == exportEps) { // export(3); // // if the export as svg button is clicked // else if (e.getSource() == exportSvg) { // export(4); // } else if (e.getSource() == exportCsv) { // export(5); } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; Font rangeFont = chart.getXYPlot().getRangeAxis().getLabelFont(); Font rangeTickFont = chart.getXYPlot().getRangeAxis().getTickLabelFont(); Font domainFont = chart.getXYPlot().getDomainAxis().getLabelFont(); Font domainTickFont = chart.getXYPlot().getDomainAxis().getTickLabelFont(); if (LogY.isSelected()) { try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } else { NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); } if (LogX.isSelected()) { try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setDomainAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setDomainAxis(domainAxis); LogX.setSelected(false); } } else { NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setDomainAxis(domainAxis); } chart.getXYPlot().getDomainAxis().setLabelFont(domainFont); chart.getXYPlot().getDomainAxis().setTickLabelFont(domainTickFont); chart.getXYPlot().getRangeAxis().setLabelFont(rangeFont); chart.getXYPlot().getRangeAxis().setTickLabelFont(rangeTickFont); for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); double[][] seriesArray = series.toArray(); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(seriesArray[1][k], maxY); minY = Math.min(seriesArray[1][k], minY); maxX = Math.max(seriesArray[0][k], maxX); minX = Math.min(seriesArray[0][k], minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxY - minY) < .001) { // axis.setRange(minY - 1, maxY + 1); else { /* * axis.setRange(Double.parseDouble(num.format(minY - * (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY + * (Math.abs(maxY) .1)))); */ if ((maxY - minY) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1)); } axis.setAutoTickUnitSelection(true); axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxX - minX) < .001) { // axis.setRange(minX - 1, maxX + 1); else { if ((maxX - minX) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minX, maxX); } axis.setAutoTickUnitSelection(true); if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getXYPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { if (e.getSource() != tree) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (timeSeries) { editGraph(); } else { editProbGraph(); } } } } public void mousePressed(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0) { JMenuItem recalculate = new JMenuItem("Recalculate Statistics"); recalculate.addActionListener(this); recalculate.setActionCommand("recalculate"); popup.add(recalculate); } if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0) { JMenuItem recalculate = new JMenuItem("Recalculate Statistics"); recalculate.addActionListener(this); recalculate.setActionCommand("recalculate"); popup.add(recalculate); } if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); // colors.put("Red ", draw.getNextPaint()); // colors.put("Blue ", draw.getNextPaint()); // colors.put("Green ", draw.getNextPaint()); // colors.put("Yellow ", draw.getNextPaint()); // colors.put("Magenta ", draw.getNextPaint()); // colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); colors.put("Gray (Light)", new java.awt.Color(238, 238, 238)); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } public void editGraph() { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); LogX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { XYPlot plot = (XYPlot) chart.getXYPlot(); Font rangeFont = chart.getXYPlot().getRangeAxis().getLabelFont(); Font rangeTickFont = chart.getXYPlot().getRangeAxis().getTickLabelFont(); Font domainFont = chart.getXYPlot().getDomainAxis().getLabelFont(); Font domainTickFont = chart.getXYPlot().getDomainAxis().getTickLabelFont(); if (((JCheckBox) e.getSource()).isSelected()) { try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setRangeAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setDomainAxis(domainAxis); LogX.setSelected(false); } } else { NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setDomainAxis(domainAxis); } chart.getXYPlot().getDomainAxis().setLabelFont(domainFont); chart.getXYPlot().getDomainAxis().setTickLabelFont(domainTickFont); chart.getXYPlot().getRangeAxis().setLabelFont(rangeFont); chart.getXYPlot().getRangeAxis().setTickLabelFont(rangeTickFont); } }); LogY.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { XYPlot plot = (XYPlot) chart.getXYPlot(); Font rangeFont = chart.getXYPlot().getRangeAxis().getLabelFont(); Font rangeTickFont = chart.getXYPlot().getRangeAxis().getTickLabelFont(); Font domainFont = chart.getXYPlot().getDomainAxis().getLabelFont(); Font domainTickFont = chart.getXYPlot().getDomainAxis().getTickLabelFont(); if (((JCheckBox) e.getSource()).isSelected()) { try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } else { NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); } chart.getXYPlot().getDomainAxis().setLabelFont(domainFont); chart.getXYPlot().getDomainAxis().setTickLabelFont(domainTickFont); chart.getXYPlot().getRangeAxis().setLabelFont(rangeFont); chart.getXYPlot().getRangeAxis().setTickLabelFont(rangeTickFont); } }); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } Properties p = null; if (learnSpecs != null) { try { String[] split = outDir.split(separator); p = new Properties(); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); } catch (Exception e) { } } String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean addMean = false; boolean addVar = false; boolean addDev = false; boolean addTerm = false; boolean addPercent = false; boolean addConst = false; boolean addBif = false; directories = new ArrayList<String>(); for (String file : files) { if ((file.length() > 3 && (file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (file.length() > 4 && file.substring(file.length() - 5).equals(".dtsd"))) { if (file.contains("run-") || file.contains("mean")) { addMean = true; } else if (file.contains("run-") || file.contains("variance")) { addVar = true; } else if (file.contains("run-") || file.contains("standard_deviation")) { addDev = true; } else if (file.startsWith("term-time")) { addTerm = true; } else if (file.contains("percent-term-time")) { addPercent = true; } else if (file.contains("sim-rep")) { addConst = true; } else if (file.contains("bifurcation")) { addBif = true; } else { IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4)); boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; String[] files3 = new File(outDir + separator + file).list(); // for (int i = 1; i < files3.length; i++) { // String index = files3[i]; // int j = i; // while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) > // files3[j] = files3[j - 1]; // j = j - 1; // files3[j] = index; for (String getFile : files3) { if ((getFile.length() > 3 && (getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (getFile.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile).isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if ((getFile2.length() > 3 && (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (getFile2.length() > 4 && getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); boolean addMean2 = false; boolean addVar2 = false; boolean addDev2 = false; boolean addTerm2 = false; boolean addPercent2 = false; boolean addConst2 = false; boolean addBif2 = false; for (String f : files3) { if (f.contains(printer_id.substring(0, printer_id.length() - 8)) || f.contains(".dtsd")) { if (f.contains("run-") || f.contains("mean")) { addMean2 = true; } else if (f.contains("run-") || f.contains("variance")) { addVar2 = true; } else if (f.contains("run-") || f.contains("standard_deviation")) { addDev2 = true; } else if (f.startsWith("term-time")) { addTerm2 = true; } else if (f.contains("percent-term-time")) { addPercent2 = true; } else if (f.contains("sim-rep")) { addConst2 = true; } else if (f.contains("bifurcation")) { addBif2 = true; } else { IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4)); boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; String[] files2 = new File(outDir + separator + file + separator + f).list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; for (String getFile2 : files2) { if (getFile2.length() > 3 && (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)) || getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); boolean addMean3 = false; boolean addVar3 = false; boolean addDev3 = false; boolean addTerm3 = false; boolean addPercent3 = false; boolean addConst3 = false; boolean addBif3 = false; for (String f2 : files2) { if (f2.contains(printer_id.substring(0, printer_id.length() - 8)) || f2.contains(".dtsd")) { if (f2.contains("run-") || f2.contains("mean")) { addMean3 = true; } else if (f2.contains("run-") || f2.contains("variance")) { addVar3 = true; } else if (f2.contains("run-") || f2.contains("standard_deviation")) { addDev3 = true; } else if (f2.startsWith("term-time")) { addTerm3 = true; } else if (f2.contains("percent-term-time")) { addPercent3 = true; } else if (f2.contains("sim-rep")) { addConst3 = true; } else if (f2.contains("bifurcation")) { addBif3 = true; } else { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); boolean added = false; for (int j = 0; j < d2.getChildCount(); j++) { if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4)) && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (addMean3) { IconNode n = new IconNode("Average", "Average"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev3) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar3) { IconNode n = new IconNode("Variance", "Variance"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm3) { IconNode n = new IconNode("Termination Time", "Termination Time"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent3) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst3) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addBif3) { IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r2 = null; for (String s : files2) { if (s.contains("run-")) { r2 = s; } } if (r2 != null) { for (String s : files2) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + ".dtsd").exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d2.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d2.getChildCount(); j++) { if (d2.getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } } else { d2.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0) || new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (addMean2) { IconNode n = new IconNode("Average", "Average"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev2) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar2) { IconNode n = new IconNode("Variance", "Variance"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm2) { IconNode n = new IconNode("Termination Time", "Termination Time"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent2) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst2) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addBif2) { IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r = null; for (String s : files3) { if (s.contains("run-")) { r = s; } } if (r != null) { for (String s : files3) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d.getChildCount(); j++) { if (d.getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } } else { d.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (addMean) { IconNode n = new IconNode("Average", "Average"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar) { IconNode n = new IconNode("Variance", "Variance"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm) { IconNode n = new IconNode("Termination Time", "Termination Time"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addBif) { IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String runs = null; for (String s : new File(outDir).list()) { if (s.contains("run-")) { runs = s; } } if (runs != null) { for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + "run-" + (i + 1) + ".dtsd").exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (simDir.getChildCount() > 3) { boolean added = false; for (int j = 3; j < simDir.getChildCount(); j++) { if (simDir .getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } } else { simDir.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { all = new JPanel(new BorderLayout()); specPanel = new JPanel(); scrollpane = new JScrollPane(); refreshTree(); addTreeListener(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); scroll.getVerticalScrollBar().setUnitIncrement(10); // JButton ok = new JButton("Ok"); /* * ok.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { double minY; double maxY; double * scaleY; double minX; double maxX; double scaleX; change = true; * try { minY = Double.parseDouble(YMin.getText().trim()); maxY = * Double.parseDouble(YMax.getText().trim()); scaleY = * Double.parseDouble(YScale.getText().trim()); minX = * Double.parseDouble(XMin.getText().trim()); maxX = * Double.parseDouble(XMax.getText().trim()); scaleX = * Double.parseDouble(XScale.getText().trim()); NumberFormat num = * NumberFormat.getInstance(); num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { * JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles * into the inputs " + "to change the graph's dimensions!", "Error", * JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; * selected = ""; ArrayList<XYSeries> graphData = new * ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = * (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int * thisOne = -1; for (int i = 1; i < graphed.size(); i++) { * GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && * (graphed.get(j - * 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { * graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, * index); } ArrayList<GraphSpecies> unableToGraph = new * ArrayList<GraphSpecies>(); HashMap<String, * ArrayList<ArrayList<Double>>> allData = new HashMap<String, * ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { * if (g.getDirectory().equals("")) { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8)).exists()) { * readGraphSpecies(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getRunNumber() + * "." + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir).list()) { if * (s.length() > 3 && s.substring(0, 4).equals("run-")) { * ableToGraph = true; } } } catch (Exception e1) { ableToGraph = * false; } if (ableToGraph) { int next = 1; while (!new File(outDir * + separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + "run-" + next + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + "run-1." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame, * y.getText().trim(), g.getRunNumber().toLowerCase(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } else { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getDirectory() + separator + * g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { readGraphSpecies( outDir + * separator + g.getDirectory() + separator + g.getRunNumber() + "." * + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber(), g.getDirectory()); for (int i = 2; i < * graphSpecies.size(); i++) { String index = graphSpecies.get(i); * ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) * && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { * graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, * data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); * data.set(j, index2); } allData.put(g.getRunNumber() + " " + * g.getDirectory(), data); } graphData.add(new * XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = * 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir + separator + * g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, * 4).equals("run-")) { ableToGraph = true; } } } catch (Exception * e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; * while (!new File(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + "run-1." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = * 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : * unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset * = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); * i++) { dataset.addSeries(graphData.get(i)); } * fixGraph(title.getText().trim(), x.getText().trim(), * y.getText().trim(), dataset); * chart.getXYPlot().setRenderer(rend); XYPlot plot = * chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } * else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); * axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); * axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) * plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); * axis.setRange(minX, maxX); axis.setTickUnit(new * NumberTickUnit(scaleX)); } //f.dispose(); } }); */ // final JButton cancel = new JButton("Cancel"); // cancel.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // selected = ""; // int size = graphed.size(); // for (int i = 0; i < size; i++) { // graphed.remove(); // for (GraphSpecies g : old) { // graphed.add(g); // f.dispose(); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(3, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xMin); titlePanel1.add(XMin); titlePanel1.add(yMin); titlePanel1.add(YMin); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(xMax); titlePanel1.add(XMax); titlePanel1.add(yMax); titlePanel1.add(YMax); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel1.add(xScale); titlePanel1.add(XScale); titlePanel1.add(yScale); titlePanel1.add(YScale); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(resize); titlePanel2.add(XVariable); titlePanel2.add(LogX); titlePanel2.add(LogY); titlePanel2.add(visibleLegend); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); // JPanel buttonPanel = new JPanel(); // buttonPanel.add(ok); // buttonPanel.add(deselect); // buttonPanel.add(cancel); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); // all.add(buttonPanel, "South"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; setChange(true); try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination") && !g.getRunNumber().equals("Bifurcation Statistics")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() == false && new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) { extension = "dtsd"; } data = readData(outDir + separator + g.getRunNumber() + "." + extension, g.getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber() .toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination") && !g.getRunNumber().equals("Bifurcation Statistics")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) { ArrayList<ArrayList<Double>> data; //if the data has already been put into the data structure if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() == false && new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) { extension = "dtsd"; } data = readData( outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + extension, g.getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } //if it's one of the stats/termination files else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end average else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end variance else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end standard deviation else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end termination time else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end percent termination else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end constraint termination else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } chart.getXYPlot().setRenderer(rend); } //end of "Ok" option being true else { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } } // WindowListener w = new WindowListener() { // public void windowClosing(WindowEvent arg0) { // cancel.doClick(); // public void windowOpened(WindowEvent arg0) { // public void windowClosed(WindowEvent arg0) { // public void windowIconified(WindowEvent arg0) { // public void windowDeiconified(WindowEvent arg0) { // public void windowActivated(WindowEvent arg0) { // public void windowDeactivated(WindowEvent arg0) { // f.addWindowListener(w); // f.setContentPane(all); // f.pack(); // Dimension screenSize; // try { // Toolkit tk = Toolkit.getDefaultToolkit(); // screenSize = tk.getScreenSize(); // catch (AWTError awe) { // screenSize = new Dimension(640, 480); // Dimension frameSize = f.getSize(); // if (frameSize.height > screenSize.height) { // frameSize.height = screenSize.height; // if (frameSize.width > screenSize.width) { // frameSize.width = screenSize.width; // int xx = screenSize.width / 2 - frameSize.width / 2; // int yy = screenSize.height / 2 - frameSize.height / 2; // f.setLocation(xx, yy); // f.setVisible(true); } } private void refreshTree() { tree = new JTree(simDir); if (!topLevel && learnSpecs == null) { tree.addMouseListener(this); } tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); } private void addTreeListener() { boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName()) && node.getParent() != null && !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) { selected = node.getName(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else if (selected.equals("Termination Time")) { select = 0; } else if (selected.equals("Percent Termination")) { select = 0; } else if (selected.equals("Constraint Termination")) { select = 0; } else if (selected.equals("Bifurcation Statistics")) { select = 0; } else { try { if (selected.contains("run-")) { select = Integer.parseInt(selected.substring(4)) + 2; } else { select = -1; } } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixGraphChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = graphSpecies.get(i + 1); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } else { String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); //tree.setSelectionRow(1); } else { tree.setSelectionRow(0); //tree.setSelectionRow(selectionRow); } } private JPanel fixGraphChoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination") || selected.equals("Bifurcation Statistics")) { if (selected.equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + selected + "." + extension).exists() == false) extension = "dtsd"; readGraphSpecies(outDir + separator + selected + "." + extension); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination") || selected.equals("Bifurcation Statistics")) { if (selected.equals("Average") && new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Bifurcation Statistics") && new File(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs; specs = new JLabel("Variables"); JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connect"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Fill"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)")); } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } /* * else if * (graph.getShapeAndPaint().getPaintName().equals * ("Red ")) { cols[15]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Blue ")) { cols[16]++; * } else if * (graph.getShapeAndPaint().getPaintName() * .equals("Green ")) { cols[17]++; } else if * (graph. * getShapeAndPaint().getPaintName().equals("Yellow " * )) { cols[18]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getShapeAndPaint().getPaintName * ().equals("Cyan ")) { cols[20]++; } */ else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) { cols[34]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible .get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(), series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB()); } } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { curData = dataset; // chart = ChartFactory.createXYLineChart(title, x, y, dataset, // PlotOrientation.VERTICAL, // true, true, false); chart.getXYPlot().setDataset(dataset); chart.setTitle(title); chart.getXYPlot().getDomainAxis().setLabel(x); chart.getXYPlot().getRangeAxis().setLabel(y); // chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); // chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); // chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export() { try { int output = 2; /* Default is currently pdf */ int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) { output = 0; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) { output = 1; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) { output = 2; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) { output = 3; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) { output = 4; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) { output = 5; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) { output = 6; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) { output = 7; } if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void export(int output) { // jpg = 0 // png = 1 // pdf = 2 // eps = 3 // svg = 4 // csv = 5 (data) // dat = 6 (data) // tsd = 7 (data) try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void exportDataFile(File file, int output) { try { int count = curData.getSeries(0).getItemCount(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (curData.getSeries(i).getItemCount() != count) { JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } for (int j = 0; j < count; j++) { Number Xval = curData.getSeries(0).getDataItem(j).getX(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) { JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } } FileOutputStream csvFile = new FileOutputStream(file); PrintWriter csvWriter = new PrintWriter(csvFile); if (output == 7) { csvWriter.print("(("); } else if (output == 6) { csvWriter.print(" } csvWriter.print("\"Time\""); count = curData.getSeries(0).getItemCount(); int pos = 0; for (int i = 0; i < curData.getSeriesCount(); i++) { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print("\"" + curData.getSeriesKey(i) + "\""); if (curData.getSeries(i).getItemCount() > count) { count = curData.getSeries(i).getItemCount(); pos = i; } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } for (int j = 0; j < count; j++) { if (output == 7) { csvWriter.print(","); } for (int i = 0; i < curData.getSeriesCount(); i++) { if (i == 0) { if (output == 7) { csvWriter.print("("); } csvWriter.print(curData.getSeries(pos).getDataItem(j).getX()); } XYSeries data = curData.getSeries(i); if (j < data.getItemCount()) { XYDataItem item = data.getDataItem(j); if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print(item.getY()); } else { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } } if (output == 7) { csvWriter.println(")"); } csvWriter.close(); csvFile.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning, boolean output) { if (files.size() > 0) { ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); lock.lock(); try { warn = warning; // TSDParser p = new TSDParser(startFile, biomodelsim, false); ArrayList<ArrayList<Double>> data; if (directory == null) { data = readData(outDir + separator + files.get(0), "", directory, warn); } else { data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn); } averageOrder = graphSpecies; boolean first = true; for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>(); // int count = 0; for (String run : files) { if (directory == null) { if (new File(outDir + separator + run).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } } } else { if (new File(outDir + separator + directory + separator + run).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } } } // ArrayList<ArrayList<Double>> data = p.getData(); for (int k = 0; k < data.get(0).size(); k++) { if (first) { double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); dataCounts.put(put, 1); } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } for (int i = 0; i < data.size(); i++) { if (i == 0) { variance.get(i).add((data.get(i)).get(k)); average.get(i).add(put); } else { variance.get(i).add(0.0); average.get(i).add((data.get(i)).get(k)); } } } else { int index = -1; double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); } else { put = (data.get(0)).get(k); } } else if (k == data.get(0).size() - 1 && k == 1) { if (average.get(0).size() > 1) { put = (average.get(0)).get(k); } else { put = (data.get(0)).get(k); } } else { put = (data.get(0)).get(k); } if (average.get(0).contains(put)) { index = average.get(0).indexOf(put); int count = dataCounts.get(put); dataCounts.put(put, count + 1); for (int i = 1; i < data.size(); i++) { double old = (average.get(i)).get(index); (average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1))); double newMean = (average.get(i)).get(index); double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean) * ((data.get(i)).get(k) - old)) / count; (variance.get(i)).set(index, vary); } } else { dataCounts.put(put, 1); for (int a = 0; a < average.get(0).size(); a++) { if (average.get(0).get(a) > put) { index = a; break; } } if (index == -1) { index = average.get(0).size() - 1; } average.get(0).add(put); variance.get(0).add(put); for (int a = 1; a < average.size(); a++) { average.get(a).add(data.get(a).get(k)); variance.get(a).add(0.0); } if (index != average.get(0).size() - 1) { for (int a = average.get(0).size() - 2; a >= 0; a if (average.get(0).get(a) > average.get(0).get(a + 1)) { for (int b = 0; b < average.size(); b++) { double temp = average.get(b).get(a); average.get(b).set(a, average.get(b).get(a + 1)); average.get(b).set(a + 1, temp); temp = variance.get(b).get(a); variance.get(b).set(a, variance.get(b).get(a + 1)); variance.get(b).set(a + 1, temp); } } else { break; } } } } } } first = false; } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } averageOrder = null; } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error", JOptionPane.ERROR_MESSAGE); } lock.unlock(); if (output) { DataParser m = new DataParser(graphSpecies, average); DataParser d = new DataParser(graphSpecies, deviation); DataParser v = new DataParser(graphSpecies, variance); if (directory == null) { m.outputTSD(outDir + separator + "mean.tsd"); v.outputTSD(outDir + separator + "variance.tsd"); d.outputTSD(outDir + separator + "standard_deviation.tsd"); } else { m.outputTSD(outDir + separator + directory + separator + "mean.tsd"); v.outputTSD(outDir + separator + directory + separator + "variance.tsd"); d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd"); } } if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } return null; } public void run() { reb2sac.getRunButton().doClick(); } public void save() { if (timeSeries) { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); setChange(false); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Probability Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); setChange(false); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public void saveAs() { if (timeSeries) { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File( outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName()); if (topLevel) { graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } else { if (graphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + graphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n"); setChange(false); biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } else { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File( outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); if (topLevel) { graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } else { if (probGraphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + probGraphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Probability Graph Data"); store.close(); log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n"); setChange(false); biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void open(String filename) { if (timeSeries) { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint")))); } if (graph.containsKey("plot.domain.grid.line.paint")) { chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint")))); } chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) { LogX.setSelected(true); } else { LogX.setSelected(false); } if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) { LogY.setSelected(true); } else { LogY.setSelected(false); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } int xnumber = 0; if (graph.containsKey("species.xnumber." + next)) { xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next)); } graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next) .trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id." + next), graph.getProperty("species.name." + next), xnumber, Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } updateXNumber = false; XVariable.addItem("time"); refresh(); } catch (IOException except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint")))); } chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter()); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter()); } if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { String color = graph.getProperty("species.paint." + next).trim(); Paint paint; if (color.startsWith("Custom_")) { paint = new Color(Integer.parseInt(color.replace("Custom_", ""))); } else { paint = colors.get(color); } probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next), Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } refreshProb(); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public boolean isTSDGraph() { return timeSeries; } public void refresh() { lock2.lock(); if (timeSeries) { if (learnSpecs != null) { updateSpecies(); } double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); num.setGroupingUsed(false); * minY = Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + "run-" + // nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber() .toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData( outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + // g.getDirectory() + separator // + "run-" + nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } data = readData( outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } chart.getXYPlot().setRenderer(rend); } else { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { if (graphProbs.contains(g.getID())) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { String compare = g.getID().replace(" (", "~"); if (graphProbs.contains(compare.split("~")[0].trim())) { for (int i = 0; i < graphProbs.size(); i++) { if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis() .getLabel(), histDataset, rend); } lock2.unlock(); } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, String p) { shape = s; if (p.startsWith("Custom_")) { paint = new Color(Integer.parseInt(p.replace("Custom_", ""))); } else { paint = colors.get(p); } } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Custom_" + ((Color) paint).getRGB(); } public void setPaint(String paint) { if (paint.startsWith("Custom_")) { this.paint = new Color(Integer.parseInt(paint.replace("Custom_", ""))); } else { this.paint = colors.get(paint); } } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory, id; private int xnumber, number; private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species, int xnumber, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.xnumber = xnumber; this.number = number; this.directory = directory; this.id = id; } private void setDirectory(String directory) { this.directory = directory; } private void setXNumber(int xnumber) { this.xnumber = xnumber; } private void setNumber(int number) { this.number = number; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getXNumber() { return xnumber; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } private String getID() { return id; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } public void setChange(boolean change) { this.change = change; biomodelsim.markTabDirty(change); } public boolean hasChanged() { return change; } private void probGraph(String label) { chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false); applyChartTheme(chart); ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter()); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); legend = chart.getLegend(); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); setChange(false); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); } private void editProbGraph() { final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { old.add(g); } final JPanel titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JCheckBox gradient = new JCheckBox("Paint In Gradient Style"); gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter)); final JCheckBox shadow = new JCheckBox("Paint Bar Shadows"); shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5); String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) { if (file.contains("sim-rep")) { add = true; } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile).isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); String[] files2 = new File(outDir + separator + file).list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; boolean add2 = false; for (String f : files2) { if (f.equals("sim-rep.txt")) { add2 = true; } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; for (String getFile : new File(outDir + separator + file + separator + f).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); for (String f2 : new File(outDir + separator + file + separator + f).list()) { if (f2.equals("sim-rep.txt")) { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0) || new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt")) .isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (add2) { IconNode n = new IconNode("sim-rep", "sim-rep"); d.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (add) { IconNode n = new IconNode("sim-rep", "sim-rep"); simDir.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { tree = new JTree(simDir); tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); final JPanel all = new JPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } public void treeExpanded(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } }); // for (int i = 0; i < tree.getRowCount(); i++) { // tree.expandRow(i); JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); final JPanel specPanel = new JPanel(); boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName())) { selected = node.getName(); int select; if (selected.equals("sim-rep")) { select = 0; } else { select = -1; } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixProbChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphProbs.get(i)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory() .equals(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } else { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } boolean allChecked = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = series.get(i).getText(); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); } else { String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = graphProbs.get(i); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(1, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(yLabel); titlePanel1.add(y); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(gradient); titlePanel2.add(shadow); titlePanel2.add(visibleLegend); titlePanel2.add(new JPanel()); titlePanel2.add(new JPanel()); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { setChange(true); lastSelected = selected; selected = ""; BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); if (gradient.isSelected()) { rend.setBarPainter(new GradientBarPainter()); } else { rend.setBarPainter(new StandardBarPainter()); } if (shadow.isSelected()) { rend.setShadowVisible(true); } else { rend.setShadowVisible(false); } int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend); } else { selected = ""; int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } for (GraphProbs g : old) { probGraphed.add(g); } } } } private JPanel fixProbChoices(final String directory) { if (directory.equals("")) { readProbSpecies(outDir + separator + "sim-rep.txt"); } else { readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt"); } for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); j = j - 1; } graphProbs.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Constraint"); JLabel color = new JLabel("Color"); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphProbs.size(); i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)")); } } } for (GraphProbs graph : probGraphed) { if (graph.getPaintName().equals("Red")) { cols[0]++; } else if (graph.getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getPaintName().equals("Green")) { cols[2]++; } else if (graph.getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getPaintName().equals("Black")) { cols[14]++; } /* * else if (graph.getPaintName().equals("Red ")) { * cols[15]++; } else if * (graph.getPaintName().equals("Blue ")) { * cols[16]++; } else if * (graph.getPaintName().equals("Green ")) { * cols[17]++; } else if * (graph.getPaintName().equals("Yellow ")) { * cols[18]++; } else if * (graph.getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getPaintName().equals("Cyan ")) { * cols[20]++; } */ else if (graph.getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getPaintName().equals("Gray (Light)")) { cols[34]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText() .trim(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphProbs g : remove) { probGraphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); } } }); boxes.add(temp); JTextField seriesName = new JTextField(graphProbs.get(i)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem()); g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem())); } } } else { for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB()); g.setPaint(colorsButtons.get(i).getBackground()); } } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); return speciesPanel; } private void readProbSpecies(String file) { graphProbs = new ArrayList<String>(); ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } for (String s : data) { if (!s.split(" ")[0].equals("#total")) { graphProbs.add(s.split(" ")[0]); } } } private double[] readProbs(String file) { ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return new double[0]; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } double[] dataSet = new double[data.size()]; double total = 0; int i = 0; if (data.get(0).split(" ")[0].equals("#total")) { total = Double.parseDouble(data.get(0).split(" ")[1]); i = 1; } for (; i < data.size(); i++) { if (total == 0) { dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]); } else { dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total); } } return dataSet; } private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) { Paint chartBackground = chart.getBackgroundPaint(); Paint plotBackground = chart.getPlot().getBackgroundPaint(); Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint(); chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false); applyChartTheme(chart); chart.getCategoryPlot().setRenderer(rend); chart.setBackgroundPaint(chartBackground); chart.getPlot().setBackgroundPaint(plotBackground); chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine); ChartPanel graph = new ChartPanel(chart); legend = chart.getLegend(); if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } if (probGraphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } public void refreshProb() { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis() .getLabel(), histDataset, rend); } private void updateSpecies() { String background; try { Properties p = new Properties(); String[] split = outDir.split(separator); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else { background = null; } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); background = null; } learnSpecs = new ArrayList<String>(); if (background != null) { if (background.contains(".gcm")) { BioModel gcm = new BioModel(biomodelsim.getRoot()); gcm.load(background); learnSpecs = gcm.getSpecies(); } else if (background.contains(".lpn")) { LhpnFile lhpn = new LhpnFile(biomodelsim.log); lhpn.load(background); /* HashMap<String, Properties> speciesMap = lhpn.getContinuous(); * for (String s : speciesMap.keySet()) { learnSpecs.add(s); } */ // ADDED BY SB. TSDParser extractVars; ArrayList<String> datFileVars = new ArrayList<String>(); // ArrayList<String> allVars = new ArrayList<String>(); Boolean varPresent = false; // Finding the intersection of all the variables present in all // data files. for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) { extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false); datFileVars = extractVars.getSpecies(); if (i == 1) { learnSpecs.addAll(datFileVars); } for (String s : learnSpecs) { varPresent = false; for (String t : datFileVars) { if (s.equalsIgnoreCase(t)) { varPresent = true; break; } } if (!varPresent) { learnSpecs.remove(s); } } } // END ADDED BY SB. } else { SBMLDocument document = Gui.readSBML(background); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { learnSpecs.add(((Species) ids.get(i)).getId()); } } } for (int i = 0; i < learnSpecs.size(); i++) { String index = learnSpecs.get(i); int j = i; while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) { learnSpecs.set(j, learnSpecs.get(j - 1)); j = j - 1; } learnSpecs.set(j, index); } } public boolean getWarning() { return warn; } private class GraphProbs { private Paint paint; private String species, directory, id, paintName; private int number; private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) { this.paint = paint; this.paintName = paintName; this.species = species; this.number = number; this.directory = directory; this.id = id; } private Paint getPaint() { return paint; } private void setPaint(Paint p) { paint = p; } private String getPaintName() { return paintName; } private void setPaintName(String p) { paintName = p; } private String getSpecies() { return species; } private void setSpecies(String s) { species = s; } private String getDirectory() { return directory; } private String getID() { return id; } private int getNumber() { return number; } private void setNumber(int n) { number = n; } } private Hashtable makeIcons() { Hashtable<String, Icon> icons = new Hashtable<String, Icon>(); icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon()); icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon()); icons.put("computer", MetalIconFactory.getTreeComputerIcon()); icons.put("c", TextIcons.getIcon("c")); icons.put("java", TextIcons.getIcon("java")); icons.put("html", TextIcons.getIcon("html")); return icons; } public static void applyChartTheme(JFreeChart chart) { final StandardChartTheme chartTheme = (StandardChartTheme) org.jfree.chart.StandardChartTheme .createJFreeTheme(); final Font oldExtraLargeFont = chartTheme.getExtraLargeFont(); final Font oldLargeFont = chartTheme.getLargeFont(); final Font oldRegularFont = chartTheme.getRegularFont(); final Font oldSmallFont = chartTheme.getSmallFont(); final Font extraLargeFont = new Font("Sans-serif", oldExtraLargeFont.getStyle(), oldExtraLargeFont.getSize()); final Font largeFont = new Font("Sans-serif", oldLargeFont.getStyle(), oldLargeFont.getSize()); final Font regularFont = new Font("Sans-serif", oldRegularFont.getStyle(), oldRegularFont.getSize()); final Font smallFont = new Font("Sans-serif", oldSmallFont.getStyle(), oldSmallFont.getSize()); chartTheme.setExtraLargeFont(extraLargeFont); chartTheme.setLargeFont(largeFont); chartTheme.setRegularFont(regularFont); chartTheme.setSmallFont(smallFont); chartTheme.apply(chart); } } class IconNodeRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -940588131120912851L; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); Icon icon = ((IconNode) value).getIcon(); if (icon == null) { Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons"); String name = ((IconNode) value).getIconName(); if ((icons != null) && (name != null)) { icon = (Icon) icons.get(name); if (icon != null) { setIcon(icon); } } } else { setIcon(icon); } return this; } } class IconNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 2887169888272379817L; protected Icon icon; protected String iconName; private String hiddenName; public IconNode() { this(null, ""); } public IconNode(Object userObject, String name) { this(userObject, true, null, name); } public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) { super(userObject, allowsChildren); this.icon = icon; hiddenName = name; } public String getName() { return hiddenName; } public void setName(String name) { hiddenName = name; } public void setIcon(Icon icon) { this.icon = icon; } public Icon getIcon() { return icon; } public String getIconName() { if (iconName != null) { return iconName; } else { String str = userObject.toString(); int index = str.lastIndexOf("."); if (index != -1) { return str.substring(++index); } else { return null; } } } public void setIconName(String name) { iconName = name; } } class TextIcons extends MetalIconFactory.TreeLeafIcon { private static final long serialVersionUID = 1623303213056273064L; protected String label; private static Hashtable<String, String> labels; protected TextIcons() { } public void paintIcon(Component c, Graphics g, int x, int y) { super.paintIcon(c, g, x, y); if (label != null) { FontMetrics fm = g.getFontMetrics(); int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2; int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2; g.drawString(label, x + offsetX, y + offsetY + fm.getHeight()); } } public static Icon getIcon(String str) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } TextIcons icon = new TextIcons(); icon.label = (String) labels.get(str); return icon; } public static void setLabelSet(String ext, String label) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } labels.put(ext, label); } private static void setDefaultSet() { labels.put("c", "C"); labels.put("java", "J"); labels.put("html", "H"); labels.put("htm", "H"); labels.put("g", "" + (char) 10003); // and so on /* * labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc" * ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++"); * labels.put("exe" ,"BIN"); labels.put("class" ,"BIN"); * labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF"); * * labels.put("", ""); */ } }
package reb2sac; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; import parser.*; import lpn.gui.LHPNEditor; import lpn.parser.Abstraction; import lpn.parser.LhpnFile; import lpn.parser.Translator; import main.*; import gillespieSSAjava.GillespieSSAJavaSingleStep; import gcm.gui.GCM2SBMLEditor; import gcm.parser.GCMFile; import gcm.util.GlobalConstants; import graph.*; import sbmleditor.*; import stategraph.BuildStateGraphThread; import stategraph.PerfromSteadyStateMarkovAnalysisThread; import stategraph.PerfromTransientMarkovAnalysisThread; import stategraph.StateGraph; import util.*; import verification.AbstPane; /** * This class creates the properties file that is given to the reb2sac program. * It also executes the reb2sac program. * * @author Curtis Madsen */ public class Run implements ActionListener { private Process reb2sac; private String separator; private Reb2Sac r2s; StateGraph sg; public Run(Reb2Sac reb2sac) { r2s = reb2sac; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } } /** * This method is given which buttons are selected and creates the * properties file from all the other information given. * * @param useInterval * * @param stem */ public void createProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, double absError, String outDir, long rndSeed, int run, String[] termCond, String[] intSpecies, String printer_id, String printer_track_quantity, String[] getFilename, String selectedButtons, Component component, String filename, double rap1, double rap2, double qss, int con, JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs, JList loopAbs, JList postAbs, AbstPane abstPane) { Properties abs = new Properties(); if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) { int gcmIndex = 1; for (int i = 0; i < preAbs.getModel().getSize(); i++) { String abstractionOption = (String) preAbs.getModel().getElementAt(i); if (abstractionOption.equals("complex-formation-and-sequestering-abstraction") || abstractionOption.equals("operator-site-reduction-abstraction")) { // abstractionOption.equals("species-sequestering-abstraction")) abs.setProperty("gcm.abstraction.method." + gcmIndex, abstractionOption); gcmIndex++; } else abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), abstractionOption); } for (int i = 0; i < loopAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs.getModel().getElementAt(i)); } // abs.setProperty("reb2sac.abstraction.method.0.1", // "enzyme-kinetic-qssa-1"); // abs.setProperty("reb2sac.abstraction.method.0.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.0.3", // "multiple-products-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.4", // "multiple-reactants-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.5", // "single-reactant-product-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.6", // "dimer-to-monomer-substitutor"); // abs.setProperty("reb2sac.abstraction.method.0.7", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.1", // "modifier-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.2", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.1", // "operator-site-forward-binding-remover"); // abs.setProperty("reb2sac.abstraction.method.2.3", // "enzyme-kinetic-rapid-equilibrium-1"); // abs.setProperty("reb2sac.abstraction.method.2.4", // "irrelevant-species-remover"); // abs.setProperty("reb2sac.abstraction.method.2.5", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.2.6", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.7", // "similar-reaction-combiner"); // abs.setProperty("reb2sac.abstraction.method.2.8", // "modifier-constant-propagation"); } // if (selectedButtons.contains("abs")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction"); // else if (selectedButtons.contains("nary")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction-level-assignment"); for (int i = 0; i < postAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel().getElementAt(i)); } abs.setProperty("simulation.printer", printer_id); abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); // if (selectedButtons.contains("monteCarlo")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "distribute-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.3", // "kinetic-law-constants-simplifier"); // else if (selectedButtons.contains("none")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "kinetic-law-constants-simplifier"); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]); if (split.length > 1) { String[] levels = split[1].split(","); for (int j = 0; j < levels.length; j++) { abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1), levels[j]); } } } } abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); abs.setProperty("reb2sac.qssa.condition.1", "" + qss); abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); if (selectedButtons.contains("none")) { abs.setProperty("reb2sac.abstraction.method", "none"); } if (selectedButtons.contains("abs")) { abs.setProperty("reb2sac.abstraction.method", "abs"); } else if (selectedButtons.contains("nary")) { abs.setProperty("reb2sac.abstraction.method", "nary"); } if (abstPane != null) { for (Integer i = 0; i < abstPane.preAbsModel.size(); i++) { abs.setProperty("abstraction.transform." + abstPane.preAbsModel.getElementAt(i).toString(), "preloop" + i.toString()); } for (Integer i = 0; i < abstPane.loopAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) { String value = abs.getProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString()); value = value + "mainloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop" + i.toString()); } } for (Integer i = 0; i < abstPane.postAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i)) || abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) { String value = abs.getProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString()); value = value + "postloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), "postloop" + i.toString()); } } for (String s : abstPane.transforms) { if (!abstPane.preAbsModel.contains(s) && !abstPane.loopAbsModel.contains(s) && !abstPane.postAbsModel.contains(s)) { abs.remove(s); } } } if (selectedButtons.contains("ODE")) { abs.setProperty("reb2sac.simulation.method", "ODE"); } else if (selectedButtons.contains("monteCarlo")) { abs.setProperty("reb2sac.simulation.method", "monteCarlo"); } else if (selectedButtons.contains("markov")) { abs.setProperty("reb2sac.simulation.method", "markov"); } else if (selectedButtons.contains("sbml")) { abs.setProperty("reb2sac.simulation.method", "SBML"); } else if (selectedButtons.contains("dot")) { abs.setProperty("reb2sac.simulation.method", "Network"); } else if (selectedButtons.contains("xhtml")) { abs.setProperty("reb2sac.simulation.method", "Browser"); } else if (selectedButtons.contains("lhpn")) { abs.setProperty("reb2sac.simulation.method", "LPN"); } if (!selectedButtons.contains("monteCarlo")) { // if (selectedButtons.equals("none_ODE") || // selectedButtons.equals("abs_ODE")) { abs.setProperty("ode.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("ode.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("ode.simulation.time.step", "inf"); } else { abs.setProperty("ode.simulation.time.step", "" + timeStep); } abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep); abs.setProperty("ode.simulation.absolute.error", "" + absError); abs.setProperty("ode.simulation.out.dir", outDir); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); } if (!selectedButtons.contains("ODE")) { // if (selectedButtons.equals("none_monteCarlo") || // selectedButtons.equals("abs_monteCarlo")) { abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs.setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("monte.carlo.simulation.time.step", "inf"); } else { abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); abs.setProperty("monte.carlo.simulation.out.dir", outDir); if (usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "sad"); abs.setProperty("computation.analysis.sad.path", sadFile.getName()); } } if (!usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "constraint"); } if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) { abs.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { abs.setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { if (!getFilename[getFilename.length - 1].contains(".")) { getFilename[getFilename.length - 1] += "."; filename += "."; } int cut = 0; for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename.length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties")); abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for abstraction.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * This method is given what data is entered into the nary frame and creates * the nary properties file from that information. */ public void createNaryProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, String outDir, long rndSeed, int run, String printer_id, String printer_track_quantity, String[] getFilename, Component component, String filename, JRadioButton monteCarlo, String stopE, double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel, ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond, String[] intSpecies, double rap1, double rap2, double qss, int con, ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) { Properties nary = new Properties(); try { FileInputStream load = new FileInputStream(new File(outDir + separator + "species.properties")); nary.load(load); load.close(); } catch (Exception e) { JOptionPane.showMessageDialog(component, "Species Properties File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE); } nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1"); nary.setProperty("reb2sac.abstraction.method.0.2", "reversible-to-irreversible-transformer"); nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.4", "multiple-reactants-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.5", "single-reactant-product-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor"); nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover"); nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1"); nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover"); nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner"); nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction"); nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer"); nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator"); nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator"); nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator"); nary.setProperty("reb2sac.nary.order.decider", "distinct"); nary.setProperty("simulation.printer", printer_id); nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); nary.setProperty("reb2sac.analysis.stop.enabled", stopE); nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR); for (int i = 0; i < getSpeciesProps.size(); i++) { if (!(inhib.get(i).getText().trim() != "<<none>>")) { nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i), inhib.get(i).getText().trim()); } String[] consLevels = Utility.getList(conLevel.get(i), consLevel.get(i)); for (int j = 0; j < counts.get(i); j++) { nary.remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1)); } for (int j = 0; j < consLevels.length; j++) { nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1), consLevels[j]); } } if (monteCarlo.isSelected()) { nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { nary.setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { nary.setProperty("monte.carlo.simulation.time.step", "inf"); } else { nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); nary.setProperty("monte.carlo.simulation.runs", "" + run); nary.setProperty("monte.carlo.simulation.out.dir", "."); } for (int i = 0; i < finalS.length; i++) { if (finalS[i].trim() != "<<unknown>>") { nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]); } } if (usingSSA.isSelected() && monteCarlo.isSelected()) { nary.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < intSpecies.length; i++) { if (intSpecies[i] != "") { nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]); } } nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); nary.setProperty("reb2sac.qssa.condition.1", "" + qss); nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { nary.setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { FileOutputStream store = new FileOutputStream(new File(filename.replace(".sbml", "").replace(".xml", "") + ".properties")); nary.store(store, getFilename[getFilename.length - 1].replace(".sbml", "").replace(".xml", "") + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for simulation.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * Executes the reb2sac program. If ODE, monte carlo, or markov is selected, * this method creates a Graph object. * * @param runTime * @param refresh */ public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml, JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo, String sim, String printer_id, String printer_track_quantity, String outDir, JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA, String ssaFile, Gui biomodelsim, JTabbedPane simTab, String root, JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct, double timeLimit, double runTime, String modelFile, AbstPane abstPane, JRadioButton abstraction, String lpnProperty, double absError, double timeStep, double printInterval, int runs, long rndSeed, boolean refresh) { Runtime exec = Runtime.getRuntime(); int exitValue = 255; while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) { outDir = outDir.substring(0, outDir.length() - 1 - outDir.split(separator)[outDir.split(separator).length - 1].length()); } try { long time1; String directory = ""; String theFile = ""; String sbmlName = ""; String lhpnName = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } if (nary.isSelected() && gcmEditor != null && (monteCarlo.isSelected() || xhtml.isSelected())) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (direct != null && !direct.equals("") && direct.contains("=")) { String[] d = direct.split("_"); ArrayList<String> dd = new ArrayList<String>(); for (int i = 0; i < d.length; i++) { if (!d[i].contains("=")) { String di = d[i]; while (!d[i].contains("=")) { i++; di += "_" + d[i]; } dd.add(di); } else { dd.add(d[i]); } } for (String di : dd) { if (di.contains("-")) { if (gcm.getPromoters().containsKey(di.split("=")[0].split("-")[0])) { Properties promoterProps = gcm.getPromoters().get(di.split("=")[0].split("-")[0]); promoterProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } if (gcm.getSpecies().containsKey(di.split("=")[0].split("-")[0])) { Properties speciesProps = gcm.getSpecies().get(di.split("=")[0].split("-")[0]); speciesProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } String influence = ""; for (String infl : gcm.getInfluences().keySet()) { boolean matchInfl = true; for (String part : di.split("=")[0].split("-")[0].split("_")) { if (!infl.contains(part)) { matchInfl = false; } } if (matchInfl) { influence = infl; } } if (!influence.equals("")) { Properties influenceProps = gcm.getInfluences().get(influence); influenceProps.put(di.split("=")[0].split("-")[1].replace("\"", ""), di.split("=")[1]); } } else { if (gcm.getGlobalParameters().containsKey(di.split("=")[0])) { gcm.getGlobalParameters().put(di.split("=")[0], di.split("=")[1]); } if (gcm.getParameters().containsKey(di.split("=")[0])) { gcm.getParameters().put(di.split("=")[0], di.split("=")[1]); } } } } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); if (lpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lpnFile.addProperty(lpnProperty); } lpnFile.save(root + separator + simName + separator + lpnName); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate(root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + simName + separator + lpnName.replace(".lpn", ".xml")); t1.outputSBML(); } else { return 0; } } if (nary.isSelected() && gcmEditor == null && !sim.contains("markov-chain-analysis") && !lhpn.isSelected() && naryRun == 1) { log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work); } else if (sbml.isSelected()) { sbmlName = JOptionPane.showInputDialog(component, "Enter Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (sbmlName != null && !sbmlName.trim().equals("")) { sbmlName = sbmlName.trim(); if (sbmlName.length() > 4) { if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml") || !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) { sbmlName += ".xml"; } } else { sbmlName += ".xml"; } File f = new File(root + separator + sbmlName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + sbmlName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { progress.setIndeterminate(true); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + modelFile); t1.BuildTemplate(root + separator + simName + separator + modelFile, lpnProperty); } else { t1.BuildTemplate(root + separator + modelFile, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); exitValue = 0; } else if (gcmEditor != null && nary.isSelected()) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); if (lpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lpnFile.addProperty(lpnProperty); } lpnFile.save(root + separator + simName + separator + lpnName); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate(root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); } else { time1 = System.nanoTime(); return 0; } exitValue = 0; } else { if (r2s.reb2sacAbstraction() && (abstraction.isSelected() || nary.isSelected())) { log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + theFile, null, work); } else { log.addText("Outputting SBML file:\n" + root + separator + sbmlName + "\n"); time1 = System.nanoTime(); FileOutputStream fileOutput = new FileOutputStream(new File(root + separator + sbmlName)); FileInputStream fileInput = new FileInputStream(new File(filename)); int read = fileInput.read(); while (read != -1) { fileOutput.write(read); read = fileInput.read(); } fileInput.close(); fileOutput.close(); exitValue = 0; } } } else { time1 = System.nanoTime(); } } else if (lhpn.isSelected()) { lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 4) { if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) { lhpnName += ".lpn"; } } else { lhpnName += ".lpn"; } File f = new File(root + separator + lhpnName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + lhpnName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); if (abstraction.isSelected()) { Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + lhpnName); } else { lhpnFile.save(root + separator + lhpnName); } time1 = System.nanoTime(); exitValue = 0; } else { ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel); if (lhpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lhpnFile.addProperty(lpnProperty); } lhpnFile.save(root + separator + lhpnName); log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName + "\n"); } else { return 0; } exitValue = 0; } } else { time1 = System.nanoTime(); exitValue = 0; } } else if (dot.isSelected()) { if (nary.isSelected() && gcmEditor != null) { LhpnFile lhpnFile = new LhpnFile(log); lhpnFile.load(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn"); lhpnFile.printDot(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".dot"); time1 = System.nanoTime(); exitValue = 0; } else if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); if (abstraction.isSelected()) { Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.printDot(root + separator + simName + separator + modelFile.replace(".lpn", ".dot")); } else { lhpnFile.printDot(root + separator + simName + separator + modelFile.replace(".lpn", ".dot")); } time1 = System.nanoTime(); exitValue = 0; } else { log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); } } else if (xhtml.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); } else if (usingSSA.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile, null, work); } else { if (sim.equals("atacs")) { log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work); } else if (sim.contains("markov-chain-analysis")) { time1 = System.nanoTime(); LhpnFile lhpnFile = null; if (modelFile.contains(".lpn")) { lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); } else { new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn").delete(); ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (direct != null && !direct.equals("") && direct.contains("=")) { String[] d = direct.split("_"); ArrayList<String> dd = new ArrayList<String>(); for (int i = 0; i < d.length; i++) { if (!d[i].contains("=")) { String di = d[i]; while (!d[i].contains("=")) { i++; di += "_" + d[i]; } dd.add(di); } else { dd.add(d[i]); } } for (String di : dd) { if (di.contains("-")) { if (gcm.getPromoters().containsKey(di.split("=")[0].split("-")[0])) { Properties promoterProps = gcm.getPromoters().get(di.split("=")[0].split("-")[0]); promoterProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } if (gcm.getSpecies().containsKey(di.split("=")[0].split("-")[0])) { Properties speciesProps = gcm.getSpecies().get(di.split("=")[0].split("-")[0]); speciesProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } String influence = ""; for (String infl : gcm.getInfluences().keySet()) { boolean matchInfl = true; for (String part : di.split("=")[0].split("-")[0].split("_")) { if (!infl.contains(part)) { matchInfl = false; } } if (matchInfl) { influence = infl; } } if (!influence.equals("")) { Properties influenceProps = gcm.getInfluences().get(influence); influenceProps.put(di.split("=")[0].split("-")[1].replace("\"", ""), di.split("=")[1]); } } else { if (gcm.getGlobalParameters().containsKey(di.split("=")[0])) { gcm.getGlobalParameters().put(di.split("=")[0], di.split("=")[1]); } if (gcm.getParameters().containsKey(di.split("=")[0])) { gcm.getParameters().put(di.split("=")[0], di.split("=")[1]); } } } } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); lhpnFile = gcm.convertToLHPN(specs, conLevel); if (lhpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lhpnFile.addProperty(lpnProperty); } lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn"); log.addText("Saving GCM file as LHPN:\n" + filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn" + "\n"); } else { return 0; } } if (lhpnFile != null) { sg = new StateGraph(lhpnFile); BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg); buildStateGraph.start(); buildStateGraph.join(); if (sim.equals("steady-state-markov-chain-analysis")) { if (!sg.getStop()) { log.addText("Performing steady state Markov chain analysis.\n"); PerfromSteadyStateMarkovAnalysisThread performMarkovAnalysis = new PerfromSteadyStateMarkovAnalysisThread(sg); if (modelFile.contains(".lpn")) { performMarkovAnalysis.start(absError, null); } else { ArrayList<String> conditions = new ArrayList<String>(); for (int i = 0; i < gcmEditor.getGCM().getConditions().size(); i++) { if (gcmEditor.getGCM().getConditions().get(i).startsWith("St")) { conditions.add(Translator.getProbpropExpression(gcmEditor.getGCM().getConditions().get(i))); } } performMarkovAnalysis.start(absError, conditions); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream(new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", true); biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } } else if (sim.equals("transient-markov-chain-analysis")) { if (!sg.getStop()) { log.addText("Performing transient Markov chain analysis with uniformization.\n"); PerfromTransientMarkovAnalysisThread performMarkovAnalysis = new PerfromTransientMarkovAnalysisThread(sg, progress); time1 = System.nanoTime(); if (lpnProperty != null && !lpnProperty.equals("")) { String[] condition = Translator.getProbpropParts(Translator.getProbpropExpression(lpnProperty)); boolean globallyTrue = false; if (lpnProperty.contains("PF")) { condition[0] = "true"; } else if (lpnProperty.contains("PG")) { condition[0] = "true"; globallyTrue = true; } performMarkovAnalysis.start(timeLimit, timeStep, printInterval, absError, condition, globallyTrue); } else { performMarkovAnalysis.start(timeLimit, timeStep, printInterval, absError, null, false); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream(new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", true); if (sg.outputTSD(directory + separator + "percent-term-time.tsd")) { if (refresh) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } } } } } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } } if (refresh) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } exitValue = 0; } else { Preferences biosimrc = Preferences.userRoot(); if (sim.equals("gillespieJava")) { time1 = System.nanoTime(); int index = -1; for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { simTab.setSelectedIndex(i); index = i; } } GillespieSSAJavaSingleStep javaSim = new GillespieSSAJavaSingleStep(); String SBMLFileName = directory + separator + theFile; javaSim.PerformSim(SBMLFileName, outDir, timeLimit, timeStep, rndSeed, ((Graph) simTab.getComponentAt(index))); exitValue = 0; return exitValue; } else if (biosimrc.get("biosim.sim.command", "").equals("")) { time1 = System.nanoTime(); log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename + "\n"); reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile, null, work); } else { String command = biosimrc.get("biosim.sim.command", ""); String fileStem = theFile.replaceAll(".xml", ""); fileStem = fileStem.replaceAll(".sbml", ""); command = command.replaceAll("filename", fileStem); command = command.replaceAll("sim", sim); log.addText(command + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec(command, null, work); } } } String error = ""; try { InputStream reb = reb2sac.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); // int count = 0; String line; double time = 0; double oldTime = 0; int runNum = 0; int prog = 0; while ((line = br.readLine()) != null) { try { if (line.contains("Time")) { time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line.length())); if (oldTime > time) { runNum++; } oldTime = time; time += (runNum * timeLimit); double d = ((time * 100) / runTime); String s = d + ""; double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s.length())); if (decimal >= 0.5) { prog = (int) (Math.ceil(d)); } else { prog = (int) (d); } } // else { // log.addText(line); } catch (Exception e) { } progress.setValue(prog); // if (steps > 0) { // count++; // progress.setValue(count); // log.addText(output); } InputStream reb2 = reb2sac.getErrorStream(); int read = reb2.read(); while (read != -1) { error += (char) read; read = reb2.read(); } br.close(); isr.close(); reb.close(); reb2.close(); } catch (Exception e) { } if (reb2sac != null) { exitValue = reb2sac.waitFor(); } long time2 = System.nanoTime(); long minutes; long hours; long days; double secs = ((time2 - time1) / 1000000000.0); long seconds = ((time2 - time1) / 1000000000); secs = secs - seconds; minutes = seconds / 60; secs = seconds % 60 + secs; hours = minutes / 60; minutes = minutes % 60; days = hours / 24; hours = hours % 60; String time; String dayLabel; String hourLabel; String minuteLabel; String secondLabel; if (days == 1) { dayLabel = " day "; } else { dayLabel = " days "; } if (hours == 1) { hourLabel = " hour "; } else { hourLabel = " hours "; } if (minutes == 1) { minuteLabel = " minute "; } else { minuteLabel = " minutes "; } if (seconds == 1) { secondLabel = " second"; } else { secondLabel = " seconds"; } if (days != 0) { time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (hours != 0) { time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (minutes != 0) { time = minutes + minuteLabel + secs + secondLabel; } else { time = secs + secondLabel; } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n"); if (exitValue != 0) { if (exitValue == 143) { JOptionPane.showMessageDialog(Gui.frame, "The simulation was" + " canceled by the user.", "Canceled Simulation", JOptionPane.ERROR_MESSAGE); } else if (exitValue == 139) { JOptionPane.showMessageDialog(Gui.frame, "The selected model is not a valid sbml file." + "\nYou must select an sbml file.", "Not An SBML File", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!\n" + "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE); } } else { if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) { } else if (sbml.isSelected()) { if (sbmlName != null && !sbmlName.trim().equals("")) { String gcmName = sbmlName.replace(".xml", ".gcm"); Gui.createGCMFromSBML(root, root + separator + sbmlName, sbmlName, gcmName, true); if (!biomodelsim.updateOpenGCM(gcmName)) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmName, biomodelsim, log, false, null, null, null, false); biomodelsim.addTab(gcmName, gcm, "GCM Editor"); biomodelsim.addToTree(gcmName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(gcmName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (lhpn.isSelected()) { if (lhpnName != null && !lhpnName.trim().equals("")) { if (!biomodelsim.updateOpenLHPN(lhpnName)) { biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null, biomodelsim, log), "LHPN Editor"); biomodelsim.addToTree(lhpnName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (dot.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } } else if (xhtml.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n"); exec.exec("gnome-open " + out + ".xhtml", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n"); exec.exec("open " + out + ".xhtml", null, work); } else { log.addText("Executing:\ncmd /c start " + directory + out + ".xhtml" + "\n"); exec.exec("cmd /c start " + out + ".xhtml", null, work); } } else if (usingSSA.isSelected()) { // if (!printer_id.equals("null.printer")) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } if (refresh) { ((Graph) simTab.getComponentAt(i)).refresh(); } } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (refresh) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } else if (sim.equals("atacs")) { log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA " + filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "out.hse\n"); exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work); if (refresh) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } // simTab.add("Probability Graph", new // Graph(printer_track_quantity, // outDir.split(separator)[outDir.split(separator).length - // simulation results", // printer_id, outDir, "time", biomodelsim, null, log, null, // false)); // simTab.getComponentAt(simTab.getComponentCount() - // 1).setName("ProbGraph"); } else { // if (!printer_id.equals("null.printer")) { if (ode.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } if (refresh) { ((Graph) simTab.getComponentAt(i)).refresh(); } } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (refresh) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } else if (monteCarlo.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } if (refresh) { ((Graph) simTab.getComponentAt(i)).refresh(); } } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (refresh) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } } } } catch (InterruptedException e1) { JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!", "Error In Execution", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } catch (IOException e1) { JOptionPane.showMessageDialog(Gui.frame, "File I/O Error!", "File I/O Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } return exitValue; } /** * This method is called if a button that cancels the simulation is pressed. */ public void actionPerformed(ActionEvent e) { if (reb2sac != null) { reb2sac.destroy(); } if (sg != null) { sg.stop(); } } }