answer
stringlengths
17
10.2M
package nom.bdezonia.zorbage.misc; /** * * @author Barry DeZonia * */ public class RealUtils { private RealUtils() { } public static boolean near(float f1, float f2, float tol) { if (tol < 0) throw new IllegalArgumentException("negative tolerance given"); return Math.abs(f1-f2) <= tol; } public static boolean near(double f1, double f2, double tol) { if (tol < 0) throw new IllegalArgumentException("negative tolerance given"); return Math.abs(f1-f2) <= tol; } public static double distance1d(double x1, double x2) { return Math.abs(x2-x1); } // TODO: protect from underflow public static double distance2d(double x1, double y1, double x2, double y2) { double dx = Math.abs(x2 - x1); double dy = Math.abs(y2 - y1); double max = Math.max(dx, dy); if (max == 0) return 0; dx /= max; dy /= max; return max * Math.sqrt(dx*dx + dy*dy); } // TODO: protect from underflow public static double distance3d(double x1, double y1, double z1, double x2, double y2, double z2) { double dx = Math.abs(x2 - x1); double dy = Math.abs(y2 - y1); double dz = Math.abs(z2 - z1); double max = Math.max(dx, dy); max = Math.max(max, dz); if (max == 0) return 0; dx /= max; dy /= max; dz /= max; return max * Math.sqrt(dx*dx + dy*dy + dz*dz); } // TODO: protect from underflow public static double distanceNd(double[] p1, double[] p2, double[] scratchSpace) { if (p1.length != p2.length || p1.length != scratchSpace.length) throw new IllegalArgumentException("mismatched dimenions in distanceNd()"); if (p1 == scratchSpace || p2 == scratchSpace) throw new IllegalArgumentException("scratch space must be dofferent from inputs"); if (p1.length == 0) return 0; for (int i = 0; i < p1.length; i++) { scratchSpace[i] = Math.abs(p2[i] - p1[i]); } double max = scratchSpace[0]; for (int i = 1; i < p1.length; i++) { max = Math.max(max, scratchSpace[i]); } if (max == 0) return 0; for (int i = 0; i < p1.length; i++) { scratchSpace[i] /= max; } double sumSq = 0; for (int i = 0; i < p1.length; i++) { sumSq += scratchSpace[i] * scratchSpace[i]; } return max * Math.sqrt(sumSq); } }
package org.aksw.sparqlify.qa.sinks; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.sql.DataSource; import org.aksw.commons.collections.Pair; import org.aksw.sparqlify.algebra.sql.nodes.SqlOp; import org.aksw.sparqlify.algebra.sql.nodes.SqlOpQuery; import org.aksw.sparqlify.algebra.sql.nodes.SqlOpTable; import org.aksw.sparqlify.core.algorithms.ViewQuad; import org.aksw.sparqlify.core.domain.input.ViewDefinition; import org.aksw.sparqlify.qa.exceptions.NotImplementedException; import org.aksw.sparqlify.qa.metrics.MetricImpl; import org.apache.commons.lang.math.RandomUtils; import org.h2.jdbc.JdbcSQLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Node_Blank; import com.hp.hpl.jena.graph.Node_Literal; import com.hp.hpl.jena.graph.Node_URI; import com.hp.hpl.jena.graph.Node_Variable; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.sparql.core.Quad; /** * TODO: check if the prepared statements make sense performance-wise * * @author Patrick Westphal <patrick.westphal@informatik.uni-leipzig.de> * */ @Component public class RdbSink implements MeasureDataSink { @Autowired @Qualifier("resDb") private DataSource sinkDb; protected Connection conn; private long nextId; private long assessmentId; // db table names protected List<String> tableNames; protected final String measureDatumTbl = "measure_datum"; protected final String nodeTripleTbl = "node_triple"; protected final String nodeTbl = "node"; protected final String quadTbl = "quad"; protected final String tripleTbl = "triple"; protected final String varTbl = "variable"; protected final String viewDefTbl = "view_definition"; protected final String md2nodeTbl = "measure_datum__node"; protected final String md2nodeTripleTbl = "measure_datum__node_triple"; protected final String md2quadTbl = "measure_datum__quad"; protected final String md2tripleTbl = "measure_datum__triple"; protected final String md2varTbl = "measure_datum__variable"; protected final String md2viewDefTbl = "measure_datum__view_definition"; protected final String trpl2quadTbl = "triple__quad"; protected final String trpl2viewDefTbl = "triple__view_definition"; protected final String vd2quadTbl = "view_definition__quad"; protected final String vd2varTbl = "view_definition__variable"; @PostConstruct private void init() throws SQLException { conn = sinkDb.getConnection(); initDb(); assessmentId = RandomUtils.nextLong(); tableNames = Arrays.asList(measureDatumTbl, nodeTripleTbl, nodeTbl, quadTbl, tripleTbl, varTbl, viewDefTbl, md2nodeTbl, md2nodeTripleTbl, md2quadTbl, md2tripleTbl, md2varTbl, md2viewDefTbl, trpl2quadTbl, trpl2viewDefTbl, vd2quadTbl, vd2varTbl); } @PreDestroy private void cleanUp() throws SQLException { conn.close(); } // for testing purposes protected void emptyDb() throws SQLException { List<String> redoTblNames = emptyTblsOrReturnFailed(tableNames); while (redoTblNames.size() > 0) { redoTblNames = emptyTblsOrReturnFailed(redoTblNames); } } private List<String> emptyTblsOrReturnFailed(List<String> tblsNames) throws SQLException { List<String> redoTblNames = new ArrayList<String>(); for (String tblName : tblsNames) { try { conn.createStatement().executeUpdate( "DELETE FROM " + tblName + ";"); } catch (JdbcSQLException e) { redoTblNames.add(tblName); } } return redoTblNames; } private void initDb() throws SQLException { // get id counter conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS next_id (id bigint);"); ResultSet res = conn.createStatement().executeQuery("SELECT id FROM next_id LIMIT 1"); if (res.next()) { nextId = res.getLong("id"); } else { conn.createStatement().executeUpdate("INSERT INTO next_id VALUES (0);"); nextId = 0; } // generic measure datum table conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + measureDatumTbl + " (" + "id bigint PRIMARY KEY, " + "dimension varchar(400), " + "metric varchar(400), " + "value real NOT NULL, " + "assessment_id bigint NOT NULL, " + "timestamp timestamp default current_timestamp " + ");"); // node table conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + nodeTbl + " (" + "id bigint PRIMARY KEY, " + "name varchar(300) NOT NULL" + ");"); // node triple table conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + nodeTripleTbl + " (" + "id bigint PRIMARY KEY, " + "position varchar(20), " + "subject varchar(300) , " + "predicate varchar(300), " + "object varchar(3000) " + ");"); // quad table conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + quadTbl + " (" + "id bigint PRIMARY KEY, " + "graph varchar(300), " + "subject varchar(300), " + "predicate varchar(300), " + "object varchar(3000)" + ");"); // triple table conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + tripleTbl + " (" + "id bigint PRIMARY KEY, " + "subject varchar(500), " + "predicate varchar(500), " + "object varchar(3000) " + ");"); // variable table conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + varTbl + " (" + "id bigint PRIMARY KEY, " + "name varchar(50) " + ");"); // view definition table conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + viewDefTbl + " (" + "id bigint PRIMARY KEY, " + "name varchar(200), " + "mapping_sql_op varchar(3000), " + "mapping_definitions varchar(3000) " + ");"); // measure datum -- node conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + md2nodeTbl + " (" + "measure_datum_id bigint REFERENCES " + measureDatumTbl + "(id), " + "node_id bigint REFERENCES " + nodeTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY(measure_datum_id, node_id, assessment_id)" + ");"); // measure datum -- node triple conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + md2nodeTripleTbl + " (" + "measure_datum_id bigint REFERENCES " + measureDatumTbl + "(id), " + "node_triple_id bigint REFERENCES " + nodeTripleTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY (measure_datum_id, node_triple_id, assessment_id)" + ");"); // measure datum -- quad conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + md2quadTbl + " (" + "measure_datum_id bigint REFERENCES " + measureDatumTbl + "(id), " + "quad_id bigint REFERENCES " + quadTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY(measure_datum_id, quad_id, assessment_id)" + ");"); // measure datum -- triple conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + md2tripleTbl + " (" + "measure_datum_id bigint REFERENCES " + measureDatumTbl + "(id), " + "triple_id bigint REFERENCES " + tripleTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY (measure_datum_id, triple_id, assessment_id)" + ");"); // measure datum -- variable conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + md2varTbl + " (" + "measure_datum_id bigint REFERENCES " + measureDatumTbl + "(id), " + "variable_id bigint REFERENCES " + varTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY (measure_datum_id, variable_id, assessment_id)" + ");"); // measure datum -- view definition conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + md2viewDefTbl + " (" + "measure_datum_id bigint REFERENCES " + measureDatumTbl + "(id), " + "view_definition_id bigint REFERENCES " + viewDefTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY(measure_datum_id, view_definition_id, assessment_id)" + ");"); // triple -- quad conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + trpl2quadTbl + " (" + "triple_id bigint REFERENCES " + tripleTbl + "(id), " + "quad_id bigint REFERENCES " + quadTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY (triple_id, quad_id, assessment_id)" + ");"); // triple -- view definition conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + trpl2viewDefTbl + " (" + "triple_id bigint REFERENCES " + tripleTbl + "(id), " + "view_definition_id bigint REFERENCES " + viewDefTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY (triple_id, view_definition_id, assessment_id)" + ");"); // view definition -- quad conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + vd2quadTbl + " (" + "view_definition_id bigint REFERENCES view_definition(id), " + "quad_id bigint REFERENCES quad(id), " + "assessment_id bigint, " + "PRIMARY KEY(view_definition_id, quad_id, assessment_id)" + ");"); // view definition -- variable conn.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + vd2varTbl + " (" + "view_definition_id bigint REFERENCES " + viewDefTbl + "(id), " + "variable_id bigint REFERENCES " + varTbl + "(id), " + "assessment_id bigint, " + "PRIMARY KEY (variable_id, view_definition_id, assessment_id)" + ");"); conn.commit(); } @Override public void initMeasure(String name, Class<? extends MetricImpl> class1, String parentDimension) throws NotImplementedException { // nothing to do here.. } @Override public void write(MeasureDatum datum) throws SQLException { if (datum instanceof DatasetMeasureDatum) { /* a DatasetMeasureDatum has the structure of a generic measure * datum, i.e. dimension name, metric name and value */ String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); long measureDatumId = getNextId(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); } else if (datum instanceof MappingMeasureDatum) { /* a MappingMeasureDatum has the generic structure + a set of view * quad candidates being a Set<ViewQuad<ViewDefinition>> */ writeMappingMeasureDatum((MappingMeasureDatum) datum); } else if (datum instanceof MappingQuadMeasureDatum) { /* a MappingQuadMeasureDatum has the generic structure + a list of * quad - view definition pair * List<Pair<Quad, ViewDefinition>> quadViewDefs */ writeMappingQuadMeasureDatum((MappingQuadMeasureDatum) datum); } else if (datum instanceof MappingVarMeasureDatum) { /* a MappingVarMeasureDatum has the generic structure + a list of * variables List<Pair<Node_Variable, ViewDefinition>> */ writeMappingVarMeasureDatum((MappingVarMeasureDatum) datum); } else if (datum instanceof NodeMeasureDatum) { /* a NodeMeasureDatum has the generic structure + a node (Node) */ writeNodeMeasureDatum((NodeMeasureDatum) datum); } else if (datum instanceof NodeTripleMeasureDatum) { /* a NodeTripleMeasureDatum has the generic structure + a triple * position (TriplePosition), a triple (Triple) and a set of view * quads (Set<ViewQuad<ViewDefinition>>) */ writeNodeTripleMeasureDatum((NodeTripleMeasureDatum) datum); } else if(datum instanceof TripleMeasureDatum) { /* a TripleMeasureDatum has the generic structure + a triple * (Triple) and a set of view quads (Set<ViewQuad<ViewDefinition>>) */ writeTripleMeasureDatum((TripleMeasureDatum) datum); } else if (datum instanceof TriplesMeasureDatum) { /* a TriplesMeasureDatum has the generic structure + a list of * triple-view quad pairs * (List<Pair<Triple, Set<ViewQuad<ViewDefinition>>>>) */ writeTriplesMeasureDatum((TriplesMeasureDatum) datum); } } /** * Method to write the generic part of a measure datum to the database */ private void writeMeasureDatum(long measureDatumId, String dimension, String metric, float value) throws SQLException { PreparedStatement insStmnt = conn.prepareStatement( "INSERT INTO " + measureDatumTbl + " VALUES (?, ?, ?, ?, ?, ?);"); insStmnt.setLong(1, measureDatumId); insStmnt.setString(2, dimension); insStmnt.setString(3, metric); insStmnt.setFloat(4, value); insStmnt.setLong(5, assessmentId); insStmnt.setNull(6, Types.TIMESTAMP); insStmnt.executeUpdate(); conn.commit(); } /** * @param datum: a MappingMeasureDatum comprising the following attributes: * - String dimension * - String metric * - float value * - Set<ViewQuad<ViewDefinition>> candidates * @throws SQLException */ private void writeMappingMeasureDatum(MappingMeasureDatum datum) throws SQLException { // write generic part long measureDatumId = getNextId(); String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); // write candidates if (datum.getViewDefs() != null) { for (ViewQuad<ViewDefinition> viewQuad : datum.getViewDefs()) { Quad quad = viewQuad.getQuad(); ViewDefinition viewDef = viewQuad.getView(); long quadId = writeQuad(quad); long viewDefId = writeViewDef(viewDef); writeMeasureDatum2quad(measureDatumId, quadId); writeMeasureDatum2viewDef(measureDatumId, viewDefId); writeViewDef2quad(viewDefId, quadId); } } } /** * @param datum: a MappingQuadMeasureDatum comprising the following * attributes: * - String dimension * - String metric * - float value * - ArrayList<Pair<Quad, ViewDefinition>> quadViewDefs * @throws SQLException */ private void writeMappingQuadMeasureDatum(MappingQuadMeasureDatum datum) throws SQLException { // write generic metric part String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); long measureDatumId = getNextId(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); // write viewQuad part for (Pair<Quad, ViewDefinition> viewQuad : datum.getQuadViewDefs()) { ViewDefinition viewDef = viewQuad.second; long viewDefId = writeViewDef(viewDef); // write n:m entries writeMeasureDatum2viewDef(measureDatumId, viewDefId); // quad may be null in case of the property completeness metric Quad quad = viewQuad.first; if (quad != null) { long quadId = writeQuad(quad); // write n:m entries writeMeasureDatum2quad(measureDatumId, quadId); writeViewDef2quad(viewDefId, quadId); } } } /** * @param datum: a MappingVarMeasureDatum comprising the following * attributes: * - String dimension * - String metric * - float value * - ArrayList<Pair<Var, ViewDefinition>> nodeViewDefs * @throws SQLException */ private void writeMappingVarMeasureDatum(MappingVarMeasureDatum datum) throws SQLException { // write generic measure datum part long measureDatumId = getNextId(); String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); // write node-view defintion part for (Pair<Node_Variable, ViewDefinition> varViewDef : datum.getNodeViewDefs()) { // write var Node_Variable var = varViewDef.first; long varId = writeVariable(var); // write view definition ViewDefinition viewDef = varViewDef.second; long viewDefId = writeViewDef(viewDef); // write measure datum view definition m:n writeMeasureDatum2viewDef(measureDatumId, viewDefId); // write measure datum variable n:m writeMeasureDatum2var(measureDatumId, varId); // write view definition variable n:m writeViewDef2var(viewDefId, varId); } } /** * @param datum: a NodeMeasureDatum comprises the following attributes: * - String dimension * - String metric * - float value * - Node node * @throws SQLException */ private void writeNodeMeasureDatum(NodeMeasureDatum datum) throws SQLException { String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); long measureDatumId = getNextId(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); long nodeId = writeNode(datum.getNode()); // write measure datum node n:m writeMeasureDatum2node(measureDatumId, nodeId); } /** * @param datum: a NodeTripleMeasureDatum comprises the following attributes: * - String dimension * - String metric * - float value * - TriplePosition pos * - Triple triple * - Set<ViewQuad<ViewDefinition>> viewQuads * @throws SQLException */ private void writeNodeTripleMeasureDatum(NodeTripleMeasureDatum datum) throws SQLException { // write generic measure datum part String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); long measureDatumId = getNextId(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); long nodeTripleId = writeNodeTriple(datum); // write measure datum node triple n:m writeMeasureDatum2nodeTriple(measureDatumId, nodeTripleId); } /** * @param datum: a TripleMeasureDatum comprises the following attributes: * - String dimension * - String metric * - float value * - Triple triple * - Set<ViewQuad<ViewDefinition>> viewQuads * @throws SQLException */ private void writeTripleMeasureDatum(TripleMeasureDatum datum) throws SQLException { // write generic measure datum part String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); long measureDatumId = getNextId(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); Triple triple = datum.getTriple(); long tripleId = writeTriple(triple); writeMeasureDatum2triple(measureDatumId, tripleId); if (datum.getViewQuads() != null) { for (ViewQuad<ViewDefinition> viewQuad : datum.getViewQuads()) { // write quad Quad quad = viewQuad.getQuad(); long quadId = writeQuad(quad); // write view definition ViewDefinition viewDef = viewQuad.getView(); long viewDefId = writeViewDef(viewDef); // write measure datum quad n:m writeMeasureDatum2quad(measureDatumId, quadId); // write measure datum view definition n:m writeMeasureDatum2viewDef(measureDatumId, viewDefId); // write view definitoin quad n_m writeViewDef2quad(viewDefId, quadId); } } } /** * @param datum: a TriplesMeasureDatum comprises the following attributes: * - String dimension * - String metric * - float value * - List<Pair<Triple, Set<ViewQuad<ViewDefinition>>>> tripleViewQuads * @throws SQLException */ private void writeTriplesMeasureDatum(TriplesMeasureDatum datum) throws SQLException { // write generic measure datum part String dimensionName = datum.getDimension(); String metricName = datum.getMetric(); float value = datum.getValue(); long measureDatumId = getNextId(); writeMeasureDatum(measureDatumId, dimensionName, metricName, value); for (Pair<Triple, Set<ViewQuad<ViewDefinition>>> tripleViewQuads : datum.getPinpoinInfos()) { // write triple Triple triple = tripleViewQuads.first; long tripleId = writeTriple(triple); Set<ViewQuad<ViewDefinition>> viewQuads = tripleViewQuads.second; for (ViewQuad<ViewDefinition> viewQuad : viewQuads) { // write quad Quad quad = viewQuad.getQuad(); long quadId = writeQuad(quad); // write view ViewDefinition viewDef = viewQuad.getView(); long viewDefId = writeViewDef(viewDef); // write triple quad n:m writeTriple2quad(tripleId, quadId); // write triple view n:m writeTriple2viewDef(tripleId, viewDefId); } // write measure datum triple n:m writeMeasureDatum2triple(measureDatumId, tripleId); } } private long writeQuad(Quad quad) throws SQLException { long quadId; String quadGraph = quad.getGraph().getURI(); Node subject = quad.getSubject(); String quadSubject = getNodeStrRepr(subject); Node predicate = quad.getPredicate(); String quadPredicate = getNodeStrRepr(predicate); // get object string representation Node object = quad.getObject(); String quadObject = getNodeStrRepr(object); // check if already exists PreparedStatement qpQuery = conn.prepareStatement( "SELECT id FROM " + quadTbl + " " + "WHERE graph=? AND subject=? AND predicate=? AND object=?;"); qpQuery.setString(1, quadGraph); qpQuery.setString(2, quadSubject); qpQuery.setString(3, quadPredicate); qpQuery.setString(4, quadObject); ResultSet qpRes = qpQuery.executeQuery(); if (!qpRes.next()) { // quad does not exist in the database, yet quadId = getNextId(); PreparedStatement qpStmnt = conn.prepareStatement( "INSERT INTO " + quadTbl + " VALUES (?, ?, ?, ?, ?);"); qpStmnt.setLong(1, quadId); qpStmnt.setString(2, quadGraph); qpStmnt.setString(3, quadSubject); qpStmnt.setString(4, quadPredicate); qpStmnt.setString(5, quadObject); qpStmnt.executeUpdate(); } else { // quad does exist quadId = qpRes.getLong("id"); } return quadId; } private long writeTriple(Triple triple) throws SQLException { Node subject = triple.getSubject(); String subjectStr = getNodeStrRepr(subject); Node predicate = triple.getPredicate(); String predicateStr = getNodeStrRepr(predicate); Node object = triple.getObject(); String objectStr = getNodeStrRepr(object); long tripleId; // check if already exists PreparedStatement tripleQStmnt = conn.prepareStatement( "SELECT id FROM " + tripleTbl + " " + "WHERE subject=? AND predicate=? AND object=?;"); tripleQStmnt.setString(1, subjectStr); tripleQStmnt.setString(2, predicateStr); tripleQStmnt.setString(3, objectStr); ResultSet res = tripleQStmnt.executeQuery(); if (!res.next()) { tripleId = getNextId(); // triple does not exist in the database, yet PreparedStatement tripleIStmnt = conn.prepareStatement( "INSERT INTO " + tripleTbl + " VALUES(?, ?, ?, ?);"); tripleIStmnt.setLong(1, tripleId); tripleIStmnt.setString(2, subjectStr); tripleIStmnt.setString(3, predicateStr); tripleIStmnt.setString(4, objectStr); tripleIStmnt.executeUpdate(); conn.commit(); } else { // triple alreasy exists in the database tripleId = res.getLong("id"); } return tripleId; } private long writeViewDef(ViewDefinition viewDef) throws SQLException { String viewDefName = viewDef.getName(); long viewDefId; // check if exists PreparedStatement vdQStmnt = conn.prepareStatement( "SELECT id FROM " + viewDefTbl + " WHERE name=?;"); vdQStmnt.setString(1, viewDefName); ResultSet res = vdQStmnt.executeQuery(); if (!res.next()) { // view does not exist in DB viewDefId = getNextId(); String viewDefMappSqlOp = null; SqlOp sqlOp = viewDef.getMapping().getSqlOp(); if (sqlOp instanceof SqlOpQuery) { viewDefMappSqlOp = ((SqlOpQuery) sqlOp).getQueryString(); } else if (sqlOp instanceof SqlOpTable) { viewDefMappSqlOp = ((SqlOpTable) sqlOp).getTableName(); } String viewDefMappDefs = viewDef.getMapping().getVarDefinition() .toPrettyString(); PreparedStatement vdIStmnt = conn.prepareStatement( "INSERT INTO " + viewDefTbl + " VALUES (?, ?, ?, ?);"); vdIStmnt.setLong(1, viewDefId); vdIStmnt.setString(2, viewDefName); vdIStmnt.setString(3, viewDefMappSqlOp); vdIStmnt.setString(4, viewDefMappDefs); vdIStmnt.executeUpdate(); conn.commit(); } else { // view definition already exists in DB viewDefId = res.getLong("id"); } return viewDefId; } private long writeVariable(Node_Variable var) throws SQLException { String varName = var.toString(); long varId; // check if already exists PreparedStatement varQStmnt = conn.prepareStatement( "SELECT id FROM " + varTbl + " WHERE name=?;"); varQStmnt.setString(1, varName); ResultSet res = varQStmnt.executeQuery(); if (!res.next()) { // variable does not exist in the database, yet varId = getNextId(); PreparedStatement varIStmnt = conn.prepareStatement( "INSERT INTO " + varTbl + " VALUES (?, ?);"); varIStmnt.setLong(1, varId); varIStmnt.setString(2, varName); varIStmnt.executeUpdate(); conn.commit(); } else { // variable already exists varId = res.getLong("id"); } return varId; } private long writeNode(Node node) throws SQLException { String nodeName = getNodeStrRepr(node); long nodeId; // check if already exists PreparedStatement nodeQStmnt = conn.prepareStatement( "SELECT id FROM " + nodeTbl + " WHERE name=?;"); nodeQStmnt.setString(1, nodeName); ResultSet res = nodeQStmnt.executeQuery(); if (!res.next()) { // node does not exist in the database, yet nodeId = getNextId(); PreparedStatement nodeIStmnt = conn.prepareStatement( "INSERT INTO " + nodeTbl + " VALUES (?, ?);"); nodeIStmnt.setLong(1, nodeId); nodeIStmnt.setString(2, nodeName); nodeIStmnt.executeUpdate(); conn.commit(); } else { // node already exists in the database nodeId = res.getLong("id"); } return nodeId; } private long writeNodeTriple(NodeTripleMeasureDatum datum) throws SQLException { String nodeTriplePosition = datum.getTriplePosition().name(); Node subject = datum.getTriple().getSubject(); String nodeTripleSubject = getNodeStrRepr(subject); Node predicate = datum.getTriple().getPredicate(); String nodeTriplePredicate = getNodeStrRepr(predicate); Node object = datum.getTriple().getObject(); String nodeTripleObject = getNodeStrRepr(object); long nodeTripleId; // check if already exists PreparedStatement ntQStmnt = conn.prepareStatement( "SELECT id FROM " + nodeTripleTbl + " " + "WHERE position=? AND subject=? AND predicate=? AND object=?;"); ntQStmnt.setString(1, nodeTriplePosition); ntQStmnt.setString(2, nodeTripleSubject); ntQStmnt.setString(3, nodeTriplePredicate); ntQStmnt.setString(4, nodeTripleObject); ResultSet res = ntQStmnt.executeQuery(); if (!res.next()) { // node triple does not exist in the database, yet nodeTripleId = getNextId(); // schema: // id bigint, position varchar(20), subject varchar(300), // predicate varchar(300), object varchar(300) PreparedStatement ntIStmnt = conn.prepareStatement( "INSERT INTO " + nodeTripleTbl + " VALUES (?, ? , ?, ?, ?)"); ntIStmnt.setLong(1, nodeTripleId); ntIStmnt.setString(2, nodeTriplePosition); ntIStmnt.setString(3, nodeTripleSubject); ntIStmnt.setString(4, nodeTriplePredicate); ntIStmnt.setString(5, nodeTripleObject); ntIStmnt.executeUpdate(); conn.commit(); } else { nodeTripleId = res.getLong("id"); } return nodeTripleId; } private void writeMeasureDatum2node(long measureDatumId, long nodeId) throws SQLException { // check if entry already exists PreparedStatement md2nodeQStmnt = conn.prepareStatement( "SELECT measure_datum_id FROM " + md2nodeTbl + " " + "WHERE measure_datum_id=? AND node_id=? AND assessment_id=?;"); md2nodeQStmnt.setLong(1, measureDatumId); md2nodeQStmnt.setLong(2, nodeId); md2nodeQStmnt.setLong(3, assessmentId); ResultSet res = md2nodeQStmnt.executeQuery(); if (!res.next()) { // extry does not exist in the database, yet PreparedStatement md2nodeIStmnt = conn.prepareStatement( "INSERT INTO " + md2nodeTbl + " VALUES(?, ?, ?);"); md2nodeIStmnt.setLong(1, measureDatumId); md2nodeIStmnt.setLong(2, nodeId); md2nodeIStmnt.setLong(3, assessmentId); md2nodeIStmnt.executeUpdate(); conn.commit(); } } private void writeMeasureDatum2nodeTriple(long measureDatumId, long nodeTripleId) throws SQLException { // check if already exists PreparedStatement md2ntQStmnt = conn.prepareStatement( "SELECT measure_datum_id FROM " + md2nodeTripleTbl + " " + "WHERE measure_datum_id=? AND node_triple_id=? " + "AND assessment_id=?"); md2ntQStmnt.setLong(1, measureDatumId); md2ntQStmnt.setLong(2, nodeTripleId); md2ntQStmnt.setLong(3, assessmentId); ResultSet res = md2ntQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement md2ntIStmnt = conn.prepareStatement( "INSERT INTO " + md2nodeTripleTbl + " VALUES (?, ?, ?);"); md2ntIStmnt.setLong(1, measureDatumId); md2ntIStmnt.setLong(2, nodeTripleId); md2ntIStmnt.setLong(3, assessmentId); md2ntIStmnt.executeUpdate(); conn.commit(); } } private void writeMeasureDatum2quad(long measureDatumId, long quadId) throws SQLException { // check if entry already exists PreparedStatement md2qpQStmnt = conn.prepareStatement( "SELECT measure_datum_id FROM " + md2quadTbl + " " + "WHERE measure_datum_id=? AND quad_id=? AND assessment_id=?;"); md2qpQStmnt.setLong(1, measureDatumId); md2qpQStmnt.setLong(2, quadId); md2qpQStmnt.setLong(3, assessmentId); ResultSet res = md2qpQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement md2qpIStmnt = conn.prepareStatement( "INSERT INTO " + md2quadTbl + " VALUES (?, ?, ?);"); md2qpIStmnt.setLong(1, measureDatumId); md2qpIStmnt.setLong(2, quadId); md2qpIStmnt.setLong(3, assessmentId); md2qpIStmnt.executeUpdate(); conn.commit(); } } private void writeMeasureDatum2triple(long measureDatumid, long tripleid) throws SQLException { // check if entry already exists PreparedStatement md2trplQStmnt = conn.prepareStatement( "SELECT measure_datum_id FROM " + md2tripleTbl + " " + "WHERE measure_datum_id=? AND triple_id=? AND assessment_id=?;"); md2trplQStmnt.setLong(1, measureDatumid); md2trplQStmnt.setLong(2, tripleid); md2trplQStmnt.setLong(3, assessmentId); ResultSet res = md2trplQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement md2trplIStmnt = conn.prepareStatement( "INSERT INTO " + md2tripleTbl + " VALUES (?, ?, ?);"); md2trplIStmnt.setLong(1, measureDatumid); md2trplIStmnt.setLong(2, tripleid); md2trplIStmnt.setLong(3, assessmentId); md2trplIStmnt.executeUpdate(); conn.commit(); } } private void writeMeasureDatum2var(long measureDatumId, long varId) throws SQLException { // check if entry already exits PreparedStatement md2varQStmnt = conn.prepareStatement( "SELECT measure_datum_id FROM " + md2varTbl + " " + "WHERE measure_datum_id=? AND variable_id=? AND assessment_id=?;"); md2varQStmnt.setLong(1, measureDatumId); md2varQStmnt.setLong(2, varId); md2varQStmnt.setLong(3, assessmentId); ResultSet res = md2varQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement md2varIStmnt = conn.prepareStatement( "INSERT INTO " + md2varTbl + " VALUES (?, ?, ?);"); md2varIStmnt.setLong(1, measureDatumId); md2varIStmnt.setLong(2, varId); md2varIStmnt.setLong(3, assessmentId); md2varIStmnt.executeUpdate(); conn.commit(); } } private void writeMeasureDatum2viewDef(long measureDatumId, long viewDefId) throws SQLException { // check if entry already exists PreparedStatement md2vdQStmnt = conn.prepareStatement( "SELECT measure_datum_id FROM " + md2viewDefTbl + " " + "WHERE measure_datum_id=? AND view_definition_id=? " + "AND assessment_id=?;"); md2vdQStmnt.setLong(1, measureDatumId); md2vdQStmnt.setLong(2, viewDefId); md2vdQStmnt.setLong(3, assessmentId); ResultSet res = md2vdQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement md2vdIStmnt = conn.prepareStatement( "INSERT INTO " + md2viewDefTbl + " VALUES (?, ?, ?);"); md2vdIStmnt.setLong(1, measureDatumId); md2vdIStmnt.setLong(2, viewDefId); md2vdIStmnt.setLong(3, assessmentId); md2vdIStmnt.executeUpdate(); conn.commit(); } } private void writeTriple2quad(long tripleId, long quadId) throws SQLException { // check if entry already exists PreparedStatement trpl2qudQStmnt = conn.prepareStatement( "SELECT triple_id FROM " + trpl2quadTbl + " " + "WHERE triple_id=? AND quad_id=? AND assessment_id=?;"); trpl2qudQStmnt.setLong(1, tripleId); trpl2qudQStmnt.setLong(2, quadId); trpl2qudQStmnt.setLong(3, assessmentId); ResultSet res = trpl2qudQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement trpl2qudIStmnt = conn.prepareStatement( "INSERT INTO " + trpl2quadTbl + " VALUES (?, ?, ?);"); trpl2qudIStmnt.setLong(1, tripleId); trpl2qudIStmnt.setLong(2, quadId); trpl2qudIStmnt.setLong(3, assessmentId); trpl2qudIStmnt.executeUpdate(); conn.commit(); } } private void writeTriple2viewDef(long tripleId, long viewDefId) throws SQLException { // check if entry exists PreparedStatement trpl2vdQStmnt = conn.prepareStatement( "SELECT triple_id FROM " + trpl2viewDefTbl + " " + "WHERE triple_id=? AND view_definition_id=? AND assessment_id=?;"); trpl2vdQStmnt.setLong(1, tripleId); trpl2vdQStmnt.setLong(2, viewDefId); trpl2vdQStmnt.setLong(3, assessmentId); ResultSet res = trpl2vdQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement trpl2vdIStmnt = conn.prepareStatement( "INSERT INTO " + trpl2viewDefTbl + " VALUES (?,?, ?);"); trpl2vdIStmnt.setLong(1, tripleId); trpl2vdIStmnt.setLong(2, viewDefId); trpl2vdIStmnt.setLong(3, assessmentId); trpl2vdIStmnt.executeUpdate(); conn.commit(); } } private void writeViewDef2quad(long viewDefId, long quadId) throws SQLException { // check if entry already exists PreparedStatement vd2qpQStmnt = conn.prepareStatement( "SELECT view_definition_id FROM " + vd2quadTbl + " " + "WHERE view_definition_id=? AND quad_id=? " + "AND assessment_id=?"); vd2qpQStmnt.setLong(1, viewDefId); vd2qpQStmnt.setLong(2, quadId); vd2qpQStmnt.setLong(3, assessmentId); ResultSet res = vd2qpQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement vd2qpIStmnt = conn.prepareStatement( "INSERT INTO " + vd2quadTbl + " VALUES (?, ?, ?);"); vd2qpIStmnt.setLong(1, viewDefId); vd2qpIStmnt.setLong(2, quadId); vd2qpIStmnt.setLong(3, assessmentId); vd2qpIStmnt.executeUpdate(); conn.commit(); } } private void writeViewDef2var(long viewDefId, long varId) throws SQLException { // check if entry already exists PreparedStatement vd2varQStmnt = conn.prepareStatement( "SELECT view_definition_id FROM " + vd2varTbl + " " + "WHERE view_definition_id=? AND variable_id=? AND assessment_id=?;"); vd2varQStmnt.setLong(1, viewDefId); vd2varQStmnt.setLong(2, varId); vd2varQStmnt.setLong(3, assessmentId); ResultSet res = vd2varQStmnt.executeQuery(); if (!res.next()) { // entry does not exist in the database, yet PreparedStatement vd2varIStmnt = conn.prepareStatement( "INSERT INTO " + vd2varTbl + " VALUES (?, ?, ?);"); vd2varIStmnt.setLong(1, viewDefId); vd2varIStmnt.setLong(2, varId); vd2varIStmnt.setLong(3, assessmentId); vd2varIStmnt.executeUpdate(); conn.commit(); } } private long getNextId() throws SQLException { conn.createStatement().executeUpdate("UPDATE next_id SET id=" + (++nextId) + ";"); return nextId; } private String getNodeStrRepr(Node node) { String repr; if (node.isBlank()) { repr = ((Node_Blank) node).getBlankNodeLabel(); } else if (node.isLiteral()) { repr = ((Node_Literal) node).toString(); } else if (node.isURI()) { repr = ((Node_URI) node).getURI(); } else if (node.isVariable()) { repr = ((Node_Variable) node).toString(); } else { repr = node.toString(); } return repr; } }
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 org.apdplat.word.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author */ public class WordConfTools { private static final Logger LOGGER = LoggerFactory.getLogger(WordConfTools.class); private static final Map<String, String> conf = new HashMap<>(); public static void set(String key, String value){ conf.put(key, value); } public static int getInt(String key, int defaultValue){ LOGGER.info(""+key); return conf.get(key) == null ? defaultValue : getInt(key); } public static int getInt(String key){ LOGGER.info(""+key); return Integer.parseInt(conf.get(key)); } public static String get(String key, String defaultValue){ LOGGER.info(""+key); return conf.get(key) == null ? defaultValue : conf.get(key); } public static String get(String key){ LOGGER.info(""+key); return conf.get(key); } static{ reload(); } public static void reload(){ conf.clear(); LOGGER.info(""); long start = System.currentTimeMillis(); loadConf("word.conf"); loadConf("word.local.conf"); checkSystemProperties(); long cost = System.currentTimeMillis() - start; LOGGER.info(""+cost+" "+conf.size()); LOGGER.info(""); for(String key : conf.keySet()){ LOGGER.info(key+"="+conf.get(key)); } } /** * * @param confFile */ private static void loadConf(String confFile) { InputStream in = WordConfTools.class.getClassLoader().getResourceAsStream(confFile); if(in == null){ LOGGER.info(""+confFile); return; } try(BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"))){ String line; while((line = reader.readLine()) != null){ line = line.trim(); if("".equals(line) || line.startsWith(" continue; } String[] attr = line.split("="); if(attr != null && attr.length == 2){ conf.put(attr[0].trim(), attr[1].trim()); } } } catch (IOException ex) { System.err.println(":"+ex.getMessage()); throw new RuntimeException(ex); } } private static void checkSystemProperties() { for(String key : conf.keySet()){ String value = System.getProperty(key); if(value != null){ conf.put(key, value); LOGGER.info(""+key+"="+value); } } } public static void main(String[] args){ } }
package org.apdplat.word.vector; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apdplat.word.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author */ public class Word2Vector { private static final Logger LOGGER = LoggerFactory.getLogger(Word2Vector.class); public static void main(String[] args){ String input = "target/word.txt"; String output = "target/vector.txt"; String vocabulary = "target/vocabulary.txt"; int window = 2; int vectorLength = 30; if(args.length == 3){ input = args[0]; output = args[1]; vocabulary = args[2]; } if(args.length == 5){ input = args[0]; output = args[1]; vocabulary = args[2]; window = Integer.parseInt(args[3]); vectorLength = Integer.parseInt(args[4]); } long start = System.currentTimeMillis(); word2Vec(input, output, vocabulary, window, vectorLength); long cost = System.currentTimeMillis()-start; LOGGER.info("cost time:"+cost+" ms"); } private static void word2Vec(String input, String output, String vocabulary, int window, int vectorLength) { float max=(float)Runtime.getRuntime().maxMemory()/1000000; float total=(float)Runtime.getRuntime().totalMemory()/1000000; float free=(float)Runtime.getRuntime().freeMemory()/1000000; String pre=":"+max+"-"+total+"+"+free+"="+(max-total+free); try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input),"utf-8")); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output),"utf-8")); BufferedWriter vocabularyWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(vocabulary),"utf-8"))){ int textLength=0; long start = System.currentTimeMillis(); LOGGER.info("1"); LOGGER.info(""+window); Map<String, List<ContextWord>> map = new HashMap<>(); Map<String, Integer> frq = new HashMap<>(); String line = null; while((line = reader.readLine()) != null){ textLength += line.length(); word2Vec(map, frq, line, window); } long cost = System.currentTimeMillis()-start; LOGGER.info(""+ textLength/cost+" /"+cost/1000+" "+map.size()+""+frq.size()); LOGGER.info("2TOPN"); LOGGER.info(""+vectorLength); start = System.currentTimeMillis(); normalize(map, frq, vectorLength); LOGGER.info(""+ (System.currentTimeMillis()-start)/1000+" "+map.size()); LOGGER.info("3"); start = System.currentTimeMillis(); List<String> list = new ArrayList<>(); for(Entry<String, List<ContextWord>> entry : map.entrySet()){ list.add(entry.getKey()+" : "+entry.getValue().toString()); } Collections.sort(list); for(String item : list){ writer.write(item+"\n"); } list.clear(); for(Entry<String, Integer> entry : Utils.getSortedMapByValue(frq)){ vocabularyWriter.write(entry.getKey()+" "+entry.getValue()+"\n"); } LOGGER.info(""+ (System.currentTimeMillis()-start)/1000+" "+list.size()); }catch(Exception e){ LOGGER.error("", e); } max=(float)Runtime.getRuntime().maxMemory()/1000000; total=(float)Runtime.getRuntime().totalMemory()/1000000; free=(float)Runtime.getRuntime().freeMemory()/1000000; String post=":"+max+"-"+total+"+"+free+"="+(max-total+free); LOGGER.info(pre); LOGGER.info(post); } private static void word2Vec(Map<String, List<ContextWord>> map, Map<String, Integer> frq, String line, int distance){ String[] words = line.split(" "); if(words.length > 10000){ LOGGER.info(""+words.length); } for(int i=0; i<words.length; i++){ if(i > 0 && i % 10000 == 0){ LOGGER.info(": "+i/(float)words.length*100+" %"); } String word = words[i]; if(!Utils.isChineseCharAndLengthAtLeastTwo(word)){ continue; } Integer count = frq.get(word); if(count == null){ count = 1; }else{ count++; } frq.put(word, count); //word for(int j=1; j<=distance; j++){ //word int index = i-j; contextWord(words, index, j, word, map); //word index = i+j; contextWord(words, index, j, word, map); } } } /** * * @param words * @param index * @param distance * @param word * @param map */ private static void contextWord(String[] words, int index, int distance, String word, Map<String, List<ContextWord>> map){ String _word = null; if(index > -1 && index < words.length){ _word = words[index]; } if(_word != null && Utils.isChineseCharAndLengthAtLeastTwo(_word)){ addToMap(map, word, _word, distance); } } private static void addToMap(Map<String, List<ContextWord>> map, String word, String _word, int distance){ List<ContextWord> value = map.get(word); if(value == null){ value = new ArrayList<>(); map.put(word, value); } float s = (float)1/distance; boolean find=false; for(ContextWord item : value){ if(item.getWord().equals(_word)){ float score = item.getScore()+s; item.setScore(score); find = true; break; } } if(!find){ ContextWord item = new ContextWord(_word, s); value.add(item); } } private static void normalize(Map<String, List<ContextWord>> map, Map<String, Integer> frq, int count) { for(String key : map.keySet()){ List<ContextWord> value = map.get(key); float max=0; for(ContextWord word : value){ //float score = word.getScore() / (float)Math.sqrt(frq.get(word.getWord())); //word.setScore(score); if(word.getScore() > max){ max = word.getScore(); } } for(ContextWord word : value){ word.setScore(word.getScore()/max); } Collections.sort(value); int len = value.size(); //TOPN if(len > count){ value = value.subList(0, count); } map.put(key, value); } } private static class ContextWord implements Comparable{ private String word; private float score; public ContextWord(String word, Float score) { this.word = word; this.score = score; } @Override public String toString() { return word + " " + score; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } @Override public int compareTo(Object o) { float target = ((ContextWord)o).getScore(); if(this.getScore() < target){ return 1; } if(this.getScore() == target){ return 0; } return -1; } } }
package org.davidmoten.hilbert; import java.math.BigInteger; import java.util.Arrays; import java.util.BitSet; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.guavamini.annotations.VisibleForTesting; public final class HilbertCurve { private final int bits; private final int dimensions; // cached calculations private final int length; private final long N; private final long M; private final long initialMask; private HilbertCurve(int bits, int dimensions) { this.bits = bits; this.dimensions = dimensions; // cache a few calculated values for small perf improvements this.length = bits * dimensions; this.N = 2L << (bits - 1); this.M = 1L << (bits - 1); this.initialMask = 1L << (bits - 1); } /** * Returns a builder for and object that performs transformations for a * Hilbert curve with the given number of bits. * * @param bits * depth of the Hilbert curve. If bits is one, this is the * top-level Hilbert curve * @return builder for object to do transformations with the Hilbert Curve */ public static HilbertCurveBuilder bits(int bits) { return new HilbertCurveBuilder(bits); } /** * Builds a {@link HilbertCurve} instance. */ public static class HilbertCurveBuilder { final int bits; private HilbertCurveBuilder(int bits) { Preconditions.checkArgument(bits > 0, "bits must be greater than zero"); this.bits = bits; } public HilbertCurve dimensions(int dimensions) { Preconditions.checkArgument(dimensions > 1, "dimensions must be at least 2"); return new HilbertCurve(bits, dimensions); } } public BigInteger index(long... point) { Preconditions.checkArgument(point.length == dimensions); return toBigInteger(transposedIndex(point)); } public long[] point(BigInteger index) { Preconditions.checkNotNull(index); Preconditions.checkArgument(index.signum() != -1, "index cannot be negative"); return transposedIndexToPoint(transpose(index)); } public long[] point(long index) { return point(BigInteger.valueOf(index)); } @VisibleForTesting long[] transpose(BigInteger index) { byte[] bytes = index.toByteArray(); Util.reverse(bytes); BitSet b = BitSet.valueOf(bytes); long[] x = new long[dimensions]; for (int idx = 0; idx < b.length(); idx++) { if (b.get(idx)) { int dim = (length - idx - 1) % dimensions; int shift = (idx / dimensions) % bits; x[dim] |= 1 << shift; } } return x; } /** * <p> * Given the axes (coordinates) of a point in N-Dimensional space, find the * distance to that point along the Hilbert curve. That distance will be * transposed; broken into pieces and distributed into an array. * * <p> * The number of dimensions is the length of the hilbertAxes array. * * <p> * Note: In Skilling's paper, this function is called AxestoTranspose. * * @param point * Point in N-space * @return The Hilbert distance (or index) as a transposed Hilbert index */ @VisibleForTesting long[] transposedIndex(long... point) { int n = point.length; // n: Number of dimensions long[] x = Arrays.copyOf(point, n); long p, q, t; int i; // Inverse undo for (q = M; q > 1; q >>= 1) { p = q - 1; for (i = 0; i < n; i++) if ((x[i] & q) != 0) x[0] ^= p; // invert else { t = (x[0] ^ x[i]) & p; x[0] ^= t; x[i] ^= t; } } // exchange // Gray encode for (i = 1; i < n; i++) x[i] ^= x[i - 1]; t = 0; for (q = M; q > 1; q >>= 1) if ((x[n - 1] & q) != 0) t ^= q - 1; for (i = 0; i < n; i++) x[i] ^= t; return x; } /** * Converts the Hilbert transposed index into an N-dimensional point * expressed as a vector of {@code long}. * * In Skilling's paper this function is named {@code TransposeToAxes} * * @param transposedIndex * distance along the Hilbert curve in transposed form * @return the coordinates of the point represented by the transposed index * on the Hilbert curve */ private long[] transposedIndexToPoint(long... x) { // Note that x is mutated by this method (as a performance improvement // to avoid allocation) int n = x.length; // number of dimensions long p, q, t; int i; // Gray decode by H ^ (H/2) t = x[n - 1] >> 1; // Corrected error in Skilling's paper on the following line. The // appendix had i >= 0 leading to negative array index. for (i = n - 1; i > 0; i x[i] ^= x[i - 1]; x[0] ^= t; // Undo excess work for (q = 2; q != N; q <<= 1) { p = q - 1; for (i = n - 1; i >= 0; i if ((x[i] & q) != 0L) x[0] ^= p; // invert else { t = (x[0] ^ x[i]) & p; x[0] ^= t; x[i] ^= t; } } // exchange return x; } // Quote from Paul Chernoch // Interleaving means take one bit from the first matrix element, one bit // from the next, etc, then take the second bit from the first matrix // element, second bit from the second, all the way to the last bit of the // last element. Combine those bits in that order into a single BigInteger, // which can have as many bits as necessary. This converts the array into a // single number. @VisibleForTesting BigInteger toBigInteger(long... transposedIndex) { BitSet b = new BitSet(length); int bIndex = length - 1; long mask = initialMask; for (int i = 0; i < bits; i++) { for (int j = 0; j < transposedIndex.length; j++) { if ((transposedIndex[j] & mask) != 0) { b.set(bIndex); } bIndex } mask >>= 1; } if (b.isEmpty()) return BigInteger.ZERO; else { byte[] bytes = b.toByteArray(); // make Big Endian Util.reverse(bytes); return new BigInteger(1, bytes); } } }
package org.davidmoten.rx.pool; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Subscription; import com.github.davidmoten.guavamini.Preconditions; import io.reactivex.Scheduler; import io.reactivex.Scheduler.Worker; import io.reactivex.Single; import io.reactivex.SingleObserver; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.MpscLinkedQueue; import io.reactivex.plugins.RxJavaPlugins; class MemberSingle<T> extends Single<Member2<T>> implements Subscription, Closeable { final AtomicReference<Observers<T>> observers; @SuppressWarnings({ "rawtypes", "unchecked" }) static final Observers EMPTY = new Observers(new MemberSingleObserver[0], new boolean[0], 0, 0); private final SimplePlainQueue<Member2<T>> queue; private final AtomicInteger wip = new AtomicInteger(); private final Member2<T>[] members; private final Scheduler scheduler; private final int maxSize; // mutable private volatile boolean cancelled; // number of members in the pool at the moment private int count; @SuppressWarnings("unchecked") MemberSingle(NonBlockingPool2<T> pool) { this.queue = new MpscLinkedQueue<Member2<T>>(); this.members = createMembersArray(pool); this.scheduler = pool.scheduler; this.maxSize = pool.maxSize; this.observers = new AtomicReference<>(EMPTY); this.count = 1; queue.offer(members[0]); } private static <T> Member2<T>[] createMembersArray(NonBlockingPool2<T> pool) { @SuppressWarnings("unchecked") Member2<T>[] m = new Member2[pool.maxSize]; for (int i = 0; i < m.length; i++) { m[i] = pool.memberFactory.create(pool); } return m; } public void checkin(Member2<T> member) { System.out.println("checking in"); queue.offer(member); drain(); } @Override public void request(long n) { drain(); } @Override public void cancel() { this.cancelled = true; } @SuppressWarnings("resource") private void drain() { if (wip.getAndIncrement() == 0) { int missed = 1; while (true) { int c = 0; while (c < count) { if (cancelled) { queue.clear(); return; } Observers<T> obs = observers.get(); if (obs.activeCount == 0) { break; } final Member2<T> m = queue.poll(); if (m == null) { if (count < maxSize) { // haven't used all the members of the pool yet queue.offer(members[count]); count++; } else { break; } } else { Member2<T> m2; if ((m2 = m.checkout()) != null) { emit(obs, m2); } else { // put back on the queue for consideration later queue.offer(m); } } c++; } missed = wip.addAndGet(-missed); if (missed == 0) { return; } } } } private void emit(Observers<T> obs, Member2<T> m) { // get a fresh worker each time so we jump threads to // break the stack-trace (a long-enough chain of // checkout-checkins could otherwise provoke stack // overflow) // advance counter so the next and choose an Observer to emit to (round robin) int index = obs.index; MemberSingleObserver<T> o = obs.observers[index]; MemberSingleObserver<T> oNext = o; // atomically bump up the index (if that entry has not been deleted in // the meantime by disposal) while (true) { Observers<T> x = observers.get(); if (x.index == index && x.observers[index] == o) { boolean[] active = new boolean[x.active.length]; System.arraycopy(x.active, 0, active, 0, active.length); active[index] = false; int nextIndex = (index + 1) % active.length; while (nextIndex != index && !active[nextIndex]) { nextIndex = (nextIndex + 1) % active.length; } if (observers.compareAndSet(x, new Observers<T>(x.observers, active, x.activeCount - 1, nextIndex))) { oNext = x.observers[nextIndex]; break; } } else { break; } } Worker worker = scheduler.createWorker(); worker.schedule(new Emitter<T>(worker, oNext, m)); } @Override public void close() throws IOException { for (Member2<T> member : members) { try { member.close(); } catch (Exception e) { // TODO accumulate and throw? e.printStackTrace(); } } } @Override protected void subscribeActual(SingleObserver<? super Member2<T>> observer) { MemberSingleObserver<T> md = new MemberSingleObserver<T>(observer, this); observer.onSubscribe(md); add(md); if (md.isDisposed()) { remove(md); } drain(); } void add(@NonNull MemberSingleObserver<T> inner) { while (true) { Observers<T> a = observers.get(); int n = a.observers.length; @SuppressWarnings("unchecked") MemberSingleObserver<T>[] b = new MemberSingleObserver[n + 1]; System.arraycopy(a.observers, 0, b, 0, n); b[n] = inner; boolean[] active = new boolean[n + 1]; System.arraycopy(a.active, 0, active, 0, n); active[n] = true; if (observers.compareAndSet(a, new Observers<T>(b, active, a.activeCount + 1, a.index))) { return; } } } @SuppressWarnings("unchecked") void remove(@NonNull MemberSingleObserver<T> inner) { while (true) { Observers<T> a = observers.get(); int n = a.observers.length; if (n == 0) { return; } int j = -1; for (int i = 0; i < n; i++) { if (a.observers[i] == inner) { j = i; break; } } if (j < 0) { return; } Observers<T> next; if (n == 1) { next = EMPTY; } else { MemberSingleObserver<T>[] b = new MemberSingleObserver[n - 1]; System.arraycopy(a.observers, 0, b, 0, j); System.arraycopy(a.observers, j + 1, b, j, n - j - 1); boolean[] active = new boolean[n - 1]; System.arraycopy(a.active, 0, active, 0, j); System.arraycopy(a.active, j + 1, active, j, n - j - 1); int nextActiveCount = a.active[j] ? a.activeCount - 1 : a.activeCount; if (a.index > j) { next = new Observers<T>(b, active, nextActiveCount, a.index - 1); } else { next = new Observers<T>(b, active, nextActiveCount, a.index); } } if (observers.compareAndSet(a, next)) { return; } } } private static final class Observers<T> { final MemberSingleObserver<T>[] observers; // an observer is active until it is emitted to final boolean[] active; private int activeCount; final int index; Observers(MemberSingleObserver<T>[] observers, boolean[] active, int activeCount, int index) { Preconditions.checkArgument(observers.length > 0 || index == 0, "index must be -1 for zero length array"); Preconditions.checkArgument(observers.length == active.length); this.observers = observers; this.index = index; this.active = active; this.activeCount = activeCount; } } private static final class Emitter<T> implements Runnable { private final Worker worker; private final MemberSingleObserver<T> observer; private final Member2<T> m; Emitter(Worker worker, MemberSingleObserver<T> observer, Member2<T> m) { this.worker = worker; this.observer = observer; this.m = m; } @Override public void run() { worker.dispose(); try { observer.child.onSuccess(m); observer.dispose(); } catch (Throwable e) { RxJavaPlugins.onError(e); } } } static final class MemberSingleObserver<T> extends AtomicReference<MemberSingle<T>> implements Disposable { private static final long serialVersionUID = -7650903191002190468L; final SingleObserver<? super Member2<T>> child; MemberSingleObserver(SingleObserver<? super Member2<T>> child, MemberSingle<T> parent) { this.child = child; lazySet(parent); } @Override public void dispose() { MemberSingle<T> parent = getAndSet(null); if (parent != null) { parent.remove(this); } } @Override public boolean isDisposed() { return get() == null; } } }
package org.g_node.micro.commons; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSetFormatter; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.sparql.util.Context; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.jena.atlas.io.IO; import org.apache.jena.atlas.web.ContentType; import org.apache.jena.atlas.web.TypedInputStream; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RDFFormat; import org.apache.jena.riot.RDFLanguages; import org.apache.jena.riot.RDFParserRegistry; import org.apache.jena.riot.ReaderRIOT; import org.apache.jena.riot.ReaderRIOTFactory; import org.apache.jena.riot.RiotException; import org.apache.jena.riot.SysRIOT; import org.apache.jena.riot.WebContent; import org.apache.jena.riot.system.StreamRDF; import org.apache.jena.riot.system.StreamRDFLib; import org.apache.log4j.Logger; /** * Main service class for opening data from and saving data to an RDF file. * * @author Michael Sonntag (sonntag@bio.lmu.de) */ public final class RDFService { /** * Map returning the RDF formats supported by this service. */ public static final Map<String, RDFFormat> RDF_FORMAT_MAP = Collections.unmodifiableMap(new HashMap<String, RDFFormat>(3) { { put("TTL", RDFFormat.TURTLE_PRETTY); put("RDF/XML", RDFFormat.RDFXML); put("NTRIPLES", RDFFormat.NTRIPLES); put("JSON-LD", RDFFormat.JSONLD); } }); /** * Map RDF formats to the correct file ending. */ public static final Map<String, String> RDF_FORMAT_EXTENSION = Collections.unmodifiableMap(new HashMap<String, String>(3) { { put("TTL", "ttl"); put("RDF/XML", "rdf"); put("NTRIPLES", "nt"); put("JSON-LD", "jsonld"); } }); /** * Query results of this RDFService can be saved to these file formats. * Map keys should always be upper case. * Map values correspond to the file extensions that will be used to save the query results. */ public static final Map<String, String> QUERY_RESULT_FILE_FORMATS = Collections.unmodifiableMap(new HashMap<String, String>(0) { { put("CSV", "csv"); } }); /** * Access to the main LOGGER. */ private static final Logger LOGGER = Logger.getLogger(RDFService.class.getName()); /** * Open an RDF file, load the data and return the RDF model. Method will not check, * if the file is actually a valid RDF file or if the file extension matches * the content of the file. * @param fileName Path and filename of a valid RDF file. * @return Model created from the data within the provided RDF file. */ public static Model openModelFromFile(final String fileName) { return RDFDataMgr.loadModel(fileName); } /** * Method tries to open a supported file, testing if it is a valid RDF file. * The implementation of the method is implemented as it is, since Jena's RDFDataMgr.loadModel does * not close a file stream properly, if the content type of a file cannot be determined. Only after the * program is closed, the file will be accessible again. Maybe this issue will be resolved in * a later Apache Jena version. * @param uri Uri of the file to be checked. * @return True if file can be parsed as RDF or false if not. */ public static boolean isValidRdfFile(final String uri) { final Model m = ModelFactory.createDefaultModel(); final String base = SysRIOT.chooseBaseIRI(uri); final Lang hintLang = RDFLanguages.filenameToLang(uri); final Context context = null; final StreamRDF dest = StreamRDFLib.graph(m.getGraph()); TypedInputStream in = null; try { in = RDFDataMgr.open(uri, context); if (in == null) { throw new RiotException(String.join("", "Not found: ", uri)); } final ContentType ct = WebContent.determineCT(in.getContentType(), hintLang, base); if (ct == null) { throw new RiotException( String.join("", "Failed to determine the content type: (URI=", base, " : stream=", in.getContentType(), ")" )); } final Lang lang = RDFLanguages.contentTypeToLang(ct); ReaderRIOT reader = null; if (lang != null) { final ReaderRIOTFactory r = RDFParserRegistry.getFactory(lang); if (r != null) { reader = r.create(lang); } } if (reader == null) { throw new RiotException( String.join("", "No parser registered for content type: ", ct.getContentType())); } reader.read(in, base, ct, dest, context); IO.close(in); } catch (RiotException e) { IO.close(in); RDFService.LOGGER.error( String.join("", "Failed to load file '", uri, "'. Ensure it is a valid RDF file.", "\n\t\tActual error message: ", e.getMessage())); return false; } return true; } /** * Write an RDF model to an output file using an RDF file format supported by this tool, specified * in {@link RDFService#RDF_FORMAT_MAP}. * This method will overwrite any files with the same path and filename. * @param fileName Path and filename of the output file. * @param model RDF model that's supposed to be written to the file. * @param format Output format of the RDF file. */ public static void saveModelToFile(final String fileName, final Model model, final String format) { final File file = new File(fileName); try { final FileOutputStream fos = new FileOutputStream(file); RDFService.LOGGER.info( String.join( "", "Writing data to RDF file '", fileName, "' using format '", format, "'" ) ); if (RDFService.RDF_FORMAT_MAP.containsKey(format)) { RDFDataMgr.write(fos, model, RDFService.RDF_FORMAT_MAP.get(format)); } else { RDFService.LOGGER.error( String.join("", "Error when saving output file: output format '", format, "' is not supported.") ); } try { fos.close(); } catch (IOException e) { RDFService.LOGGER.error("Error closing file stream."); e.printStackTrace(); } } catch (FileNotFoundException exc) { RDFService.LOGGER.error(String.join("", "Could not open output file ", fileName)); } } /** * Helper method saving a JENA RDF {@link ResultSet} to an output file in a specified output format. * @param result JENA RDF {@link ResultSet} that will be saved. * @param resultFileFormat String containing a {@link #QUERY_RESULT_FILE_FORMATS} entry. * @param fileName String containing Path and Name of the file the results are written to. */ public static void saveResultsToSupportedFile(final ResultSet result, final String resultFileFormat, final String fileName) { final String resFileFormat = resultFileFormat.toUpperCase(Locale.ENGLISH); if (QUERY_RESULT_FILE_FORMATS.containsKey(resFileFormat)) { final String fileExt = QUERY_RESULT_FILE_FORMATS.get(resFileFormat); final String outFile = !FileService.checkFileExtension(fileName, fileExt.toUpperCase(Locale.ENGLISH)) ? String.join("", fileName, ".", fileExt) : fileName; try { final File file = new File(outFile); if (!file.exists()) { file.createNewFile(); } final FileOutputStream fop = new FileOutputStream(file); RDFService.LOGGER.info(String.join("", "Write query to file...\t\t(", outFile, ")")); if ("CSV".equals(resFileFormat)) { ResultSetFormatter.outputAsCSV(fop, result); } fop.flush(); fop.close(); } catch (IOException e) { RDFService.LOGGER.error(String.join("", "Cannot write to file...\t\t(", outFile, ")")); RDFService.LOGGER.error(e.getMessage()); e.printStackTrace(); } } else { RDFService.LOGGER.error( String.join("", "Output file format ", resultFileFormat, " is not supported by this service.") ); } } }
package org.iskycode.jeesky.sys.dao; import org.hibernate.FlushMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.stereotype.Component; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Map; /** * @author phoenix * * @param <T> * * */ @Component public class BaseDao<T> { @Autowired SessionFactory sf; @Autowired private HibernateTemplate hibernateTemplate; @Autowired private JdbcTemplate jdbcTemplate; /** * java * * @param * @return Class<?> */ public Class<?> getEntityClass() { Type genType = getClass().getGenericSuperclass(); Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); return (Class<?>) params[0]; } public Object save(Object entity) { getSession().getTransaction().begin(); Object obj = getSession().save(entity); getSession().getTransaction().commit(); return obj; } public void update(Object entity) { getSession().getTransaction().begin(); getSession().update(entity); getSession().getTransaction().commit(); } public void saveOrUpdate(Object entity) { getSession().getTransaction().begin(); getSession().saveOrUpdate(entity); getSession().getTransaction().commit(); } public void merge(Object entity) { getSession().getTransaction().begin(); getSession().merge(entity); getSession().getTransaction().commit(); } public void delete(Object entity) { getSession().getTransaction().begin(); getSession().delete(entity); getSession().getTransaction().commit(); } public void flush() { getSession().flush(); } public void clear() { getSession().clear(); } @SuppressWarnings("deprecation") public Session getSession() { sf.getCurrentSession().setFlushMode(FlushMode.AUTO); return sf.getCurrentSession(); } public Object load(String id) { return hibernateTemplate.load(getEntityClass(), id); } @SuppressWarnings("unchecked") public List<T> loadAll() { return hibernateTemplate.loadAll((Class<T>) getEntityClass()); } public List<?> find(String sql, Object... params) { return hibernateTemplate.find(sql, params); } public List<T> findByExample(T entity) { return hibernateTemplate.findByExample(entity); } @SuppressWarnings("rawtypes") public Map queryForMap(String sql) { return jdbcTemplate.queryForMap(sql); } @SuppressWarnings("rawtypes") public List queryForList(String sql) { return jdbcTemplate.queryForList(sql); } public void execute(String sql) { jdbcTemplate.execute(sql); } public int[] batchUpdate() { return jdbcTemplate.batchUpdate(); } }
package org.jboss.modules; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.SecureClassLoader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Queue; import java.util.Set; /** * @author <a href="mailto:jbailey@redhat.com">John Bailey</a> * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ModuleClassLoader extends SecureClassLoader { private static final boolean debugDefines; static { try { final Method method = ClassLoader.class.getMethod("registerAsParallelCapable"); method.invoke(null); } catch (Exception e) { // ignore } debugDefines = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { return Boolean.valueOf(System.getProperty("jboss.modules.debug.defineClass", "false")); } }).booleanValue(); } private final Module module; private final Set<Module.Flag> flags; ModuleClassLoader(final Module module, final Set<Module.Flag> flags, final AssertionSetting setting) { this.module = module; this.flags = flags; if (setting != AssertionSetting.INHERIT) { setDefaultAssertionStatus(setting == AssertionSetting.ENABLED); } } @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { return loadClass(name, false); } @Override protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { Class<?> loadedClass = loadClassInternal(className); if (resolve) resolveClass(loadedClass); return loadedClass; } protected Class<?> loadClassInternal(String className) throws ClassNotFoundException { return performLoadClass(className, false); } protected Class<?> loadClassExternal(String className) throws ClassNotFoundException { return performLoadClass(className, true); } private Class<?> performLoadClass(String className, boolean exportsOnly) throws ClassNotFoundException { if (className == null) { throw new IllegalArgumentException("name is null"); } if (className.startsWith("java.")) { // always delegate to system return findSystemClass(className); } if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, exportsOnly, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (LoaderThreadHolder.REQUEST_QUEUE) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } else { // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { return loadedClass; } final Set<Module.Flag> flags = this.flags; if (flags.contains(Module.Flag.CHILD_FIRST)) { loadedClass = loadClassLocal(className); if (loadedClass == null) { loadedClass = module.getImportedClass(className, exportsOnly); } if (loadedClass == null) { loadedClass = findSystemClass(className); } } else { loadedClass = module.getImportedClass(className, exportsOnly); if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } if (loadedClass == null) { loadedClass = loadClassLocal(className); } } if (loadedClass == null) { throw new ClassNotFoundException(className + " from [" + module+ "]"); } return loadedClass; } } private Class<?> loadClassLocal(String name) throws ClassNotFoundException { // Check to see if we can load it ClassSpec classSpec = null; try { classSpec = module.getLocalClassSpec(name); } catch (IOException e) { throw new ClassNotFoundException(name, e); } catch (RuntimeException e) { System.err.print("Unexpected runtime exception in module loader: "); e.printStackTrace(System.err); throw new ClassNotFoundException(name, e); } catch (Error e) { System.err.print("Unexpected error in module loader: "); e.printStackTrace(System.err); throw new ClassNotFoundException(name, e); } if (classSpec == null) return null; return defineClass(name, classSpec); } private Class<?> defineClass(final String name, final ClassSpec classSpec) { // Ensure that the package is loaded final int lastIdx = name.lastIndexOf('.'); if (lastIdx != -1) { // there's a package name; get the Package for it final String packageName = name.substring(0, lastIdx); final Package pkg = getPackage(packageName); if (pkg != null) { // Package is defined already if (pkg.isSealed() && ! pkg.isSealed(classSpec.getCodeSource().getLocation())) { // use the same message as the JDK throw new SecurityException("sealing violation: package " + packageName + " is sealed"); } } else { final PackageSpec spec; try { spec = getModule().getLocalPackageSpec(name); definePackage(packageName, spec); } catch (IOException e) { definePackage(packageName, null); } } } final Class<?> newClass; try { final byte[] bytes = classSpec.getBytes(); newClass = defineClass(name, bytes, 0, bytes.length, classSpec.getCodeSource()); } catch (Error e) { if (debugDefines) System.err.println("Failed to define class '" + name + "': " + e); throw e; } catch (RuntimeException e) { if (debugDefines) System.err.println("Failed to define class '" + name + "': " + e); throw e; } final AssertionSetting setting = classSpec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setClassAssertionStatus(name, setting == AssertionSetting.ENABLED); } return newClass; } private Package definePackage(final String name, final PackageSpec spec) { if (spec == null) { return definePackage(name, null, null, null, null, null, null, null); } else { final Package pkg = definePackage(name, spec.getSpecTitle(), spec.getSpecVersion(), spec.getSpecVendor(), spec.getImplTitle(), spec.getImplVersion(), spec.getImplVendor(), spec.getSealBase()); final AssertionSetting setting = spec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setPackageAssertionStatus(name, setting == AssertionSetting.ENABLED); } return pkg; } } @Override protected String findLibrary(final String libname) { return module.getLocalLibrary(libname); } @Override public URL getResource(String name) { final Resource resource = module.getExportedResource(name); return resource == null ? null : resource.getURL(); } @Override public Enumeration<URL> getResources(String name) throws IOException { final Iterable<Resource> resources = module.getExportedResources(name); final Iterator<Resource> iterator = resources.iterator(); return new Enumeration<URL>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public URL nextElement() { return iterator.next().getURL(); } }; } @Override public InputStream getResourceAsStream(final String name) { try { final Resource resource = module.getExportedResource(name); return resource == null ? null : resource.openStream(); } catch (IOException e) { return null; } } /** * Get the module for this class loader. * * @return the module */ public Module getModule() { return module; } public String toString() { return "ClassLoader for " + module; } public static ModuleClassLoader forModule(ModuleIdentifier identifier) throws ModuleLoadException { return Module.getModule(identifier).getClassLoader(); } public static ModuleClassLoader forModuleName(String identifier) throws ModuleLoadException { return forModule(ModuleIdentifier.fromString(identifier)); } public static ModuleClassLoader createAggregate(String identifier, List<String> dependencies) throws ModuleLoadException { List<ModuleIdentifier> depModuleIdentifiers = new ArrayList<ModuleIdentifier>(dependencies.size()); for(String dependencySpec : dependencies) { depModuleIdentifiers.add(ModuleIdentifier.fromString(dependencySpec)); } return InitialModuleLoader.INSTANCE.createAggregate(ModuleIdentifier.fromString(identifier), depModuleIdentifiers).getClassLoader(); } private static final class LoaderThreadHolder { private static final Thread LOADER_THREAD; private static final Queue<LoadRequest> REQUEST_QUEUE = new ArrayDeque<LoadRequest>(); static { Thread thr = new LoaderThread(); thr.setName("ModuleClassLoader Thread"); // This thread will always run as long as the VM is alive. thr.setDaemon(true); thr.start(); LOADER_THREAD = thr; } private LoaderThreadHolder() { } } static class LoadRequest { private final String className; private final ModuleClassLoader requester; private Class<?> result; private boolean exportsOnly; private boolean done; public LoadRequest(final String className, final boolean exportsOnly, final ModuleClassLoader requester) { this.className = className; this.exportsOnly = exportsOnly; this.requester = requester; } } static class LoaderThread extends Thread { @Override public void interrupt() { // no interruption } @Override public void run() { /* This resolves a know deadlock that can occur if one thread is in the process of defining a package as part of defining a class, and another thread is defining the system package that can result in loading a class. One holds the Package.pkgs lock and one holds the Classloader lock. */ Package.getPackages(); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; for (; ;) { try { LoadRequest request; synchronized (queue) { while ((request = queue.poll()) == null) { queue.wait(); } } final ModuleClassLoader loader = request.requester; Class<?> result = null; synchronized (loader) { try { result = loader.performLoadClass(request.className, request.exportsOnly); } finally { // no matter what, the requester MUST be notified request.result = result; request.done = true; loader.notifyAll(); } } } catch (Throwable t) { // ignore } } } } }
package org.jpmml.xgboost; import java.util.LinkedHashMap; import java.util.Map; import org.jpmml.converter.HasOptions; public interface HasXGBoostOptions extends HasOptions { String OPTION_BYTE_ORDER = "byte_order"; String OPTION_CHARSET = "charset"; String OPTION_COMPACT = "compact"; String OPTION_NTREE_LIMIT = "ntree_limit"; default public Map<String, ?> xgboostOptions(){ Map<String, Object> result = new LinkedHashMap<>(); result.put(HasXGBoostOptions.OPTION_COMPACT, Boolean.FALSE); return result; } }
package org.lantern.util; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.params.CoreConnectionPNames; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements an HTTP Get using host spoofing. */ public class HostSpoofedHTTPGet { private static final Logger LOGGER = LoggerFactory .getLogger(HostSpoofedHTTPGet.class); private final HttpClient client; private final String realHost; private final HttpHost masqueradeHost; public HostSpoofedHTTPGet(HttpClient client, String realHost, String masqueradeHost) { this.client = client; this.realHost = realHost; this.masqueradeHost = new HttpHost(masqueradeHost,443, "https"); } public <T> T get(String path, ResponseHandler<T> handler) { Exception finalException = null; // Try the request with all available masquerade hosts until one // succeeds. try { return doGet(masqueradeHost, path, handler); } catch (Exception e) { LOGGER.warn( "Caught exception using masqueradeHost {}, could mean that it's blocked: {}", masqueradeHost, e.getMessage(), e); finalException = e; } // None of the requests worked, handle the exception return handler.onException(finalException); } private <T> T doGet(HttpHost host, String path, ResponseHandler<T> handler) throws Exception { HttpGet request = new HttpGet(path); LOGGER.info("Seeing host header to {}", realHost); request.setHeader("Host", realHost); try { request.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); request.getParams().setParameter( ClientPNames.HANDLE_REDIRECTS, false); // Ignore cookies because host spoofing will return cookies that // don't match the requested domain request.getParams().setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); // Unable to set SO_TIMEOUT because of bug in Java 7 // request.getParams().setParameter( // CoreConnectionPNames.SO_TIMEOUT, 60000); return handler.onResponse(client .execute(host, request)); } finally { request.releaseConnection(); } } public static interface ResponseHandler<T> { T onResponse(HttpResponse response) throws Exception; T onException(Exception e); } }
package org.lightmare.utils; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Utility class to work with {@link Collection} instances * * @author Levan * */ public class CollectionUtils { public static final int FIRST_INDEX = 0; /** * Creates new {@link Set} from passed {@link Collection} instance * * @param collection * @return {@link Set}<code><T></code> */ public static <T> Set<T> translateToSet(Collection<T> collection) { Set<T> set; if (ObjectUtils.available(collection)) { set = new HashSet<T>(collection); } else { set = Collections.emptySet(); } return set; } /** * Creates new {@link Set} from passed array instance * * @param array * @return {@link Set}<code><T></code> */ public static <T> Set<T> translateToSet(T[] array) { List<T> collection; if (ObjectUtils.available(array)) { collection = Arrays.asList(array); } else { collection = null; } return translateToSet(collection); } /** * Creates new {@link List} from passed {@link Collection} instance * * @param collection * @return {@link List}<code><T></code> */ public static <T> List<T> translateToList(Collection<T> collection) { List<T> list; if (ObjectUtils.available(collection)) { list = new ArrayList<T>(collection); } else { list = Collections.emptyList(); } return list; } private static <T> T[] toArray(Class<T> type, int size) { Object arrayObject = Array.newInstance(type, size); T[] array = ObjectUtils.cast(arrayObject); return array; } /** * Checks if passed {@link Object} is array * * @param data * @return <code>boolean</code> */ public static boolean isArray(final Object data) { boolean valid = (data instanceof Object[] || data instanceof boolean[] || data instanceof byte[] || data instanceof short[] || data instanceof char[] || data instanceof int[] || data instanceof long[] || data instanceof float[] || data instanceof double[]); return valid; } /** * Checks if passed {@link Object} is {@link Object} types array * * @param data * @return <code>boolean</code> */ public static boolean isObjectArray(final Object data) { boolean valid = (data instanceof Object[]); return valid; } /** * Checks if passed {@link Object} is primitive types array * * @param data * @return <code>boolean</code> */ public static boolean isPrimitiveArray(final Object data) { boolean valid = (data instanceof boolean[] || data instanceof byte[] || data instanceof short[] || data instanceof char[] || data instanceof int[] || data instanceof long[] || data instanceof float[] || data instanceof double[]); return valid; } /** * Converts passed {@link Collection} to array of appropriated {@link Class} * type * * @param collection * @param type * @return <code>T[]</code> */ public static <T> T[] toArray(Collection<T> collection, Class<T> type) { T[] array; if (ObjectUtils.notNull(collection)) { array = toArray(type, collection.size()); array = collection.toArray(array); } else { array = null; } return array; } /** * Creates empty array of passed type * * @param type * @return <code>T[]</code> */ public static <T> T[] emptyArray(Class<T> type) { T[] empty = toArray(type, ObjectUtils.EMPTY_ARRAY_LENGTH); return empty; } /** * Peaks first element from list * * @param list * @return T */ private static <T> T getFirstFromList(List<T> list) { T value; if (ObjectUtils.available(list)) { value = list.get(FIRST_INDEX); } else { value = null; } return value; } /** * Peaks first element from collection * * @param collection * @return T */ public static <T> T getFirst(Collection<T> collection) { T value; if (ObjectUtils.available(collection)) { if (collection instanceof List) { value = getFirstFromList(((List<T>) collection)); } else { Iterator<T> iterator = collection.iterator(); value = iterator.next(); } } else { value = null; } return value; } /** * Peaks first element from array * * @param collection * @return T */ public static <T> T getFirst(T[] values) { T value; if (ObjectUtils.available(values)) { value = values[FIRST_INDEX]; } else { value = null; } return value; } }
package org.neo4j.server.osgi; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.felix.framework.Felix; import org.apache.felix.framework.util.FelixConstants; import org.apache.felix.main.AutoProcessor; import org.neo4j.server.logging.Logger; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.launch.Framework; /** * Container for an embedded OSGi framework. */ public class OSGiContainer { public static final String DEFAULT_BUNDLE_DIRECTORY = "bundles"; public static final String DEFAULT_CACHE_DIRECTORY = "cache"; private Framework osgiFramework; private HostBridge bridge; private Logger log = Logger.getLogger( OSGiContainer.class ); private String bundleDirectory; public OSGiContainer( String bundleDirectory, String cacheDirectory ) { this.bundleDirectory = bundleDirectory; Map<String, Object> configMap = new HashMap<String, Object>(); bridge = new HostBridge(); List<HostBridge> list = new ArrayList<HostBridge>(); list.add( bridge ); configMap.put( FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list ); configMap.put( Constants.FRAMEWORK_STORAGE, cacheDirectory ); configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "host.service.command; version=1.0.0"); osgiFramework = new Felix( configMap ); File bundleDirectoryAsFile = new File( bundleDirectory ); if ( !bundleDirectoryAsFile.exists() ) { bundleDirectoryAsFile.mkdirs(); } } public OSGiContainer() { this( DEFAULT_BUNDLE_DIRECTORY, DEFAULT_CACHE_DIRECTORY ); } public void start() throws BundleException { log.info( "Starting OSGi container..." ); osgiFramework.init(); Map<String, String> autoConfig = new HashMap<String, String>(); log.info( "Loading bundles from: " + new File( bundleDirectory ).getAbsolutePath() ); autoConfig.put( AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDirectory ); autoConfig.put( AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY, AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE + "," + AutoProcessor.AUTO_DEPLOY_START_VALUE ); AutoProcessor.process( autoConfig, osgiFramework.getBundleContext() ); osgiFramework.start(); for ( Bundle b : bridge.getBundles() ) { logBundleState( b ); } log.info( "OSGi is ready." ); } public Framework getFramework() { return osgiFramework; } private void logBundleState( Bundle b ) { String bundleName = b.getSymbolicName(); if ( bundleName == null ) bundleName = b.getLocation(); String state = "unknown"; switch ( b.getState() ) { case Bundle.ACTIVE: state = "active"; break; case Bundle.INSTALLED: state = "installed"; break; case Bundle.RESOLVED: state = "resolved"; break; } log.info( "\t" + state + " " + bundleName ); } public Bundle[] getBundles() { return bridge.getBundles(); } public void shutdown() throws BundleException, InterruptedException { osgiFramework.stop(); osgiFramework.waitForStop( 0 ); } public String getBundleDirectory() { return bundleDirectory; } }
package org.osiam.client.query; import org.osiam.client.exception.InvalidAttributeException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; /** * The QueryBuilder provides a fluent api to help building queries against the OSIAM Service. */ public class QueryBuilder { static final private int DEFAULT_START_INDEX = 0; static final private int DEFAULT_COUNT_PER_PAGE = 100; private Class clazz; private StringBuilder filter; private SortOrder sortOrder; private int startIndex = DEFAULT_START_INDEX; private int countPerPage = DEFAULT_COUNT_PER_PAGE; /** * The Constructor of the QueryBuilder * * @param clazz The class of Resources to query for. */ public QueryBuilder(Class clazz) { filter = new StringBuilder(); this.clazz = clazz; } /** * Add a filter on the given Attribute. * * @param attributeName The name of the attribute to filter on. * @return A {@link QueryBuilder.Filter} to specify the filtering criteria * @throws InvalidAttributeException if the given attribute is not valid for a query */ public Filter filter(String attributeName) { return query(attributeName); } /** * Add an 'logical and' operation to the filter with another attribute to filter on. * * @param attributeName The name of the attribute to filter the and clause on. * @return A {@link QueryBuilder.Filter} to specify the filtering criteria * @throws InvalidAttributeException if the given attribute is not valid for a query */ public Filter and(String attributeName) { filter.append(" and "); return query(attributeName); } /** * Adds the query of the given QueryBuilder into ( and ) to the filter * @param innerFilter the inner filter * @return The QueryBuilder with the inner filter added. */ public QueryBuilder and(QueryBuilder innerFilter){ filter.append(" and (").append(innerFilter.build().toString().replaceFirst("filter=", "")).append(")"); return this; } /** * Add an 'logical or' operation to the filter with another attribute to filter on. * * @param attributeName The name of the attribute to filter the or clause on. * @return A {@link QueryBuilder.Filter} to specify the filtering criteria * @throws InvalidAttributeException if the given attribute is not valid for a query */ public Filter or(String attributeName) { filter.append(" or "); return query(attributeName); } private Filter query(String attributeName) { if (!(isAttributeValid(attributeName))) { throw new InvalidAttributeException("Querying for this attribute is not supported"); } filter.append(attributeName); return new Filter(this); } /** * Adds the query of the given QueryBuilder into ( and ) to the filter * @param innerFilter the inner filter * @return The QueryBuilder with the inner filter added. */ public QueryBuilder or(QueryBuilder innerFilter){ filter.append(" or (").append(innerFilter.build().toString().replaceFirst("filter=", "")).append(")"); return this; } /** * Adds the given {@link SortOrder} to the query * * @param sortOrder The order in which to sort the result * @return The QueryBuilder with this sort oder added. */ public QueryBuilder withSortOrder(SortOrder sortOrder) { this.sortOrder = sortOrder; return this; } /** * Add the start Index from where on the list will be returned to the query * * @param startIndex The position to use as the first entry in the result. * @return The QueryBuilder with this start Index added. */ public QueryBuilder startIndex(int startIndex) { this.startIndex = startIndex; return this; } /** * Add the number of wanted results per page to the query * * @param count The number of items displayed per page. * @return The QueryBuilder with this count per page added. */ public QueryBuilder countPerPage(int count) { this.countPerPage = count; return this; } /** * Build the query String to use against OSIAM. * * @return The query as a String */ public Query build() { StringBuilder builder = new StringBuilder(); if (filter.length() != 0) { ensureQueryParamIsSeparated(builder); builder.append("filter=") .append(filter); } if (sortOrder != null) { ensureQueryParamIsSeparated(builder); builder.append("sortOrder=") .append(sortOrder); } if (countPerPage != DEFAULT_COUNT_PER_PAGE) { ensureQueryParamIsSeparated(builder); builder.append("count=") .append(countPerPage); } if (startIndex != DEFAULT_START_INDEX) { ensureQueryParamIsSeparated(builder); builder.append("startIndex=") .append(startIndex); } return new Query(builder.toString()); } private void ensureQueryParamIsSeparated(StringBuilder builder) { if (builder.length() != 0) { builder.append("&"); } } private boolean isAttributeValid(String attribute) { return isAttributeValid(attribute, clazz); } private boolean isAttributeValid(String attribute, Class clazz) { String compositeField = ""; if (attribute.contains(".")) { compositeField = attribute.substring(attribute.indexOf('.') + 1); } if (attribute.startsWith("meta.")) { return isAttributeValid(compositeField, org.osiam.resources.scim.Meta.class); } if (attribute.startsWith("emails.")) { return isAttributeValid(compositeField, org.osiam.resources.scim.MultiValuedAttribute.class); } if (attribute.startsWith("name.")) { return isAttributeValid(compositeField, org.osiam.resources.scim.Name.class); } for (Field field : clazz.getDeclaredFields()) { if (Modifier.isPrivate(field.getModifiers()) && field.getName().equalsIgnoreCase(attribute)) { return true; } } return false; } /** * A Filter is used to produce filter criteria for the query. At this point the conditions are mere strings. * This is going to change. */ public class Filter { private QueryBuilder qb; private Filter(QueryBuilder queryBuilder) { this.qb = queryBuilder; } private QueryBuilder addFilter(String filter, String condition) { qb.filter.append(filter); if (condition != null && condition.length() > 0) { qb.filter.append("\""). append(condition). append("\""); } return qb; } /** * Add a condition the attribute filtered for is equal to. * * @param condition The condition to meet. * @return The QueryBuilder with this filter added. */ public QueryBuilder equalTo(String condition) { return addFilter(" eq ", condition); } /** * Add a condition the attribute filtered on should contain. * * @param condition The condition to meet. * @return The QueryBuilder with this filter added. */ public QueryBuilder contains(String condition) { return addFilter(" co ", condition); } /** * Add a condition the attribute filtered on should contain. * * @param condition The condition to meet. * @return The QueryBuilder with this filter added. */ public QueryBuilder startsWith(String condition) { return addFilter(" sw ", condition); } /** * Make sure that the attribute for this filter is present. * * @return The QueryBuilder with this filter added. */ public QueryBuilder present() { return addFilter(" pr ", ""); } /** * Add a condition the attribute filtered on should be greater than. * * @param condition The condition to meet. * @return The QueryBuilder with this filter added. */ public QueryBuilder greaterThan(String condition) { return addFilter(" gt ", condition); } /** * Add a condition the attribute filtered on should be greater than or equal to. * * @param condition The condition to meet. * @return The QueryBuilder with this filter added. */ public QueryBuilder greaterEquals(String condition) { return addFilter(" ge ", condition); } /** * Add a condition the attribute filtered on should be less than. * * @param condition The condition to meet. * @return The QueryBuilder with this filter added. */ public QueryBuilder lessThan(String condition) { return addFilter(" lt ", condition); } /** * Add a condition the attribute filtered on should be less than or equal to. * * @param condition The condition to meet. * @return The QueryBuilder with this filter added. */ public QueryBuilder lessEquals(String condition) { return addFilter(" le ", condition); } } }
package org.pilgrim.hiredintech; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Scanner; public class GravityTree { static Map<Long, TreeNode> map = new HashMap<>(); public static TreeNode buildTree(long[] a) { TreeNode root = null; for (int i = 0; i < a.length; i++) { long val = a[i]; TreeNode treeNode = map.get(val); if (null == treeNode) { treeNode = new TreeNode(); treeNode.val = val; map.put(val, treeNode); } long childVal = i + 2; TreeNode treeChild = map.get(childVal); if (null == treeChild) { treeChild = new TreeNode(); treeChild.val = childVal; map.put(childVal, treeChild); } if (null != treeNode) { treeNode.add(treeChild); } root = treeNode; } while (null != root && null != root.parent) { root = root.parent; } return root; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long[] a = new long[n - 1]; for (int i = 0; i < n - 1; i++) { a[i] = in.nextLong(); } int q = in.nextInt(); long[][] exp = new long[q][2]; for (int i = 0; i < q; i++) { exp[i][0] = in.nextLong(); exp[i][1] = in.nextLong(); } in.close(); TreeNode root = buildTree(a); for (int i = 0; i < exp.length; i++) { long u = exp[i][0]; long v = exp[i][1]; long forces = 0; TreeNode nodeV = map.get(v); TreeNode nodeU = map.get(u); nodeV.on(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(nodeV); while (!queue.isEmpty()) { TreeNode from = queue.poll(); queue.addAll(from.children); long distance = getDistance(from, nodeU); forces += distance * distance; } System.out.println(forces); nodeV.off(); } } private static long getDistance(TreeNode from, TreeNode nodeU) { Long d1 = from.distance.get(nodeU.val); if (null != d1) { nodeU.distance.putIfAbsent(from.val, d1); return d1.longValue(); } Long d2 = nodeU.distance.get(from.val); if (null != d2) { from.distance.putIfAbsent(nodeU.val, d1); return d2.longValue(); } long height1 = getHeight(from); long height2 = getHeight(nodeU); long diff = height1 - height2; if (diff < 0) { diff = Math.abs(diff); nodeU = rise(nodeU, diff); } else if (diff > 0) { diff = Math.abs(diff); from = rise(from, diff); } diff = Math.abs(diff); while (from != nodeU) { from = from.parent; nodeU = nodeU.parent; diff += 2; } nodeU.distance.put(from.val, diff); from.distance.put(nodeU.val, diff); return diff; } private static TreeNode rise(TreeNode from, long diff) { for (int i = 0; i < diff; i++) { from = from.parent; } return from; } private static long getHeight(TreeNode from) { long height = 0; if (null != from && null != from.height) { return from.height.longValue(); } while (null != from && null != from.parent) { from = from.parent; height++; if (null != from.height) { return from.height.longValue() + height; } } return height; } } class TreeNode { Map<Long, Long> distance = new HashMap<>(); List<TreeNode> children = new ArrayList<>(); TreeNode parent = null; long val; boolean on = false; Long height; public boolean isOn() { return on; } public void on() { this.on = true; } public void off() { this.on = false; } public TreeNode add(TreeNode treeNode) { children.add(treeNode); treeNode.parent = this; return this; } }
package org.smoothbuild.vm.compute; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import org.smoothbuild.vm.job.algorithm.Output; public record Computed(Output output, Exception exception, ResSource resSource) { public Computed(Output output, ResSource resSource) { this(output, null, resSource); } public Computed(Exception exception, ResSource resSource) { this(null, exception, resSource); } public Computed(Output output, Exception exception, ResSource resSource) { this.output = output; this.exception = exception; this.resSource = requireNonNull(resSource); checkArgument(output == null ^ exception == null); } public boolean hasOutput() { return output != null; } public boolean hasOutputWithValue() { return output != null && output.hasValue(); } }
package org.spongepowered.api.plugin; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.regex.Pattern; /** * An annotation used to describe and mark a Sponge plugin. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Plugin { /** * @deprecated Moved to plugin-meta project */ @Deprecated Pattern ID_PATTERN = Pattern.compile("[a-z][a-z0-9-_.]*"); String id(); /** * The human readable name of the plugin as to be used in descriptions and * similar things. * * @return The plugin name, or an empty string if unknown */ String name() default ""; /** * The version of the plugin. * * @return The plugin version, or an empty string if unknown */ String version() default ""; /** * The dependencies required to load <strong>before</strong> this plugin. * * @return The plugin dependencies */ Dependency[] dependencies() default {}; /** * The description of the plugin, explaining what it can be used for. * * @return The plugin description, or an empty string if unknown */ String description() default ""; /** * The URL or website of the plugin. * * @return The plugin url, or an empty string if unknown */ String url() default ""; /** * The authors of the plugin. * * @return The plugin authors, or empty if unknown */ String[] authors() default {}; /** * The directory within the plugin's JAR file that contains this plugin's * assets. This directory defaults to: * * <p><code>assets/&lt;id&gt;</code> where 'ID' is the plugin's fully * qualified ID with all '.'s replaced with '/'s to more fit a directory * structure.</p> * * @return Asset directory */ String assets() default ""; }
package org.spongepowered.mod; import net.minecraft.launchwrapper.Launch; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.relauncher.FMLInjectionData; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.Mixins; import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider; import org.spongepowered.common.launch.SpongeLaunch; import org.spongepowered.common.launch.transformer.tracker.TrackerRegistry; import org.spongepowered.launch.JavaVersionCheckUtils; import java.io.File; import java.lang.reflect.Field; import java.util.Map; @IFMLLoadingPlugin.MCVersion("1.12.2") public class SpongeCoremod implements IFMLLoadingPlugin { static File modFile; public static final class TokenProvider implements IEnvironmentTokenProvider { @Override public int getPriority() { return IEnvironmentTokenProvider.DEFAULT_PRIORITY; } @Override public Integer getToken(String token, MixinEnvironment env) { if ("FORGE".equals(token)) { return Integer.valueOf(ForgeVersion.getBuildVersion()); } else if ("FML".equals(token)) { String fmlVersion = Loader.instance().getFMLVersionString(); int build = Integer.parseInt(fmlVersion.substring(fmlVersion.lastIndexOf('.') + 1)); return Integer.valueOf(build); } return null; } } public SpongeCoremod() { // This MUST be the first line in the constructor, to prevent // JavaVersionCheckUtils from being passed through the transformer // chain, and thereby triggering Mixin to switch to PREINIT. Launch.classLoader.addTransformerExclusion("org.spongepowered.launch.JavaVersionCheckUtils"); try { // Note: This is still needed because it checks if at least Java 8u40 is installed JavaVersionCheckUtils.ensureJava8(); } catch (Exception e) { e.printStackTrace(); this.clearSecurityManager(); Runtime.getRuntime().exit(1); } SpongeLaunch.addJreExtensionsToClassPath(); Launch.classLoader.addClassLoaderExclusion("org.spongepowered.common.launch."); Launch.classLoader.addClassLoaderExclusion("org.slf4j."); // Let's get this party started SpongeLaunch.initPaths((File) FMLInjectionData.data()[6]); // 6 = game dir SpongeLaunch.setupMixinEnvironment(); // Detect dev/production env if (this.isProductionEnvironment()) { Mixins.registerErrorHandlerClass("org.spongepowered.mod.mixin.handler.MixinErrorHandler"); } Mixins.addConfiguration("mixins.forge.core.json"); Mixins.addConfiguration("mixins.forge.bungeecord.json"); Mixins.addConfiguration("mixins.forge.entityactivation.json"); MixinEnvironment.getDefaultEnvironment().registerTokenProviderClass("org.spongepowered.mod.SpongeCoremod$TokenProvider"); // Add pre-init mixins Mixins.addConfiguration("mixins.forge.preinit.json"); MixinEnvironment.getEnvironment(Phase.PREINIT).registerTokenProviderClass("org.spongepowered.mod.SpongeCoremod$TokenProvider"); Mixins.addConfiguration("mixins.forge.init.json"); MixinEnvironment.getEnvironment(Phase.INIT).registerTokenProviderClass("org.spongepowered.mod.SpongeCoremod$TokenProvider"); Launch.classLoader.addClassLoaderExclusion("org.spongepowered.api.event.Cancellable"); Launch.classLoader.addClassLoaderExclusion("org.spongepowered.api.eventgencore.annotation.PropertySettings"); Launch.classLoader.addClassLoaderExclusion("org.spongepowered.api.util.ResettableBuilder"); // Transformer exclusions Launch.classLoader.addTransformerExclusion("ninja.leaping.configurate."); Launch.classLoader.addTransformerExclusion("org.apache.commons.lang3."); Launch.classLoader.addTransformerExclusion("org.spongepowered.mod.interfaces.IMixinEvent"); Launch.classLoader.addTransformerExclusion("scala."); SpongeLaunch.setupSuperClassTransformer(); // Setup method tracking //TrackerRegistry.initialize(); // Setup IItemHandler and IItemHandlerModifiable method tracking //TrackerRegistry.registerTracker("org.spongepowered.mod.tracker.FluidTracker"); //TrackerRegistry.registerTracker("org.spongepowered.mod.tracker.ItemHandlerTracker"); } private boolean isProductionEnvironment() { return System.getProperty("net.minecraftforge.gradle.GradleStart.csvDir") == null; } private void clearSecurityManager() { // Nice try, FML try { Field field = System.class.getDeclaredField("security"); field.setAccessible(true); field.set(null, null); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } @Override public String[] getASMTransformerClass() { return new String[] { SpongeLaunch.SUPERCLASS_TRANSFORMER }; } @Override public String getModContainerClass() { return "org.spongepowered.mod.SpongeMod"; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { // Register SpongeAPI mod container FMLInjectionData.containers.add("org.spongepowered.mod.SpongeApiModContainer"); modFile = (File) data.get("coremodLocation"); if (modFile == null) { modFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); } } @Override public String getAccessTransformerClass() { return "org.spongepowered.mod.asm.transformer.SpongeAccessTransformer"; } }
package org.vaadin.maddon.form; import com.vaadin.ui.AbstractComponentContainer; import com.vaadin.ui.AbstractField; import com.vaadin.ui.AbstractTextField; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.UI; import com.vaadin.ui.Window; import org.vaadin.maddon.BeanBinder; import org.vaadin.maddon.MBeanFieldGroup; import org.vaadin.maddon.MBeanFieldGroup.FieldGroupListener; import org.vaadin.maddon.button.MButton; import org.vaadin.maddon.button.PrimaryButton; import org.vaadin.maddon.layouts.MHorizontalLayout; /** * Abstract super class for simple editor forms. * * @param <T> the type of the bean edited */ public abstract class AbstractForm<T> extends CustomComponent implements FieldGroupListener { public AbstractForm() { addAttachListener(new AttachListener() { @Override public void attach(AttachEvent event) { lazyInit(); } }); } protected void lazyInit() { setCompositionRoot(createContent()); adjustSaveButtonState(); adjustResetButtonState(); } private MBeanFieldGroup<T> fieldGroup; @Override public void onFieldGroupChange(MBeanFieldGroup beanFieldGroup) { adjustSaveButtonState(); adjustResetButtonState(); } protected void adjustSaveButtonState() { if (isAttached() && isEagarValidation() && isBound()) { boolean beanModified = fieldGroup.isBeanModified(); boolean valid = fieldGroup.isValid(); getSaveButton().setEnabled(beanModified && valid); } } protected boolean isBound() { return fieldGroup != null; } protected void adjustResetButtonState() { if (isAttached() && isEagarValidation() && isBound()) { boolean beanModified = fieldGroup.isBeanModified(); getResetButton().setEnabled(beanModified); } } public interface SavedHandler<T> { void onSave(T entity); } public interface ResetHandler<T> { void onReset(T entity); } private T entity; private SavedHandler<T> savedHandler; private ResetHandler<T> resetHandler; private boolean eagarValidation; public boolean isEagarValidation() { return eagarValidation; } /** * In case one is working with "detached entities" enabling eager validation * will highly improve usability. The validity of the form will be updated * on each changes and save/cancel buttons will reflect to the validity and * possible changes. * * @param eagarValidation true if the form should have eager validation */ public void setEagarValidation(boolean eagarValidation) { this.eagarValidation = eagarValidation; } public MBeanFieldGroup<T> setEntity(T entity) { this.entity = entity; if (entity != null) { if (isBound()) { fieldGroup.unbind(); } fieldGroup = BeanBinder.bind(entity, this); if (isEagarValidation()) { fieldGroup.withEagarValidation(this); adjustSaveButtonState(); adjustResetButtonState(); } setVisible(true); return fieldGroup; } else { setVisible(false); return null; } } public void setSavedHandler(SavedHandler<T> savedHandler) { this.savedHandler = savedHandler; } public void setResetHandler(ResetHandler<T> resetHandler) { this.resetHandler = resetHandler; } public ResetHandler<T> getResetHandler() { return resetHandler; } public SavedHandler<T> getSavedHandler() { return savedHandler; } public Window openInModalPopup() { Window window = new Window("Edit entry", this); window.setModal(true); UI.getCurrent().addWindow(window); focusFirst(); return window; } /** * @return A default toolbar containing save/cancel buttons */ public HorizontalLayout getToolbar() { return new MHorizontalLayout( getSaveButton(), getResetButton() ); } protected Button createCancelButton() { return new MButton("Cancel"); } private Button resetButton; public Button getResetButton() { if (resetButton == null) { setResetButton(createCancelButton()); } return resetButton; } public void setResetButton(Button resetButton) { this.resetButton = resetButton; this.resetButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { reset(event); } }); } protected Button createSaveButton() { return new PrimaryButton("Save"); } private Button saveButton; public void setSaveButton(Button saveButton) { this.saveButton = saveButton; saveButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { save(event); } }); } public Button getSaveButton() { if (saveButton == null) { setSaveButton(createSaveButton()); } return saveButton; } protected void save(Button.ClickEvent e) { savedHandler.onSave(entity); } protected void reset(Button.ClickEvent e) { resetHandler.onReset(entity); } public void focusFirst() { Component compositionRoot = getCompositionRoot(); findFieldAndFocus(compositionRoot); } private boolean findFieldAndFocus(Component compositionRoot) { if (compositionRoot instanceof AbstractComponentContainer) { AbstractComponentContainer cc = (AbstractComponentContainer) compositionRoot; for (Component component : cc) { if (component instanceof AbstractTextField) { AbstractTextField abstractTextField = (AbstractTextField) component; abstractTextField.selectAll(); return true; } if (component instanceof AbstractField) { AbstractField abstractField = (AbstractField) component; abstractField.focus(); return true; } if (component instanceof AbstractComponentContainer) { if (findFieldAndFocus(component)) { return true; } } } } return false; } /** * This method should return the actual content of the form, including * possible toolbar. * * Example implementation could look like this: <code> * public class PersonForm extends AbstractForm&lt;Person&gt; { * * private TextField firstName = new MTextField(&quot;First Name&quot;); * private TextField lastName = new MTextField(&quot;Last Name&quot;); * * \@Override * protected Component createContent() { * return new MVerticalLayout( * new FormLayout( * firstName, * lastName * ), * getToolbar() * ); * } * } * </code> * * @return the content of the form * */ protected abstract Component createContent(); }
package org.vngx.jsch.userauth; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.vngx.jsch.Buffer; import org.vngx.jsch.Util; import org.vngx.jsch.algorithm.AlgorithmManager; import org.vngx.jsch.algorithm.SignatureDSA; import org.vngx.jsch.algorithm.SignatureRSA; import org.vngx.jsch.cipher.Cipher; import org.vngx.jsch.cipher.CipherManager; import org.vngx.jsch.algorithm.Algorithms; import org.vngx.jsch.exception.JSchException; import org.vngx.jsch.hash.Hash; import org.vngx.jsch.hash.HashManager; import org.vngx.jsch.util.DataUtil; import org.vngx.jsch.util.KeyType; /** * Implementation of <code>Identity</code> for an identity key file. * * @see org.vngx.jsch.Identity * * @author Atsuhiko Yamanaka * @author Michael Laudati */ public class IdentityFile implements Identity { private static final int OPENSSH = 0; private static final int FSECURE = 1; //private static final int PUTTY = 2; /** Name of identity. */ private final String _identity; /** MD5 hash function. */ private final Hash _hash; /** Cipher (3DES-CBC or AES 256) used for encryption. */ private Cipher _cipher; /** Key value. */ private byte[] _key; /** Initialization vector for encryption. */ private byte[] _iv; private byte[] _encodedData; /** Key type for identity (RSA or DSA). */ private KeyType _keyType = null; /** Vendor type for key file (OpenSSH or FSecure). */ private int _vendor = OPENSSH; private byte[] _publicKeyBlob = null; private boolean _encrypted = true; // DSA private byte[] _pDSA; private byte[] _qDSA; private byte[] _gDSA; private byte[] _pubKeyDSA; private byte[] _prvKeyDSA; // RSA private byte[] _nRSA; // modulus private byte[] _eRSA; // public exponent private byte[] _dRSA; // private exponent /** * Factory method to create a new instance of <code>IdentityFile</code> for * the specified private key file and public key file. * * @param prvfile * @param pubfile * @return identity file instance * @throws JSchException */ public static IdentityFile newInstance(String prvfile, String pubfile) throws JSchException { byte[] prvkey, pubkey; FileChannel fc = null; try { // Attempt to read in private key file fc = new FileInputStream(prvfile).getChannel(); ByteBuffer bb = ByteBuffer.wrap(prvkey = new byte[(int) fc.size()]); fc.read(bb); } catch(Exception e) { throw new JSchException("Failed to read private key file: "+e, e); } finally { if( fc != null ) { try { fc.close(); } catch(IOException ioe) { /* Ignore error. */ } fc = null; } } String _pubfile = pubfile; if( pubfile == null ) { _pubfile = prvfile + ".pub"; } try { // Attempt to read in the public key file fc = new FileInputStream(_pubfile).getChannel(); ByteBuffer bb = ByteBuffer.wrap(pubkey = new byte[(int) fc.size()]); fc.read(bb); } catch(Exception e) { if( pubfile != null ) { // The pubfile is explicitly given, but not accessible. throw new JSchException("Failed to read public key file: "+e, e); } pubkey = null; // TODO Temp until figured out... } finally { if( fc != null ) { try { fc.close(); } catch(IOException ioe) { /* Ignore error. */ } fc = null; } } // Create new identity instance and return return newInstance(prvfile, prvkey, pubkey); } /** * Factory method to create a new instance of <code>IdentityFile</code> for * the specified name, private key and public key. * * @param name * @param prvkey * @param pubkey * @return identity file * @throws JSchException */ public static IdentityFile newInstance(String name, byte[] prvkey, byte[] pubkey) throws JSchException { try { return new IdentityFile(name, prvkey, pubkey); } finally { Util.bzero(prvkey); } } /** * Private constructor to prevent direct instantiation. Instances should be * created using the factory methods <code>newInstance()</code>. * * @param name * @param prvkey * @param pubkey * @throws JSchException */ private IdentityFile(String name, byte[] prvkey, byte[] pubkey) throws JSchException { _identity = name; try { _cipher = CipherManager.getManager().createCipher(Cipher.CIPHER_3DES_CBC); _key = new byte[_cipher.getBlockSize()]; _iv = new byte[_cipher.getIVSize()]; _hash = HashManager.getManager().createHash(Hash.HASH_MD5); byte[] buf = prvkey; int len = buf.length, i = 0; // Loop past any invalid dash data found in some identity files while( i < len ) { if( buf[i] == '-' && i + 4 < len && buf[i + 1] == '-' && buf[i + 2] == '-' && buf[i + 3] == '-' && buf[i + 4] == '-' ) { break; } i++; } while( i < len ) { if( buf[i] == 'B' && i+3 < len && buf[i + 1] == 'E' && buf[i + 2] == 'G' && buf[i + 3] == 'I' ) { i += 6; if( buf[i] == 'D' && buf[i + 1] == 'S' && buf[i + 2] == 'A' ) { _keyType = KeyType.SSH_DSS; } else if( buf[i] == 'R' && buf[i + 1] == 'S' && buf[i + 2] == 'A' ) { _keyType = KeyType.SSH_RSA; } else if( buf[i] == 'S' && buf[i + 1] == 'S' && buf[i + 2] == 'H' ) { // FSecure _keyType = KeyType.UNKNOWN; _vendor = FSECURE; } else { throw new JSchException("invalid privatekey: " + _identity); } i += 3; continue; } if( buf[i] == 'A' && i+7 < len && buf[i + 1] == 'E' && buf[i + 2] == 'S' && buf[i + 3] == '-' && buf[i + 4] == '2' && buf[i + 5] == '5' && buf[i + 6] == '6' && buf[i + 7] == '-' ) { i += 8; if( CipherManager.getManager().isSupported(Cipher.CIPHER_AES256_CBC) ) { _cipher = CipherManager.getManager().createCipher(Cipher.CIPHER_AES256_CBC); _key = new byte[_cipher.getBlockSize()]; _iv = new byte[_cipher.getIVSize()]; } else { throw new JSchException("privatekey: aes256-cbc is not available " + _identity); } continue; } // If AES-192 encryption if( buf[i] == 'A' && i + 7 < len && buf[i + 1] == 'E' && buf[i + 2] == 'S' && buf[i + 3] == '-' && buf[i + 4] == '1' && buf[i + 5] == '9' && buf[i + 6] == '2' && buf[i + 7] == '-' ) { i += 8; if( CipherManager.getManager().isSupported(Cipher.CIPHER_AES192_CBC) ) { _cipher = CipherManager.getManager().createCipher(Cipher.CIPHER_AES192_CBC); _key = new byte[_cipher.getBlockSize()]; _iv = new byte[_cipher.getIVSize()]; } else { throw new JSchException("privatekey: aes192-cbc is not available " + _identity); } continue; } // If AES-128 encryption if( buf[i] == 'A' && i + 7 < len && buf[i + 1] == 'E' && buf[i + 2] == 'S' && buf[i + 3] == '-' && buf[i + 4] == '1' && buf[i + 5] == '2' && buf[i + 6] == '8' && buf[i + 7] == '-' ) { i += 8; if( CipherManager.getManager().isSupported(Cipher.CIPHER_AES128_CBC) ) { _cipher = CipherManager.getManager().createCipher(Cipher.CIPHER_AES128_CBC); _key = new byte[_cipher.getBlockSize()]; _iv = new byte[_cipher.getIVSize()]; } else { throw new JSchException("privatekey: aes128-cbc is not available " + _identity); } continue; } if( buf[i] == 'C' && i+3 < len && buf[i + 1] == 'B' && buf[i + 2] == 'C' && buf[i + 3] == ',' ) { i += 4; for( int ii = 0; ii < _iv.length; ii++ ) { _iv[ii] = (byte) (((a2b(buf[i++]) << 4) & 0xf0) + (a2b(buf[i++]) & 0xf)); } continue; } if( buf[i] == 0x0d && i + 1 < len && buf[i + 1] == 0x0a ) { i++; continue; } if( buf[i] == 0x0a && i + 1 < len ) { if( buf[i + 1] == 0x0a ) { i += 2; break; } if( buf[i + 1] == 0x0d && i + 2 < len && buf[i + 2] == 0x0a ) { i += 3; break; } boolean inheader = false; for( int j = i + 1; j < len; j++ ) { if( buf[j] == 0x0a ) { break; } if( buf[j] == ':' ) { inheader = true; break; } } if( !inheader ) { i++; _encrypted = false; // no passphrase break; } } i++; } if( _keyType == null ) { throw new JSchException("invalid privatekey: " + _identity); } int start = i; while( i < len ) { if( buf[i] == 0x0a ) { boolean xd = (buf[i - 1] == 0x0d); System.arraycopy(buf, i + 1, buf, i - (xd ? 1 : 0), len - i - 1 - (xd ? 1 : 0)); if( xd ) { len } len continue; } if( buf[i] == '-' ) { break; } i++; } _encodedData = Util.fromBase64(buf, start, i - start); if( _encodedData.length > 4 && // FSecure _encodedData[0] == (byte) 0x3f && _encodedData[1] == (byte) 0x6f && _encodedData[2] == (byte) 0xf9 && _encodedData[3] == (byte) 0xeb ) { Buffer _buf = new Buffer(_encodedData); _buf.getInt(); // 0x3f6ff9be _buf.getInt(); @SuppressWarnings("unused") byte[] typeName = _buf.getString(); byte[] cipherName = _buf.getString(); String cipher = Util.byte2str(cipherName); if( cipher.equals("3des-cbc") ) { _buf.getInt(); byte[] foo = new byte[_encodedData.length - _buf.getOffSet()]; _buf.getBytes(foo); _encodedData = foo; _encrypted = true; throw new JSchException("unknown privatekey format: " + _identity); } else if( cipher.equals("none") ) { _buf.getInt(); //_buf.getInt(); _encrypted = false; byte[] foo = new byte[_encodedData.length - _buf.getOffSet()]; _buf.getBytes(foo); _encodedData = foo; } } if( pubkey == null ) { return; } buf = pubkey; len = buf.length; if( buf.length > 4 && // FSecure's public key buf[0] == '-' && buf[1] == '-' && buf[2] == '-' && buf[3] == '-' ) { i = 0; do { i++; } while( len > i && buf[i] != 0x0a ); if( len <= i ) { return; } while( i < len ) { if( buf[i] == 0x0a ) { boolean inheader = false; for( int j = i + 1; j < len; j++ ) { if( buf[j] == 0x0a ) { break; } if( buf[j] == ':' ) { inheader = true; break; } } if( !inheader ) { i++; break; } } i++; } if( len <= i ) { return; } start = i; while( i < len ) { if( buf[i] == 0x0a ) { System.arraycopy(buf, i + 1, buf, i, len - i - 1); len continue; } if( buf[i] == '-' ) { break; } i++; } _publicKeyBlob = Util.fromBase64(buf, start, i - start); if( _keyType == KeyType.UNKNOWN && _publicKeyBlob.length > 8 ) { if( _publicKeyBlob[8] == 'd' ) { _keyType = KeyType.SSH_DSS; } else if( _publicKeyBlob[8] == 'r' ) { _keyType = KeyType.SSH_RSA; } } } else { if( buf[0] != 's' || buf[1] != 's' || buf[2] != 'h' || buf[3] != '-' ) { return; } i = 0; while( i < len ) { if( buf[i] == ' ' ) { break; } i++; } i++; if( i >= len ) { return; } start = i; while( i < len ) { if( buf[i] == ' ' || buf[i] == '\n' ) { break; } i++; } _publicKeyBlob = Util.fromBase64(buf, start, i - start); if( _publicKeyBlob.length < 4 + 7 ) { // It must start with "ssh-XXX". _publicKeyBlob = null; } } } catch(JSchException e) { throw e; } catch(Exception e) { throw new JSchException("Failed to create IdentityFile instance: "+e, e); } } @Override public String getAlgorithmName() { return _keyType.toString(); } @Override public boolean setPassphrase(byte[] passphrase) throws JSchException { /* hash is MD5 h(0) <- hash(passphrase, iv); h(n) <- hash(h(n-1), passphrase, iv); key <- (h(0),...,h(n))[0,..,key.length]; */ try { if( _encrypted ) { if( passphrase == null ) { return false; } int hsize = _hash.getBlockSize(); byte[] hn = new byte[_key.length / hsize * hsize + (_key.length % hsize == 0 ? 0 : hsize)]; byte[] tmp = null; if( _vendor == OPENSSH ) { for( int index = 0; index + hsize <= hn.length; ) { if( tmp != null ) { _hash.update(tmp, 0, tmp.length); } _hash.update(passphrase, 0, passphrase.length); _hash.update(_iv, 0, _iv.length > 8 ? 8 : _iv.length); tmp = _hash.digest(); System.arraycopy(tmp, 0, hn, index, tmp.length); index += tmp.length; } System.arraycopy(hn, 0, _key, 0, _key.length); } else if( _vendor == FSECURE ) { for( int index = 0; index + hsize <= hn.length; ) { if( tmp != null ) { _hash.update(tmp, 0, tmp.length); } _hash.update(passphrase, 0, passphrase.length); tmp = _hash.digest(); System.arraycopy(tmp, 0, hn, index, tmp.length); index += tmp.length; } System.arraycopy(hn, 0, _key, 0, _key.length); } } if( decrypt() ) { _encrypted = false; return true; } _pDSA = _qDSA = _gDSA = _pubKeyDSA = _prvKeyDSA = null; return false; } catch(Exception e) { throw new JSchException("Failed to set passphrase: "+e, e); } finally { Util.bzero(passphrase); } } @Override public byte[] getPublicKeyBlob() { if( _publicKeyBlob != null ) { return _publicKeyBlob; } // Generate public key blob based on key type byte[] keyBlob = null; switch( _keyType ) { case SSH_RSA: if( _eRSA == null ) { return null; } keyBlob = new byte[KeyType.SSH_RSA.toString().length() + 4 + _eRSA.length + 4 + _nRSA.length + 4]; Buffer rsaBuf = new Buffer(keyBlob); rsaBuf.putString(KeyType.SSH_RSA.getBytes()); rsaBuf.putString(_eRSA); rsaBuf.putString(_nRSA); return keyBlob; case SSH_DSS: if( _pDSA == null ) { return null; } keyBlob = new byte[KeyType.SSH_DSS.toString().length() + 4 + _pDSA.length + 4 + _qDSA.length + 4 + _gDSA.length + 4 + _pubKeyDSA.length + 4]; Buffer dsaBuf = new Buffer(keyBlob); dsaBuf.putString(KeyType.SSH_DSS.getBytes()); dsaBuf.putString(_pDSA); dsaBuf.putString(_qDSA); dsaBuf.putString(_gDSA); dsaBuf.putString(_pubKeyDSA); return keyBlob; default: throw new IllegalStateException("Failed to generate public key blob, invalid key type: "+_keyType); } } @Override public byte[] getSignature(byte[] data) { switch( _keyType ) { case SSH_RSA: { try { SignatureRSA rsa = AlgorithmManager.getManager().createAlgorithm(Algorithms.SIGNATURE_RSA); rsa.setPrvKey(_dRSA, _nRSA); rsa.update(data); byte[] sig = rsa.sign(); byte[] buffer = new byte[KeyType.SSH_RSA.toString().length() + 4 + sig.length + 4]; Buffer buf = new Buffer(buffer); buf.putString(KeyType.SSH_RSA.getBytes()); buf.putString(sig); return buffer; } catch(Exception e) { // TODO Error handling? } return null; } case SSH_DSS: { try { SignatureDSA dsa = AlgorithmManager.getManager().createAlgorithm(Algorithms.SIGNATURE_DSS); dsa.setPrvKey(_prvKeyDSA, _pDSA, _qDSA, _gDSA); dsa.update(data); byte[] sig = dsa.sign(); byte[] buffer = new byte[KeyType.SSH_DSS.toString().length() + 4 + sig.length + 4]; Buffer buf = new Buffer(buffer); buf.putString(KeyType.SSH_DSS.getBytes()); buf.putString(sig); return buffer; } catch(Exception e) { // TODO Error handling? } return null; } default: throw new IllegalStateException("Failed to get signature, invalid key type: "+_keyType); } } @Override public boolean decrypt() { switch( _keyType ) { case SSH_RSA: return decryptRSA(); case SSH_DSS: return decryptDSS(); default: throw new IllegalStateException("Failed to decrypt, invalid key type: "+_keyType); } } /** * Get the unencrypted private key file bytes. */ public byte[] getPrivateKey() throws JSchException { if (_encrypted) { throw new IllegalStateException("Key is ecrypted"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { switch( _keyType ) { case SSH_RSA: { out.write(" byte[] b = getRSAPrivateKey(); out.write(Util.toBase64(b, 0, b.length)); out.write("\n break; } case SSH_DSS: { out.write(" byte[] b = getDSSPrivateKey(); out.write(Util.toBase64(b, 0, b.length)); out.write("\n break; } default: throw new IllegalStateException("Failed to decrypt, invalid key type: "+_keyType); } } catch (IOException e) { } return out.toByteArray(); } boolean decryptRSA() { try { if( !_encrypted && _nRSA != null ) { return true; } byte[] plain = getRSAPrivateKey(); if( _vendor == FSECURE ) { // FSecure Buffer buf = new Buffer(plain); int foo = buf.getInt(); if( plain.length != foo + 4 ) { return false; } _eRSA = buf.getMPIntBits(); _dRSA = buf.getMPIntBits(); _nRSA = buf.getMPIntBits(); buf.getMPIntBits(); // u_array buf.getMPIntBits(); // p_array buf.getMPIntBits(); // q_array return true; } int[] index = new int[1]; int length = 0; if( plain[index[0]] != 0x30 ) { return false; } index[0]++; // SEQUENCE length = plain[index[0]++] & 0xff; if( (length & 0x80) != 0 ) { int foo = length & 0x7f; length = 0; while( foo length = (length << 8) + (plain[index[0]++] & 0xff); } } if( plain[index[0]] != 0x02 ) { return false; } DataUtil.readINTEGER(index, plain); _nRSA = DataUtil.readINTEGER(index, plain); _eRSA = DataUtil.readINTEGER(index, plain); _dRSA = DataUtil.readINTEGER(index, plain); DataUtil.readINTEGER(index, plain); // p_array DataUtil.readINTEGER(index, plain); // q_array DataUtil.readINTEGER(index, plain); // dmp1_array DataUtil.readINTEGER(index, plain); // dmq1_array DataUtil.readINTEGER(index, plain); // iqmp_array } catch(Exception e) { // TODO Error handling? return false; } return true; } byte[] getRSAPrivateKey() throws JSchException { byte[] plain; if( _encrypted ) { if( _vendor == OPENSSH ) { _cipher.init(Cipher.DECRYPT_MODE, _key, _iv); plain = new byte[_encodedData.length]; _cipher.update(_encodedData, 0, _encodedData.length, plain, 0); } else if( _vendor == FSECURE ) { for( int i = 0; i < _iv.length; i++ ) { _iv[i] = 0; } _cipher.init(Cipher.DECRYPT_MODE, _key, _iv); plain = new byte[_encodedData.length]; _cipher.update(_encodedData, 0, _encodedData.length, plain, 0); } else { throw new JSchException("Unknown vendor id: " + _vendor); } } else { plain = _encodedData; } return plain; } boolean decryptDSS() { try { if( !_encrypted && _pDSA != null ) { return true; } byte[] plain = getDSSPrivateKey(); if( _vendor == FSECURE ) { // FSecure Buffer buf = new Buffer(plain); int foo = buf.getInt(); if( plain.length != foo + 4 ) { return false; } _pDSA = buf.getMPIntBits(); _gDSA = buf.getMPIntBits(); _qDSA = buf.getMPIntBits(); _pubKeyDSA = buf.getMPIntBits(); _prvKeyDSA = buf.getMPIntBits(); return true; } int[] index = new int[1]; int length = 0; if( plain[index[0]] != 0x30 ) { return false; } index[0]++; // SEQUENCE length = plain[index[0]++] & 0xff; if( (length & 0x80) != 0 ) { int foo = length & 0x7f; length = 0; while( foo length = (length << 8) + (plain[index[0]++] & 0xff); } } if( plain[index[0]] != 0x02 ) { return false; } DataUtil.readINTEGER(index, plain); _pDSA = DataUtil.readINTEGER(index, plain); _qDSA = DataUtil.readINTEGER(index, plain); _gDSA = DataUtil.readINTEGER(index, plain); _pubKeyDSA = DataUtil.readINTEGER(index, plain); _prvKeyDSA = DataUtil.readINTEGER(index, plain); } catch(Exception e) { // TODO Error handling? return false; } return true; } byte[] getDSSPrivateKey() throws JSchException { byte[] plain; if( _encrypted ) { if( _vendor == OPENSSH ) { _cipher.init(Cipher.DECRYPT_MODE, _key, _iv); plain = new byte[_encodedData.length]; _cipher.update(_encodedData, 0, _encodedData.length, plain, 0); } else if( _vendor == FSECURE ) { for( int i = 0; i < _iv.length; i++ ) { _iv[i] = 0; } _cipher.init(Cipher.DECRYPT_MODE, _key, _iv); plain = new byte[_encodedData.length]; _cipher.update(_encodedData, 0, _encodedData.length, plain, 0); } else { throw new JSchException("Unknown vendor id: " + _vendor); } } else { plain = _encodedData; } return plain; } @Override public boolean isEncrypted() { return _encrypted; } @Override public String getName() { return _identity; } @Override public void clear() { Util.bzero(_encodedData); Util.bzero(_prvKeyDSA); Util.bzero(_dRSA); Util.bzero(_key); Util.bzero(_iv); } private static byte a2b(byte c) { if( '0' <= c && c <= '9' ) { return (byte) (c - '0'); } if( 'a' <= c && c <= 'z' ) { return (byte) (c - 'a' + 10); } return (byte) (c - 'A' + 10); } @Override protected void finalize() throws Throwable { clear(); super.finalize(); } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object o) { return o == this || (o instanceof IdentityFile && getName().equals(((IdentityFile) o).getName())); } }
package org.wmaop.bdd.jbehave; import static org.junit.Assume.assumeThat; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.hamcrest.core.IsNull; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.failures.FailingUponPendingStep; import org.jbehave.core.io.StoryFinder; import org.jbehave.core.junit.JUnitStories; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.Format; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.AbstractStepsFactory; import org.jbehave.core.steps.InjectableStepsFactory; import org.junit.BeforeClass; import org.junit.runner.RunWith; import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner; @RunWith(JUnitReportingRunner.class) public class JBehaveRunner extends JUnitStories { public JBehaveRunner() { JUnitReportingRunner.recommendedControls(configuredEmbedder()); } @BeforeClass public static void setup() { assumeThat(System.getProperty("skipStories"), IsNull.nullValue()); } @Override public Configuration configuration() { return new MostUsefulConfiguration().usePendingStepStrategy(new FailingUponPendingStep()).useStoryReporterBuilder( new StoryReporterBuilder() .withDefaultFormats().withPathResolver(new ResolveToPackagedName()) .withFormats(Format.HTML) .withFailureTrace(true).withFailureTraceCompression(true)); } @Override public InjectableStepsFactory stepsFactory() { return new AbstractStepsFactory(configuration()) { @Override public Object createInstanceOfType(Class<?> type) { return new WmJBehaveSteps(); } @Override protected List<Class<?>> stepsTypes() { return new ArrayList<>(Arrays.asList(WmJBehaveSteps.class)); } }; } @Override public List<String> storyPaths() { return new StoryFinder().findPaths(new File(System.getProperty("storyPath", "src/test/resources")).getAbsolutePath(), "**/*.story", ""); } }
package permafrost.tundra.lang; import com.wm.data.IData; import com.wm.data.IDataPortable; import com.wm.data.IDataUtil; import com.wm.lang.ns.NSNode; import com.wm.util.Table; import com.wm.util.coder.IDataCodable; import com.wm.util.coder.ValuesCodable; import org.apache.log4j.Level; import permafrost.tundra.collection.ListHelper; import permafrost.tundra.data.IDataHelper; import permafrost.tundra.io.FileHelper; import permafrost.tundra.io.InputStreamHelper; import permafrost.tundra.math.BigDecimalHelper; import permafrost.tundra.math.BigIntegerHelper; import permafrost.tundra.math.ByteHelper; import permafrost.tundra.math.DoubleHelper; import permafrost.tundra.math.FloatHelper; import permafrost.tundra.math.IntegerHelper; import permafrost.tundra.math.LongHelper; import permafrost.tundra.math.ShortHelper; import permafrost.tundra.mime.MIMETypeHelper; import permafrost.tundra.security.MessageDigestHelper; import permafrost.tundra.server.NodePermission; import permafrost.tundra.server.ServerLogger; import permafrost.tundra.time.DateTimeHelper; import permafrost.tundra.time.DurationHelper; import permafrost.tundra.time.TimeZoneHelper; import permafrost.tundra.xml.namespace.IDataNamespaceContext; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.activation.MimeType; import javax.xml.datatype.Duration; /** * A collection of convenience methods for working with Objects. */ public final class ObjectHelper { /** * Disallow instantiation of this class. */ private ObjectHelper() {} /** * Returns true if the given objects are considered equal; correctly supports comparing com.wm.data.IData objects. * * @param firstObject The first object in the comparison. * @param secondObject The seconds object in the comparison. * @return True if the two objects are equal, otherwise false. */ public static boolean equal(Object firstObject, Object secondObject) { boolean result; if (firstObject != null && secondObject != null) { if (firstObject instanceof IData && secondObject instanceof IData) { result = IDataUtil.equals((IData)firstObject, (IData)secondObject); } else { result = firstObject.equals(secondObject); } } else { result = (firstObject == null && secondObject == null); } return result; } /** * Returns the first non-null argument. * * @param objects A list of arguments to be coalesced. * @param <T> The type of the arguments. * @return The first non-null argument, or null. */ public static <T> T coalesce(T... objects) { if (objects != null) { for (T object : objects) { if (object != null) return object; } } return null; } /** * Returns the first non-null argument. * * @param objects A list of arguments to be coalesced. * @param <T> The type of the arguments. * @return The first non-null argument, or null. */ public static <T> T coalesce(Iterable<T> objects) { if (objects != null) { for (T object : objects) { if (object != null) return object; } } return null; } /** * Compares two Objects. * * @param object1 The first Object to be compared. * @param object2 The second Object to be compared. * @return A value less than zero if the first object comes before the second object, a value of zero if * they are equal, or a value of greater than zero if the first object comes after the second * object according to the comparison of all the keys and values in each document. */ @SuppressWarnings("unchecked") public static int compare(Object object1, Object object2) { int result = 0; if (object1 == null || object2 == null) { if (object1 != null) { result = 1; } else if (object2 != null) { result = -1; } } else { if (object1 instanceof Comparable && object1.getClass().isAssignableFrom(object2.getClass())) { result = ((Comparable)object1).compareTo(object2); } else if (object2 instanceof Comparable && object2.getClass().isAssignableFrom(object1.getClass())) { result = ((Comparable)object2).compareTo(object1) * -1; } else if (object1 != object2) { // last ditch effort: compare two incomparable objects using their hash codes result = Integer.valueOf(object1.hashCode()).compareTo(object2.hashCode()); } } return result; } /** * Returns true if the given object is considered empty. * * @param object The object to check the emptiness of. * @return True if the object is considered empty. */ public static boolean isEmpty(Object object) { return object == null || (object instanceof String && object.equals("")) || (object instanceof Object[] && ((Object[])object).length == 0) || (object instanceof Collection && ((Collection)object).size() == 0) || (object instanceof IData && IDataHelper.size((IData)object) == 0); } /** * Returns true if the given object is an instance of the given class. * * @param object The object to be checked against the given class. * @param className The name of the class the given object will be tested against. * @return True if the given object is an instance of the given class. */ public static boolean instance(Object object, String className) { boolean isInstance; try { isInstance = instance(object, className, false); } catch(ClassNotFoundException ex) { isInstance = false; } return isInstance; } /** * Returns true if the given object is an instance of the given class. * * @param object The object to be checked against the given class. * @param className The name of the class the given object will be tested against. * @param raise If true, throws an exception if the class with the given name does not exist. * @return True if the given object is an instance of the given class. * @throws ClassNotFoundException If the given class name is not found. */ public static boolean instance(Object object, String className, boolean raise) throws ClassNotFoundException { try { return className != null && instance(object, Class.forName(className)); } catch(ClassNotFoundException ex) { if (raise) { throw ex; } else { return false; } } } /** * Returns true if the given object is an instance of the given class. * * @param object The object to be checked against the given class. * @param klass The class the given object will be tested against. * @return True if the given object is an instance of the given class. */ public static boolean instance(Object object, Class klass) { return klass != null && klass.isInstance(object); } /** * Returns true if the given object is a primitive or an array of primitives. * * @param object An object to check. * @return True if the given object is a primitive or an array of primitives. */ public static boolean isPrimitive(Object object) { if (object == null) return false; Class klass = object.getClass(); return klass.isPrimitive() || (klass.isArray() && !(object instanceof Object[])); } /** * Returns a string representation of the given object. * * @param object The object to stringify. * @return A string representation of the given object. */ public static String stringify(Object object) { if (object == null) return null; String output; if (object instanceof NSNode) { output = ((NSNode)object).getNSName().toString(); } else if (object instanceof IData[] || object instanceof Table || object instanceof IDataCodable[] || object instanceof IDataPortable[] || object instanceof ValuesCodable[]) { output = ArrayHelper.stringify(IDataHelper.toIDataArray(object)); } else if (object instanceof IData || object instanceof IDataCodable || object instanceof IDataPortable || object instanceof ValuesCodable) { output = IDataHelper.toIData(object).toString(); } else if (object instanceof Object[][]) { output = TableHelper.stringify((Object[][])object); } else if (object instanceof Object[]) { output = ArrayHelper.stringify((Object[])object); } else { output = object.toString(); } return output; } /** * Returns the given item if it is already an array, or a new array with the given type whose first element is the * given item. * * @param item The item to be converted to an array. * @return Either the item itself if it is already an array or a new array containing the item as its only element. */ public static Object[] arrayify(Object item) { Object[] array = null; if (item instanceof Object[]) { array = (Object[])item; } else if (item != null) { array = (Object[])Array.newInstance(item.getClass(), 1); array[0] = item; } return array; } /** * Returns a List containing all elements in the given item if it is an array, or a List containing the item itself * if it is not an array. * * @param item The item to be converted to a List. * @return Either a List containing all elements in the given item if it is an array, or a List containing the item * itself if it is not an array. */ public static List<Object> listify(Object item) { List<Object> list = new ArrayList<Object>(); if (item instanceof Object[]) { list.addAll(ListHelper.of((Object[])item)); } else if (item != null) { list.add(item); } return list; } /** * Returns the nearest class which is an ancestor to the classes of the given objects. * * @param objects One or more objects to return the nearest ancestor for. * @return The nearest ancestor class which is an ancestor to the classes of the given objects. */ public static Class<?> getNearestAncestor(Object... objects) { return ClassHelper.getNearestAncestor(toClassSet(objects)); } /** * Returns the nearest class which is an ancestor to the classes of the given objects. * * @param objects One or more objects to return the nearest ancestor for. * @return The nearest ancestor class which is an ancestor to the classes of the given objects. */ public static Class<?> getNearestAncestor(Collection<?> objects) { return ClassHelper.getNearestAncestor(toClassSet(objects)); } /** * Returns all the ancestor classes from nearest to furthest for the given class. * * @param objects One or more objects to fetch the ancestors classes of. * @return All the ancestor classes from nearest to furthest for the class of the given object. */ public static Set<Class<?>> getAncestors(Object... objects) { return ClassHelper.getAncestors(toClassSet(objects)); } /** * Returns all the ancestor classes from nearest to furthest for the given class. * * @param object An object to fetch the ancestors classes of. * @return All the ancestor classes from nearest to furthest for the class of the given object. */ public static Set<Class<?>> getAncestors(Object object) { return object == null ? new LinkedHashSet<Class<?>>() : ClassHelper.getAncestors(object.getClass()); } /** * Converts the given list of objects to a set of classes. * * @param objects One or more objects to return a set of classes for. * @return The set of classes for the given list of objects. */ private static Set<Class<?>> toClassSet(Object... objects) { Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); if (objects != null) { for (Object object : objects) { if (object != null) classes.add(object.getClass()); } } else { classes.add(Object.class); } return classes; } /** * Converts the given list of objects to a set of classes. * * @param objects One or more objects to return a set of classes for. * @return The set of classes for the given list of objects. */ private static Set<Class<?>> toClassSet(Collection<?> objects) { Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); if (objects != null) { for (Object object : objects) { if (object != null) classes.add(object.getClass()); } } else { classes.add(Object.class); } return classes; } /** * Converts a string, byte array or stream to a string, byte array or stream. * * @param object The object to be converted. * @param charsetName The character set to use. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, String charsetName, String mode) throws IOException { return convert(object, CharsetHelper.normalize(charsetName), mode); } /** * Converts a string, byte array or stream to a string, byte array or stream. * * @param object The object to be converted. * @param charset The character set to use. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, Charset charset, String mode) throws IOException { return convert(object, charset, ObjectConvertMode.normalize(mode)); } /** * Converts a string, byte array or stream to a string, byte array or stream. * * @param object The object to be converted. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, String mode) throws IOException { return convert(object, ObjectConvertMode.normalize(mode)); } /** * Converts a string, byte array or stream to a string, byte array or stream. * * @param object The object to be converted. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, ObjectConvertMode mode) throws IOException { return convert(object, CharsetHelper.DEFAULT_CHARSET, mode); } /** * Converts a string, byte array or stream to a string, byte array or stream. * * @param object The object to be converted. * @param charset The character set to use. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, Charset charset, ObjectConvertMode mode) throws IOException { if (object == null) return null; mode = ObjectConvertMode.normalize(mode); if (mode == ObjectConvertMode.BYTES) { object = BytesHelper.normalize(object, charset); } else if (mode == ObjectConvertMode.STRING) { object = StringHelper.normalize(object, charset); } else if (mode == ObjectConvertMode.BASE64) { object = BytesHelper.base64Encode(BytesHelper.normalize(object, charset)); } else if (mode == ObjectConvertMode.STREAM) { object = InputStreamHelper.normalize(object, charset); } else { throw new IllegalArgumentException("Unsupported conversion mode specified: " + mode); } return object; } /** * Converts the given object to the given class. * * @param object The object to be converted. * @param klass The class to convert the object to. * @param <T> The class to convert the object to. * @return The given object converted to the given class. */ @SuppressWarnings("unchecked") public static <T> T convert(Object object, Class<T> klass) { return convert(object, null, klass); } /** * Converts the given object to the given class. * * @param object The object to be converted. * @param charset The charset to use for string related conversions. * @param klass The class to convert the object to. * @param <T> The class to convert the object to. * @return The given object converted to the given class. */ @SuppressWarnings("unchecked") public static <T> T convert(Object object, Charset charset, Class<T> klass) { return convert(object, charset, klass, false); } /** * Converts the given object to the given class. * * @param object The object to be converted. * @param klass The class to convert the object to. * @param required If true and the object could not be converted, throws an exception. * @param <T> The class to convert the object to. * @return The given object converted to the given class. */ @SuppressWarnings("unchecked") public static <T> T convert(Object object, Class<T> klass, boolean required) { return convert(object, null, klass, required); } /** * Converts the given object to the given class. * * @param object The object to be converted. * @param charset The charset to use for string related conversions. * @param klass The class to convert the object to. * @param required If true and the object could not be converted, throws an exception. * @param <T> The class to convert the object to. * @return The given object converted to the given class. */ @SuppressWarnings("unchecked") public static <T> T convert(Object object, Charset charset, Class<T> klass, boolean required) { if (required) { if (object == null) { throw new NullPointerException("object must not be null"); } else if (klass == null) { throw new NullPointerException("klass must not be null"); } } else if (object == null || klass == null) { return null; } T value = null; try { if (klass.isInstance(object)) { value = (T)object; } else if (klass.isAssignableFrom(byte[].class)) { value = (T)BytesHelper.normalize(object, charset); } else if (klass.isAssignableFrom(InputStream.class)) { value = (T)InputStreamHelper.normalize(object, charset); } else if (klass.isAssignableFrom(String.class)) { value = (T)StringHelper.normalize(object, charset); } else if (klass.isAssignableFrom(Boolean.class)) { value = (T)BooleanHelper.normalize(object); } else if (klass.isAssignableFrom(BigDecimal.class)) { value = (T)BigDecimalHelper.normalize(object); } else if (klass.isAssignableFrom(BigInteger.class)) { value = (T)BigIntegerHelper.normalize(object); } else if (klass.isAssignableFrom(Double.class)) { value = (T)DoubleHelper.normalize(object); } else if (klass.isAssignableFrom(Float.class)) { value = (T)FloatHelper.normalize(object); } else if (klass.isAssignableFrom(Long.class)) { value = (T)LongHelper.normalize(object); } else if (klass.isAssignableFrom(Integer.class)) { value = (T)IntegerHelper.normalize(object); } else if (klass.isAssignableFrom(Short.class)) { value = (T)ShortHelper.normalize(object); } else if (klass.isAssignableFrom(Byte.class)) { value = (T)ByteHelper.normalize(object); } else if (klass.isAssignableFrom(Class.class)) { value = (T)ClassHelper.normalize(object); } else if (klass.isEnum()) { value = EnumHelper.normalize(object, klass); } else if (klass.isAssignableFrom(IData.class) && (object instanceof IDataCodable || object instanceof IDataPortable || object instanceof ValuesCodable || object instanceof Map)) { value = (T)IDataHelper.toIData(object); } else if (klass.isAssignableFrom(Character.class) && object instanceof String && ((String)object).length() > 0) { value = (T)Character.valueOf(((String)object).charAt(0)); } else if (klass.isAssignableFrom(Calendar.class) && object instanceof String) { value = (T)DateTimeHelper.parse((String)object); } else if (klass.isAssignableFrom(Date.class) && object instanceof String) { value = (T)DateTimeHelper.parse((String)object).getTime(); } else if (klass.isAssignableFrom(Duration.class) && object instanceof String) { value = (T)DurationHelper.parse((String)object); } else if (klass.isAssignableFrom(Charset.class) && object instanceof String) { value = (T)CharsetHelper.of((String)object); } else if (klass.isAssignableFrom(MimeType.class) && object instanceof String) { value = (T)MIMETypeHelper.of((String)object); } else if (klass.isAssignableFrom(NodePermission.class) && object instanceof String) { value = (T)NodePermission.normalize((String)object); } else if (klass.isAssignableFrom(IDataNamespaceContext.class) && object instanceof IData) { value = (T)IDataNamespaceContext.of((IData)object); } else if (klass.isAssignableFrom(Locale.class) && object instanceof IData) { value = (T)LocaleHelper.toLocale((IData)object); } else if (klass.isAssignableFrom(MessageDigest.class) && object instanceof String) { value = (T)MessageDigestHelper.normalize((String)object); } else if (klass.isAssignableFrom(TimeZone.class) && object instanceof String) { value = (T)TimeZoneHelper.get((String)object); } else if (klass.isAssignableFrom(File.class) && object instanceof String) { value = (T)FileHelper.construct((String)object); } else if (klass.isAssignableFrom(Level.class) && (object instanceof String || object instanceof Number)) { if (object instanceof String) { value = (T)ServerLogger.toLevel((String)object); } else { value = (T)ServerLogger.toLevel(((Number)object).intValue()); } } } catch (IOException ex) { throw new RuntimeException(ex); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } if (required && value == null) { throw new UnsupportedOperationException(MessageFormat.format("Unsupported class conversion from {0} to {1}", object.getClass().getName(), klass.getName())); } return value; } }
package permafrost.tundra.net.uri; import com.wm.data.IData; import com.wm.data.IDataCursor; import com.wm.data.IDataFactory; import com.wm.data.IDataUtil; import permafrost.tundra.data.IDataHelper; import permafrost.tundra.data.transform.Transformer; import permafrost.tundra.data.transform.net.uri.Decoder; import permafrost.tundra.data.transform.net.uri.Encoder; import permafrost.tundra.flow.variable.SubstitutionHelper; import permafrost.tundra.lang.ArrayHelper; import permafrost.tundra.lang.CharsetHelper; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A collection of convenience methods for working with URIs. */ public final class URIHelper { /** * The default character set used for URI strings. */ public static final Charset DEFAULT_CHARSET = Charset.forName("US-ASCII"); /** * The default character set name used for URI strings. */ public static final String DEFAULT_CHARSET_NAME = DEFAULT_CHARSET.name(); /** * The character used to delimit the items in a URI's path. */ public static final String URI_PATH_DELIMITER = "/"; /** * The character used to delimit the start of a URI's query string. */ public static final String URI_QUERY_DELIMITER = "?"; /** * The character used to delimit the user from the password in a URI's authority section. */ public static final String URI_USER_PASSWORD_DELIMITER = ":"; /** * Disallow instantiation of this class. */ private URIHelper() {} /** * Parses a URI string into an IData representation. * * @param input The URI string to be parsed. * @return An IData representation of the given URI. * @throws URISyntaxException If the given string is an invalid URI. */ public static IData parse(String input) throws URISyntaxException { if (input == null) return null; return toIData(fromString(input)); } /** * Emits a URI given as an IData document as a string. * * @param input An IData containing a specific URI structure to be serialized. * @return The URI string representing the given IData. * @throws URISyntaxException If the given string is an invalid URI. */ public static String emit(IData input) throws URISyntaxException { if (input == null) return null; return toString(fromIData(input)); } public static String normalize(String input) throws URISyntaxException { return toString(normalize(fromString(input))); } public static IData normalize(IData input) throws URISyntaxException { return toIData(normalize(fromIData(input))); } public static URI normalize(URI uri) { if (uri == null) return null; return uri.normalize(); } public static String encode(String input) { return encode(input, DEFAULT_CHARSET); } public static String encode(String input, String charsetName) { return encode(input, CharsetHelper.normalize(charsetName, DEFAULT_CHARSET)); } public static String encode(String input, Charset charset) { if (input == null) return null; String output; try { output = URLEncoder.encode(input, CharsetHelper.normalize(charset, DEFAULT_CHARSET).name()).replace("+", "%20"); } catch (UnsupportedEncodingException ex) { throw new IllegalArgumentException(ex); // this should never happen } return output; } public static String[] encode(String[] input) { return encode(input, DEFAULT_CHARSET); } public static String[] encode(String[] input, String charsetName) { return encode(input, CharsetHelper.normalize(charsetName, DEFAULT_CHARSET)); } public static String[] encode(String[] input, Charset charset) { if (input == null) return null; String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) { output[i] = encode(input[i], charset); } return output; } public static IData encode(IData document, Charset charset) { return Transformer.transform(document, new Encoder(charset)); } public static String decode(String input) { return decode(input, DEFAULT_CHARSET); } public static String decode(String input, String charsetName) { return decode(input, CharsetHelper.normalize(charsetName, DEFAULT_CHARSET)); } public static String decode(String input, Charset charset) { if (input == null) return null; String output; try { output = URLDecoder.decode(input, CharsetHelper.normalize(charset, DEFAULT_CHARSET).name()); } catch (UnsupportedEncodingException ex) { throw new IllegalArgumentException(ex); // this should never happen } return output; } public static String[] decode(String[] input) { return decode(input, DEFAULT_CHARSET); } public static String[] decode(String[] input, String charsetName) { return decode(input, CharsetHelper.normalize(charsetName, DEFAULT_CHARSET)); } public static String[] decode(String[] input, Charset charset) { if (input == null) return null; String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) { output[i] = decode(input[i], charset); } return output; } public static IData decode(IData document, Charset charset) { return Transformer.transform(document, new Decoder(charset)); } /** * Performs variable substitution on the components of the given URI string. * * @param uri The URI string to perform variable substitution on. * @param scope The scope variables are resolved against. * @return The resulting URI string after variable substitution. * @throws URISyntaxException If the given string is not a valid URI. */ public static String substitute(String uri, IData scope) throws URISyntaxException { if (uri != null) { // possible URI template if (uri.contains("{")) { uri = expandTemplate(uri, scope); } IData parsedURI = parse(uri); // possible variable substitution strings if (uri.contains("%25")) { parsedURI = SubstitutionHelper.substitute(parsedURI, null, true, false, null, scope); } uri = emit(parsedURI); } return uri; } /** * Regular expression pattern to match URI template style variables. */ private static final Pattern URI_TEMPLATE_VARIABLE = Pattern.compile("\\{([^\\{\\}]+)\\}"); /** * Expands the given URI template using the given variable scope. * * @param template The URI template to expand. * @param scope The scope against which variable references in the template are resolved. * @return The expanded URI template where variable references have been resolved against the given scope. */ private static String expandTemplate(String template, IData scope) { if (template != null) { StringBuilder builder = new StringBuilder(); Matcher matcher = URI_TEMPLATE_VARIABLE.matcher(template); int index = 0; while (matcher.find()) { builder.append(template, index, matcher.start()); builder.append(encode(SubstitutionHelper.resolve(matcher.group(1), String.class, matcher.group(0), null, scope))); index = matcher.end(); } if (index > 0) { builder.append(template.substring(index)); template = builder.toString(); } } return template; } /** * Converts a URI object to an IData representation. * * @param uri The URI object to be converted. * @return An IData representation of the given URI. */ public static IData toIData(URI uri) { if (uri == null) return null; IData output = IDataFactory.create(); IDataCursor cursor = output.getCursor(); try { String scheme = uri.getScheme(); // schemes are case-insensitive, according to RFC 2396 if (scheme != null) scheme = scheme.toLowerCase(); IDataHelper.put(cursor, "scheme", scheme, false); IData query = null; if (uri.isOpaque()) { String schemeSpecificPart = uri.getRawSchemeSpecificPart(); if (schemeSpecificPart != null) { if (schemeSpecificPart.contains(URI_QUERY_DELIMITER)) { query = URIQueryHelper.parse(schemeSpecificPart.substring(schemeSpecificPart.indexOf(URI_QUERY_DELIMITER) + 1), true); schemeSpecificPart = schemeSpecificPart.substring(0, schemeSpecificPart.indexOf(URI_QUERY_DELIMITER)); } IDataHelper.put(cursor, "body", decode(schemeSpecificPart)); } } else { String authority = uri.getAuthority(); if (authority != null) { // hosts are case-insensitive, according to RFC 2396, but we will preserve the case to be safe String host = uri.getHost(); IData authorityDocument = IDataFactory.create(); IDataCursor ac = authorityDocument.getCursor(); try { if (host == null) { // if host is null, then this URI must be registry-based IDataHelper.put(ac, "registry", authority); } else { IData server = IDataFactory.create(); IDataCursor sc = server.getCursor(); try { // parse user-info component according to the format user:[password] String user = uri.getUserInfo(); String password = null; if (user != null && user.contains(URI_USER_PASSWORD_DELIMITER)) { password = user.substring(user.indexOf(URI_USER_PASSWORD_DELIMITER) + 1); user = user.substring(0, user.indexOf(URI_USER_PASSWORD_DELIMITER)); } IDataHelper.put(sc, "user", user, false); IDataHelper.put(sc, "password", password, false); IDataHelper.put(sc, "host", host, false); // if port is -1, then it wasn't specified in the URI int port = uri.getPort(); if (port >= 0) IDataHelper.put(sc, "port", port, String.class); } finally { sc.destroy(); } IDataHelper.put(ac, "server", server); } IDataUtil.put(cursor, "authority", authorityDocument); } finally { ac.destroy(); } } String path = uri.getPath(); if (path != null && !path.equals("")) { String[] paths = URIPathHelper.parse(path); if (paths != null && paths.length > 0) { String file = null; if (!path.endsWith(URI_PATH_DELIMITER)) { file = ArrayHelper.get(paths, -1); paths = ArrayHelper.drop(paths, -1); } IDataHelper.put(cursor, "path", paths, false); IDataHelper.put(cursor, "path.absolute?", path.startsWith(URI_PATH_DELIMITER), String.class); IDataHelper.put(cursor, "file", file, false); } } query = URIQueryHelper.parse(uri.getRawQuery(), true); } IDataHelper.put(cursor, "query", query, false); IDataHelper.put(cursor, "fragment", uri.getFragment(), false); IDataHelper.put(cursor, "absolute?", uri.isAbsolute(), String.class); IDataHelper.put(cursor, "opaque?", uri.isOpaque(), String.class); } finally { cursor.destroy(); } return output; } /** * Converts an IData document to a URI object. * * @param input An IData containing a specific URI structure. * @return The resulting URI object representing the given IData. * @throws URISyntaxException If the given IData document represents an invalid URI. */ public static URI fromIData(IData input) throws URISyntaxException { if (input == null) return null; URI uri; IDataCursor cursor = input.getCursor(); try { String scheme = IDataUtil.getString(cursor, "scheme"); // schemes are case-insensitive, according to RFC 2396 if (scheme != null) scheme = scheme.toLowerCase(); String fragment = IDataHelper.get(cursor, "fragment", String.class); IData queryDocument = IDataHelper.get(cursor, "query", IData.class); String query = URIQueryHelper.emit(queryDocument, false); String body = IDataHelper.get(cursor, "body", String.class); IData authority = IDataHelper.get(cursor, "authority", IData.class); String[] paths = IDataHelper.get(cursor, "path", String[].class); boolean absolutePath = IDataHelper.getOrDefault(cursor, "path.absolute?", Boolean.class, true); String file = IDataHelper.get(cursor, "file", String.class); if (body == null && !(authority == null && paths == null && file == null)) { // create an hierarchical URI String path; if ((paths != null || file != null) && (absolutePath || authority != null)) { path = URI_PATH_DELIMITER; } else { path = null; } if (paths != null && paths.length > 0) { path = (path == null ? "" : path) + ArrayHelper.join(paths, URI_PATH_DELIMITER); } if (file == null) { if (path != null && !path.equals(URI_PATH_DELIMITER)) { path = path + URI_PATH_DELIMITER; } } else { if (path == null) { path = file; } else if (path.equals(URI_PATH_DELIMITER)) { path = path + file; } else { path = path + URI_PATH_DELIMITER + file; } } if (authority == null) { uri = new URI(scheme, null, path, query, fragment); } else { IDataCursor ac = authority.getCursor(); String registry = IDataHelper.get(ac, "registry", String.class); IData server = IDataHelper.get(ac, "server", IData.class); ac.destroy(); if (registry == null) { IDataCursor sc = server.getCursor(); // hosts are case-insensitive, according to RFC 2396, but we will preserve the case to be safe String host = IDataHelper.get(sc, "host", String.class); int port = IDataHelper.getOrDefault(sc, "port", Integer.class, -1); // remove the explicit port if it is the default port for the scheme if (port != -1 && isDefaultPort(scheme, port)) { port = -1; } String userinfo = IDataHelper.get(sc, "user", String.class); if (userinfo != null) { if (userinfo.equals("")) { userinfo = null; // ignore empty strings } else { String password = IDataHelper.get(sc, "password", String.class); if (password != null && !(password.equals(""))) userinfo = userinfo + ":" + password; } } sc.destroy(); uri = new URI(scheme, userinfo, host, port, path, query, fragment); } else { uri = new URI(scheme, registry, path, query, fragment); } } } else if (query != null) { uri = new URI(scheme, (body == null ? "" : body) + URI_QUERY_DELIMITER + query, fragment); } else if (body != null) { uri = new URI(scheme, body, fragment); } else { uri = new URI(""); } } finally { cursor.destroy(); } return uri; } /** * Parses a given string to a URI object. * * @param input A URI string to be parsed. * @return The parsed URI object. */ public static URI fromString(String input) throws URISyntaxException { if (input == null) return null; // treat Windows UNC file URIs as server-based rather than path-based if (input.toLowerCase().startsWith("file: input = "file://" + input.substring(9, input.length()); } return new URI(input); } /** * Emits a URI given as an IData document as a string. * * @param uri A URI object to be serialized. * @return The serialized URI. */ public static String toString(URI uri) { if (uri == null) return null; String output = uri.toASCIIString(); // support Windows UNC file URIs, and work-around Java bug with // file URIs where scheme is followed by ':/' rather than '://' if (output.startsWith("file:") && uri.getHost() == null) { output = "file://" + output.substring(5, output.length()); } return output; } /** * Returns the default port for the given scheme. * * @param scheme The URI scheme. * @return The default port for the given scheme, if defined. */ public static Integer getDefaultPort(String scheme) { Integer defaultPort = null; if (scheme != null) { defaultPort = DEFAULT_PORTS.get(scheme.toLowerCase()); } return defaultPort; } /** * Returns true if the given port is the default port for the given scheme. * * @param scheme The URI scheme. * @param port The port to check. * @return True if the given port is the default port for the given scheme. */ public static boolean isDefaultPort(String scheme, int port) { boolean isDefaultPort = false; if (scheme != null) { String key = scheme.toLowerCase(); isDefaultPort = DEFAULT_PORTS.containsKey(key) && DEFAULT_PORTS.get(key) == port; } return isDefaultPort; } private static final Map<String, Integer> DEFAULT_PORTS = new TreeMap<String, Integer>(); static { DEFAULT_PORTS.put("acap", 674); DEFAULT_PORTS.put("afp", 548); DEFAULT_PORTS.put("dict", 2628); DEFAULT_PORTS.put("dns", 53); DEFAULT_PORTS.put("ftp", 21); DEFAULT_PORTS.put("ftps", 990); DEFAULT_PORTS.put("git", 9418); DEFAULT_PORTS.put("gopher", 70); DEFAULT_PORTS.put("http", 80); DEFAULT_PORTS.put("https", 443); DEFAULT_PORTS.put("imap", 143); DEFAULT_PORTS.put("ipp", 631); DEFAULT_PORTS.put("ipps", 631); DEFAULT_PORTS.put("irc", 194); DEFAULT_PORTS.put("ircs", 6697); DEFAULT_PORTS.put("ldap", 389); DEFAULT_PORTS.put("ldaps", 636); DEFAULT_PORTS.put("mms", 1755); DEFAULT_PORTS.put("msrp", 2855); DEFAULT_PORTS.put("mtqp", 1038); DEFAULT_PORTS.put("nfs", 111); DEFAULT_PORTS.put("nntp", 119); DEFAULT_PORTS.put("nntps", 563); DEFAULT_PORTS.put("pop", 110); DEFAULT_PORTS.put("prospero", 1525); DEFAULT_PORTS.put("redis", 6379); DEFAULT_PORTS.put("rsync", 873); DEFAULT_PORTS.put("rtsp", 554); DEFAULT_PORTS.put("rtsps", 322); DEFAULT_PORTS.put("rtspu", 5005); DEFAULT_PORTS.put("scp", 22); DEFAULT_PORTS.put("sftp", 22); DEFAULT_PORTS.put("smb", 445); DEFAULT_PORTS.put("snmp", 161); DEFAULT_PORTS.put("ssh", 22); DEFAULT_PORTS.put("svn", 3690); DEFAULT_PORTS.put("telnet", 23); DEFAULT_PORTS.put("ventrilo", 3784); DEFAULT_PORTS.put("vnc", 5900); DEFAULT_PORTS.put("wais", 210); DEFAULT_PORTS.put("ws", 80); DEFAULT_PORTS.put("wss", 443); } }
package permafrost.tundra.tn.route; import com.wm.app.b2b.server.InvokeState; import com.wm.app.b2b.server.ServiceException; import com.wm.app.tn.db.Datastore; import com.wm.app.tn.db.SQLStatements; import com.wm.app.tn.db.SQLWrappers; import com.wm.data.IData; import permafrost.tundra.lang.Startable; import permafrost.tundra.server.SchedulerHelper; import permafrost.tundra.server.SchedulerStatus; import permafrost.tundra.server.ServerThreadFactory; import permafrost.tundra.util.concurrent.BoundedPriorityBlockingQueue; import permafrost.tundra.util.concurrent.ImmediateFuture; import permafrost.tundra.util.concurrent.PrioritizedThreadPoolExecutor; import javax.xml.datatype.Duration; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Calendar; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Used to defer processing of bizdocs to a dedicated thread pool. */ public class Deferrer implements Startable { /** * SQL statement for seeding deferred queue on startup. */ protected final static String SELECT_DEFERRED_BIZDOCS_FOR_SEEDING = "SELECT DocID FROM BizDoc WHERE UserStatus = 'DEFERRED' AND LastModified <= ? AND DocTimestamp = (SELECT MIN(DocTimestamp) FROM BizDoc WHERE UserStatus = 'DEFERRED' AND LastModified <= ?)"; /** * The default timeout for database queries. */ protected static final int DEFAULT_SQL_STATEMENT_QUERY_TIMEOUT_SECONDS = 30; /** * How long to keep threads alive in the pool when idle. */ protected static final long DEFAULT_THREAD_KEEP_ALIVE_MILLISECONDS = 5 * 60 * 1000L; /** * How often to reseed from the database to self-heal after outages and load balance. */ protected static final long DEFAULT_RESEED_SCHEDULE_MILLISECONDS = 60 * 1000L; /** * How old deferred documents need to be before they get reseeded. */ protected static final long DEFAULT_RESEED_BIZDOC_AGE = 5 * 60 * 1000L; /** * The default maximum capacity for the work queue. */ protected static final int DEFAULT_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2; /** * The default maximum capacity for the work queue. */ protected static final int DEFAULT_WORK_QUEUE_CAPACITY = DEFAULT_THREAD_POOL_SIZE * 256; /** * Maximum time to wait to shutdown the executor in nanoseconds. */ protected static final long DEFAULT_SHUTDOWN_TIMEOUT = 5L * 60 * 1000 * 1000 * 1000; /** * Is this object started or stopped? */ protected volatile boolean started; /** * The executors used to run deferred jobs by thread priority. */ protected volatile ThreadPoolExecutor executor; /** * The scheduler used to self-heal and load balance by seeding deferred documents from database regularly. */ protected volatile ScheduledExecutorService scheduler; /** * The level of concurrency to use, equal to the number of threads in the pool used for processing. */ protected volatile int concurrency; /** * The maximum capacity of the work queue. */ protected volatile int capacity; /** * Initialization on demand holder idiom. */ private static class Holder { /** * The singleton instance of the class. */ private static final Deferrer DEFERRER = new Deferrer(); } /** * Creates a new Deferrer. */ public Deferrer() { this(DEFAULT_THREAD_POOL_SIZE); } /** * Creates a new Deferrer. * * @param concurrency The level of concurrency to use. */ public Deferrer(int concurrency) { this(concurrency, DEFAULT_WORK_QUEUE_CAPACITY); } /** * Creates a new Deferrer. * * @param concurrency The level of concurrency to use. * @param capacity The maximum capacity of the work queue. */ public Deferrer(int concurrency, int capacity) { this.concurrency = concurrency; this.capacity = capacity; } /** * Returns the singleton instance of this class. * * @return the singleton instance of this class. */ public static Deferrer getInstance() { return Holder.DEFERRER; } /** * Defers the given route to be run by a dedicated thread pool. Runs route immediately if deferrer has been * shutdown. * * @param route The route to be deferred. * @return A future containing the result of the route. * @throws ServiceException If route throws an exception. */ public Future<IData> defer(CallableRoute route) throws ServiceException { if (route == null) throw new NullPointerException("route must not be null"); Future<IData> result = null; if (isStarted()) { result = executor.submit(route); } if (result == null) { // fallback to routing on the current thread, if deferrer is shutdown or otherwise busy result = new ImmediateFuture<IData>(route.call()); } return result; } /** * Returns the current level of concurrency used. * * @return the current level of concurrency used. */ public int getConcurrency() { return concurrency; } /** * Sets the size of the thread pool. * * @param concurrency The level of concurrency to use. */ public synchronized void setConcurrency(int concurrency) { if (concurrency < 1) throw new IllegalArgumentException("concurrency must be >= 1"); this.concurrency = concurrency; } /** * Sets the maximum capacity of the work queue. * * @param capacity The maximum capacity of the work queue. */ public synchronized void setCapacity(int capacity) { if (capacity < 1) throw new IllegalArgumentException("capacity must be >= 1"); this.capacity = capacity; } /** * Returns the number of queued tasks. * * @return the number of queued tasks. */ public int size() { int size = 0; if (isStarted()) { size = executor.getQueue().size(); } return size; } /** * Seeds the work queue with any bizdocs in the database with user status "DEFERRED", regardless of age. */ public void seed() { seed(0); } /** * Seeds the work queue with any bizdocs in the database with user status "DEFERRED" with the given age. * * @param age The age that candidate bizdocs must be before being seeded. */ public void seed(Duration age) { seed(age.getTimeInMillis(Calendar.getInstance())); } /** * Attempt to directly route bizdocs in the database with user status "DEFERRED" with the given age. * * @param age The age in milliseconds that candidate bizdocs must be before being seeded. */ public void seed(long age) { if (isStarted()) { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = Datastore.getConnection(); statement = connection.prepareStatement(SELECT_DEFERRED_BIZDOCS_FOR_SEEDING); statement.setQueryTimeout(DEFAULT_SQL_STATEMENT_QUERY_TIMEOUT_SECONDS); statement.clearParameters(); Timestamp timestamp = new Timestamp(System.currentTimeMillis() - age); SQLWrappers.setTimestamp(statement, 1, timestamp); SQLWrappers.setTimestamp(statement, 2, timestamp); while (isStarted()) { try { resultSet = statement.executeQuery(); if (resultSet.next()) { String id = resultSet.getString(1); if (id == null) { break; } else { try { CallableRoute route = new CallableRoute(id); route.call(); } catch (Exception ex) { // do nothing } } } else { break; } } finally { SQLWrappers.close(resultSet); connection.commit(); } } } catch (SQLException ex) { connection = Datastore.handleSQLException(connection, ex); throw new RuntimeException(ex); } finally { SQLStatements.releaseStatement(statement); Datastore.releaseConnection(connection); } } } /** * Starts this object. */ @Override public synchronized void start() { if (!started) { ThreadFactory threadFactory = new ServerThreadFactory("TundraTN/Defer Worker", null, InvokeState.getCurrentState(), Thread.NORM_PRIORITY, false); executor = new PrioritizedThreadPoolExecutor(concurrency, concurrency, DEFAULT_THREAD_KEEP_ALIVE_MILLISECONDS, TimeUnit.MILLISECONDS, new BoundedPriorityBlockingQueue<Runnable>(capacity), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy()); scheduler = Executors.newScheduledThreadPool(1, new ServerThreadFactory("TundraTN/Defer Seeder", InvokeState.getCurrentState())); scheduler.scheduleWithFixedDelay(new Runnable() { public void run() { if (SchedulerHelper.status() == SchedulerStatus.STARTED) { seed(DEFAULT_RESEED_BIZDOC_AGE); } } }, DEFAULT_RESEED_SCHEDULE_MILLISECONDS, DEFAULT_RESEED_SCHEDULE_MILLISECONDS, TimeUnit.MILLISECONDS); started = true; } } /** * Stops this object. */ @Override public synchronized void stop() { if (started) { started = false; try { scheduler.shutdown(); executor.shutdown(); executor.awaitTermination(DEFAULT_SHUTDOWN_TIMEOUT, TimeUnit.NANOSECONDS); } catch(InterruptedException ex) { // ignore interruption to this thread } finally { scheduler.shutdownNow(); executor.shutdownNow(); } } } /** * Returns true if the object is started. * @return true if the object is started. */ @Override public boolean isStarted() { return started; } }
package pitt.search.semanticvectors; import org.apache.lucene.document.Document; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.BytesRef; import org.netlib.blas.BLAS; import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod; import pitt.search.semanticvectors.utils.Bobcat; import pitt.search.semanticvectors.utils.SigmoidTable; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.BinaryVector; import pitt.search.semanticvectors.vectors.PermutationUtils; import pitt.search.semanticvectors.vectors.PermutationVector; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.vectors.VectorUtils; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger; /** * Generates predication vectors incrementally.Requires as input an index containing * documents with the fields "subject", "predicate" and "object" * * Produces as output the files: elementalvectors.bin, predicatevectors.bin and semanticvectors.bin * * This class requires an index with a specific structure that can be generated * * * @author Trevor Cohen, Dominic Widdows */ public class ESPperm { private static final int MAX_EXP = 6; private static final Logger logger = Logger.getLogger(ESPperm.class.getCanonicalName()); private FlagConfig flagConfig; private VectorStore elementalItemVectors; private VectorStoreRAM semanticItemVectors, permutationVectors; private static final String SUBJECT_FIELD = "subject"; private static final String PREDICATE_FIELD = "predicate"; private static final String OBJECT_FIELD = "object"; private static final String PREDICATION_FIELD = "predication"; private String[] itemFields = {SUBJECT_FIELD, OBJECT_FIELD}; private int tc = 0; private double initial_alpha = 0.025; private double alpha = 0.025; private double min_alpha = 0.0001; private SigmoidTable sigmoidTable = new SigmoidTable(MAX_EXP,1000); private ConcurrentHashMap<String,ConcurrentSkipListMap<Double, String>> termDic; private ConcurrentHashMap<String,Double> totalPool; //total pool of terms probabilities for negative sampling corpus private LuceneUtils luceneUtils; private HashSet<String> addedConcepts; private static Random random; private java.util.concurrent.atomic.AtomicInteger dc = new java.util.concurrent.atomic.AtomicInteger(0); private java.util.concurrent.atomic.AtomicInteger pc = new java.util.concurrent.atomic.AtomicInteger(0); private ConcurrentLinkedQueue<Document> theQ = new ConcurrentLinkedQueue<Document>(); private ConcurrentLinkedQueue<Integer> randomStartpoints = new ConcurrentLinkedQueue<Integer>(); private ConcurrentHashMap<String,String> semtypes = new ConcurrentHashMap<String,String>(); private HashMap<Object,String> cuis = new HashMap<Object,String>(); private ConcurrentHashMap<String, Double> subsamplingProbabilities; private ESPperm(FlagConfig flagConfig) { }; /** * Creates ESP vectors incrementally, using the fields "subject" and "object" from a Lucene index. */ public static void createIncrementalESPVectors(FlagConfig flagConfig) throws IOException { ESPperm incrementalESPVectors = new ESPperm(flagConfig); random = new Random(); incrementalESPVectors.flagConfig = flagConfig; incrementalESPVectors.initialize(); VerbatimLogger.info("Performing first round of ESP training ..."); incrementalESPVectors.trainIncrementalESPVectors(); VerbatimLogger.info("Done with createIncrementalESPVectors."); } /** * Creates elemental and semantic vectors for each concept, and elemental vectors for predicates. * * @throws IOException */ private void initialize() throws IOException { if (this.luceneUtils == null) { this.luceneUtils = new LuceneUtils(flagConfig); } elementalItemVectors = new ElementalVectorStore(flagConfig); semanticItemVectors = new VectorStoreRAM(flagConfig); //to accommodate pre-training if (!flagConfig.initialtermvectors().isEmpty()) { String[] initialVectorFiles = flagConfig.initialtermvectors().split(","); if (initialVectorFiles.length == 2) { elementalItemVectors = new VectorStoreRAM(flagConfig); ((VectorStoreRAM) elementalItemVectors).initFromFile(initialVectorFiles[0]); ((VectorStoreRAM) semanticItemVectors).initFromFile(initialVectorFiles[1]); VerbatimLogger.info("Initialized elemental vectors from "+initialVectorFiles[0]+"\n"); VerbatimLogger.info("Initialized semantic vectors from "+initialVectorFiles[1]+"\n"); } } //permit dueling VectorTypes (e.g. permutation and real) - probably worth refactoring VectorType originalVectorType = flagConfig.vectortype(); flagConfig.setVectortype(VectorType.PERMUTATION); permutationVectors = new VectorStoreRAM(flagConfig); flagConfig.setVectortype(originalVectorType); flagConfig.setContentsfields(itemFields); termDic = new ConcurrentHashMap<String, ConcurrentSkipListMap<Double, String>>(); totalPool = new ConcurrentHashMap<String, Double>(); addedConcepts = new HashSet<String>(); // Term counter to track initialization progress. int termCounter = 0; for (String fieldName : itemFields) { Terms terms = luceneUtils.getTermsForField(fieldName); if (terms == null) { throw new NullPointerException(String.format( "No terms for field '%s'. Please check that index at '%s' was built correctly for use with ESP.", fieldName, flagConfig.luceneindexpath())); } TermsEnum termsEnum = terms.iterator(); BytesRef bytes; while((bytes = termsEnum.next()) != null) { Term term = new Term(fieldName, bytes); if (!luceneUtils.termFilter(term)) { VerbatimLogger.fine("Filtering out term: " + term + "\n"); continue; } if (!addedConcepts.contains(term.text())) { addedConcepts.add(term.text()); if (!elementalItemVectors.containsVector(term.text())) { if (flagConfig.initialtermvectors().isEmpty()) elementalItemVectors.getVector(term.text()); // Causes vector to be created. else //pretraining { if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH)) random.setSeed(Bobcat.asLong(term.text())); //deterministic initialization ((VectorStoreRAM) elementalItemVectors).putVector(term.text(), VectorFactory.generateRandomVector( flagConfig.vectortype(), flagConfig.dimension(), flagConfig.seedlength(), random)); } } //store the semantic type String semtype = ""; if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH)) random.setSeed(Bobcat.asLong("_SEMANTIC_"+term.text())); //deterministic initialization if (flagConfig.semtypesandcuis()) { PostingsEnum docEnum = luceneUtils.getDocsForTerm(term); docEnum.nextDoc(); Document theDoc = luceneUtils.getDoc(docEnum.docID()); if (term.field().equals(SUBJECT_FIELD)) semtype = theDoc.get("subject_semtype"); else if (term.field().equals(OBJECT_FIELD)) semtype = theDoc.get("object_semtype"); semtypes.put(term.text(), semtype); String cui = ""; if (term.field().equals(SUBJECT_FIELD)) cui = theDoc.get("subject_CUI"); else if (term.field().equals(OBJECT_FIELD)) cui = theDoc.get("object_CUI"); cuis.put(term.text(), cui); if (!semanticItemVectors.containsVector(term.text())) semanticItemVectors.putVector(term.text(), VectorFactory.generateRandomVector( flagConfig.vectortype(), flagConfig.dimension(), flagConfig.seedlength(), random)); } else { if (!semanticItemVectors.containsVector(term.text())) semanticItemVectors.putVector(term.text(), VectorFactory.generateRandomVector( flagConfig.vectortype(), flagConfig.dimension(), flagConfig.seedlength(), random)); semtype = "universal"; //ignore semantic types } //table for negative sampling, stratified by semantic type (if available) if (! termDic.containsKey(semtype)) { System.out.println(semtype); totalPool.put(semtype,0d); termDic.put(semtype, new ConcurrentSkipListMap<Double, String>()); } //determine frequency with which a concept is drawn as a negative sample //following the word2vec work, we use unigram^.75 //totalPool is a ConcurrentHashMap - it defines a range for each concept (for each semantic type, if these are used) //the relative size of the range determines the negative sampling frequency for each concept int countSubj = luceneUtils.getGlobalDocFreq(new Term("subject",term.text())); int countObj = luceneUtils.getGlobalDocFreq(new Term("object",term.text())); double globalFreq = (countSubj + countObj) / (double) luceneUtils.getNumDocs()*2; double discount = 1; if (flagConfig.discountnegativesampling() && globalFreq > flagConfig.samplingthreshold()) { discount = Math.sqrt(flagConfig.samplingthreshold() / globalFreq); } //negative sampling table totalPool.put(semtype, totalPool.get(semtype)+Math.pow(discount*(countSubj+countObj), .75)); termDic.get(semtype).put(totalPool.get(semtype), term.text()); // Output term counter. termCounter++; if ((termCounter > 0) && ((termCounter % 10000 == 0) || ( termCounter < 10000 && termCounter % 1000 == 0 ))) { VerbatimLogger.info("Initialized " + termCounter + " term vectors ... "); } } } } // Now elemental vectors for the predicate field. Terms predicateTerms = luceneUtils.getTermsForField(PREDICATE_FIELD); String[] dummyArray = new String[] { PREDICATE_FIELD }; // To satisfy LuceneUtils.termFilter interface. TermsEnum termsEnum = predicateTerms.iterator(); BytesRef bytes; while((bytes = termsEnum.next()) != null) { Term term = new Term(PREDICATE_FIELD, bytes); // frequency thresholds do not apply to predicates... but the stopword list does if (!luceneUtils.termFilter(term, dummyArray, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, 1)) continue; if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH)) random.setSeed(Bobcat.asLong(term.text().trim())); PermutationVector thePerm = new PermutationVector(PermutationUtils.getRandomPermutation(flagConfig.vectortype(), flagConfig.dimension(),random)); Vector inversePerm = new PermutationVector(PermutationUtils.getInversePermutation(thePerm.getCoordinates())); if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH)) random.setSeed(Bobcat.asLong(term.text().trim()+"-INV")); PermutationVector theInvPerm = new PermutationVector(PermutationUtils.getRandomPermutation(flagConfig.vectortype(), flagConfig.dimension(),random)); Vector inverseInvPerm = new PermutationVector(PermutationUtils.getInversePermutation(theInvPerm.getCoordinates())); permutationVectors.putVector(term.text().trim(), thePerm); permutationVectors.putVector("_"+term.text().trim(), inversePerm); permutationVectors.putVector(term.text().trim() + "-INV", theInvPerm); permutationVectors.putVector("_"+term.text().trim() + "-INV", inverseInvPerm); } //precalculate probabilities for subsampling (need to iterate again once total term frequency known) if (flagConfig.samplingthreshold() > -1 && flagConfig.samplingthreshold() < 1) { subsamplingProbabilities = new ConcurrentHashMap<String, Double>(); double totalConceptCount = luceneUtils.getNumDocs()*2; //there are two concepts per predication VerbatimLogger.info("Populating subsampling probabilities - total concept count = " + totalConceptCount + " which is " + (totalConceptCount / luceneUtils.getNumDocs()) + " per doc on average"); int count = 0; Iterator<String> termIterator = addedConcepts.iterator(); Object termName; while (termIterator.hasNext() && (termName = termIterator.next()) != null) { if (++count % 10000 == 0) VerbatimLogger.info("."); // Skip terms that don't pass the filter. if (!semanticItemVectors.containsVector(termName)) continue; double subFreq = luceneUtils.getGlobalDocFreq(new Term("subject",termName.toString())); double obFreq = luceneUtils.getGlobalDocFreq(new Term("object",termName.toString())); double globalFreq = (subFreq + obFreq) / (double) totalConceptCount; if (globalFreq > flagConfig.samplingthreshold()) { double discount = 1; //(globalFreq - flagConfig.samplingthreshold()) / globalFreq; subsamplingProbabilities.put(termName.toString(), (discount - Math.sqrt(flagConfig.samplingthreshold() / globalFreq))); } } //all terms for one field VerbatimLogger.info("\n"); if (subsamplingProbabilities !=null && subsamplingProbabilities.size() > 0) VerbatimLogger.info("Selected for subsampling: " + subsamplingProbabilities.size() + " terms.\n"); } } /** * Each TrainPredThred draws from the predication queue, and sends the predication for processing. * TrainPredThreads operate in parallel * @author tcohen * */ private class TrainPredThread implements Runnable { BLAS blas = null; public TrainPredThread(int threadno) { this.blas = BLAS.getInstance(); } @Override public void run() { Document document = null; int complete = 0; while (! (complete == -1 && theQ.isEmpty())) { document = theQ.poll(); if (document == null) { complete = populateQueue(); document = theQ.poll(); } if (document != null) processPredicationDocument(document, blas); } } } /** * Look up the sigmoid function of input "z" in a pregenerated lookup table * @param z * @return */ public double sigmoid(double z) { return sigmoidTable.sigmoid(z); } /** * Returns zero minus the extent to which a negative-sample/predicate product is related to an index concept * This scalar is applied to the negative sample vector upon superposition, * drawing the system state closer to a state in which the similarity between these vectors is minimal * @param v1 * @param v2 * @param flagConfig * @param blas * @return */ public double shiftAway(Vector v1, Vector v2, FlagConfig flagConfig, BLAS blas, int[] permutation) { if (!flagConfig.vectortype().equals(VectorType.BINARY)) return -sigmoid(VectorUtils.scalarProduct(v1, v2, flagConfig, blas, permutation)); else return -100*Math.max(VectorUtils.scalarProduct(v1, v2, flagConfig, blas, permutation),0); } /** * Returns 1 minus the extent to which a positive-sample/predicate product is related to an index concept * This scalar is applied to the negative sample vector upon superposition, * drawing the system state closer to a state in which the similarity between these vectors is maximal * @param v1 * @param v2 * @param flagConfig * @param blas * @return */ public double shiftToward(Vector v1, Vector v2, FlagConfig flagConfig, BLAS blas, int[] permutation) { if (!flagConfig.vectortype().equals(VectorType.BINARY)) return 1-sigmoid(VectorUtils.scalarProduct(v1, v2, flagConfig, blas, permutation)); else return 100-100*Math.max(VectorUtils.scalarProduct(v1, v2, flagConfig, blas, permutation),0); } /** * Encode a single predication * @param subject * @param predicate * @param object * @param subsem subject semantic type * @param obsem object semantic type * @param blas */ private void processPredication(String subject, String predicate, String object, String subsem, String obsem, BLAS blas) { Vector subjectSemanticVector = semanticItemVectors.getVector(subject); Vector copyOfSubjectSemanticVector = semanticItemVectors.getVector(subject).copy(); Vector objectElementalVector = elementalItemVectors.getVector(object); PermutationVector predicatePermutation= (PermutationVector) permutationVectors.getVector(predicate); PermutationVector inversePermutation = (PermutationVector) permutationVectors.getVector("_"+predicate); if (!flagConfig.semtypesandcuis()) //if UMLS semantic types not available { subsem = "universal"; obsem = "universal"; } ArrayList<Vector> objNegSamples = new ArrayList<Vector>(); HashSet<String> duplicates = new HashSet<String>(); //get flagConfig.negsamples() negative samples as counterpoint to E(object) while (objNegSamples.size() <= flagConfig.negsamples()) { Vector objectsNegativeSample = null; int ocnt=0; //draw negative samples, using a unigram distribution for now while (objectsNegativeSample == null) { double test = random.nextDouble()*totalPool.get(obsem); if (termDic.get(obsem).ceilingEntry(test) != null) { String testConcept = termDic.get(obsem).ceilingEntry(test).getValue(); if (++ocnt > 10 && flagConfig.semtypesandcuis()) //probably a rare semantic type { test = random.nextDouble()*totalPool.get("dsyn"); testConcept = termDic.get("dsyn").ceilingEntry(test).getValue(); } if (duplicates.contains(testConcept)) continue; duplicates.add(testConcept); if (!testConcept.equals(object)) // don't use the observed object as a negative sample objectsNegativeSample = elementalItemVectors.getVector(testConcept); } } objNegSamples.add(objectsNegativeSample); } //observed predication double shiftToward = shiftToward(subjectSemanticVector,objectElementalVector, flagConfig, blas, predicatePermutation.getCoordinates()); VectorUtils.superposeInPlace(objectElementalVector, subjectSemanticVector, flagConfig, blas, shiftToward*alpha, predicatePermutation.getCoordinates()); VectorUtils.superposeInPlace(copyOfSubjectSemanticVector, objectElementalVector, flagConfig, blas, shiftToward*alpha, inversePermutation.getCoordinates()); //negative samples for (Vector objNegativeSample:objNegSamples) { double shiftAway = shiftAway(subjectSemanticVector,objNegativeSample, flagConfig, blas, predicatePermutation.getCoordinates()); VectorUtils.superposeInPlace(objNegativeSample, subjectSemanticVector, flagConfig, blas, shiftAway*alpha, predicatePermutation.getCoordinates()); VectorUtils.superposeInPlace(copyOfSubjectSemanticVector, objNegativeSample, flagConfig, blas, shiftAway*alpha, inversePermutation.getCoordinates()); } } /** * Process an individual predication (each Document object contains one predication) * in both directions (i.e. a PRED b; b PRED-INV a) * @param document **/ private void processPredicationDocument(Document document, BLAS blas) { String subject = document.get(SUBJECT_FIELD); String predicate = document.get(PREDICATE_FIELD); String object = document.get(OBJECT_FIELD); String predication = subject+predicate+object; String subsem = document.get("subject_semtype"); String obsem = document.get("object_semtype"); boolean encode = true; if (!flagConfig.semtypesandcuis()) { subsem = "universal"; obsem = "universal"; } if (!(elementalItemVectors.containsVector(object) && elementalItemVectors.containsVector(subject) && permutationVectors.containsVector(predicate))) { logger.fine("skipping predication " + subject + " " + predicate + " " + object); encode = false; } //subsampling of predications int predCount = luceneUtils.getGlobalTermFreq(new Term(PREDICATION_FIELD,predication)); double predFreq = (predCount / (double) luceneUtils.getNumDocs()); if (predFreq > flagConfig.samplingthreshold()*0.01) if (random.nextDouble() <= ( 1 - Math.sqrt(flagConfig.samplingthreshold()*0.01) / predFreq)) encode = false; //subsampling of terms above some threshold if (this.subsamplingProbabilities != null && this.subsamplingProbabilities.contains(subject) && random.nextDouble() <= this.subsamplingProbabilities.get(subject)) { encode = false; logger.fine("skipping predication " + object + " " + predicate + "-INV " + subject); } if (this.subsamplingProbabilities != null && this.subsamplingProbabilities.contains(object) && random.nextDouble() <= this.subsamplingProbabilities.get(object)) { encode = false; logger.fine("skipping predication " + subject + " " + predicate + " " + object); } if (encode) { this.processPredication(subject, predicate, object, subsem, obsem, blas); this.processPredication(object, predicate+"-INV", subject, obsem, subsem, blas); pc.incrementAndGet(); } if (pc.get() > 0 && pc.get() % 10000 == 0) { VerbatimLogger.info("Processed " + pc + " predications ... "); double progress = (tc*luceneUtils.getNumDocs() + dc.get()) / ((double) luceneUtils.getNumDocs()*(flagConfig.trainingcycles() +1) ); VerbatimLogger.info((100*progress)+"% complete ..."); alpha = Math.max(initial_alpha - (initial_alpha-min_alpha)*progress, min_alpha); VerbatimLogger.info("\nUpdated alpha to "+alpha+".."); } } /** * Points in total document collection to draw queue from (for randomization without excessive seek time) */ private void initializeRandomizationStartpoints() { this.randomStartpoints = new ConcurrentLinkedQueue<Integer>(); int increments = luceneUtils.getNumDocs() / 100000; boolean remainder = luceneUtils.getNumDocs() % 100000 > 0; if (remainder) increments++; ArrayList<Integer> toRandomize = new ArrayList<Integer>(); for (int x = 0; x < increments; x++) toRandomize.add(x * 100000); Collections.shuffle(toRandomize); randomStartpoints.addAll(toRandomize); } /** * * Populate the queue of predication-documents * 100,000 (or fewer if fewer remain) predication-documents are drawn, beginning * at a random start point in the Lucene index * * These random start points are retained in a separate queue and shuffled upon each epoch. * So the chunks of 100,000 predications are presented in different order across epochs. * * @return the number of documents added to the queue */ private synchronized int populateQueue() { if (dc.get() >= luceneUtils.getNumDocs()) return -1; if (theQ.size() > 100000) return 0; if (randomStartpoints.isEmpty()) return -1; int qb = randomStartpoints.poll(); //the index number of the first predication-document to be drawn int qe = qb + (100000); //the index number of the last predication-document to be drawn int qplus = 0; //the number of predication-documents added to the queue for (int qc=qb; qc < qe && qc < luceneUtils.getNumDocs() && dc.get() < luceneUtils.getNumDocs()-1; qc++) { try { Document nextDoc = luceneUtils.getDoc(qc); dc.incrementAndGet(); if (nextDoc != null) { theQ.add(nextDoc); qplus++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } VerbatimLogger.info("Added "+qplus+" documents to queue, now carrying "+theQ.size()); if (qplus == 0) return -1; else return qplus; } /** * Process word embeddings - i.e. P(text_word|subject) * @param embeddingVector * @param contextVectors * @param contextLabels * @param learningRate * @param blas * @param permutation * @param inversePermutation */ private void processEmbeddings( ArrayList<Vector> embeddingVectors, ArrayList<Vector> contextVectors, ArrayList<Integer> contextLabels, double learningRate, BLAS blas, int[] permutation, int[] inversePermutation) { double scalarProduct = 0; double error = 0; int counter = 0; Vector embeddingVector = VectorFactory.createZeroVector(flagConfig.vectortype(), flagConfig.dimension()); float weightReduction = 1; //assume the first vector is the word vector - it is weighted as much as all the ngrams in concert if balanced_subwords is true for (int v = 0; v < embeddingVectors.size(); v++) { weightReduction = 1 / ((float) embeddingVectors.size()); embeddingVector.superpose(embeddingVectors.get(v), weightReduction, null); } //for each contextVector (there should be one "true" context vector, and a number of negative samples) for (Vector contextVec : contextVectors) { Vector duplicateContextVec = contextVec.copy(); scalarProduct = VectorUtils.scalarProduct(embeddingVector, duplicateContextVec, flagConfig, blas, permutation); if (!flagConfig.vectortype().equals(VectorType.BINARY)) //sigmoid function { //if label == 1, a context word - so the error is the (1-predicted probability of for this word) - ideally 0 //if label == 0, a negative sample - so the error is the (predicted probability for this word) - ideally 0 if (scalarProduct > MAX_EXP) error = contextLabels.get(counter++) - 1; else if (scalarProduct < -MAX_EXP) error = contextLabels.get(counter++); else error = (float) (contextLabels.get(counter++) - sigmoidTable.sigmoid(scalarProduct)); } else //RELU-like function for binary vectors { scalarProduct = Math.max(scalarProduct, 0); error = contextLabels.get(counter++) - scalarProduct; //avoid passing floating points (the default behavior currently is to ignore these if the first superposition weight is an Integer) error = Math.round(error*100); } //update the context vector and embedding vector, respectively if (error != 0) { VectorUtils.superposeInPlace(embeddingVector, contextVec, flagConfig, blas, learningRate * error, inversePermutation); weightReduction = 1; //assume the first vector is the word vector - it is weighted as much as all the ngrams in concert for (int v = 0; v < embeddingVectors.size(); v++) { //if (v > 0) weightReduction = 1 / (float) embeddingVectors.size(); if (flagConfig.balanced_subwords) { if (v > 0) weightReduction = 1 / ((float) embeddingVectors.size()); } //technically should be embeddingVectors.size() -1 else weightReduction = 1 / ((float) embeddingVectors.size()); VectorUtils.superposeInPlace(duplicateContextVec, embeddingVectors.get(v), flagConfig, blas, weightReduction * learningRate * error, permutation); } } } } /** * Performs training by iterating over predications. Assumes that elemental vector stores are populated. * * @throws IOException */ private void trainIncrementalESPVectors() throws IOException { // For BINARY vectors, assign higher learning rates on account of the limited floating point precision of the voting record if (flagConfig.vectortype().equals(VectorType.BINARY)) { initial_alpha = 0.25; alpha = 0.25; min_alpha = 0.001; } //loop through the number of assigned epochs for (tc=0; tc <= flagConfig.trainingcycles(); tc++) { initializeRandomizationStartpoints(); theQ = new ConcurrentLinkedQueue<Document>(); dc.set(0); populateQueue(); double time = System.currentTimeMillis(); int numthreads = flagConfig.numthreads(); ExecutorService executor = Executors.newFixedThreadPool(numthreads); for (int q = 0; q < numthreads; q++) { executor.execute(new TrainPredThread(q)); } executor.shutdown(); // Wait until all threads are finish while (!executor.isTerminated()) { if (theQ.size() < 50000) populateQueue(); } VerbatimLogger.info("Time for cycle "+tc+" : "+((System.currentTimeMillis() - time) / (1000*60)) +" minutes"); VerbatimLogger.info("Processed "+pc.get()+" total predications (total on disk = "+luceneUtils.getNumDocs()+")"); //normalization with each epoch if the vectors are not binary vectors if (!flagConfig.vectortype().equals(VectorType.BINARY) && !flagConfig.notnormalized) { Enumeration<ObjectVector> semanticVectorEnumeration = semanticItemVectors.getAllVectors(); Enumeration<ObjectVector> elementalVectorEnumeration = elementalItemVectors.getAllVectors(); while (semanticVectorEnumeration.hasMoreElements()) { semanticVectorEnumeration.nextElement().getVector().normalize(); elementalVectorEnumeration.nextElement().getVector().normalize(); } } } // Finished all epochs Enumeration<ObjectVector> e = null; if (flagConfig.semtypesandcuis()) //write out cui vectors and normalize semantic vectors { // Also write out cui version of semantic vectors File vectorFile = new File("cuivectors.bin"); java.nio.file.Files.deleteIfExists(vectorFile.toPath()); String parentPath = vectorFile.getParent(); if (parentPath == null) parentPath = ""; FSDirectory fsDirectory = FSDirectory.open(FileSystems.getDefault().getPath(parentPath)); IndexOutput outputStream = fsDirectory.createOutput(vectorFile.getName(), IOContext.DEFAULT); outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); // Tally votes of semantic vectors and write out. e = semanticItemVectors.getAllVectors(); while (e.hasMoreElements()) { ObjectVector ov = e.nextElement(); if (flagConfig.vectortype().equals(VectorType.BINARY)) ((BinaryVector) ov.getVector()).tallyVotes(); else if (!flagConfig.notnormalized) ov.getVector().normalize(); if (cuis.containsKey(ov.getObject())) { outputStream.writeString(cuis.get(ov.getObject())); ov.getVector().writeToLuceneStream(outputStream); } } outputStream.close(); } else //just tally votes of semantic vectors { e = semanticItemVectors.getAllVectors(); while (e.hasMoreElements()) { ObjectVector ov = e.nextElement(); if (flagConfig.vectortype().equals(VectorType.BINARY)) ((BinaryVector) ov.getVector()).tallyVotes(); else if (!flagConfig.notnormalized()) ov.getVector().normalize(); } } e = elementalItemVectors.getAllVectors(); while (e.hasMoreElements()) { Vector nextVec = e.nextElement().getVector(); if (flagConfig.vectortype().equals(VectorType.BINARY)) ((BinaryVector) nextVec).tallyVotes(); else if (!flagConfig.notnormalized) nextVec.normalize(); } VectorStoreWriter.writeVectors( flagConfig.semanticvectorfile(), flagConfig, semanticItemVectors); VectorStoreWriter.writeVectors( flagConfig.elementalvectorfile(), flagConfig, elementalItemVectors); flagConfig.setVectortype(VectorType.PERMUTATION); VectorStoreWriter.writeVectors( flagConfig.permutationcachefile(), flagConfig, permutationVectors); VerbatimLogger.info("Finished writing semantic item and context vectors.\n"); } /** * Main method for building ESP indexes. */ public static void main(String[] args) throws IllegalArgumentException, IOException { FlagConfig flagConfig = FlagConfig.getFlagConfig(args); args = flagConfig.remainingArgs; if (flagConfig.luceneindexpath().isEmpty()) { throw (new IllegalArgumentException("-luceneindexpath argument must be provided.")); } VerbatimLogger.info("Building ESP model from index in: " + flagConfig.luceneindexpath() + "\n"); VerbatimLogger.info("Minimum frequency = " + flagConfig.minfrequency() + "\n"); VerbatimLogger.info("Maximum frequency = " + flagConfig.maxfrequency() + "\n"); VerbatimLogger.info("Number non-alphabet characters = " + flagConfig.maxnonalphabetchars() + "\n"); createIncrementalESPVectors(flagConfig); } }
package pl.grzeslowski.jsupla; import java.util.Collection; import static java.lang.String.format; public final class Preconditions { public static int min(int value, int min) { if (value < min) { throw new IllegalArgumentException(format("Given value %s is smaller than minimal value %s!", value, min)); } return value; } public static long min(long value, long min) { if (value < min) { throw new IllegalArgumentException(format("Given value %s is smaller than minimal value %s!", value, min)); } return value; } public static short min(short value, short min) { if (value < min) { throw new IllegalArgumentException(format("Given value %s is smaller than minimal value %s!", value, min)); } return value; } public static short max(short value, short max) { if (value > max) { throw new IllegalArgumentException(format("Given value %s is bigger than maximal value %s!", value, max)); } return value; } public static int max(int value, int max) { if (value > max) { throw new IllegalArgumentException(format("Given value %s is bigger than maximal value %s!", value, max)); } return value; } public static long max(long value, long max) { if (value > max) { throw new IllegalArgumentException(format("Given value %s is bigger than maximal value %s!", value, max)); } return value; } public static int size(int value, int min, int max) { return max(min(value, min), max); } public static <T> Collection<T> size(Collection<T> collection, int min, int max) { return sizeMax(sizeMin(collection, min), max); } public static <T extends CharSequence> T size(T collection, int min, int max) { return sizeMax(sizeMin(collection, min), max); } public static <T> T[] size(T[] collection, int min, int max) { return sizeMax(sizeMin(collection, min), max); } public static byte[] size(byte[] collection, int min, int max) { return sizeMax(sizeMin(collection, min), max); } public static byte[] size(byte[] collection, long min, long max) { return sizeMax(sizeMin(collection, min), max); } public static <T> Collection<T> sizeMax(Collection<T> collection, int max) { final int size = collection.size(); if (size > max) { throw new IllegalArgumentException(format("Collection size %s is too big, max %s!", size, max)); } return collection; } public static <T extends CharSequence> T sizeMax(T collection, int max) { final int size = collection.length(); if (size > max) { throw new IllegalArgumentException(format("CharSequence size %s is too big, max %s!", size, max)); } return collection; } public static <T> T[] sizeMax(T[] collection, int max) { final int size = collection.length; if (size > max) { throw new IllegalArgumentException(format("Collection size %s is too big, max %s!", size, max)); } return collection; } public static byte[] sizeMax(byte[] collection, int max) { final int size = collection.length; if (size > max) { throw new IllegalArgumentException(format("Collection size %s is too big, max %s!", size, max)); } return collection; } public static byte[] sizeMax(byte[] collection, long max) { final int size = collection.length; if (size > max) { throw new IllegalArgumentException(format("Collection size %s is too big, max %s!", size, max)); } return collection; } public static <T> Collection<T> sizeMin(Collection<T> collection, int min) { final int size = collection.size(); if (size < min) { throw new IllegalArgumentException(format("Collection size %s is too small, min %s!", size, min)); } return collection; } public static <T extends CharSequence> T sizeMin(T collection, int min) { final int size = collection.length(); if (size < min) { throw new IllegalArgumentException(format("CharSequence size %s is too small, min %s!", size, min)); } return collection; } public static <T> T[] sizeMin(T[] collection, int min) { final int size = collection.length; if (size < min) { throw new IllegalArgumentException(format("Collection size %s is too small, min %s!", size, min)); } return collection; } public static byte[] sizeMin(byte[] collection, int min) { final int size = collection.length; if (size < min) { throw new IllegalArgumentException(format("Collection size %s is too small, min %s!", size, min)); } return collection; } public static byte[] sizeMin(byte[] collection, long min) { final int size = collection.length; if (size < min) { throw new IllegalArgumentException(format("Collection size %s is too small, min %s!", size, min)); } return collection; } public static byte[] checkArrayLength(byte[] bytes, int length) { if (bytes.length != length) { throw new IllegalArgumentException( format("Length of array should be %s but was %s!", length, bytes.length)); } return bytes; } public static char[] checkArrayLength(char[] bytes, int length) { if (bytes.length != length) { throw new IllegalArgumentException( format("Length of array should be %s but was %s!", length, bytes.length)); } return bytes; } public static <T> T[] checkArrayLength(T[] array, int length) { if (array.length != length) { throw new IllegalArgumentException( format("Length of array should be %s but was %s!", length, array.length)); } return array; } public static int byteSize(int byteValue) { return size(byteValue, Byte.MIN_VALUE, Byte.MAX_VALUE); } public static int unsignedByteSize(int unsignedByteValue) { return size(unsignedByteValue, 0, 255); } private Preconditions() { } }
package rinde.logistics.pdptw.mas; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newLinkedHashMap; import static rinde.sim.util.StochasticSuppliers.constant; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.measure.unit.NonSI; import javax.measure.unit.SI; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.stat.descriptive.StatisticalSummary; import org.eclipse.swt.SWT; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import rinde.logistics.pdptw.mas.comm.AuctionCommModel; import rinde.logistics.pdptw.mas.comm.SolverBidder; import rinde.logistics.pdptw.mas.route.SolverRoutePlanner; import rinde.logistics.pdptw.solver.CheapestInsertionHeuristic; import rinde.sim.core.Simulator; import rinde.sim.core.model.pdp.Depot; import rinde.sim.core.model.pdp.Parcel; import rinde.sim.core.model.pdp.TimeWindowPolicy.TimeWindowPolicies; import rinde.sim.core.model.pdp.Vehicle; import rinde.sim.pdptw.common.DynamicPDPTWProblem.StopConditions; import rinde.sim.pdptw.common.ObjectiveFunction; import rinde.sim.pdptw.common.TimeLinePanel; import rinde.sim.pdptw.experiment.Experiment; import rinde.sim.pdptw.gendreau06.Gendreau06ObjectiveFunction; import rinde.sim.pdptw.measure.Analysis; import rinde.sim.pdptw.scenario.Depots; import rinde.sim.pdptw.scenario.IntensityFunctions; import rinde.sim.pdptw.scenario.Locations; import rinde.sim.pdptw.scenario.Metrics; import rinde.sim.pdptw.scenario.Models; import rinde.sim.pdptw.scenario.PDPScenario; import rinde.sim.pdptw.scenario.PDPScenario.ProblemClass; import rinde.sim.pdptw.scenario.PDPScenario.SimpleProblemClass; import rinde.sim.pdptw.scenario.Parcels; import rinde.sim.pdptw.scenario.ScenarioGenerator; import rinde.sim.pdptw.scenario.ScenarioIO; import rinde.sim.pdptw.scenario.TimeSeries; import rinde.sim.pdptw.scenario.TimeSeries.TimeSeriesGenerator; import rinde.sim.pdptw.scenario.TimeWindows; import rinde.sim.pdptw.scenario.Vehicles; import rinde.sim.scenario.ScenarioController.UICreator; import rinde.sim.ui.View; import rinde.sim.ui.renderers.PDPModelRenderer; import rinde.sim.ui.renderers.PlaneRoadModelRenderer; import rinde.sim.ui.renderers.RoadUserRenderer; import rinde.sim.ui.renderers.UiSchema; import rinde.sim.util.StochasticSupplier; import rinde.sim.util.StochasticSuppliers; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import com.google.common.io.Files; import com.google.common.primitives.Longs; public class Generator { // all times are in ms unless otherwise indicated private static final long TICK_SIZE = 1000L; private static final double VEHICLE_SPEED_KMH = 50d; private static final int NUM_VEHICLES = 10; private static final double AREA_WIDTH = 10; private static final long SCENARIO_HOURS = 12L; private static final long SCENARIO_LENGTH = SCENARIO_HOURS * 60 * 60 * 1000L; private static final int NUM_ORDERS = 360; private static final long HALF_DIAG_TT = 509117L; private static final long ONE_AND_HALF_DIAG_TT = 1527351L; private static final long TWO_DIAG_TT = 2036468L; private static final long PICKUP_DURATION = 5 * 60 * 1000L; private static final long DELIVERY_DURATION = 5 * 60 * 1000L; private static final long INTENSITY_PERIOD = 60 * 60 * 1000L; private static final int TARGET_NUM_INSTANCES = 10; // These parameters influence the dynamism selection settings private static final double DYN_STEP_SIZE = 0.05; private static final double DYN_BANDWIDTH = 0.01; public static void main(String[] args) { main2(args); final PDPScenario scen; try { scen = ScenarioIO.read(new File( "files/dataset/0-0.60#0.scen")); } catch (final IOException e) { throw new IllegalStateException(); } run(scen); } public static void run(PDPScenario s) { final ObjectiveFunction objFunc = Gendreau06ObjectiveFunction.instance(); Experiment .build(Gendreau06ObjectiveFunction.instance()) .addScenario(s) .addConfiguration( new TruckConfiguration(SolverRoutePlanner .supplier(CheapestInsertionHeuristic.supplier(objFunc)), SolverBidder.supplier(objFunc, CheapestInsertionHeuristic.supplier(objFunc)), ImmutableList.of(AuctionCommModel.supplier()))) .showGui(new UICreator() { @Override public void createUI(Simulator sim) { final UiSchema schema = new UiSchema(false); schema.add(Vehicle.class, SWT.COLOR_RED); schema.add(Depot.class, SWT.COLOR_CYAN); schema.add(Parcel.class, SWT.COLOR_BLUE); View.create(sim) .with(new PlaneRoadModelRenderer()) .with(new RoadUserRenderer(schema, false)) .with(new PDPModelRenderer()) .with(new TimeLinePanel()) .show(); } }) .perform(); } static class GeneratorSettings { final TimeSeriesType timeSeriesType; final long urgency; final long dayLength; final long officeHours; final ImmutableMap<String, String> properties; GeneratorSettings(TimeSeriesType type, long urg, long dayLen, long officeH, Map<String, String> props) { timeSeriesType = type; urgency = urg; dayLength = dayLen; officeHours = officeH; properties = ImmutableMap.copyOf(props); } } enum TimeSeriesType { SINE, HOMOGENOUS, UNIFORM; } public static void main2(String[] args) { final List<Long> urgencyLevels = Longs.asList(0, 5, 10, 15, 20, 25, 30, 35, 40, 45); final ImmutableMap.Builder<GeneratorSettings, ScenarioGenerator> generatorsMap = ImmutableMap .builder(); for (final long urg : urgencyLevels) { final long urgency = urg * 60 * 1000L; // The office hours is the period in which new orders are accepted, it // is defined as [0,officeHoursLength). final long officeHoursLength; if (urgency < HALF_DIAG_TT) { officeHoursLength = SCENARIO_LENGTH - TWO_DIAG_TT - PICKUP_DURATION - DELIVERY_DURATION; } else { officeHoursLength = SCENARIO_LENGTH - urgency - ONE_AND_HALF_DIAG_TT - PICKUP_DURATION - DELIVERY_DURATION; } final double numPeriods = officeHoursLength / (double) INTENSITY_PERIOD; final Map<String, String> props = newLinkedHashMap(); props.put("expected_num_orders", Integer.toString(NUM_ORDERS)); props.put("time_series", "sine Poisson "); props.put("time_series.period", Long.toString(INTENSITY_PERIOD)); props.put("time_series.num_periods", Double.toString(numPeriods)); props.put("pickup_duration", Long.toString(PICKUP_DURATION)); props.put("delivery_duration", Long.toString(DELIVERY_DURATION)); props.put("width_height", String.format("%1.1fx%1.1f", AREA_WIDTH, AREA_WIDTH)); final GeneratorSettings sineSettings = new GeneratorSettings( TimeSeriesType.SINE, urg, SCENARIO_LENGTH, officeHoursLength, props); final TimeSeriesGenerator sineTsg = TimeSeries.nonHomogenousPoisson( officeHoursLength, IntensityFunctions .sineIntensity() .area(NUM_ORDERS / numPeriods) .period(INTENSITY_PERIOD) .height(StochasticSuppliers.uniformDouble(-.99, 3d)) .phaseShift( StochasticSuppliers.uniformDouble(0, INTENSITY_PERIOD)) .buildStochasticSupplier()); props.put("time_series", "homogenous Poisson"); props.put("time_series.intensity", Double.toString((double) NUM_ORDERS / (double) officeHoursLength)); props.remove("time_series.period"); props.remove("time_series.num_periods"); final TimeSeriesGenerator homogTsg = TimeSeries.homogenousPoisson( officeHoursLength, NUM_ORDERS); final GeneratorSettings homogSettings = new GeneratorSettings( TimeSeriesType.HOMOGENOUS, urg, SCENARIO_LENGTH, officeHoursLength, props); final StochasticSupplier<Double> maxDeviation = StochasticSuppliers .uniformDouble(0, 15 * 60 * 1000); props.put("time_series", "uniform"); // props.put("time_series.max_deviation", Long.toString(maxDeviation)); props.remove("time_series.intensity"); final TimeSeriesGenerator uniformTsg = TimeSeries.uniform( officeHoursLength, NUM_ORDERS, maxDeviation); final GeneratorSettings uniformSettings = new GeneratorSettings( TimeSeriesType.UNIFORM, urg, SCENARIO_LENGTH, officeHoursLength, props); generatorsMap.put(sineSettings, createGenerator(SCENARIO_LENGTH, urgency, sineTsg)); generatorsMap.put(homogSettings, createGenerator(SCENARIO_LENGTH, urgency, homogTsg)); generatorsMap.put(uniformSettings, createGenerator(SCENARIO_LENGTH, urgency, uniformTsg)); } final ImmutableMap<GeneratorSettings, ScenarioGenerator> scenarioGenerators = generatorsMap .build(); final RandomGenerator rng = new MersenneTwister(123L); for (final Entry<GeneratorSettings, ScenarioGenerator> entry : scenarioGenerators .entrySet()) { final GeneratorSettings generatorSettings = entry.getKey(); System.out.println("URGENCY: " + generatorSettings.urgency); if (generatorSettings.timeSeriesType == TimeSeriesType.SINE) { createScenarios(rng, generatorSettings, entry.getValue(), .0, .51, 11); } else if (generatorSettings.timeSeriesType == TimeSeriesType.HOMOGENOUS) { createScenarios(rng, generatorSettings, entry.getValue(), .54, .61, 2); } else if (generatorSettings.timeSeriesType == TimeSeriesType.UNIFORM) { createScenarios(rng, generatorSettings, entry.getValue(), .64, 1, 8); } } } static void createScenarios(RandomGenerator rng, GeneratorSettings generatorSettings, ScenarioGenerator generator, double dynLb, double dynUb, int levels) { final List<PDPScenario> scenarios = newArrayList(); final Multimap<Double, PDPScenario> dynamismScenariosMap = LinkedHashMultimap .create(); System.out.println(generatorSettings.timeSeriesType); while (scenarios.size() < levels * TARGET_NUM_INSTANCES) { final PDPScenario scen = generator.generate(rng, "temp"); Metrics.checkTimeWindowStrictness(scen); final StatisticalSummary urgency = Metrics.measureUrgency(scen); final long expectedUrgency = generatorSettings.urgency * 60000L; if (Math.abs(urgency.getMean() - expectedUrgency) < 0.01 && urgency.getStandardDeviation() < 0.01) { // System.out.println(urgency.getMean() + " +- " // + urgency.getStandardDeviation()); final double dynamism = Metrics.measureDynamism(scen, generatorSettings.officeHours); System.out.print(String.format("%1.3f ", dynamism)); if ((dynamism % DYN_STEP_SIZE < DYN_BANDWIDTH || dynamism % DYN_STEP_SIZE > DYN_STEP_SIZE - DYN_BANDWIDTH) && dynamism <= dynUb && dynamism >= dynLb) { final double targetDyn = Math.round(dynamism / DYN_STEP_SIZE) * DYN_STEP_SIZE;// Math.round(dynamism // * 100d) / // 100d; final int numInstances = dynamismScenariosMap.get(targetDyn).size(); if (numInstances < TARGET_NUM_INSTANCES) { final String instanceId = " + Integer.toString(numInstances); dynamismScenariosMap.put(targetDyn, scen); final String problemClassId = String.format("%d-%1.2f", (long) (urgency.getMean() / 60000), targetDyn); System.out.println(); System.out.println(" > ACCEPT " + problemClassId); final String fileName = "files/dataset/" + problemClassId + instanceId; try { Files.createParentDirs(new File(fileName)); writePropertiesFile(scen, urgency, dynamism, problemClassId, instanceId, generatorSettings, fileName); Analysis.writeLocationList(Metrics.getServicePoints(scen), new File(fileName + ".points")); Analysis.writeTimes(scen.getTimeWindow().end, Metrics.getArrivalTimes(scen), new File(fileName + ".times")); final ProblemClass pc = new SimpleProblemClass(problemClassId); final PDPScenario finalScenario = PDPScenario.builder(pc) .copyProperties(scen) .problemClass(pc) .instanceId(instanceId) .build(); ScenarioIO.write(finalScenario, new File(fileName + ".scen")); } catch (final IOException e) { throw new IllegalStateException(e); } // System.out.println(dynamism); // ss.addValue(dynamism * 100d); scenarios.add(scen); } // return; } } else { // run(scen); } } } static void writePropertiesFile(PDPScenario scen, StatisticalSummary urgency, double dynamism, String problemClassId, String instanceId, GeneratorSettings settings, String fileName) { final DateTimeFormatter formatter = ISODateTimeFormat .dateHourMinuteSecondMillis(); final ImmutableMap.Builder<String, Object> properties = ImmutableMap .<String, Object> builder() .put("problem_class", problemClassId) .put("id", instanceId) .put("dynamism", dynamism) .put("urgency_mean", urgency.getMean()) .put("urgency_sd", urgency.getStandardDeviation()) .put("creation_date", formatter.print(System.currentTimeMillis())) .put("creator", System.getProperty("user.name")) .put("day_length", settings.dayLength) .put("office_opening_hours", settings.officeHours); properties.putAll(settings.properties); final ImmutableMultiset<Enum<?>> eventTypes = Metrics .getEventTypeCounts(scen); for (final Multiset.Entry<Enum<?>> en : eventTypes.entrySet()) { properties.put(en.getElement().name(), en.getCount()); } try { Files .write( Joiner.on("\n").withKeyValueSeparator(" = ") .join(properties.build()), new File(fileName + ".properties"), Charsets.UTF_8); } catch (final IOException e) { throw new IllegalStateException(e); } } static ScenarioGenerator createGenerator(long scenarioLength, long urgency, TimeSeriesGenerator tsg) { return ScenarioGenerator .builder() // global .timeUnit(SI.MILLI(SI.SECOND)) .scenarioLength(scenarioLength) .tickSize(TICK_SIZE) .speedUnit(NonSI.KILOMETERS_PER_HOUR) .distanceUnit(SI.KILOMETER) .stopCondition( Predicates.and(StopConditions.VEHICLES_DONE_AND_BACK_AT_DEPOT, StopConditions.TIME_OUT_EVENT)) // parcels .parcels( Parcels .builder() .announceTimes(tsg) .pickupDurations(constant(PICKUP_DURATION)) .deliveryDurations(constant(DELIVERY_DURATION)) .neededCapacities(constant(0)) .locations(Locations.builder() .min(0d) .max(AREA_WIDTH) .uniform()) .timeWindows(TimeWindows.builder() .pickupUrgency(constant(urgency)) .pickupTimeWindowLength(constant(5 * 60 * 1000L)) .deliveryOpening(constant(0L)) .minDeliveryLength(constant(10 * 60 * 1000L)) .deliveryLengthFactor(constant(3d)) .build()) .build()) // vehicles .vehicles( Vehicles.builder() .capacities(constant(1)) .centeredStartPositions() .creationTimes(constant(-1L)) .numberOfVehicles(constant(NUM_VEHICLES)) .speeds(constant(VEHICLE_SPEED_KMH)) .timeWindowsAsScenario() .build()) // depots .depots(Depots.singleCenteredDepot()) // models .addModel(Models.roadModel(VEHICLE_SPEED_KMH, true)) .addModel(Models.pdpModel(TimeWindowPolicies.TARDY_ALLOWED)) .build(); } }
package seedu.scheduler.logic.parser; import seedu.scheduler.logic.commands.*; import seedu.scheduler.commons.util.StringUtil; import seedu.scheduler.commons.exceptions.IllegalValueException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static seedu.scheduler.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.scheduler.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern ENTRY_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace //@@author A0139956L private static final Pattern PATH_DATA_ARGS_FORMAT = Pattern.compile("(?<name>[\\p{Alnum}|/]+)"); //@@author A0161210A // Pattern allows all parameters to be optional and allow natural language inputs private static final Pattern ENTRY_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)?" + "(?<isStartTimePrivate>p?)(?:(from/|f/|st/)(?<startTime>[^/]+))?" + "(?<isEndTimePrivate>p?)(?:(to/|et/)(?<endTime>[^/]+))?" + "(?<isDatePrivate>p?)(?:(on/|sdate/|sd/|)(?<date>[^/]+))?" + "(?<isEndDatePrivate>p?)(?:(ed/|by/|edate/)(?<endDate>[^/]+))?" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags //@@author //@@author A0152962B private static final Pattern ENTRY_EDIT_ARGS_FORMAT = Pattern.compile("(?<targetIndex>\\d+)" + "(?<name>[^/]+)" + "(?<isStartTimePrivate>p?)(?:(from/|f/|st/)(?<startTime>[^/]+))?" + "(?<isEndTimePrivate>p?)(?:(to/|et/)(?<endTime>[^/]+))?" + "(?<isDatePrivate>p?)(?:(on/|date/|sd/|by/)(?<date>[^/]+))?" + "(?<isEndDatePrivate>p?)(?:(edate/|ed/)(?<endDate>[^/]+))?" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags //@@author public Parser() { } /** * Parses user input into command for execution. * * @param userInput * full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); //@@author A0161210A switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case AddCommand.COMMAND_WORD2: return prepareAdd(arguments); //@@author case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case DeleteCommand.COMMAND_WORD2: return prepareDelete(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case EditCommand.COMMAND_WORD2: return prepareEdit(arguments); case MarkedCommand.COMMAND_WORD: return prepareMarked(arguments); case MarkedCommand.COMMAND_WORD2: return prepareMarked(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case ClearCommand.COMMAND_WORD2: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case FindCommand.COMMAND_WORD2: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return prepareList(arguments); case ListCommand.COMMAND_WORD2: return prepareList(arguments); //@@author A0139956L case PathCommand.COMMAND_WORD: return preparePath(arguments); case PathCommand.COMMAND_WORD2: return preparePath(arguments); //@@author case ExitCommand.COMMAND_WORD: return new ExitCommand(); case ExitCommand.COMMAND_WORD2: return new ExitCommand(); //@@author A0152962B case UndoableCommand.COMMAND_WORD_UNDO: UndoableCommand.undoManager.undo(); return null; case UndoableCommand.COMMAND_WORD_REDO: UndoableCommand.undoManager.redo(); return null; //@@author case HelpCommand.COMMAND_WORD: return new HelpCommand(); case HelpCommand.COMMAND_WORD2: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add entry command. * * @param args * full command args string * @return the prepared command */ private Command prepareAdd(String args) { final Matcher matcher = ENTRY_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { return new AddCommand(matcher.group("name"), matcher.group("startTime"), matcher.group("endTime"), matcher.group("date"), matcher.group("endDate"), getTagsFromArgs(matcher.group("tagArguments"))); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Extracts the new entry's tags from the add command's tag arguments * string. Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete entry command. * * @param args * full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } //@@author A0152962B /** * Parses arguments into the context of the edit entry command. * * @param args full command args string * @return the newly prepared command */ private Command prepareEdit(String args) { final Matcher matcher = ENTRY_EDIT_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } try { return new EditCommand(Integer.parseInt(matcher.group("targetIndex")), matcher.group("name"), matcher.group("startTime"), matcher.group("endTime"), matcher.group("date"), matcher.group("endDate"), getTagsFromArgs(matcher.group("tagArguments"))); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author A0126090N /** * Parses arguments in the context of the completed entry command. * * @param args full command args string * @return the prepared command */ private Command prepareMarked(String args) { Optional<Integer> index = parseIndex(args); // Validate arg string format if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkedCommand.MESSAGE_USAGE)); } return new MarkedCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned * integer is given as the index. Returns an {@code Optional.empty()} * otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = ENTRY_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find entry command. * * @param args * full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } //@@author A0139956L private Command prepareList(String args) { if(args.contains("sort") || args.equals("")) { return new ListCommand(args); } else { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE)); } } /** * Parses arguments in the context of the file path command. * * @param args full command args string * @return the prepared command */ private Command preparePath(String args) { final Matcher matcher = PATH_DATA_ARGS_FORMAT.matcher(args.trim()); //Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, PathCommand.MESSAGE_USAGE)); } else { String filePath = matcher.group("name").trim().replaceAll("/$", "") + ".xml"; //store input to filePath return new PathCommand(filePath); //push input to PathCommand } } //@@author }
package us.mcthemeparks.voiceplus; import co.aikar.commands.ACF; import org.bukkit.plugin.java.JavaPlugin; import java.io.IOException; @SuppressWarnings({"unused", "deprecated"}) public class VoicePlus extends JavaPlugin { public static VoicePlus instance; @Override public void onEnable() { instance = this; enableMessage(); if (VoicePlusConfig.enableMetrics) startMetrics(); new VoicePlusConfig(); ACF.createManager(this).registerCommand(new VoicePlusCommands()); } private void enableMessage() { getLogger().info("|======================================|"); getLogger().info("| Plugin: VoicePlus |"); getLogger().info("| Created By: Clarkcj |"); getLogger().info("| Contributions By: willies952002 |"); getLogger().info("| Version: 2.7.2 |"); getLogger().info("|======================================|"); } private void startMetrics() { try { getLogger().info("Starting Metrics"); new org.mcstats.Metrics(this).start(); new org.bstats.Metrics(this); } catch (IOException e) { getLogger().severe("Failed to Submit Metrics Data to MCStats"); } } @Override public void onDisable() { } }
package valandur.webapi.servlet; import io.swagger.annotations.Api; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiOperation; import org.spongepowered.api.Platform; import org.spongepowered.api.Server; import org.spongepowered.api.Sponge; import org.spongepowered.api.resourcepack.ResourcePack; import org.spongepowered.api.text.Text; import valandur.webapi.WebAPI; import valandur.webapi.api.cache.plugin.ICachedPluginContainer; import valandur.webapi.api.server.IServerStat; import valandur.webapi.api.servlet.BaseServlet; import valandur.webapi.api.servlet.Permission; import valandur.webapi.cache.plugin.CachedPluginContainer; import valandur.webapi.server.ServerService; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Path("info") @Api(tags = { "Info" }, value = "Get information and stats about the Minecraft server") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public class InfoServlet extends BaseServlet { @GET @Permission("info") @ApiOperation( value = "Server info", notes = "Get general information about the Minecraft server.") public ServerInfo getInfo() { return WebAPI.runOnMain(ServerInfo::new); } @GET @Path("/stats") @Permission("stats") @ApiOperation( value = "Server stats", notes = "Get statistical information about the server, such as player count, " + "cpu and memory usage over time.") public ServerStats getStats(@QueryParam("limit") Integer limit) { if (limit != null) { return new ServerStats(limit); } return new ServerStats(); } @GET @Path("/servlets") @Permission("servlets") @ApiOperation( value = "List servlets", notes = "Lists all the active servlets running in the Web-API") public Map<String, String> listServlets() { return servletService.getRegisteredServlets().entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getName())); } @ApiModel("ServerInfo") public static class ServerInfo { private Text motd; @ApiModelProperty(value = "The message of the day set on the server", required = true) public Text getMotd() { return motd; } private int players; @ApiModelProperty(value = "The amount of players currently playing on the server", required = true) public int getPlayers() { return players; } private int maxPlayers; @ApiModelProperty(value = "The maximum amount of players allowed on the server", required = true) public int getMaxPlayers() { return maxPlayers; } private String address; @ApiModelProperty("The address that the server is bound to") public String getAddress() { return address; } private boolean onlineMode; @ApiModelProperty(value = "True if the server is in online mode and verifies connections, false otherwise", required = true) public boolean isOnlineMode() { return onlineMode; } private String resourcePack; @ApiModelProperty("The name of the resource pack this is used on the server") public String getResourcePack() { return resourcePack; } private boolean hasWhitelist; @ApiModelProperty(value = "True if the server has activated the whitelist, false otherwise", required = true) public boolean isHasWhitelist() { return hasWhitelist; } private int uptimeTicks; @ApiModelProperty(value = "The number of ticks the server has been running", required = true) public int getUptimeTicks() { return uptimeTicks; } private double tps; @ApiModelProperty(value = "The average ticks per second the server is running with", required = true) public double getTps() { return tps; } private String minecraftVersion; @ApiModelProperty(value = "The Minecraft version running on the server", required = true) public String getMinecraftVersion() { return minecraftVersion; } private ICachedPluginContainer game; @ApiModelProperty(required = true) public ICachedPluginContainer getGame() { return game; } private ICachedPluginContainer api; @ApiModelProperty(required = true) public ICachedPluginContainer getApi() { return api; } private ICachedPluginContainer implementation; @ApiModelProperty(required = true) public ICachedPluginContainer getImplementation() { return implementation; } public ServerInfo() { Server server = Sponge.getServer(); Platform platform = Sponge.getPlatform(); this.motd = server.getMotd().toBuilder().build(); this.players = server.getOnlinePlayers().size(); this.maxPlayers = server.getMaxPlayers(); if (server.getBoundAddress().isPresent()) { InetSocketAddress addr = server.getBoundAddress().get(); this.address = addr.getHostName() + (addr.getPort() == 25565 ? "" : addr.getPort()); } this.onlineMode = server.getOnlineMode(); this.resourcePack = server.getDefaultResourcePack().map(ResourcePack::getName).orElse(null); this.hasWhitelist = server.hasWhitelist(); this.uptimeTicks = server.getRunningTimeTicks(); this.tps = server.getTicksPerSecond(); this.minecraftVersion = platform.getMinecraftVersion().getName(); this.game = new CachedPluginContainer(platform.getContainer(Platform.Component.GAME)); this.api = new CachedPluginContainer(platform.getContainer(Platform.Component.API)); this.implementation = new CachedPluginContainer(platform.getContainer(Platform.Component.IMPLEMENTATION)); } } @ApiModel("ServerStats") public static class ServerStats { private List<IServerStat<Double>> tps; @ApiModelProperty(value = "Historic values for the average ticks per second", required = true) public List<IServerStat<Double>> getTps() { return tps; } private List<IServerStat<Integer>> players; @ApiModelProperty(value = "Historic values for the number of online players", required = true) public List<IServerStat<Integer>> getPlayers() { return players; } private List<IServerStat<Double>> cpu; @ApiModelProperty(value = "Historic values for the cpu load", required = true) public List<IServerStat<Double>> getCpu() { return cpu; } private List<IServerStat<Double>> memory; @ApiModelProperty(value = "Historic values for the memory load", required = true) public List<IServerStat<Double>> getMemory() { return memory; } private List<IServerStat<Double>> disk; @ApiModelProperty(value = "Historic values for the disk usage", required = true) public List<IServerStat<Double>> getDisk() { return disk; } public ServerStats() { this(Integer.MAX_VALUE); } public ServerStats(int limit) { ServerService srv = WebAPI.getServerService(); int size = srv.getNumEntries(); int l = Math.min(limit, size); this.tps = srv.getAverageTps().subList(size - l, size); this.players = srv.getOnlinePlayers().subList(size - l, size); this.cpu = srv.getCpuLoad().subList(size - l, size); this.memory = srv.getMemoryLoad().subList(size - l, size); this.disk = srv.getDiskUsage().subList(size - l, size); } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.flags.custom.PreprovisionCapacity; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundIntFlag DROP_CACHES = defineIntFlag("drop-caches", 3, "The int value to write into /proc/sys/vm/drop_caches for each tick. " + "1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.", "Takes effect on next tick.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag( "enable-crowdstrike", true, "Whether to enable CrowdStrike.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag( "enable-nessus", true, "Whether to enable Nessus.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_FLEET_SSHD_CONFIG = defineFeatureFlag( "enable-fleet-sshd-config", false, "Whether fleet should manage the /etc/ssh/sshd_config file.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag FLEET_CANARY = defineFeatureFlag( "fleet-canary", false, "Whether the host is a fleet canary.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag SERVICE_MODEL_CACHE = defineFeatureFlag( "service-model-cache", true, "Whether the service model is cached.", "Takes effect on restart of config server.", HOSTNAME); public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag( "disabled-host-admin-tasks", List.of(), String.class, "List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped", "Takes effect on next host admin tick", HOSTNAME, NODE_TYPE); public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag( "docker-version", "1.13.1-102.git7f2769b", "The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " + "2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " + "If docker-version is not of this format, it must be parseable by YumPackageName::fromString.", "Takes effect on next tick.", HOSTNAME); public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag( "thin-pool-gb", -1, "The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " + "If <0, the default is used (which may depend on the zone and node type).", "Takes effect immediately (but used only during provisioning).", NODE_TYPE); public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag( "container-cpu-cap", 0, "Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " + "to cap CPU at 200%, set this to 2, etc.", "Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart", HOSTNAME, APPLICATION_ID); public static final UnboundBooleanFlag USE_BUCKET_SPACE_METRIC = defineFeatureFlag( "use-bucket-space-metric", true, "Whether to use vds.datastored.bucket_space.buckets_total (true) instead of " + "vds.datastored.alldisks.buckets (false, legacy).", "Takes effect on the next deployment of the application", APPLICATION_ID); public static final UnboundStringFlag TLS_INSECURE_MIXED_MODE = defineStringFlag( "tls-insecure-mixed-mode", "tls_client_mixed_server", "TLS insecure mixed mode. Allowed values: ['plaintext_client_mixed_server', 'tls_client_mixed_server', 'tls_client_tls_server']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag( "tls-insecure-authorization-mode", "log_only", "TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag( "use-adaptive-dispatch", false, "Should adaptive dispatch be used over round robin", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag( "reboot-interval-in-days", 30, "No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " + "scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).", "Takes effect on next run of NodeRebooter"); public static final UnboundBooleanFlag RETIRE_WITH_PERMANENTLY_DOWN = defineFeatureFlag( "retire-with-permanently-down", false, "If enabled, retirement will end with setting the host status to PERMANENTLY_DOWN, " + "instead of ALLOWED_TO_BE_DOWN (old behavior).", "Takes effect on the next run of RetiredExpirer.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_DYNAMIC_PROVISIONING = defineFeatureFlag( "enable-dynamic-provisioning", false, "Provision a new docker host when we otherwise can't allocate a docker node", "Takes effect on next deployment", APPLICATION_ID); public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag( "preprovision-capacity", List.of(), PreprovisionCapacity.class, "List of node resources and their count that should be present in zone to receive new deployments. When a " + "preprovisioned is taken, new will be provisioned within next iteration of maintainer.", "Takes effect on next iteration of HostProvisionMaintainer."); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, "Node resource memory in Gb for admin cluster nodes", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag( "host-hardening", false, "Whether to enable host hardening Linux baseline.", "Takes effect on next tick or on host-admin restart (may vary where used).", HOSTNAME); public static final UnboundStringFlag ZOOKEEPER_SERVER_MAJOR_MINOR_VERSION = defineStringFlag( "zookeeper-server-version", "3.5", "The version of ZooKeeper server to use (major.minor, not full version)", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_QUORUM_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-quorum-communication", "OFF", "How to setup TLS for ZooKeeper quorum communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-client-server-communication", "OFF", "How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag( "use-tls-for-zookeeper-client", false, "Whether to use TLS for ZooKeeper clients", "Takes effect on restart of process", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag ENABLE_DISK_WRITE_TEST = defineFeatureFlag( "enable-disk-write-test", false, "Regularly issue a small write to disk and fail the host if it is not successful", "Takes effect on next node agent tick (but does not clear existing failure reports)", HOSTNAME); public static final UnboundBooleanFlag GENERATE_L4_ROUTING_CONFIG = defineFeatureFlag( "generate-l4-routing-config", false, "Whether routing nodes should generate L4 routing config", "Takes effect immediately", ZONE_ID, HOSTNAME); public static final UnboundBooleanFlag USE_REFRESHED_ENDPOINT_CERTIFICATE = defineFeatureFlag( "use-refreshed-endpoint-certificate", false, "Whether an application should start using a newer certificate/key pair if available", "Takes effect on the next deployment of the application", APPLICATION_ID); public static final UnboundBooleanFlag VALIDATE_ENDPOINT_CERTIFICATES = defineFeatureFlag( "validate-endpoint-certificates", false, "Whether endpoint certificates should be validated before use", "Takes effect on the next deployment of the application"); public static final UnboundStringFlag ENDPOINT_CERTIFICATE_BACKFILL = defineStringFlag( "endpoint-certificate-backfill", "disable", "Whether the endpoint certificate maintainer should backfill missing certificate data from cameo", "Takes effect on next scheduled run of maintainer - set to \"disable\", \"dryrun\" or \"enable\"" ); public static final UnboundBooleanFlag USE_NEW_ATHENZ_FILTER = defineFeatureFlag( "use-new-athenz-filter", false, "Use new Athenz filter that supports access-tokens", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag USE_RPM_PACKAGES_FOR_DATA_HIGHWAY = defineFeatureFlag( "use-rpm-packages-for-data-highway", false, "Whether RPM packages should be used for Data Highway", "Takes effect on restart of Docker container", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag DOCKER_IMAGE_OVERRIDE = defineStringFlag( "docker-image-override", "", "Override the Docker image to use for deployments. This must containing the image name only, without tag", "Takes effect on next host-admin tick", APPLICATION_ID); public static final UnboundBooleanFlag ENDPOINT_CERT_IN_SHARED_ROUTING = defineFeatureFlag( "endpoint-cert-in-shared-routing", false, "Whether to provision and use endpoint certs for apps in shared routing zones", "Takes effect on next deployment of the application", APPLICATION_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package org.smoothbuild.lang.type; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.quackery.Case.newCase; import static org.quackery.Suite.suite; import static org.smoothbuild.util.Lists.list; import static org.testory.Testory.given; import static org.testory.Testory.thenReturned; import static org.testory.Testory.when; import java.util.List; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.quackery.Case; import org.quackery.Case.Body; import org.quackery.Quackery; import org.quackery.Suite; import org.quackery.junit.QuackeryRunner; import org.smoothbuild.lang.value.Array; import org.smoothbuild.lang.value.Blob; import org.smoothbuild.lang.value.SString; import org.smoothbuild.lang.value.Value; import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.testing.EqualsTester; @RunWith(QuackeryRunner.class) public class TypesTest { private static final TypesDb typesDb = new TestingTypesDb(); private static final Type type = typesDb.type(); private static final Type string = typesDb.string(); private static final Type blob = typesDb.blob(); private static final Type a = typesDb.generic("a"); @Test public void name() { assertEquals("Type", type.name()); assertEquals("String", string.name()); assertEquals("Blob", blob.name()); assertEquals("Person", personType().name()); assertEquals("a", a.name()); assertEquals("[Type]", array(type).name()); assertEquals("[String]", array(string).name()); assertEquals("[Blob]", array(blob).name()); assertEquals("[Person]", array(personType()).name()); assertEquals("[a]", array(a).name()); assertEquals("[[Type]]", array(array(type)).name()); assertEquals("[[String]]", array(array(string)).name()); assertEquals("[[Blob]]", array(array(blob)).name()); assertEquals("[[Person]]", array(array(personType())).name()); assertEquals("[[a]]", array(array(a)).name()); } @Test public void to_string() { assertEquals("Type(\"Type\"):" + type.hash(), type.toString()); assertEquals("Type(\"String\"):" + string.hash(), string.toString()); assertEquals("Type(\"Blob\"):" + blob.hash(), blob.toString()); assertEquals("Type(\"Person\"):" + personType().hash(), personType().toString()); assertEquals("Type(\"a\"):" + a.hash(), a.toString()); assertEquals("Type(\"[Type]\"):" + array(type).hash(), array(type).toString()); assertEquals("Type(\"[String]\"):" + array(string).hash(), array(string).toString()); assertEquals("Type(\"[Blob]\"):" + array(blob).hash(), array(blob).toString()); assertEquals("Type(\"[Person]\"):" + array(personType()).hash(), array(personType()).toString()); assertEquals("Type(\"[a]\"):" + array(a).hash(), array(a).toString()); assertEquals("Type(\"[[Type]]\"):" + array(array(type)).hash(), array(array(type)).toString()); assertEquals("Type(\"[[String]]\"):" + array(array(string)).hash(), array(array(string)).toString()); assertEquals("Type(\"[[Blob]]\"):" + array(array(blob)).hash(), array(array(blob)).toString()); assertEquals("Type(\"[[Person]]\"):" + array(array(personType())).hash(), array(array(personType())).toString()); assertEquals("Type(\"[[a]]\"):" + array(array(a)).hash(), array(array(a)).toString()); } @Test public void jType() { assertEquals(Type.class, type.jType()); assertEquals(SString.class, string.jType()); assertEquals(Blob.class, blob.jType()); assertEquals(Value.class, a.jType()); assertEquals(Array.class, array(type).jType()); assertEquals(Array.class, array(string).jType()); assertEquals(Array.class, array(blob).jType()); assertEquals(Array.class, array(a).jType()); } @Test public void core_type() throws Exception { assertEquals(type, type.coreType()); assertEquals(string, string.coreType()); assertEquals(personType(), personType().coreType()); assertEquals(a, a.coreType()); assertEquals(string, array(string).coreType()); assertEquals(personType(), array(personType()).coreType()); assertEquals(a, array(a).coreType()); assertEquals(string, array(array(string)).coreType()); assertEquals(personType(), array(array(personType())).coreType()); assertEquals(a, array(array(a)).coreType()); } @Test public void core_depth() throws Exception { assertEquals(0, type.coreDepth()); assertEquals(0, string.coreDepth()); assertEquals(0, personType().coreDepth()); assertEquals(0, a.coreDepth()); assertEquals(1, array(string).coreDepth()); assertEquals(1, array(personType()).coreDepth()); assertEquals(1, array(a).coreDepth()); assertEquals(2, array(array(string)).coreDepth()); assertEquals(2, array(array(personType())).coreDepth()); assertEquals(2, array(array(a)).coreDepth()); } @Test public void super_type() throws Exception { assertEquals(null, type.superType()); assertEquals(null, string.superType()); assertEquals(null, blob.superType()); assertEquals(string, personType().superType()); assertEquals(null, a.superType()); assertEquals(null, array(type).superType()); assertEquals(null, array(string).superType()); assertEquals(null, array(blob).superType()); assertEquals(array(string), array(personType()).superType()); assertEquals(null, array(a).superType()); assertEquals(null, array(array(type)).superType()); assertEquals(null, array(array(string)).superType()); assertEquals(null, array(array(blob)).superType()); assertEquals(array(array(string)), array(array(personType())).superType()); assertEquals(null, array(array(a)).superType()); } @Test public void hierarchy() throws Exception { assertHierarchy(list(string)); assertHierarchy(list(string, personType())); assertHierarchy(list(a)); assertHierarchy(list(array(string))); assertHierarchy(list(array(string), array(personType()))); assertHierarchy(list(array(a))); assertHierarchy(list(array(array(string)))); assertHierarchy(list(array(array(string)), array(array(personType())))); assertHierarchy(list(array(array(a)))); } private static void assertHierarchy(List<Type> hierarchy) { Type type; given(type = hierarchy.get(hierarchy.size() - 1)); when(() -> type.hierarchy()); thenReturned(hierarchy); } @Test public void is_generic() throws Exception { assertTrue(a.isGeneric()); assertFalse(type.isGeneric()); assertFalse(string.isGeneric()); assertFalse(blob.isGeneric()); assertFalse(personType().isGeneric()); assertFalse(array(a).isGeneric()); assertFalse(array(type).isGeneric()); assertFalse(array(string).isGeneric()); assertFalse(array(blob).isGeneric()); assertFalse(array(personType()).isGeneric()); } @Quackery public static Suite is_assignable_from() throws Exception { List<Type> types = list( type, array(type), array(array(type)), string, array(string), array(array(string)), blob, array(blob), array(array(blob)), personType(), array(personType()), array(array(personType())), a, array(a), array(array(a))); Set<Conversion> conversions = ImmutableSet.of( new Conversion(type, type), new Conversion(type, a), new Conversion(string, string), new Conversion(string, personType()), new Conversion(string, a), new Conversion(blob, blob), new Conversion(blob, a), new Conversion(personType(), personType()), new Conversion(personType(), a), new Conversion(a, a), new Conversion(array(type), array(type)), new Conversion(array(type), array(a)), new Conversion(array(type), a), new Conversion(array(string), array(string)), new Conversion(array(string), array(personType())), new Conversion(array(string), array(a)), new Conversion(array(string), a), new Conversion(array(blob), array(blob)), new Conversion(array(blob), array(a)), new Conversion(array(blob), a), new Conversion(array(personType()), array(personType())), new Conversion(array(personType()), array(a)), new Conversion(array(personType()), a), new Conversion(array(a), array(a)), new Conversion(array(a), a), new Conversion(array(array(type)), array(array(type))), new Conversion(array(array(type)), array(array(a))), new Conversion(array(array(type)), array(a)), new Conversion(array(array(type)), a), new Conversion(array(array(string)), array(array(string))), new Conversion(array(array(string)), array(array(personType()))), new Conversion(array(array(string)), array(array(a))), new Conversion(array(array(string)), array(a)), new Conversion(array(array(string)), a), new Conversion(array(array(blob)), array(array(blob))), new Conversion(array(array(blob)), array(array(a))), new Conversion(array(array(blob)), array(a)), new Conversion(array(array(blob)), a), new Conversion(array(array(personType())), array(array(personType()))), new Conversion(array(array(personType())), array(array(a))), new Conversion(array(array(personType())), array(a)), new Conversion(array(array(personType())), a), new Conversion(array(array(a)), array(array(a))), new Conversion(array(array(a)), array(a)), new Conversion(array(array(a)), a)); Suite suite = suite("isAssignableFrom"); for (Type destination : types) { for (Type source : types) { boolean expected = conversions.contains(new Conversion(destination, source)); suite = suite.add(testIsAssignableFrom(destination, source, expected)); } } return suite; } private static Case testIsAssignableFrom(Type destination, Type source, boolean expected) { String testName = destination.name() + " is " + (expected ? "" : "NOT") + "assignable from " + source.name(); Body testBody = () -> assertEquals(expected, destination.isAssignableFrom(source)); return newCase(testName, testBody); } private static class Conversion { private final Type destination; private final Type source; public Conversion(Type destination, Type source) { this.destination = destination; this.source = source; } @Override public boolean equals(Object object) { if (!(object instanceof Conversion)) { return false; } Conversion that = (Conversion) object; return this.destination.equals(that.destination) && this.source.equals(that.source); } @Override public int hashCode() { return Objects.hashCode(destination, source); } } @Test public void common_super_type() throws Exception { assertCommon(type, type, type); assertCommon(type, string, null); assertCommon(type, blob, null); assertCommon(type, a, type); assertCommon(type, array(type), null); assertCommon(type, array(string), null); assertCommon(type, array(blob), null); assertCommon(type, array(a), null); assertCommon(string, string, string); assertCommon(string, blob, null); assertCommon(string, a, string); assertCommon(string, array(string), null); assertCommon(string, array(type), null); assertCommon(string, array(blob), null); assertCommon(string, array(a), null); assertCommon(blob, blob, blob); assertCommon(blob, a, blob); assertCommon(blob, array(type), null); assertCommon(blob, array(string), null); assertCommon(blob, array(blob), null); assertCommon(blob, array(a), null); assertCommon(a, a, a); assertCommon(a, array(type), array(type)); assertCommon(a, array(string), array(string)); assertCommon(a, array(blob), array(blob)); assertCommon(a, array(a), array(a)); assertCommon(array(type), array(type), array(type)); assertCommon(array(type), array(string), null); assertCommon(array(type), array(blob), null); assertCommon(array(type), array(a), array(type)); assertCommon(array(string), array(string), array(string)); assertCommon(array(string), array(blob), null); assertCommon(array(string), array(a), array(string)); assertCommon(array(string), a, array(string)); assertCommon(array(blob), array(blob), array(blob)); assertCommon(array(blob), array(a), array(blob)); assertCommon(array(blob), a, array(blob)); assertCommon(array(a), array(a), array(a)); assertCommon(array(a), a, array(a)); } private static void assertCommon(Type type1, Type type2, Type expected) { assertCommonSuperTypeImpl(type1, type2, expected); assertCommonSuperTypeImpl(type2, type1, expected); } private static void assertCommonSuperTypeImpl(Type type1, Type type2, Type expected) { when(() -> type1.commonSuperType(type2)); thenReturned(expected); } @Test public void array_element_types() { assertEquals(type, array(type).elemType()); assertEquals(string, array(string).elemType()); assertEquals(blob, array(blob).elemType()); assertEquals(personType(), array(personType()).elemType()); assertEquals(a, array(a).elemType()); assertEquals(array(type), array(array(type)).elemType()); assertEquals(array(string), array(array(string)).elemType()); assertEquals(array(blob), array(array(blob)).elemType()); assertEquals(array(personType()), array(array(personType())).elemType()); assertEquals(array(a), array(array(a)).elemType()); } @Test public void equals_and_hashcode() { EqualsTester tester = new EqualsTester(); tester.addEqualityGroup(typesDb.type(), typesDb.type()); tester.addEqualityGroup(typesDb.string(), typesDb.string()); tester.addEqualityGroup(typesDb.blob(), typesDb.blob()); tester.addEqualityGroup(personType(), personType()); tester.addEqualityGroup(typesDb.generic("a"), typesDb.generic("a")); tester.addEqualityGroup(array(type), array(type)); tester.addEqualityGroup(array(string), array(string)); tester.addEqualityGroup(array(blob), array(blob)); tester.addEqualityGroup(array(personType()), array(personType())); tester.addEqualityGroup(array(a), array(a)); tester.addEqualityGroup(array(array(type)), array(array(type))); tester.addEqualityGroup(array(array(string)), array(array(string))); tester.addEqualityGroup(array(array(blob)), array(array(blob))); tester.addEqualityGroup(array(array(personType())), array(array(personType()))); tester.addEqualityGroup(array(array(a)), array(array(a))); tester.testEquals(); } private static StructType personType() { return typesDb.struct( "Person", ImmutableMap.of("firstName", string, "lastName", string)); } private static ArrayType array(Type elementType) { return typesDb.array(elementType); } @Test public void type_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("Type")); thenReturned(null); } @Test public void string_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("String")); thenReturned(typesDb.string()); } @Test public void blob_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("Blob")); thenReturned(typesDb.blob()); } @Test public void type_array_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("[Type]")); thenReturned(null); } @Test public void string_array_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("[String]")); thenReturned(null); } @Test public void blob_array_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("[Blob]")); thenReturned(null); } @Test public void file_array_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("[File]")); thenReturned(null); } @Test public void nil_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("[a]")); thenReturned(null); } @Test public void unknown_type_non_array_type_from_string() throws Exception { when(typesDb.nonArrayTypeFromString("notAType")); thenReturned(null); } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import java.util.function.Predicate; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundBooleanFlag ROOT_CHAIN_GRAPH = defineFeatureFlag( "root-chain-graph", true, List.of("hakonhall"), "2022-10-05", "2022-11-04", "Whether to run all tasks in the root task chain up to the one failing to converge (false), or " + "run all tasks in the root task chain whose dependencies have converged (true). And when suspending, " + "whether to run the tasks in sequence (false) or in reverse sequence (true).", "On first tick of the root chain after (re)start of host admin.", ZONE_ID, NODE_TYPE, HOSTNAME); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag QUERY_DISPATCH_POLICY = defineStringFlag( "query-dispatch-policy", "adaptive", List.of("baldersheim"), "2022-08-20", "2023-01-01", "Select query dispatch policy, valid values are adaptive, round-robin, best-of-random-2," + " latency-amortized-over-requests, latency-amortized-over-time", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag( "keep-storage-node-up", true, List.of("hakonhall"), "2022-07-07", "2022-11-07", "Whether to leave the storage node (with wanted state) UP while the node is permanently down.", "Takes effect immediately for nodes transitioning to permanently down.", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2023-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag( "feed-niceness", 0.0, List.of("baldersheim"), "2022-06-24", "2023-01-01", "How nice feeding shall be", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag( "mbus-java-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag( "mbus-cpp-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag( "rpc-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-java-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-cpp-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag( "rpc-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag( "mbus-num-network-threads", 1, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus network", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag( "shared-string-repo-no-reclaim", false, List.of("baldersheim"), "2022-06-14", "2023-01-01", "Controls whether we do track usage and reclaim unused enum values in shared string repo", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2023-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag( "load-code-as-hugepages", false, List.of("baldersheim"), "2022-05-13", "2023-01-01", "Will try to map the code segment with huge (2M) pages", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2023-05-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2023-03-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-12-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2023-02-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2023-01-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-12-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", true, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", false, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", true, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag( "dispatch-notifications", false, List.of("enygaard"), "2022-05-02", "2022-12-30", "Whether we should send notification for a given tenant", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag( "enable-proxy-protocol-mixed-mode", true, List.of("tokle"), "2022-05-09", "2022-12-01", "Enable or disable proxy protocol mixed mode", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag( "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class, List.of("hmusum"), "2022-07-05", "2022-12-01", "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag( "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class, List.of("hmusum"), "2022-07-05", "2022-12-01", "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag( "use-yumproxy-v2", false, List.of("tokle"), "2022-05-05", "2022-12-01", "Use yumproxy-v2", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag( "log-file-compression-algorithm", "", List.of("arnej"), "2022-06-14", "2024-12-31", "Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd", "Takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag( "separate-metric-check-config", false, List.of("olaa"), "2022-07-04", "2023-01-01", "Determines whether one metrics config check should be written per Vespa node", "Takes effect on next tick", HOSTNAME); public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag( "tls-capabilities-enforcement-mode", "disable", List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01", "Configure Vespa TLS capability enforcement mode", "Takes effect on restart of Docker container", APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION ); public static final UnboundBooleanFlag CLEANUP_TENANT_ROLES = defineFeatureFlag( "cleanup-tenant-roles", false, List.of("olaa"), "2022-08-10", "2023-01-01", "Determines whether old tenant roles should be deleted", "Takes effect next maintenance run" ); public static final UnboundBooleanFlag USE_TWO_PHASE_DOCUMENT_GC = defineFeatureFlag( "use-two-phase-document-gc", false, List.of("vekterli"), "2022-08-24", "2022-12-01", "Use two-phase document GC in content clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag RESTRICT_DATA_PLANE_BINDINGS = defineFeatureFlag( "restrict-data-plane-bindings", false, List.of("mortent"), "2022-09-08", "2023-02-01", "Use restricted data plane bindings", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundStringFlag CSRF_MODE = defineStringFlag( "csrf-mode", "disabled", List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "Set mode for CSRF filter ('disabled', 'log_only', 'enabled')", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag SOFT_REBUILD = defineFeatureFlag( "soft-rebuild", true, List.of("mpolden"), "2022-09-27", "2022-12-01", "Whether soft rebuild can be used to rebuild hosts with remote disk", "Takes effect on next run of OsUpgradeActivator" ); public static final UnboundListFlag<String> CSRF_USERS = defineListFlag( "csrf-users", List.of(), String.class, List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "List of users to enable CSRF filter for. Use empty list for everyone.", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag ENABLE_OTELCOL = defineFeatureFlag( "enable-otel-collector", false, List.of("olaa"), "2022-09-23", "2023-01-01", "Whether an OpenTelemetry collector should be enabled", "Takes effect at next tick", APPLICATION_ID); public static final UnboundBooleanFlag CONSOLE_CSRF = defineFeatureFlag( "console-csrf", false, List.of("bjorncs", "tokle"), "2022-09-26", "2023-06-01", "Enable CSRF token in console", "Takes effect immediately", CONSOLE_USER_EMAIL); public static final UnboundBooleanFlag USE_WIREGUARD_ON_CONFIGSERVERS = defineFeatureFlag( "use-wireguard-on-configservers", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on config servers", "Takes effect on configserver restart", HOSTNAME); public static final UnboundBooleanFlag USE_WIREGUARD_ON_TENANT_HOSTS = defineFeatureFlag( "use-wireguard-on-tenant-hosts", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on tenant hosts", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag AUTH0_SESSION_LOGOUT = defineStringFlag( "auth0-session-logout", "disabled", List.of("bjorncs", "tokle"), "2022-10-17", "2023-06-01", "Set mode for Auth0 session logout ('disabled', 'log_only', 'enabled')", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag ENABLED_MAIL_VERIFICATION = defineFeatureFlag( "enabled-mail-verification", false, List.of("olaa"), "2022-10-28", "2023-01-01", "Enable mail verification", "Takes effect immediately"); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return defineStringFlag(flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, value -> true, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, Predicate<String> validator, FetchVector.Dimension... dimensions) { return define((i, d, v) -> new UnboundStringFlag(i, d, v, validator), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultValue, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package org.smoothbuild.lang.type; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import static org.smoothbuild.lang.type.Conversions.canConvert; import static org.smoothbuild.lang.type.Types.BLOB; import static org.smoothbuild.lang.type.Types.BLOB_ARRAY; import static org.smoothbuild.lang.type.Types.FILE; import static org.smoothbuild.lang.type.Types.FILE_ARRAY; import static org.smoothbuild.lang.type.Types.NIL; import static org.smoothbuild.lang.type.Types.NOTHING; import static org.smoothbuild.lang.type.Types.STRING; import static org.smoothbuild.lang.type.Types.STRING_ARRAY; import static org.smoothbuild.lang.type.Types.allTypes; import static org.smoothbuild.lang.type.Types.arrayOf; import static org.smoothbuild.lang.type.Types.basicTypes; import static org.testory.Testory.given; import static org.testory.Testory.thenReturned; import static org.testory.Testory.when; import java.util.HashSet; import java.util.Set; import org.junit.Test; import com.google.common.testing.EqualsTester; public class TypesTest { private ArrayType type; @Test public void basic_types() { when(basicTypes()); thenReturned(containsInAnyOrder(STRING, BLOB, FILE, NOTHING)); } @Test public void all_types() { when(allTypes()); thenReturned(containsInAnyOrder(STRING, BLOB, FILE, NOTHING, STRING_ARRAY, BLOB_ARRAY, FILE_ARRAY, NIL)); } @Test public void array_elem_types() { assertEquals(STRING_ARRAY.elemType(), STRING); assertEquals(BLOB_ARRAY.elemType(), BLOB); assertEquals(FILE_ARRAY.elemType(), FILE); assertEquals(NIL.elemType(), NOTHING); } @Test public void equals_and_hashcode() { EqualsTester tester = new EqualsTester(); tester.addEqualityGroup(NOTHING); tester.addEqualityGroup(STRING); tester.addEqualityGroup(BLOB); tester.addEqualityGroup(FILE); tester.addEqualityGroup(STRING_ARRAY, arrayOf(STRING)); tester.addEqualityGroup(BLOB_ARRAY, arrayOf(BLOB)); tester.addEqualityGroup(FILE_ARRAY, arrayOf(FILE)); tester.addEqualityGroup(NIL, arrayOf(NOTHING)); tester.testEquals(); } @Test public void to_string() { assertEquals("String", STRING.toString()); } @Test public void all_types_returns_list_sorted_by_super_type_dependency() { Set<Type> visited = new HashSet<>(); for (Type type : allTypes()) { for (Type visitedType : visited) { assertFalse(canConvert(visitedType, type)); } visited.add(type); } } @Test public void string_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("String")); thenReturned(STRING); } @Test public void blob_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("Blob")); thenReturned(BLOB); } @Test public void file_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("File")); thenReturned(FILE); } @Test public void nothing_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("Nothing")); thenReturned(NOTHING); } @Test public void string_array_name() throws Exception { given(type = Types.arrayOf(STRING)); when(() -> type.name()); thenReturned("[String]"); } @Test public void string_array_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("[String]")); thenReturned(null); } @Test public void blob_array_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("[Blob]")); thenReturned(null); } @Test public void file_array_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("[File]")); thenReturned(null); } @Test public void nil_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("[Nothing]")); thenReturned(null); } @Test public void unknown_type_basic_type_from_string() throws Exception { when(Types.basicTypeFromString("notAType")); thenReturned(null); } @Test public void common_super_type() throws Exception { StringBuilder builder = new StringBuilder(); assertCommonSuperType(STRING, STRING, STRING, builder); assertCommonSuperType(STRING, BLOB, null, builder); assertCommonSuperType(STRING, FILE, null, builder); assertCommonSuperType(STRING, NOTHING, STRING, builder); assertCommonSuperType(STRING, STRING_ARRAY, null, builder); assertCommonSuperType(STRING, BLOB_ARRAY, null, builder); assertCommonSuperType(STRING, FILE_ARRAY, null, builder); assertCommonSuperType(STRING, NIL, null, builder); assertCommonSuperType(BLOB, BLOB, BLOB, builder); assertCommonSuperType(BLOB, FILE, BLOB, builder); assertCommonSuperType(BLOB, NOTHING, BLOB, builder); assertCommonSuperType(BLOB, STRING_ARRAY, null, builder); assertCommonSuperType(BLOB, BLOB_ARRAY, null, builder); assertCommonSuperType(BLOB, FILE_ARRAY, null, builder); assertCommonSuperType(BLOB, NIL, null, builder); assertCommonSuperType(FILE, FILE, FILE, builder); assertCommonSuperType(FILE, NOTHING, FILE, builder); assertCommonSuperType(FILE, STRING_ARRAY, null, builder); assertCommonSuperType(FILE, BLOB_ARRAY, null, builder); assertCommonSuperType(FILE, FILE_ARRAY, null, builder); assertCommonSuperType(FILE, NIL, null, builder); assertCommonSuperType(NOTHING, NOTHING, NOTHING, builder); assertCommonSuperType(NOTHING, STRING_ARRAY, STRING_ARRAY, builder); assertCommonSuperType(NOTHING, BLOB_ARRAY, BLOB_ARRAY, builder); assertCommonSuperType(NOTHING, FILE_ARRAY, FILE_ARRAY, builder); assertCommonSuperType(NOTHING, NIL, NIL, builder); assertCommonSuperType(STRING_ARRAY, STRING_ARRAY, STRING_ARRAY, builder); assertCommonSuperType(STRING_ARRAY, BLOB_ARRAY, null, builder); assertCommonSuperType(STRING_ARRAY, FILE_ARRAY, null, builder); assertCommonSuperType(STRING_ARRAY, NIL, STRING_ARRAY, builder); assertCommonSuperType(BLOB_ARRAY, BLOB_ARRAY, BLOB_ARRAY, builder); assertCommonSuperType(BLOB_ARRAY, FILE_ARRAY, BLOB_ARRAY, builder); assertCommonSuperType(BLOB_ARRAY, NIL, BLOB_ARRAY, builder); assertCommonSuperType(FILE_ARRAY, FILE_ARRAY, FILE_ARRAY, builder); assertCommonSuperType(FILE_ARRAY, NIL, FILE_ARRAY, builder); assertCommonSuperType(NIL, NIL, NIL, builder); String errors = builder.toString(); if (0 < errors.length()) { fail(errors); } } private static void assertCommonSuperType(Type type1, Type type2, Type expected, StringBuilder builder) { assertCommonSuperTypeImpl(type1, type2, expected, builder); assertCommonSuperTypeImpl(type2, type1, expected, builder); } private static void assertCommonSuperTypeImpl(Type type1, Type type2, Type expected, StringBuilder builder) { Type actual = Types.commonSuperType(type1, type2); if (expected != actual) { builder.append("commonSuperType(" + type1 + "," + type2 + ") = " + actual + " but should = " + expected + "\n"); } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundStringFlag ALLOCATE_OS_REQUIREMENT = defineStringFlag( "allocate-os-requirement", "any", List.of("hakonhall"), "2021-01-26", "2021-07-26", "Allocations of new nodes are limited to the given host OS. Must be one of 'rhel7', " + "'rhel8', or 'any'", "Takes effect on next (re)deployment.", APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "LATENCY", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicatiomanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2021-06-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag PROVISION_TENANT_ROLES = defineFeatureFlag( "provision-tenant-roles", false, List.of("tokle"), "2020-12-02", "2021-06-01", "Whether tenant roles should be provisioned", "Takes effect on next deployment (controller)", TENANT_ID); public static final UnboundBooleanFlag TENANT_IAM_ROLE = defineFeatureFlag( "application-iam-roles", false, List.of("tokle"), "2020-12-02", "2021-06-01", "Allow separate iam roles when provisioning/assigning hosts", "Takes effect immediately on new hosts, on next redeploy for applications", TENANT_ID); public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag( "hide-shared-routing-endpoint", false, List.of("tokle"), "2020-12-02", "2021-06-01", "Whether the controller should hide shared routing layer endpoint", "Takes effect immediately", APPLICATION_ID ); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_PRUNE_REMOVED = defineFeatureFlag( "use-bucket-executor-for-prune-removed", true, List.of("baldersheim"), "2021-05-04", "2021-06-01", "Wheter to use content-level bucket executor or legacy frozen buckets for prune removed", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag( "group-suspension", true, List.of("hakon"), "2021-01-22", "2021-05-22", "Allow all content nodes in a hierarchical group to suspend at the same time", "Takes effect on the next suspension request to the Orchestrator.", APPLICATION_ID); public static final UnboundBooleanFlag ENCRYPT_DISK = defineFeatureFlag( "encrypt-disk", false, List.of("hakonhall"), "2021-05-05", "2021-06-05", "Allow migrating an unencrypted data partition to being encrypted.", "Takes effect on next host-admin tick."); public static final UnboundBooleanFlag ENCRYPT_DIRTY_DISK = defineFeatureFlag( "encrypt-dirty-disk", false, List.of("hakonhall"), "2021-05-14", "2021-06-05", "Allow migrating an unencrypted data partition to being encrypted when provisioned or dirty.", "Takes effect on next host-admin tick."); public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag( "enable-feed-block-in-distributor", true, List.of("geirst"), "2021-01-27", "2021-07-01", "Enables blocking of feed in the distributor if resource usage is above limit on at least one content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag CLUSTER_CONTROLLER_MAX_HEAP_SIZE_IN_MB = defineIntFlag( "cluster-controller-max-heap-size-in-mb", 128, List.of("hmusum"), "2021-02-10", "2021-05-15", "JVM max heap size for cluster controller in Mb", "Takes effect when restarting cluster controller"); public static final UnboundIntFlag METRICS_PROXY_MAX_HEAP_SIZE_IN_MB = defineIntFlag( "metrics-proxy-max-heap-size-in-mb", 256, List.of("hmusum"), "2021-03-01", "2021-06-15", "JVM max heap size for metrics proxy in Mb", "Takes effect when restarting metrics proxy", CLUSTER_TYPE); public static final UnboundStringFlag DEDICATED_CLUSTER_CONTROLLER_FLAVOR = defineStringFlag( "dedicated-cluster-controller-flavor", "", List.of("jonmv"), "2021-02-25", "2021-05-25", "Flavor as <vpu>-<memgb>-<diskgb> to use for dedicated cluster controller nodes", "Takes effect immediately, for subsequent provisioning", APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2021-08-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag( "generate-non-mtls-endpoint", true, List.of("tokle"), "2021-02-18", "2021-10-01", "Whether to generate the non-mtls endpoint", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2021-07-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_JDISC_HTTP2 = defineFeatureFlag( "enable-jdisc-http2", false, List.of("bjorncs", "jonmv"), "2021-04-12", "2021-08-01", "Whether jdisc HTTPS connectors should allow HTTP/2", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_CUSTOM_ACL_MAPPING = defineFeatureFlag( "enable-custom-acl-mapping", false, List.of("mortent","bjorncs"), "2021-04-13", "2021-08-01", "Whether access control filters should read acl request mapping from handler or use default", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundIntFlag NUM_DISTRIBUTOR_STRIPES = defineIntFlag( "num-distributor-stripes", 0, List.of("geirst", "vekterli"), "2021-04-20", "2021-07-01", "Specifies the number of stripes used by the distributor. When 0, legacy single stripe behavior is used.", "Takes effect after distributor restart", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_ROUTING_CORE_DUMP = defineFeatureFlag( "enable-routing-core-dumps", false, List.of("tokle"), "2021-04-16", "2021-08-01", "Whether to enable core dumps for routing layer", "Takes effect on next host-admin tick", HOSTNAME); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package edu.mit.csail.uid; import edu.mit.csail.uid.sikuli_test.*; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.io.*; import java.awt.*; import java.awt.event.*; import java.net.URL; import java.util.*; import java.text.MessageFormat; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import org.apache.commons.cli.CommandLine; public class SikuliIDE extends JFrame { boolean ENABLE_RECORDING = false; private static NativeLayer _native; private ConsolePane _console; private CloseableTabbedPane _mainPane, _sidePane; private JSplitPane _codeAndUnitPane; private JTabbedPane _auxPane; private JPanel _unitPane; private StatusBar _status; private JToolBar _cmdToolBar; private CaptureButton _btnCapture; private ButtonRun _btnRun, _btnRunViz; private JMenuBar _menuBar = new JMenuBar(); private JMenu _fileMenu = new JMenu(_I("menuFile")); private JMenu _editMenu = new JMenu(_I("menuEdit")); private JMenu _runMenu = new JMenu(_I("menuRun")); private JMenu _viewMenu = new JMenu(_I("menuView")); private JMenu _helpMenu = new JMenu(_I("menuHelp")); private JCheckBoxMenuItem _chkShowUnitTest; private UnitTestRunner _testRunner; private static CommandLine _cmdLine; private static SikuliIDE _instance = null; private static Icon PY_SRC_ICON = getIconResource("/icons/py-src-16x16.png"); private boolean _inited = false; static String _I(String key, Object... args){ return I18N._I(key, args); } public static ImageIcon getIconResource(String name) { URL url= SikuliIDE.class.getResource(name); if (url == null) { System.err.println("Warning: could not load \""+name+"\" icon"); return null; } return new ImageIcon(url); } public void onStopRunning(){ Debug.log(2, "StopRunning"); this.setVisible(true); _btnRun.stopRunning(); _btnRunViz.stopRunning(); } public void onQuickCapture(){ onQuickCapture(null); } public void onQuickCapture(String arg){ Debug.log(2, "QuickCapture"); _btnCapture.capture(0); } //FIXME: singleton lock public static synchronized SikuliIDE getInstance(String args[]){ Debug.log(5, "create SikuliIDE " + args); if( _instance == null ){ _instance = new SikuliIDE(args); } return _instance; } public static synchronized SikuliIDE getInstance(){ Debug.log(5, "create SikuliIDE()"); return getInstance(null); } private JMenuItem createMenuItem(JMenuItem item, KeyStroke shortcut, ActionListener listener){ if(shortcut != null) item.setAccelerator(shortcut); item.addActionListener(listener); return item; } boolean checkDirtyPanes(){ for(int i=0;i<_mainPane.getComponentCount();i++){ JScrollPane scrPane = (JScrollPane)_mainPane.getComponentAt(i); SikuliPane codePane = (SikuliPane)scrPane.getViewport().getView(); if(codePane.isDirty()){ getRootPane().putClientProperty("Window.documentModified", true); return true; } } getRootPane().putClientProperty("Window.documentModified", false); return false; } private JMenuItem createMenuItem(String name, KeyStroke shortcut, ActionListener listener){ JMenuItem item = new JMenuItem(name); return createMenuItem(item, shortcut, listener); } private void initRunMenu() throws NoSuchMethodException{ int scMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); _runMenu.setMnemonic(java.awt.event.KeyEvent.VK_R); _runMenu.add( createMenuItem(_I("menuRunRun"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, scMask), new RunAction(RunAction.RUN))); _runMenu.add( createMenuItem(_I("menuRunRunAndShowActions"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, InputEvent.ALT_MASK | scMask), new RunAction(RunAction.RUN_SHOW_ACTIONS))); UserPreferences pref = UserPreferences.getInstance(); JMenuItem stopItem = createMenuItem(_I("menuRunStop"), KeyStroke.getKeyStroke( pref.getStopHotkey(), pref.getStopHotkeyModifiers()), new RunAction(RunAction.RUN_SHOW_ACTIONS)); stopItem.setEnabled(false); _runMenu.add(stopItem); } private void initFileMenu() throws NoSuchMethodException{ int scMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); _fileMenu.setMnemonic(java.awt.event.KeyEvent.VK_F); _fileMenu.add( createMenuItem(_I("menuFileNew"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, scMask), new FileAction(FileAction.NEW))); _fileMenu.add( createMenuItem(_I("menuFileOpen"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, scMask), new FileAction(FileAction.OPEN))); _fileMenu.add( createMenuItem(_I("menuFileSave"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, scMask), new FileAction(FileAction.SAVE))); _fileMenu.add( createMenuItem(_I("menuFileSaveAs"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, InputEvent.SHIFT_MASK | scMask), new FileAction(FileAction.SAVE_AS))); _fileMenu.add( createMenuItem(_I("menuFileExport"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, InputEvent.SHIFT_MASK | scMask), new FileAction(FileAction.EXPORT))); _fileMenu.addSeparator(); if(!Utils.isMacOSX()){ _fileMenu.add( createMenuItem(_I("menuFilePreferences"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, scMask), new FileAction(FileAction.PREFERENCES))); } _fileMenu.add( createMenuItem(_I("menuFileCloseTab"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, scMask), new FileAction(FileAction.CLOSE_TAB))); if(!Utils.isMacOSX()){ _fileMenu.addSeparator(); _fileMenu.add( createMenuItem(_I("menuFileQuit"), null, new FileAction(FileAction.QUIT))); } } private void initEditMenu() throws NoSuchMethodException{ int scMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); _editMenu.setMnemonic(java.awt.event.KeyEvent.VK_E); _editMenu.add( createMenuItem(_I("menuEditCut"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, scMask), new EditAction(EditAction.CUT))); _editMenu.add( createMenuItem(_I("menuEditCopy"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, scMask), new EditAction(EditAction.COPY))); _editMenu.add( createMenuItem(_I("menuEditPaste"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, scMask), new EditAction(EditAction.PASTE))); _editMenu.add( createMenuItem(_I("menuEditSelectAll"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, scMask), new EditAction(EditAction.SELECT_ALL))); _editMenu.addSeparator(); _editMenu.add( createMenuItem(_I("menuEditIndent"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_TAB, 0), new EditAction(EditAction.INDENT))); _editMenu.add( createMenuItem(_I("menuEditUnIndent"), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_TAB, InputEvent.SHIFT_MASK), new EditAction(EditAction.UNINDENT))); } private void initHelpMenu() throws NoSuchMethodException{ int scMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); _helpMenu.setMnemonic(java.awt.event.KeyEvent.VK_H); _helpMenu.add( createMenuItem(_I("menuHelpCheckUpdate"), null, new HelpAction(HelpAction.CHECK_UPDATE))); _helpMenu.addSeparator(); _helpMenu.add( createMenuItem(_I("menuHelpGuide"), null, new HelpAction(HelpAction.OPEN_GUIDE))); _helpMenu.add( createMenuItem(_I("menuHelpDocumentations"), null, new HelpAction(HelpAction.OPEN_DOC))); _helpMenu.add( createMenuItem(_I("menuHelpAsk"), null, new HelpAction(HelpAction.OPEN_ASK))); _helpMenu.add( createMenuItem(_I("menuHelpBugReport"), null, new HelpAction(HelpAction.OPEN_BUG_REPORT))); _helpMenu.addSeparator(); _helpMenu.add( createMenuItem(_I("menuHelpHomepage"), null, new HelpAction(HelpAction.OPEN_HOMEPAGE))); } private void initViewMenu() throws NoSuchMethodException{ int scMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); _viewMenu.setMnemonic(java.awt.event.KeyEvent.VK_V); _chkShowUnitTest = new JCheckBoxMenuItem(_I("menuViewUnitTest")); _viewMenu.add( createMenuItem(_chkShowUnitTest, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, scMask), new ViewAction(ViewAction.UNIT_TEST))); JMenuItem chkShowCmdList = new JCheckBoxMenuItem(_I("menuViewCommandList"), true); _viewMenu.add( createMenuItem(chkShowCmdList, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, scMask), new ViewAction(ViewAction.CMD_LIST))); } private void initMenuBars(JFrame frame){ try{ initFileMenu(); initEditMenu(); initRunMenu(); initViewMenu(); initHelpMenu(); } catch(NoSuchMethodException e){ e.printStackTrace(); } _menuBar.add(_fileMenu); _menuBar.add(_editMenu); _menuBar.add(_runMenu); _menuBar.add(_viewMenu); _menuBar.add(_helpMenu); frame.setJMenuBar(_menuBar); } private String[][] CommandsOnToolbar = { {"find"}, {"PATTERN"}, {_I("cmdFind")}, {"findAll"}, {"PATTERN"}, {_I("cmdFindAll")}, {"wait"}, {"PATTERN", "[timeout]"}, {_I("cmdWait")}, {"waitVanish"}, {"PATTERN", "[timeout]"}, {_I("cmdWaitVanish")}, {"exists"}, {"PATTERN", "[timeout]"}, {_I("cmdExists")}, {" {"click"}, {"PATTERN","[modifiers]"}, {_I("cmdClick")}, {"doubleClick"}, {"PATTERN","[modifiers]"}, {_I("cmdDoubleClick")}, {"rightClick"}, {"PATTERN","[modifiers]"}, {_I("cmdRightClick")}, {"hover"}, {"PATTERN"}, {_I("cmdHover")}, {"dragDrop"}, {"PATTERN", "PATTERN", "[modifiers]"}, {_I("cmdDragDrop")}, /* {"drag"}, {"PATTERN"}, {"dropAt"}, {"PATTERN", "[delay]"}, */ {"type"}, {"_text", "[modifiers]"}, {_I("cmdType")}, {"type"}, {"PATTERN", "_text", "[modifiers]"}, {_I("cmdType2")}, {"paste"}, {"_text", "[modifiers]"}, {_I("cmdPaste")}, {"paste"}, {"PATTERN", "_text", "[modifiers]"}, {_I("cmdPaste2")}, {" {"onAppear"}, {"PATTERN", "_handler"}, {_I("cmdOnAppear")}, {"onVanish"}, {"PATTERN", "_handler"}, {_I("cmdOnVanish")}, {"onChange"}, {"_handler"}, {_I("cmdOnChange")}, {"observe"}, {"[time]","[background]"}, {_I("cmdObserve")}, }; private JToolBar initCmdToolbar(){ JToolBar toolbar = new JToolBar(JToolBar.VERTICAL); UserPreferences pref = UserPreferences.getInstance(); JCheckBox chkAutoCapture = new JCheckBox(_I("cmdListAutoCapture"), pref.getAutoCaptureForCmdButtons()); chkAutoCapture.addChangeListener(new ChangeListener(){ public void stateChanged(javax.swing.event.ChangeEvent e){ boolean flag = ((JCheckBox)e.getSource()).isSelected(); UserPreferences pref = UserPreferences.getInstance(); pref.setAutoCaptureForCmdButtons(flag); } }); toolbar.add(new JLabel(_I("cmdListCommandList"))); toolbar.add(chkAutoCapture); for(int i=0;i<CommandsOnToolbar.length;i++){ String cmd = CommandsOnToolbar[i++][0]; String[] params = CommandsOnToolbar[i++]; String[] desc = CommandsOnToolbar[i]; if( cmd.equals(" toolbar.addSeparator(); else toolbar.add(new ButtonGenCommand(cmd, desc[0], params)); } return toolbar; } private JToolBar initToolbar(){ JToolBar toolbar = new JToolBar(); _btnRun = new ButtonRun(); JButton btnInsertImage = new ButtonInsertImage(); _btnCapture = new CaptureButton(); JButton btnSubregion = new ButtonSubregion(); _btnRunViz = new ButtonRunViz(); toolbar.add(_btnCapture); toolbar.add(btnInsertImage); toolbar.add(btnSubregion); toolbar.addSeparator(); if( ENABLE_RECORDING ){ JToggleButton btnRecord = new ButtonRecord(); toolbar.add(btnRecord); } toolbar.add(_btnRun); toolbar.add(_btnRunViz); toolbar.setFloatable(false); return toolbar; } private void initTabPane(){ _mainPane = new CloseableTabbedPane(); _mainPane.addCloseableTabbedPaneListener( new CloseableTabbedPaneListener(){ public boolean closeTab(int i){ try{ JScrollPane scrPane = (JScrollPane)_mainPane.getComponentAt(i); SikuliPane codePane = (SikuliPane)scrPane.getViewport().getView(); Debug.log(3, "close tab: " + _mainPane.getComponentCount()); boolean ret = codePane.close(); Debug.log(3, "close tab after: " + _mainPane.getComponentCount()); checkDirtyPanes(); return ret; } catch(Exception e){ Debug.info("Can't close this tab: " + e.getStackTrace()); return false; } } }); _mainPane.addChangeListener(new ChangeListener(){ public void stateChanged(javax.swing.event.ChangeEvent e){ JTabbedPane tab = (JTabbedPane)e.getSource(); int i = tab.getSelectedIndex(); if(i>=0) SikuliIDE.this.setTitle(tab.getTitleAt(i)); } }); } private void initAuxPane(){ _auxPane = new JTabbedPane(); _console = new ConsolePane(); _auxPane.addTab(_I("paneMessage"), _console); } private void initUnitPane(){ _testRunner = new UnitTestRunner(); _unitPane = _testRunner.getPanel(); _chkShowUnitTest.setState(false); (new ViewAction()).toggleUnitTest(null); addAuxTab(_I("paneTestTrace"), _testRunner.getTracePane()); } private void initSidePane(){ _sidePane = new CloseableTabbedPane(); _sidePane.addChangeListener(new ChangeListener(){ public void stateChanged(javax.swing.event.ChangeEvent e){ JTabbedPane pane = (JTabbedPane)e.getSource(); int sel = pane.getSelectedIndex(); if( sel == -1 ) { // all tabs closed _codeAndUnitPane.setDividerLocation(1.0D); _chkShowUnitTest.setState(false); } } }); } private StatusBar initStatusbar(){ _status = new StatusBar(); return _status; } public void addAuxTab(String tabName, JComponent com){ _auxPane.addTab(tabName, com); } private void initShortcutKeys(){ final int scMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener() { public void eventDispatched( AWTEvent e ){ java.awt.event.KeyEvent ke = (java.awt.event.KeyEvent)e; //Debug.log(ke.toString()); if( ke.getID() == java.awt.event.KeyEvent.KEY_PRESSED ){ if( ke.getKeyCode() == java.awt.event.KeyEvent.VK_TAB && ke.getModifiers() == InputEvent.CTRL_MASK) nextTab(); else if( ke.getKeyCode() == java.awt.event.KeyEvent.VK_TAB && ke.getModifiers() == (InputEvent.CTRL_MASK|InputEvent.SHIFT_MASK) ) prevTab(); } } }, AWTEvent.KEY_EVENT_MASK ); } private void nextTab(){ int i = _mainPane.getSelectedIndex(); int next = (i+1) % _mainPane.getTabCount(); _mainPane.setSelectedIndex(next); } private void prevTab(){ int i = _mainPane.getSelectedIndex(); int prev = (i-1+_mainPane.getTabCount()) % _mainPane.getTabCount(); _mainPane.setSelectedIndex(prev); } static final int DEFAULT_WINDOW_W = 1024; static final int DEFAULT_WINDOW_H = 700; // Constructor protected SikuliIDE(String[] args) { super("Sikuli IDE"); ScriptRunner.getInstance(getPyArgs()); _native.initIDE(this); initMenuBars(this); final Container c = getContentPane(); c.setLayout(new BorderLayout()); initTabPane(); initAuxPane(); initSidePane(); initUnitPane(); _codeAndUnitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, true, _mainPane, _sidePane); JSplitPane mainAndConsolePane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, true, _codeAndUnitPane, _auxPane); _cmdToolBar = initCmdToolbar(); c.add(initToolbar(), BorderLayout.NORTH); c.add(_cmdToolBar, BorderLayout.WEST); c.add(mainAndConsolePane, BorderLayout.CENTER); c.add(initStatusbar(), BorderLayout.SOUTH); c.doLayout(); setSize(DEFAULT_WINDOW_W, DEFAULT_WINDOW_H); adjustCodePaneWidth(); mainAndConsolePane.setDividerLocation(500); initShortcutKeys(); //setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); initHotkeys(); initWindowListener(); initTooltip(); if( _cmdLine.getArgs().length > 0 ){ for(String f : _cmdLine.getArgs()) loadFile(Utils.slashify(f, false)); } else (new FileAction()).doNew(null); _inited = true; setVisible(true); autoCheckUpdate(); } private void initTooltip(){ ToolTipManager tm = ToolTipManager.sharedInstance(); tm.setDismissDelay(30000); } private void autoCheckUpdate(){ UserPreferences pref = UserPreferences.getInstance(); if( !pref.getCheckUpdate() ) return; long last_check = pref.getCheckUpdateTime(); long now = (new Date()).getTime(); if(now - last_check > 1000*86400){ Debug.log(3, "check update"); (new HelpAction()).checkUpdate(true); } pref.setCheckUpdateTime(); } private void initWindowListener(){ setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { SikuliIDE.this.quit(); } }); } public boolean isInited(){ return _inited; } public void installCaptureHotkey(int key, int mod){ _native.installHotkey(key, mod, this, "onQuickCapture", "(Ljava/lang/String;)V"); } private void initHotkeys(){ UserPreferences pref = UserPreferences.getInstance(); int key = pref.getCaptureHotkey(); int mod = pref.getCaptureHotkeyModifiers(); installCaptureHotkey(key, mod); key = pref.getStopHotkey(); mod = pref.getStopHotkeyModifiers(); _native.installHotkey(key, mod, this, "onStopRunning", "()V"); } static private void initNativeLayer(){ String os = "unknown"; if(Utils.isWindows()) os = "Windows"; else if(Utils.isMacOSX()) os = "Mac"; else if(Utils.isLinux()) os = "Linux"; String className = "edu.mit.csail.uid.NativeLayerFor" + os; try{ Class c = Class.forName(className); Constructor constr = c.getConstructor(); _native = (NativeLayer)constr.newInstance(); } catch( Exception e){ e.printStackTrace(); } } public void loadFile(String file){ (new FileAction()).doNew(null); try{ getCurrentCodePane().loadFile(file); setCurrentFilename(file); } catch(IOException e){ e.printStackTrace(); } } private void adjustCodePaneWidth(){ int pos = getWidth() - _sidePane.getMinimumSize().width-15; if(_codeAndUnitPane != null && pos >= 0) _codeAndUnitPane.setDividerLocation(pos); } static boolean _runningSkl = false; public static void runSikuli(String filename, String[] args) throws IOException{ ScriptRunner srunner = new ScriptRunner(args); try{ srunner.runPython(Utils.slashify(filename,true)); } catch(Exception e){ java.util.regex.Pattern p = java.util.regex.Pattern.compile("SystemExit:( [0-9]+)"); Matcher matcher = p.matcher(e.toString()); if(matcher.find()){ Debug.info(_I("msgExit", matcher.group(1))); } else{ JOptionPane.showMessageDialog(null, _I("msgRunningSklError", filename, e)); } } } public static void runSkl(String filename, String[] args) throws IOException{ _runningSkl = true; String name = (new File(filename)).getName(); name = name.substring(0, name.lastIndexOf('.')); File tmpDir = Utils.createTempDir(); File sikuliDir = new File(tmpDir + File.separator + name + ".sikuli"); sikuliDir.mkdir(); Utils.unzip(filename, sikuliDir.getAbsolutePath()); runSikuli(sikuliDir.getAbsolutePath(), args); } static String[] getPyArgs(){ String[] pargs = _cmdLine.getArgs(); if( _cmdLine.hasOption("args") ) pargs = _cmdLine.getOptionValues("args"); return pargs; } public static void main(String[] args) { initNativeLayer(); CommandArgs cmdArgs = new CommandArgs(); _cmdLine = cmdArgs.getCommandLine(args); if( _cmdLine.hasOption("h") ){ cmdArgs.printHelp(); return; } if(args!=null && args.length>=1){ try{ String[] pargs = getPyArgs(); if( _cmdLine.hasOption("run") ){ String file = _cmdLine.getOptionValue("run"); if(file.endsWith(".skl")) runSkl(file, pargs); else if(file.endsWith(".sikuli")){ File f = new File(file); runSikuli(f.getAbsolutePath(), pargs); } return; } if( _cmdLine.getArgs().length>0 ){ String file = _cmdLine.getArgs()[0]; if(file.endsWith(".skl")){ runSkl(file, pargs); return; } } } catch(IOException e){ System.err.println("Can't open file: " + args[0] + "\n" + e); } } try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e){ e.printStackTrace(); } if(Utils.isMacOSX()){ _native.initApp(); try{ Thread.sleep(1000); } catch(InterruptedException ie){} } if(!_runningSkl){ SikuliIDE.getInstance(args); } } public void jumpTo(String funcName) throws BadLocationException{ SikuliPane pane = getCurrentCodePane(); pane.jumpTo(funcName); pane.grabFocus(); } public void jumpTo(int lineNo) throws BadLocationException{ SikuliPane pane = getCurrentCodePane(); pane.jumpTo(lineNo); pane.grabFocus(); } public SikuliPane getCurrentCodePane(){ if(_mainPane.getSelectedIndex() == -1) return null; JScrollPane scrPane = (JScrollPane)_mainPane.getSelectedComponent(); SikuliPane ret = (SikuliPane)scrPane.getViewport().getView(); return ret; } public void setCurrentFilename(String fname){ if( fname.endsWith("/") ) fname = fname.substring(0, fname.length()-1); int i = _mainPane.getSelectedIndex(); fname = fname.substring(fname.lastIndexOf("/")+1); _mainPane.setTitleAt(i, fname); this.setTitle(fname); } public void setTitle(String title){ super.setTitle("Sikuli " + IDESettings.SikuliVersion + " - " + title); } public String getCurrentBundlePath(){ SikuliPane pane = getCurrentCodePane(); return pane.getSrcBundle(); } public String getCurrentFilename(){ SikuliPane pane = getCurrentCodePane(); String fname = pane.getCurrentFilename(); return fname; } public boolean closeCurrentTab(){ SikuliPane pane = getCurrentCodePane(); (new FileAction()).doCloseTab(null); if( pane == getCurrentCodePane() ) return false; return true; } public void showPreferencesWindow(){ PreferencesWin pwin = new PreferencesWin(); pwin.setVisible(true); } class MenuAction implements ActionListener { protected Method actMethod = null; protected String action; public MenuAction(){ } public MenuAction(String item) throws NoSuchMethodException{ Class[] params = new Class[0]; Class[] paramsWithEvent = new Class[1]; try{ paramsWithEvent[0] = Class.forName("java.awt.event.ActionEvent"); actMethod = this.getClass().getMethod(item, paramsWithEvent); action = item; } catch(ClassNotFoundException cnfe){ Debug.error("Can't find menu action: " + cnfe); } } public void actionPerformed(ActionEvent e) { if(actMethod != null){ try{ Debug.log(2, "MenuAction." + action); Object[] params = new Object[1]; params[0] = e; actMethod.invoke(this, params); } catch(Exception ex){ ex.printStackTrace(); } } } } class RunAction extends MenuAction { static final String RUN = "run"; static final String RUN_SHOW_ACTIONS = "runShowActions"; public RunAction(){ super(); } public RunAction(String item) throws NoSuchMethodException{ super(item); } public void run(ActionEvent ae){ _btnRun.runCurrentScript(); } public void runShowActions(ActionEvent ae){ _btnRunViz.runCurrentScript(); } } // Uncomment this for Mac OS X 10.5 (Java5) /* static void openURL(String url){ try{ String cmd[] = {"open", url}; Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); return; } catch(Exception e){ Debug.info("Can't open " + url); } } */ static void openURL(String url){ try{ URL u = new URL(url); java.awt.Desktop.getDesktop().browse(u.toURI()); } catch(Exception ex){ ex.printStackTrace(); } } class ViewAction extends MenuAction { static final String UNIT_TEST = "toggleUnitTest"; static final String CMD_LIST = "toggleCmdList"; public ViewAction(){ super(); } public ViewAction(String item) throws NoSuchMethodException{ super(item); } public void toggleCmdList(ActionEvent ae){ _cmdToolBar.setVisible(!_cmdToolBar.isVisible()); } public void toggleUnitTest(ActionEvent ae){ if( _chkShowUnitTest.getState() ){ _sidePane.addTab(_I("tabUnitTest"), _unitPane); adjustCodePaneWidth(); } else _sidePane.remove(_unitPane); } } public void quit(){ (new FileAction()).doQuit(null); } class HelpAction extends MenuAction { static final String CHECK_UPDATE = "doCheckUpdate"; static final String OPEN_DOC = "openDoc"; static final String OPEN_GUIDE = "openGuide"; static final String OPEN_ASK = "openAsk"; static final String OPEN_BUG_REPORT = "openBugReport"; static final String OPEN_HOMEPAGE = "openHomepage"; public HelpAction(){ super(); } public HelpAction(String item) throws NoSuchMethodException{ super(item); } public void openDoc(ActionEvent ae){ openURL("http://sikuli.org/documentation.shtml"); } public void openGuide(ActionEvent ae){ openURL("http://sikuli.org/trac/wiki/reference-0.10"); } public void openAsk(ActionEvent ae){ openURL("https://answers.launchpad.net/sikuli"); } public void openBugReport(ActionEvent ae){ openURL("https://bugs.launchpad.net/sikuli/+filebug"); } public void openHomepage(ActionEvent ae){ openURL("http://sikuli.org"); } public boolean checkUpdate(boolean isAutoCheck){ AutoUpdater au = new AutoUpdater(); UserPreferences pref = UserPreferences.getInstance(); Debug.log("Check update"); if( au.checkUpdate() ){ String ver = au.getVersion(); String details = au.getDetails(); if(isAutoCheck && pref.getLastSeenUpdate().equals(ver)) return false; UpdateFrame f = new UpdateFrame( _I("dlgUpdateAvailable", ver), details ); UserPreferences.getInstance().setLastSeenUpdate(ver); return true; } return false; } public void doCheckUpdate(ActionEvent ae){ if(!checkUpdate(false)){ JOptionPane.showMessageDialog(null, _I("msgNoUpdate"), "Sikuli " + IDESettings.SikuliVersion, JOptionPane.INFORMATION_MESSAGE); } } } class EditAction extends MenuAction { static final String CUT = "doCut"; static final String COPY = "doCopy"; static final String PASTE = "doPaste"; static final String SELECT_ALL = "doSelectAll"; static final String INDENT = "doIndent"; static final String UNINDENT = "doUnindent"; public EditAction(){ super(); } public EditAction(String item) throws NoSuchMethodException{ super(item); } private void performEditorAction(String action, ActionEvent ae){ SikuliIDE ide = SikuliIDE.getInstance(); SikuliPane pane = ide.getCurrentCodePane(); pane.getActionMap().get(action).actionPerformed(ae); } public void doCut(ActionEvent ae){ performEditorAction(DefaultEditorKit.cutAction, ae); } public void doCopy(ActionEvent ae){ performEditorAction(DefaultEditorKit.copyAction, ae); } public void doPaste(ActionEvent ae){ performEditorAction(DefaultEditorKit.pasteAction, ae); } public void doSelectAll(ActionEvent ae){ performEditorAction(DefaultEditorKit.selectAllAction, ae); } public void doIndent(ActionEvent ae){ SikuliIDE ide = SikuliIDE.getInstance(); SikuliPane pane = ide.getCurrentCodePane(); (new SikuliEditorKit.InsertTabAction()).actionPerformed(pane); } public void doUnindent(ActionEvent ae){ SikuliIDE ide = SikuliIDE.getInstance(); SikuliPane pane = ide.getCurrentCodePane(); (new SikuliEditorKit.DeindentAction()).actionPerformed(pane); } } class FileAction extends MenuAction { static final String NEW = "doNew"; static final String OPEN = "doLoad"; static final String SAVE = "doSave"; static final String SAVE_AS = "doSaveAs"; static final String EXPORT = "doExport"; static final String CLOSE_TAB = "doCloseTab"; static final String PREFERENCES = "doPreferences"; static final String QUIT = "doQuit"; public FileAction(){ super(); } public FileAction(String item) throws NoSuchMethodException{ super(item); } public void doQuit(ActionEvent ae){ SikuliIDE ide = SikuliIDE.getInstance(); while(true){ SikuliPane codePane = ide.getCurrentCodePane(); if(codePane == null) break; if(!ide.closeCurrentTab()) return; } System.exit(0); } public void doPreferences(ActionEvent ae){ SikuliIDE.getInstance().showPreferencesWindow(); } public void doNew(ActionEvent ae){ SikuliPane codePane = new SikuliPane(); JScrollPane scrPane = new JScrollPane(codePane); scrPane.setRowHeaderView(new LineNumberView(codePane)); _mainPane.addTab(_I("tabUntitled"), scrPane); _mainPane.setSelectedIndex(_mainPane.getTabCount()-1); codePane.addCaretListener(new CaretListener(){ public void caretUpdate(CaretEvent evt){ SikuliPane comp = (SikuliPane)evt.getSource(); int line = comp.getLineAtCaret(); int col = comp.getColumnAtCaret(); if(_status != null) _status.setCaretPosition(line, col); } }); codePane.requestFocus(); } public void doLoad(ActionEvent ae){ try{ doNew(ae); SikuliPane codePane = SikuliIDE.getInstance().getCurrentCodePane(); String fname = codePane.loadFile(); if(fname!=null) SikuliIDE.getInstance().setCurrentFilename(fname); else doCloseTab(ae); } catch(IOException eio){ eio.printStackTrace(); } } public void doSave(ActionEvent ae){ try{ SikuliPane codePane = SikuliIDE.getInstance().getCurrentCodePane(); String fname = codePane.saveFile(); if(fname!=null) SikuliIDE.getInstance().setCurrentFilename(fname); } catch(IOException eio){ eio.printStackTrace(); } } public void doSaveAs(ActionEvent ae){ try{ SikuliPane codePane = SikuliIDE.getInstance().getCurrentCodePane(); String fname = codePane.saveAsFile(); if(fname!=null) SikuliIDE.getInstance().setCurrentFilename(fname); } catch(IOException eio){ eio.printStackTrace(); } } public void doExport(ActionEvent ae){ try{ SikuliPane codePane = SikuliIDE.getInstance().getCurrentCodePane(); String fname = codePane.exportAsZip(); } catch(Exception ex){ ex.printStackTrace(); } } public void doCloseTab(ActionEvent ae){ SikuliPane codePane = SikuliIDE.getInstance().getCurrentCodePane(); try{ if(codePane.close()) _mainPane.remove(_mainPane.getSelectedIndex()); } catch(IOException e){ Debug.info("Can't close this tab: " + e.getStackTrace()); } } } class ButtonRecord extends JToggleButton implements ActionListener { public ButtonRecord(){ super(); URL imageURL = SikuliIDE.class.getResource("/icons/record.png"); setIcon(new ImageIcon(imageURL)); setMaximumSize(new Dimension(26,26)); setBorderPainted(false); setToolTipText("Record"); addActionListener(this); } private void initSikuliGenerator(){ } public void startSikuliGenerator(){ try{ String args[] = {"/tmp/sikuli-video.mov", "/tmp/sikuli-event.log"}; //FIXME: test if this works.. Class c = Class.forName("SikuliGenerator"); Class[] t_params = { String[].class, SikuliPane.class }; Constructor constr = c.getConstructor(t_params); constr.newInstance(new Object[]{ args, getCurrentCodePane() }); /* SikuliGenerator sg = new SikuliGenerator(args, getCurrentCodePane()); */ } catch(Exception e){ System.err.println("Error in starting up SikuliGenerator..."); e.printStackTrace(); } } public void actionPerformed(ActionEvent ae) { if( getModel().isSelected() ){ Debug.info("start recording"); Thread recordThread = new Thread(){ public void run() { Utils.runRecorder(); Debug.info("recording completed"); getModel().setSelected(false); startSikuliGenerator(); } }; recordThread.start(); } else{ Debug.info("stop recording..."); Utils.stopRecorder(); } } } class ButtonRunViz extends ButtonRun { public ButtonRunViz(){ super(); URL imageURL = SikuliIDE.class.getResource("/icons/runviz.png"); setIcon(new ImageIcon(imageURL)); setToolTipText(_I("menuRunRunAndShowActions")); } protected void runPython(File f) throws IOException{ ScriptRunner srunner = new ScriptRunner(getPyArgs()); String path = SikuliIDE.getInstance().getCurrentBundlePath(); srunner.addTempHeader("initSikuli()"); srunner.addTempHeader("setShowActions(True)"); srunner.runPython(path, f); } } class ButtonRun extends JButton implements ActionListener { private Thread _runningThread = null; public ButtonRun(){ super(); URL imageURL = SikuliIDE.class.getResource("/icons/run.png"); setIcon(new ImageIcon(imageURL)); setMaximumSize(new Dimension(26,26)); setBorderPainted(false); initTooltip(); addActionListener(this); } protected void runPython(File f) throws IOException{ ScriptRunner srunner = new ScriptRunner(getPyArgs()); String path= SikuliIDE.getInstance().getCurrentBundlePath(); srunner.addTempHeader("initSikuli()"); srunner.runPython(path, f); } private void initTooltip(){ UserPreferences pref = UserPreferences.getInstance(); String strHotkey = Utils.convertKeyToText( pref.getStopHotkey(), pref.getStopHotkeyModifiers() ); String stopHint = _I("btnRunStopHint", strHotkey); setToolTipText(_I("btnRun", stopHint)); } private int findErrorSource(Throwable thr, String filename) { String err = thr.toString(); if(err.startsWith("Traceback")){ java.util.regex.Pattern p = java.util.regex.Pattern.compile( ", line (\\d+),"); java.util.regex.Matcher m = p.matcher(err); if(m.find()){ Debug.log(4, "error line: " + m.group(1)); return Integer.parseInt(m.group(1)); } } else if(err.startsWith("SyntaxError")){ java.util.regex.Pattern p = java.util.regex.Pattern.compile( ", (\\d+), (\\d+),"); java.util.regex.Matcher m = p.matcher(err); if(m.find()){ Debug.log(4, "SyntaxError error line: " + m.group(1)); return Integer.parseInt(m.group(1)); } } return _findErrorSource(thr, filename); } private int _findErrorSource(Throwable thr, String filename) { StackTraceElement[] s; Throwable t = thr; while (t != null) { s = t.getStackTrace(); Debug.log(4, "stack trace:"); for (int i = s.length-1; i >= 0 ; i StackTraceElement si = s[i]; Debug.log(4, si.getLineNumber() + " " + si.getFileName()); if( si.getLineNumber()>=0 && filename.equals( si.getFileName() ) ){ return si.getLineNumber(); } } t = t.getCause(); Debug.log(3, "cause: " + t); } return -1; } public void stopRunning(){ if(_runningThread != null){ _runningThread.interrupt(); _runningThread.stop(); } } public void actionPerformed(ActionEvent ae) { runCurrentScript(); } public void addErrorMark(int line){ JScrollPane scrPane = (JScrollPane)_mainPane.getSelectedComponent(); LineNumberView lnview = (LineNumberView)(scrPane.getRowHeader().getView()); lnview.addErrorMark(line); SikuliPane codePane = SikuliIDE.this.getCurrentCodePane(); //codePane.setErrorHighlight(line); } public void resetErrorMark(){ JScrollPane scrPane = (JScrollPane)_mainPane.getSelectedComponent(); LineNumberView lnview = (LineNumberView)(scrPane.getRowHeader().getView()); lnview.resetErrorMark(); SikuliPane codePane = SikuliIDE.this.getCurrentCodePane(); //codePane.setErrorHighlight(-1); } public void runCurrentScript() { _runningThread = new Thread(){ public void run(){ SikuliPane codePane = SikuliIDE.getInstance().getCurrentCodePane(); File tmpFile; try{ tmpFile = File.createTempFile("sikuli-tmp",".py"); try{ BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(tmpFile), "UTF8")); codePane.write(bw); SikuliIDE.getInstance().setVisible(false); _console.clear(); resetErrorMark(); runPython(tmpFile); } catch(Exception e){ java.util.regex.Pattern p = java.util.regex.Pattern.compile("SystemExit:( [0-9]+)"); Matcher matcher = p.matcher(e.toString()); if(matcher.find()){ Debug.info(_I("msgExit", matcher.group(1))); } else{ Debug.info(_I("msgStopped")); int srcLine = findErrorSource(e, tmpFile.getAbsolutePath()); if(srcLine != -1){ Debug.info( _I("msgErrorLine", srcLine) ); addErrorMark(srcLine); try{ codePane.jumpTo(srcLine); } catch(BadLocationException be){} codePane.requestFocus(); } Debug.info( _I("msgErrorMsg", e.toString()) ); } } finally{ SikuliIDE.getInstance().setVisible(true); _runningThread = null; } } catch(IOException e){ e.printStackTrace(); } } }; _runningThread.start(); } } } class ButtonInsertImage extends JButton implements ActionListener{ public ButtonInsertImage(){ super(); URL imageURL = SikuliIDE.class.getResource("/icons/insert-image.png"); setIcon(new ImageIcon(imageURL)); setMaximumSize(new Dimension(26,26)); setBorderPainted(false); setToolTipText(SikuliIDE._I("btnInsertImageHint")); addActionListener(this); } public void actionPerformed(ActionEvent ae) { SikuliPane codePane = SikuliIDE.getInstance().getCurrentCodePane(); File file = new FileChooser(SikuliIDE.getInstance()).loadImage(); if(file == null) return; String path = Utils.slashify(file.getAbsolutePath(), false); System.out.println("load: " + path); ImageButton icon = new ImageButton(codePane, codePane.getFileInBundle(path).getAbsolutePath()); codePane.insertComponent(icon); } } class ButtonSubregion extends JButton implements ActionListener, Observer{ public ButtonSubregion(){ super(); URL imageURL = SikuliIDE.class.getResource("/icons/subregion.png"); setIcon(new ImageIcon(imageURL)); setMaximumSize(new Dimension(26,26)); setBorderPainted(false); setToolTipText( SikuliIDE._I("btnRegionHint") ); addActionListener(this); } public void update(Subject s){ if(s instanceof CapturePrompt){ CapturePrompt cp = (CapturePrompt)s; ScreenImage r = cp.getSelection(); if(r==null) return; cp.close(); Rectangle roi = r.getROI(); complete((int)roi.getX(), (int)roi.getY(), (int)roi.getWidth(), (int)roi.getHeight()); } } public void actionPerformed(ActionEvent ae) { SikuliIDE ide = SikuliIDE.getInstance(); SikuliPane codePane = ide.getCurrentCodePane(); ide.setVisible(false); CapturePrompt prompt = new CapturePrompt(null, this); prompt.prompt(500); ide.setVisible(true); } public void complete(int x, int y, int w, int h){ Debug.log(7,"Region: %d %d %d %d", x, y, w, h); SikuliIDE ide = SikuliIDE.getInstance(); SikuliPane codePane = ide.getCurrentCodePane(); ide.setVisible(false); JButton icon = new RegionButton(codePane, x, y, w, h); codePane.insertComponent(icon); ide.setVisible(true); codePane.requestFocus(); } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundStringFlag ALLOCATE_OS_REQUIREMENT = defineStringFlag( "allocate-os-requirement", "rhel7", List.of("hakonhall"), "2021-01-26", "2021-07-26", "Allocations of new nodes are limited to the given host OS. Must be one of 'rhel7', " + "'rhel8', or 'any'", "Takes effect on next (re)deployment.", APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "LATENCY", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicatiomanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2021-04-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-client-server-communication", "OFF", List.of("hmusum"), "2020-12-02", "2021-04-01", "How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag( "use-tls-for-zookeeper-client", false, List.of("hmusum"), "2020-12-02", "2021-04-01", "Whether to use TLS for ZooKeeper clients", "Takes effect on restart of process", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag PROVISION_TENANT_ROLES = defineFeatureFlag( "provision-tenant-roles", false, List.of("tokle"), "2020-12-02", "2021-04-01", "Whether tenant roles should be provisioned", "Takes effect on next deployment (controller)", TENANT_ID); public static final UnboundBooleanFlag TENANT_IAM_ROLE = defineFeatureFlag( "application-iam-roles", false, List.of("tokle"), "2020-12-02", "2021-04-01", "Allow separate iam roles when provisioning/assigning hosts", "Takes effect immediately on new hosts, on next redeploy for applications", TENANT_ID); public static final UnboundIntFlag MAX_TRIAL_TENANTS = defineIntFlag( "max-trial-tenants", -1, List.of("ogronnesby"), "2020-12-03", "2021-04-01", "The maximum nr. of tenants with trial plan, -1 is unlimited", "Takes effect immediately" ); public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag( "hide-shared-routing-endpoint", false, List.of("tokle"), "2020-12-02", "2021-06-01", "Whether the controller should hide shared routing layer endpoint", "Takes effect immediately", APPLICATION_ID ); public static final UnboundBooleanFlag USE_ACCESS_CONTROL_CLIENT_AUTHENTICATION = defineFeatureFlag( "use-access-control-client-authentication", false, List.of("tokle"), "2020-12-02", "2021-04-01", "Whether application container should set up client authentication on default port based on access control element", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_PENDING_MOVE_OPS = defineIntFlag( "max-pending-move-ops", 10, List.of("baldersheim"), "2021-02-15", "2021-04-01", "Max number of move operations inflight", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_LID_SPACE_COMPACT = defineFeatureFlag( "use-bucket-executor-for-lid-space-compact", false, List.of("baldersheim"), "2021-01-24", "2021-03-01", "Wheter to use content-level bucket executor or legacy frozen buckets", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_BUCKET_MOVE = defineFeatureFlag( "use-bucket-executor-for-bucket-move", false, List.of("baldersheim"), "2021-02-15", "2021-04-01", "Wheter to use content-level bucket executor or legacy frozen buckets", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag USE_POWER_OF_TWO_CHOICES_LOAD_BALANCING = defineFeatureFlag( "use-power-of-two-choices-load-balancing", false, List.of("tokle"), "2020-12-02", "2021-04-01", "Whether to use Power of two load balancing algorithm for application", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag( "group-suspension", true, List.of("hakon"), "2021-01-22", "2021-03-22", "Allow all content nodes in a hierarchical group to suspend at the same time", "Takes effect on the next suspension request to the Orchestrator.", APPLICATION_ID); public static final UnboundBooleanFlag RECONFIGURABLE_ZOOKEEPER_SERVER_FOR_CLUSTER_CONTROLLER = defineFeatureFlag( "reconfigurable-zookeeper-server-for-cluster-controller", false, List.of("musum", "mpolden"), "2020-12-16", "2021-03-16", "Whether to use reconfigurable zookeeper server for cluster controller", "Takes effect on (re)redeployment", APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag( "enable-feed-block-in-distributor", false, List.of("geirst"), "2021-01-27", "2021-04-01", "Enables blocking of feed in the distributor if resource usage is above limit on at least one content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MAX_DEAD_BYTES_RATIO = defineDoubleFlag( "max-dead-bytes-ratio", 0.2, List.of("baldersheim", "geirst","toregge"), "2021-02-03", "2021-04-01", "max ratio of dead to used memory bytes in large data structures before compaction is attempted", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag SYNC_HOST_LOGS_TO_S3_BUCKET = defineStringFlag( "sync-host-logs-to-s3-bucket", "", List.of("andreer", "valerijf"), "2021-02-10", "2021-04-01", "Host-admin should sync host logs to an S3 bucket named by this flag. If left empty, sync is disabled", "Takes effect on next run of S3 log sync task in host-admin", APPLICATION_ID, NODE_TYPE); public static final UnboundIntFlag CLUSTER_CONTROLLER_MAX_HEAP_SIZE_IN_MB = defineIntFlag( "cluster-controller-max-heap-size-in-mb", 512, List.of("hmusum"), "2021-02-10", "2021-04-10", "JVM max heap size for cluster controller in Mb", "Takes effect when restarting cluster controller"); public static final UnboundBooleanFlag DEDICATED_CLUSTER_CONTROLLER_CLUSTER = defineFeatureFlag( "dedicated-cluster-controller-cluster", false, List.of("jonmv"), "2021-02-15", "2021-04-15", "Makes application eligible for switching to a dedicated, shared cluster controller cluster, by a maintainer", "Takes effect immediately", APPLICATION_ID); public static final UnboundStringFlag DEDICATED_CLUSTER_CONTROLLER_FLAVOR = defineStringFlag( "dedicated-cluster-controller-flavor", "", List.of("jonmv"), "2021-02-25", "2021-04-25", "Flavor as <vpu>-<memgb>-<diskgb> to use for dedicated cluster controller nodes", "Takes effect immediately, for subsequent provisioning", APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2021-08-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag( "generate-non-mtls-endpoint", true, List.of("tokle"), "2021-02-18", "2021-10-01", "Whether to generate the non-mtls endpoint", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2021-05-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag DYNAMIC_CONFIG_SERVER_PROVISIONING = defineFeatureFlag( "dynamic-config-server-provisioning", false, List.of("mpolden"), "2021-02-26", "2021-05-01", "Enable dynamic provisioning of config servers", "Takes effect immediately"); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "LATENCY", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_TASK_LIMIT = defineIntFlag( "feed-task-limit", 1000, List.of("geirst, baldersheim"), "2021-10-14", "2022-01-01", "The task limit used by the executors handling feed in proton", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_MASTER_TASK_LIMIT = defineIntFlag( "feed-master-task-limit", 0, List.of("geirst, baldersheim"), "2021-11-18", "2022-02-01", "The task limit used by the master thread in each document db in proton. Ignored when set to 0.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag SHARED_FIELD_WRITER_EXECUTOR = defineStringFlag( "shared-field-writer-executor", "NONE", List.of("geirst, baldersheim"), "2021-11-05", "2022-02-01", "Whether to use a shared field writer executor for the document database(s) in proton. " + "Valid values: NONE, INDEX, INDEX_AND_ATTRIBUTE, DOCUMENT_DB", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2022-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2022-01-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag( "hide-shared-routing-endpoint", false, List.of("tokle", "bjormel"), "2020-12-02", "2022-01-01", "Whether the controller should hide shared routing layer endpoint", "Takes effect immediately", APPLICATION_ID ); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DISK_BLOAT_FACTOR = defineDoubleFlag( "disk-bloat-factor", 0.2, List.of("baldersheim"), "2021-10-08", "2022-01-01", "Amount of bloat allowed before compacting file", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag DOCSTORE_COMPRESSION_LEVEL = defineIntFlag( "docstore-compression-level", 3, List.of("baldersheim"), "2021-10-08", "2022-01-01", "Default compression level used for document store", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag NUM_DEPLOY_HELPER_THREADS = defineIntFlag( "num-model-builder-threads", -1, List.of("balder"), "2021-09-09", "2022-01-01", "Number of threads used for speeding up building of models.", "Takes effect on first (re)start of config server"); public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag( "enable-feed-block-in-distributor", true, List.of("geirst"), "2021-01-27", "2022-01-31", "Enables blocking of feed in the distributor if resource usage is above limit on at least one content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2022-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2022-01-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-02-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag( "generate-non-mtls-endpoint", true, List.of("tokle"), "2021-02-18", "2022-02-01", "Whether to generate the non-mtls endpoint", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-02-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 128, List.of("balder", "vekterli"), "2021-06-06", "2022-01-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 1024, List.of("balder", "vekterli"), "2021-06-06", "2022-01-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag IGNORE_MERGE_QUEUE_LIMIT = defineFeatureFlag( "ignore-merge-queue-limit", false, List.of("vekterli", "geirst"), "2021-10-06", "2022-03-01", "Specifies if merges that are forwarded (chained) from another content node are always " + "allowed to be enqueued even if the queue is otherwise full.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag LARGE_RANK_EXPRESSION_LIMIT = defineIntFlag( "large-rank-expression-limit", 8192, List.of("baldersheim"), "2021-06-09", "2022-01-01", "Limit for size of rank expressions distributed by filedistribution", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-03-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_TENANT_IAM_ROLES = defineFeatureFlag( "separate-tenant-iam-roles", false, List.of("mortent"), "2021-08-12", "2022-01-01", "Create separate iam roles for tenant", "Takes effect on redeploy", TENANT_ID); public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag( "metricsproxy-num-threads", 2, List.of("balder"), "2021-09-01", "2022-01-01", "Number of threads for metrics proxy", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2021-12-31", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag ENABLE_ONPREM_TENANT_S3_ARCHIVE = defineFeatureFlag( "enable-onprem-tenant-s3-archive", false, List.of("bjorncs"), "2021-09-14", "2021-12-31", "Enable tenant S3 buckets in cd/main. Must be set on controller cluster only.", "Takes effect immediately", ZONE_ID, TENANT_ID ); public static final UnboundBooleanFlag DELETE_UNMAINTAINED_CERTIFICATES = defineFeatureFlag( "delete-unmaintained-certificates", false, List.of("andreer"), "2021-09-23", "2021-12-11", "Whether to delete certificates that are known by provider but not by controller", "Takes effect on next run of EndpointCertificateMaintainer" ); public static final UnboundBooleanFlag ENABLE_TENANT_DEVELOPER_ROLE = defineFeatureFlag( "enable-tenant-developer-role", false, List.of("bjorncs"), "2021-09-23", "2021-12-31", "Enable tenant developer Athenz role in cd/main. Must be set on controller cluster only.", "Takes effect immediately", TENANT_ID ); public static final UnboundBooleanFlag ENABLE_ROUTING_REUSE_PORT = defineFeatureFlag( "enable-routing-reuse-port", false, List.of("mortent"), "2021-09-29", "2021-12-31", "Enable reuse port in routing configuration", "Takes effect on container restart", HOSTNAME ); public static final UnboundBooleanFlag ENABLE_TENANT_OPERATOR_ROLE = defineFeatureFlag( "enable-tenant-operator-role", false, List.of("bjorncs"), "2021-09-29", "2021-12-31", "Enable tenant specific operator roles in public systems. For controllers only.", "Takes effect on subsequent maintainer invocation", TENANT_ID ); public static final UnboundIntFlag DISTRIBUTOR_MERGE_BUSY_WAIT = defineIntFlag( "distributor-merge-busy-wait", 10, List.of("geirst", "vekterli"), "2021-10-04", "2022-03-01", "Number of seconds that scheduling of new merge operations in the distributor should be inhibited " + "towards a content node that has indicated merge busy", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag DISTRIBUTOR_ENHANCED_MAINTENANCE_SCHEDULING = defineFeatureFlag( "distributor-enhanced-maintenance-scheduling", false, List.of("vekterli", "geirst"), "2021-10-14", "2022-01-31", "Enable enhanced maintenance operation scheduling semantics on the distributor", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ASYNC_APPLY_BUCKET_DIFF = defineFeatureFlag( "async-apply-bucket-diff", false, List.of("geirst", "vekterli"), "2021-10-22", "2022-01-31", "Whether portions of apply bucket diff handling will be performed asynchronously", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag( "unordered-merge-chaining", false, List.of("vekterli", "geirst"), "2021-11-15", "2022-03-01", "Enables the use of unordered merge chains for data merge operations", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag JDK_VERSION = defineStringFlag( "jdk-version", "11", List.of("hmusum"), "2021-10-25", "2022-03-01", "JDK version to use on host and inside containers. Note application-id dimension only applies for container, " + "while hostname and node type applies for host.", "Takes effect on restart for Docker container and on next host-admin tick for host", APPLICATION_ID, TENANT_ID, HOSTNAME, NODE_TYPE); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-01-31", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", false, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_LEGACY_LB_SERVICES = defineFeatureFlag( "use-legacy-lb-services", false, List.of("tokle"), "2021-11-22", "2021-12-31", "Whether to generate routing table based on legacy lb-services config", "Takes effect on container reboot", ZONE_ID, HOSTNAME); public static final UnboundBooleanFlag USE_V8_DOC_MANAGER_CFG = defineFeatureFlag( "use-v8-doc-manager-cfg", false, List.of("arnej", "baldersheim"), "2021-12-09", "2022-12-31", "Use new (preparing for Vespa 8) section in documentmanager.def", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package org.objectweb.proactive.core.util; import java.security.SecureRandom; /** * Provides an easy to get a random values for a SecureRandom PRNG * * A single PRNG is shared for the whole ProActive Runtime. * * @see SecureRandom */ public class ProActiveRandom { static private SecureRandom prng = new SecureRandom(); /** Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. */ synchronized static public boolean nextBoolean() { return prng.nextBoolean(); } /** Generates random bytes and places them into a user-supplied byte array. */ synchronized static public void nextBytes(byte[] bytes) { prng.nextBytes(bytes); } /** Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. */ synchronized static public double nextDouble() { return prng.nextDouble(); } /** Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence. */ synchronized static public float nextFloat() { return prng.nextFloat(); } /** Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.*/ synchronized static public int nextInt() { return prng.nextInt(); } /** Returns the next pseudorandom, uniformly distributed positive int value from this random number generator's sequence.*/ synchronized static public int nextPosInt() { return prng.nextInt(Integer.MAX_VALUE); } /** Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. */ synchronized static public int nextInt(int n) { return prng.nextInt(n); } /** Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. */ synchronized static public long nextLong() { return prng.nextLong(); } synchronized static public long nextPosLong() { long l = nextLong(); while (l <= 0) { l = nextLong(); } return l; } }
package client.controllers; import common.data.Budget; import common.data.Payment; import common.data.Settlement; import common.data.User; import client.BudgetExporter; import client.view.Alerts; import client.windows.AddParticipantsWindow; import client.windows.AddPaymentWindow; import client.windows.ParticipantDetailsWindow; import client.windows.SettleWindow; import client.windows.SettlementsHistoryWindow; import client.windows.UpdatePaymentWindow; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import java.math.BigDecimal; import java.net.URL; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; import java.util.stream.Collectors; public class BudgetController extends BasicController implements Initializable, SelfUpdating { @FXML private Label labelBudgetName, labelBudgetDescription; @FXML private Label labelSum, labelSumPerPerson; @FXML private Button buttonBudgetClose, buttonBudgetDelete, buttonBudgetExport; @FXML private Button buttonAddPayment, buttonAddParticipant, buttonSettle, buttonHistory; @FXML private TableView<Payment> tableUnsettledPayments; @FXML private TableColumn<Payment, String> columnUnsettledPayer, columnUnsettledDescription; @FXML private TableColumn<Payment, Integer> columnUnsettledAmount; @FXML private TableColumn<Payment, Boolean> columnConfirm; @FXML private TableView<User> tableParticipants; @FXML private TableColumn<User, String> columnUserName, columnUserMail; @FXML private TableColumn<User, BigDecimal> columnUserBalance; private final ObservableList<User> participantsList = FXCollections.observableArrayList(); private final ObservableList<Payment> unsettledPayments = FXCollections.observableArrayList(); private Budget budget; private double spentMoneySum = 0; public void setBudget(Budget budget) { this.budget = budget; labelBudgetName.setText(budget.getName()); labelBudgetDescription.setText(budget.getDescription()); if (!isCurrentUserBudgetOwner()) disableOnlyBudgetOwnerButtons(); } private void disableOnlyBudgetOwnerButtons() { buttonAddParticipant.setDisable(true); buttonSettle.setDisable(true); buttonBudgetDelete.setDisable(true); } @Override public void initialize(URL location, ResourceBundle resources) { initButtons(); initTables(); } private void initButtons() { buttonBudgetClose.setOnAction(event -> currentStage.close()); buttonBudgetExport.setOnAction(event -> exportBudget()); buttonBudgetDelete.setOnAction(event -> deleteBudget()); buttonAddParticipant.setOnAction(event -> displayAddParticipantsWindow()); buttonAddPayment.setOnAction(event -> displayAddPaymentWindow()); buttonSettle.setOnAction(event -> settlePayments()); buttonHistory.setOnAction(event -> displaySettlementsHistoryWindow()); } private void exportBudget() { try { List<Payment> settledPayments = dbHandler.getAllPayments(budget.getId(), true); List<Settlement> settlements = dbHandler.getAllSettlements(budget.getId()); BudgetExporter budgetExporter = new BudgetExporter(budget, participantsList, settledPayments, unsettledPayments, settlements, currentStage); budgetExporter.export(); } catch (RemoteException e) { e.printStackTrace(); Alerts.serverConnectionError(); } } private void deleteBudget() { Optional<ButtonType> result = Alerts.deleteBudgetConfirmation(); if (!result.isPresent() || result.get() != ButtonType.OK) return; try { dbHandler.deleteBudget(budget); currentStage.close(); } catch (RemoteException e) { e.printStackTrace(); Alerts.serverConnectionError(); } catch (Exception e) { e.printStackTrace(); // TODO budget couldn't be deleted } } private void displayAddParticipantsWindow() { AddParticipantsWindow addParticipantsWindow = new AddParticipantsWindow(this); addParticipantsWindow.initOwner(currentStage); addParticipantsWindow.setOnHidden(event -> fillTableUnsettledPayments()); addParticipantsWindow.show(); } private void displayAddPaymentWindow() { AddPaymentWindow addPaymentWindow = new AddPaymentWindow(budget, participantsList); addPaymentWindow.initOwner(currentStage); addPaymentWindow.setOnHidden(event -> fillTableUnsettledPayments()); addPaymentWindow.show(); } private void settlePayments() { try { if (unsettledPayments.size() > 0) displaySettleWindow(); else Alerts.noPaymentsToSettle(); } catch (Exception e) { e.printStackTrace(); // TODO display proper message } } private void displaySettleWindow() { SettleWindow settleWindow = new SettleWindow(this, budget, getPaymentsToSettle()); settleWindow.initOwner(currentStage); settleWindow.showAndWait(); } private List<Payment> getPaymentsToSettle() { return unsettledPayments.stream() .filter(Payment::isAccepted) .collect(Collectors.toList()); } private void displaySettlementsHistoryWindow() { SettlementsHistoryWindow historyWindow = new SettlementsHistoryWindow(budget); historyWindow.initOwner(currentStage); historyWindow.showAndWait(); } private void initTables() { initUnsettledPaymentsTable(); initParticipantsTable(); } private void initUnsettledPaymentsTable() { columnUnsettledPayer.setCellValueFactory(new PropertyValueFactory<>("payer")); columnUnsettledDescription.setCellValueFactory(new PropertyValueFactory<>("description")); columnUnsettledAmount.setCellValueFactory(new PropertyValueFactory<>("amount")); columnConfirm.setCellFactory(param -> new CheckBoxTableCell()); tableUnsettledPayments.setItems(unsettledPayments); tableUnsettledPayments.setRowFactory(param -> { TableRow<Payment> row = new TableRow<>(); row.setOnMouseClicked(mouseEvent -> handlePaymentRowClicked(row, mouseEvent)); return row; }); } private void handlePaymentRowClicked(TableRow<Payment> row, MouseEvent mouseEvent) { if (row.isEmpty() || mouseEvent.getClickCount() != 2) return; Payment payment = row.getItem(); if (isCurrentUserBudgetOwner() || isCurrentUserPaymentOwner(payment)) displayPaymentWindow(payment); // TODO else: you have no rights to edit this payment (special color or information) } private boolean isCurrentUserBudgetOwner() { return Objects.equals(currentUser, budget.getOwner()); } private boolean isCurrentUserPaymentOwner(Payment payment) { return payment.getUserId() == currentUser.getId(); } private void displayPaymentWindow(Payment payment) { UpdatePaymentWindow paymentWindow = new UpdatePaymentWindow(budget, payment, participantsList); paymentWindow.initOwner(currentStage); paymentWindow.setOnHidden(event -> fillTableUnsettledPayments()); paymentWindow.show(); } private void initParticipantsTable() { columnUserName.setCellValueFactory(new PropertyValueFactory<>("name")); columnUserMail.setCellValueFactory(new PropertyValueFactory<>("email")); columnUserBalance.setCellValueFactory(this::userBalanceCellFactory); tableParticipants.setItems(participantsList); tableParticipants.setRowFactory(param -> { TableRow<User> row = new TableRow<>(); row.setOnMouseClicked(mouseEvent -> handleParticipantCellClicked(row, mouseEvent)); return row; }); } private void handleParticipantCellClicked(TableRow<User> row, MouseEvent mouseEvent) { if (mouseEvent.getClickCount() == 2 && !row.isEmpty()) { final User participant = row.getItem(); boolean hasUnsettledPayments = unsettledPayments.stream() .anyMatch(payment -> payment.getUserId() == participant.getId()); displayParticipantDetailsWindow(participant, hasUnsettledPayments); } } private void displayParticipantDetailsWindow(User participant, boolean hasUnsettledPayments) { ParticipantDetailsWindow participantWindow = new ParticipantDetailsWindow(budget, participant, hasUnsettledPayments); participantWindow.initOwner(currentStage); participantWindow.setOnHidden(event -> { fillTableParticipants(); fillTableUnsettledPayments(); }); participantWindow.show(); } private ObservableValue<BigDecimal> userBalanceCellFactory(CellDataFeatures<User, BigDecimal> cell) { final User participant = cell.getValue(); final double balance = participant.getSpentMoney() - spentMoneySum / participantsList.size(); return new ReadOnlyObjectWrapper<>(new BigDecimal(balance).setScale(2, BigDecimal.ROUND_FLOOR)); } void addParticipants(List<User> users) { users.removeAll(participantsList); participantsList.addAll(users); try { List<User> usersSerializable = new ArrayList<>(users); dbHandler.addBudgetParticipants(budget.getId(), usersSerializable); } catch (RemoteException e) { e.printStackTrace(); Alerts.serverConnectionError(); } } public void update() { fillTableParticipants(); fillTableUnsettledPayments(); } private void fillTableUnsettledPayments() { fillTablePayments(unsettledPayments, false); updateSpentMoneySums(); } void fillTableParticipants() { participantsList.clear(); try { participantsList.addAll(dbHandler.getBudgetParticipants(budget.getId())); } catch (RemoteException e) { e.printStackTrace(); Alerts.serverConnectionError(); } } void fillTablePayments(ObservableList<Payment> payments, boolean settled) { payments.clear(); try { payments.addAll(dbHandler.getAllPayments(budget.getId(), settled)); } catch (RemoteException e) { e.printStackTrace(); Alerts.serverConnectionError(); } } private void updateSpentMoneySums() { spentMoneySum = 0; participantsList.forEach(p -> p.setSpentMoney(0)); for (Payment payment : unsettledPayments) { spentMoneySum += payment.getAmount(); Optional<User> userOptional = participantsList.stream() .filter(user -> user.getId() == payment.getUserId()) .findFirst(); if (userOptional.isPresent()) { User participant = userOptional.get(); participant.addSpentMoney(payment.getAmount()); } // TODO else: error - payment with owner not participating in budget } refreshBalanceCells(); labelSum.setText(String.format("Sum: %.2f$", spentMoneySum)); labelSumPerPerson.setText(String.format("Sum / Person: %.2f$", spentMoneySum / participantsList.size())); } private void refreshBalanceCells() { tableParticipants.getColumns().get(2).setVisible(false); tableParticipants.getColumns().get(2).setVisible(true); } @Override protected void clearErrorHighlights() { } public class CheckBoxTableCell extends TableCell<Payment, Boolean> { private final CheckBox checkBox = new CheckBox(); public CheckBoxTableCell() { setAlignment(Pos.CENTER); checkBox.setOnAction(event -> { Payment payment = (Payment) CheckBoxTableCell.this.getTableRow().getItem(); payment.setAccept(!payment.isAccepted()); }); } @Override public void updateItem(Boolean item, boolean empty) { super.updateItem(item, empty); if (!empty) { checkBox.setSelected(true); setGraphic(checkBox); checkBox.setDisable(!isCurrentUserBudgetOwner()); } else setGraphic(null); } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.flags.custom.PreprovisionCapacity; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundIntFlag DROP_CACHES = defineIntFlag("drop-caches", 3, "The int value to write into /proc/sys/vm/drop_caches for each tick. " + "1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.", "Takes effect on next tick.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag( "enable-crowdstrike", true, "Whether to enable CrowdStrike.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag( "enable-nessus", true, "Whether to enable Nessus.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag( "disabled-host-admin-tasks", List.of(), String.class, "List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped", "Takes effect on next host admin tick", HOSTNAME, NODE_TYPE); public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag( "docker-version", "1.13.1-91.git07f3374", "The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " + "2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " + "If docker-version is not of this format, it must be parseable by YumPackageName::fromString.", "Takes effect on next tick.", HOSTNAME); public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag( "thin-pool-gb", -1, "The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " + "If <0, the default is used (which may depend on the zone and node type).", "Takes effect immediately (but used only during provisioning).", NODE_TYPE); public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag( "container-cpu-cap", 0, "Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " + "to cap CPU at 200%, set this to 2, etc.", "Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart", HOSTNAME, APPLICATION_ID); public static final UnboundBooleanFlag INCLUDE_SIS_IN_TRUSTSTORE = defineFeatureFlag( "include-sis-in-truststore", false, "Whether to use the trust store backed by Athenz and (in public) Service Identity certificates in " + "host-admin and/or Docker containers", "Takes effect on restart of host-admin (for host-admin), and restart of Docker container.", // For host-admin, HOSTNAME and NODE_TYPE is available // For Docker containers, HOSTNAME and APPLICATION_ID is available // WARNING: Having different sets of dimensions is DISCOURAGED in general, but needed for here since // trust store for host-admin is determined before having access to application ID from node repo. HOSTNAME, NODE_TYPE, APPLICATION_ID); public static final UnboundStringFlag TLS_INSECURE_MIXED_MODE = defineStringFlag( "tls-insecure-mixed-mode", "tls_client_mixed_server", "TLS insecure mixed mode. Allowed values: ['plaintext_client_mixed_server', 'tls_client_mixed_server', 'tls_client_tls_server']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag( "tls-insecure-authorization-mode", "log_only", "TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag( "use-adaptive-dispatch", false, "Should adaptive dispatch be used over round robin", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_DYNAMIC_PROVISIONING = defineFeatureFlag( "enable-dynamic-provisioning", false, "Provision a new docker host when we otherwise can't allocate a docker node", "Takes effect on next deployment", APPLICATION_ID); public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag( "preprovision-capacity", List.of(), PreprovisionCapacity.class, "List of node resources and their count that should be present in zone to receive new deployments. When a " + "preprovisioned is taken, new will be provisioned within next iteration of maintainer.", "Takes effect on next iteration of HostProvisionMaintainer."); public static final UnboundBooleanFlag USE_ADVERTISED_RESOURCES = defineFeatureFlag( "use-advertised-resources", true, "When enabled, will use advertised host resources rather than actual host resources, ignore host resource " + "reservation, and fail with exception unless requested resource match advertised host resources exactly.", "Takes effect on next iteration of HostProvisionMaintainer.", APPLICATION_ID); public static final UnboundStringFlag CONFIGSERVER_RPC_AUTHORIZER = defineStringFlag( "configserver-rpc-authorizer", "enforce", "Configserver RPC authorizer. Allowed values: ['disable', 'log-only', 'enforce']", "Takes effect on restart of configserver"); public static final UnboundBooleanFlag PROVISION_APPLICATION_CERTIFICATE = defineFeatureFlag( "provision-application-certificate", false, "Provision certificate from CA and include reference in deployment", "Takes effect on deployment through controller", APPLICATION_ID); public static final UnboundBooleanFlag DIRECT_ROUTING_USE_HTTPS_4443 = defineFeatureFlag( "direct-routing-use-https-4443", false, "Decides whether NLB is pointed at container on port 4443 (https) or 4080 (http)", "Takes effect at redeployment", APPLICATION_ID ); public static final UnboundBooleanFlag MULTIPLE_GLOBAL_ENDPOINTS = defineFeatureFlag( "multiple-global-endpoints", false, "Allow applications to use new endpoints syntax in deployment.xml", "Takes effect on deployment through controller", APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, "Node resource memory in Gb for admin cluster nodes", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag( "host-hardening", false, "Whether to enable host hardening Linux baseline.", "Takes effect on next tick or on host-admin restart (may vary where used).", HOSTNAME); public static final UnboundStringFlag ZOOKEEPER_SERVER_MAJOR_MINOR_VERSION = defineStringFlag( "zookeeper-server-version", "3.4", "The version of ZooKeeper server to use (major.minor, not full version)", "Takes effect on restart of Docker container", HOSTNAME); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package ch.unizh.ini.jaer.projects.npp; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import org.tensorflow.DataType; import org.tensorflow.Graph; import org.tensorflow.Output; import org.tensorflow.SavedModelBundle; import org.tensorflow.Session; import org.tensorflow.Tensor; import org.tensorflow.types.UInt8; /** * From LabelImage example: static methods to execute TensorFlow stuff. * * @author Tobi */ public class TensorFlow { private static Logger log=Logger.getLogger("TensorFlow"); public static int maxIndex(float[] probabilities) { int best = 0; for (int i = 1; i < probabilities.length; ++i) { if (probabilities[i] > probabilities[best]) { best = i; } } return best; } public static Tensor<Float> constructAndExecuteGraphToNormalizeRGBImage(byte[] imageBytes, int W, int H, float mean, float scale) { try (Graph g = new Graph()) { GraphBuilder b = new GraphBuilder(g); // Some constants specific to the pre-trained model at: // - The model was trained with images scaled to 224x224 pixels. // - The colors, represented as R, G, B in 1-byte each were converted to // float using (value - Mean)/Scale. // final int H = 224; // final int W = 224; // final float mean = 117f; // final float scale = 1f; // Since the graph is being constructed once per execution here, we can use a constant for the // input image. If the graph were to be re-used for multiple input images, a placeholder would // have been more appropriate. final Output<String> input = b.constant("input", imageBytes); final Output<Float> output = b.div( b.sub( b.resizeBilinear( b.expandDims( b.cast(b.decodeJpeg(input, 3), Float.class), b.constant("make_batch", 0)), b.constant("size", new int[]{H, W})), b.constant("mean", mean)), b.constant("scale", scale)); try (Session s = new Session(g)) { return s.runner().fetch(output.op().name()).run().get(0).expect(Float.class); } } } private static Session session = null; public static float[] executeGraph(Graph graph, Tensor<Float> image, String inputLayerName, String outputLayerName) { // try (Graph g=graph) { try { if (session == null) { session = new Session(graph); } Tensor<Float> result = session.runner().feed(inputLayerName, image).fetch(outputLayerName).run().get(0).expect(Float.class); final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException( String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } catch (Exception e) { log.log(Level.SEVERE, "Exception running network: "+e.toString(), e.getCause()); if(session!=null){ session.close(); } return null; } } static float[] executeSession(SavedModelBundle savedModelBundle, Tensor<Float> image, String inputLayerName, String outputLayerName) { try (Session s = savedModelBundle.session(); Tensor<Float> result = s.runner().feed(inputLayerName, image).fetch(outputLayerName).run().get(0).expect(Float.class)) { final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException( String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } } static Tensor executeGraphAndReturnTensor(Graph graph, Tensor<Float> image, String inputLayerName, String outputLayerName) { try (Session s = new Session(graph); Tensor<Float> result = s.runner().feed(inputLayerName, image).fetch(outputLayerName).run().get(0).expect(Float.class)) { return result; } } //public static long heatMapPrev[][][] = new long[1][90][120]; static Tensor executeGraphAndReturnTensorWithBoolean(Graph graph, Tensor<Float> image, String inputLayerName, Tensor<Boolean> inputBool, String inputBoolName, String outputLayerName) { try (Session s = new Session(graph); Tensor<Float> result = s.runner().feed(inputLayerName, image).feed(inputBoolName, inputBool).fetch(outputLayerName).run().get(0).expect(Float.class)) { //result.copyTo(heatMap); return result; } } static void executeGraphAndReturnTensorWithBooleanArray(long[][][] array, Graph graph, Tensor<Float> image, String inputLayerName, Tensor<Boolean> inputBool, String inputBoolName, String outputLayerName) { try (Session s = new Session(graph); Tensor<Long> result = s.runner().feed(inputLayerName, image).feed(inputBoolName, inputBool).fetch(outputLayerName).run().get(0).expect(Long.class)) { //result.copyTo(heatMap); if (array != null) { result.copyTo(array); /* for (int i = 0; i < 90; i++) { for (int j = 0; j < 120; j++) { if (array[0][i][j] == 1) System.out.println(" Ball : " + Float.toString(array[0][i][j])); } } */ } } } // In the fullness of time, equivalents of the methods of this class should be auto-generated from // the OpDefs linked into libtensorflow_jni.so. That would match what is done in other languages // like Python, C++ and Go. // see public static class GraphBuilder { private Graph g; GraphBuilder(Graph g) { this.g = g; } Output<Float> div(Output<Float> x, Output<Float> y) { return binaryOp("Div", x, y); } <T> Output<T> sub(Output<T> x, Output<T> y) { return binaryOp("Sub", x, y); } <T> Output<Float> resizeBilinear(Output<T> images, Output<Integer> size) { return binaryOp3("ResizeBilinear", images, size); } <T> Output<T> expandDims(Output<T> input, Output<Integer> dim) { return binaryOp3("ExpandDims", input, dim); } <T> Output<T> concat(Output<T> x, Output<T> y) { return binaryOp("Concat", x, y); } <T, U> Output<U> cast(Output<T> value, Class<U> type) { DataType dtype = DataType.fromClass(type); return g.opBuilder("Cast", "Cast") .addInput(value) .setAttr("DstT", dtype) .build() .<U>output(0); } Output<UInt8> decodeJpeg(Output<String> contents, long channels) { return g.opBuilder("DecodeJpeg", "DecodeJpeg") .addInput(contents) .setAttr("channels", channels) .build() .<UInt8>output(0); } <T> Output<T> constant(String name, Object value, Class<T> type) { try (Tensor<T> t = Tensor.<T>create(value, type)) { return g.opBuilder("Const", name) .setAttr("dtype", DataType.fromClass(type)) .setAttr("value", t) .build() .<T>output(0); } } Output<String> constant(String name, byte[] value) { return this.constant(name, value, String.class); } Output<Integer> constant(String name, int value) { return this.constant(name, value, Integer.class); } Output<Integer> constant(String name, int[] value) { return this.constant(name, value, Integer.class); } Output<Float> constant(String name, float value) { return this.constant(name, value, Float.class); } private <T> Output<T> binaryOp(String type, Output<T> in1, Output<T> in2) { return g.opBuilder(type, type).addInput(in1).addInput(in2).build().<T>output(0); } private <T, U, V> Output<T> binaryOp3(String type, Output<U> in1, Output<V> in2) { return g.opBuilder(type, type).addInput(in1).addInput(in2).build().<T>output(0); } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.flags.custom.PreprovisionCapacity; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundIntFlag DROP_CACHES = defineIntFlag("drop-caches", 3, "The int value to write into /proc/sys/vm/drop_caches for each tick. " + "1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.", "Takes effect on next tick.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag( "enable-crowdstrike", true, "Whether to enable CrowdStrike.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag( "enable-nessus", true, "Whether to enable Nessus.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_FLEET_SSHD_CONFIG = defineFeatureFlag( "enable-fleet-sshd-config", true, "Whether fleet should manage the /etc/ssh/sshd_config file.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag FLEET_CANARY = defineFeatureFlag( "fleet-canary", false, "Whether the host is a fleet canary.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag SERVICE_MODEL_CACHE = defineFeatureFlag( "service-model-cache", true, "Whether the service model is cached.", "Takes effect on restart of config server.", HOSTNAME); public static final UnboundBooleanFlag CLEANUP_STATUS_SERVICE = defineFeatureFlag( "cleanup-status-service", false, "Whether to remove orphaned hosts and applications in the ZooKeeper status service.", "Takes effect on restart of config server.", HOSTNAME); public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag( "disabled-host-admin-tasks", List.of(), String.class, "List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped", "Takes effect on next host admin tick", HOSTNAME, NODE_TYPE); public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag( "docker-version", "1.13.1-102.git7f2769b", "The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " + "2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " + "If docker-version is not of this format, it must be parseable by YumPackageName::fromString.", "Takes effect on next tick.", HOSTNAME); public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag( "thin-pool-gb", -1, "The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " + "If <0, the default is used (which may depend on the zone and node type).", "Takes effect immediately (but used only during provisioning).", NODE_TYPE); public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag( "container-cpu-cap", 0, "Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " + "to cap CPU at 200%, set this to 2, etc.", "Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart", HOSTNAME, APPLICATION_ID); public static final UnboundBooleanFlag USE_BUCKET_SPACE_METRIC = defineFeatureFlag( "use-bucket-space-metric", true, "Whether to use vds.datastored.bucket_space.buckets_total (true) instead of " + "vds.datastored.alldisks.buckets (false, legacy).", "Takes effect on the next deployment of the application", APPLICATION_ID); public static final UnboundStringFlag TLS_INSECURE_MIXED_MODE = defineStringFlag( "tls-insecure-mixed-mode", "tls_client_mixed_server", "TLS insecure mixed mode. Allowed values: ['plaintext_client_mixed_server', 'tls_client_mixed_server', 'tls_client_tls_server']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag( "tls-insecure-authorization-mode", "log_only", "TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag( "use-adaptive-dispatch", false, "Should adaptive dispatch be used over round robin", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag( "reboot-interval-in-days", 30, "No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " + "scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).", "Takes effect on next run of NodeRebooter"); public static final UnboundBooleanFlag RETIRE_WITH_PERMANENTLY_DOWN = defineFeatureFlag( "retire-with-permanently-down", false, "If enabled, retirement will end with setting the host status to PERMANENTLY_DOWN, " + "instead of ALLOWED_TO_BE_DOWN (old behavior).", "Takes effect on the next run of RetiredExpirer.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_DYNAMIC_PROVISIONING = defineFeatureFlag( "enable-dynamic-provisioning", false, "Provision a new docker host when we otherwise can't allocate a docker node", "Takes effect on next deployment", APPLICATION_ID); public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag( "preprovision-capacity", List.of(), PreprovisionCapacity.class, "List of node resources and their count that should be present in zone to receive new deployments. When a " + "preprovisioned is taken, new will be provisioned within next iteration of maintainer.", "Takes effect on next iteration of HostProvisionMaintainer."); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, "Node resource memory in Gb for admin cluster nodes", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag( "host-hardening", false, "Whether to enable host hardening Linux baseline.", "Takes effect on next tick or on host-admin restart (may vary where used).", HOSTNAME); public static final UnboundBooleanFlag TCP_ABORT_ON_OVERFLOW = defineFeatureFlag( "tcp-abort-on-overflow", false, "Whether to set /proc/sys/net/ipv4/tcp_abort_on_overflow to 0 (false) or 1 (true)", "Takes effect on next host-admin tick.", HOSTNAME); public static final UnboundStringFlag ZOOKEEPER_SERVER_MAJOR_MINOR_VERSION = defineStringFlag( "zookeeper-server-version", "3.5", "The version of ZooKeeper server to use (major.minor, not full version)", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_QUORUM_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-quorum-communication", "OFF", "How to setup TLS for ZooKeeper quorum communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-client-server-communication", "OFF", "How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag( "use-tls-for-zookeeper-client", false, "Whether to use TLS for ZooKeeper clients", "Takes effect on restart of process", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag ENABLE_DISK_WRITE_TEST = defineFeatureFlag( "enable-disk-write-test", true, "Regularly issue a small write to disk and fail the host if it is not successful", "Takes effect on next node agent tick (but does not clear existing failure reports)", HOSTNAME); public static final UnboundBooleanFlag GENERATE_L4_ROUTING_CONFIG = defineFeatureFlag( "generate-l4-routing-config", false, "Whether routing nodes should generate L4 routing config", "Takes effect immediately", ZONE_ID, HOSTNAME); public static final UnboundBooleanFlag USE_REFRESHED_ENDPOINT_CERTIFICATE = defineFeatureFlag( "use-refreshed-endpoint-certificate", false, "Whether an application should start using a newer certificate/key pair if available", "Takes effect on the next deployment of the application", APPLICATION_ID); public static final UnboundBooleanFlag VALIDATE_ENDPOINT_CERTIFICATES = defineFeatureFlag( "validate-endpoint-certificates", false, "Whether endpoint certificates should be validated before use", "Takes effect on the next deployment of the application"); public static final UnboundStringFlag ENDPOINT_CERTIFICATE_BACKFILL = defineStringFlag( "endpoint-certificate-backfill", "disable", "Whether the endpoint certificate maintainer should backfill missing certificate data from cameo", "Takes effect on next scheduled run of maintainer - set to \"disable\", \"dryrun\" or \"enable\""); public static final UnboundBooleanFlag USE_NEW_ATHENZ_FILTER = defineFeatureFlag( "use-new-athenz-filter", false, "Use new Athenz filter that supports access-tokens", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundStringFlag DOCKER_IMAGE_REPO = defineStringFlag( "docker-image-repo", "", "Override default docker image repo. Docker image version will be Vespa version.", "Takes effect on next deployment from controller", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag DOCKER_IMAGE_OVERRIDE = defineStringFlag( "docker-image-override", "", "Override the Docker image to use for deployments. This must containing the image name only, without tag", "Takes effect on next host-admin tick", APPLICATION_ID); public static final UnboundBooleanFlag ENDPOINT_CERT_IN_SHARED_ROUTING = defineFeatureFlag( "endpoint-cert-in-shared-routing", false, "Whether to provision and use endpoint certs for apps in shared routing zones", "Takes effect on next deployment of the application", APPLICATION_ID); public static final UnboundBooleanFlag PHRASE_SEGMENTING = defineFeatureFlag( "phrase-segmenting", true, "Should 'implicit phrases' in queries we parsed to a phrase or and?", "Takes effect on redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag PROXY_PROTOCOL = defineStringFlag( "proxy-protocol", "https-only", "Enable proxy protocol support on application containers. Allowed values: ['https-only', 'https+proxy-protocol', 'proxy-protocol-only']", "Takes effect on internal redeploy", APPLICATION_ID); public static final UnboundBooleanFlag ALLOW_DIRECT_ROUTING = defineFeatureFlag( "publish-direct-routing-endpoint", false, "Whether an application should receive a directly routed endpoint in its endpoint list", "Takes effect immediately", APPLICATION_ID); public static final UnboundBooleanFlag DISABLE_ROUTING_GENERATOR = defineFeatureFlag( "disable-routing-generator", false, "Whether the controller should stop asking the routing layer for endpoints", "Takes effect immediately", APPLICATION_ID); public static final UnboundBooleanFlag DEDICATED_NODES_WHEN_UNSPECIFIED = defineFeatureFlag( "dedicated-nodes-when-unspecified", false, "Whether config-server should allocate dedicated container nodes when <nodes/> is not specified in services.xml", "Takes effect on redeploy", APPLICATION_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package org.mwc.debrief.core; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.dynamichelpers.IExtensionChangeHandler; import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.PreferenceManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveRegistry; import org.eclipse.ui.IStartup; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.internal.WorkbenchWindow; import org.eclipse.ui.part.WorkbenchPart; import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.ui.views.navigator.ResourceNavigator; import org.eclipse.ui.views.properties.PropertySheet; @SuppressWarnings("deprecation") public class Startup implements IStartup { private IPartListener partListener = new IPartListener() { @Override public void partOpened(IWorkbenchPart part) { if (part instanceof ContentOutline || part instanceof PropertySheet || part instanceof ResourceNavigator) { changeIcon(part); } } @Override public void partDeactivated(IWorkbenchPart part) { } @Override public void partClosed(IWorkbenchPart part) { } @Override public void partBroughtToTop(IWorkbenchPart part) { } @Override public void partActivated(IWorkbenchPart part) { } }; private static Image outlineImage, propertiesImage, navigatorImage; @Override public void earlyStartup() { removePerspective(); removePreferencePages(); updateMenuIcons(); new ResetPerspective().resetPerspective(); ; if (DebriefPlugin.getDefault().getCreateProject()) { new CreateDebriefProject().createStartProject(); } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage(); page.addPartListener(partListener); IViewPart view = page.findView(IPageLayout.ID_OUTLINE); if (view instanceof ContentOutline) { changeIcon(view); } view = page.findView(IPageLayout.ID_PROP_SHEET); if (view instanceof PropertySheet) { changeIcon(view); } view = page.findView(IPageLayout.ID_RES_NAV); if (view instanceof ResourceNavigator) { changeIcon(view); } } }); } private void updateMenuIcons() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ActionAccessSupport accessSupport = new ActionAccessSupport(); IAction redo = accessSupport.getAction("redo"); if (redo != null) { redo.setImageDescriptor(DebriefPlugin .getImageDescriptor("icons/16/redo.png")); } IAction undo = accessSupport.getAction("undo"); if (undo != null) { undo.setImageDescriptor(DebriefPlugin .getImageDescriptor("icons/16/undo.png")); } } }); } protected void changeIcon(IWorkbenchPart part) { try { Class<?> clazz = WorkbenchPart.class; Method method = clazz.getDeclaredMethod("setTitleImage", new Class[] {Image.class}); method.setAccessible(true); Image image = null; if (part instanceof ContentOutline) { if (outlineImage == null) { ImageDescriptor descriptor = DebriefPlugin.getImageDescriptor("icons/16/outline.png"); outlineImage = JFaceResources.getResources().createImageWithDefault(descriptor); } image = outlineImage; } if (part instanceof PropertySheet) { if (propertiesImage == null) { ImageDescriptor descriptor = DebriefPlugin.getImageDescriptor("icons/16/properties.png"); propertiesImage = JFaceResources.getResources().createImageWithDefault(descriptor); } image = propertiesImage; } if (part instanceof ResourceNavigator) { if (navigatorImage == null) { ImageDescriptor descriptor = DebriefPlugin.getImageDescriptor("icons/16/navigator.png"); navigatorImage = JFaceResources.getResources().createImageWithDefault(descriptor); } image = navigatorImage; } if (image != null) { method.invoke(part, new Object[] {image}); } } catch (Exception e) { IStatus status = new Status(IStatus.INFO, DebriefPlugin.PLUGIN_NAME, "Can't change the icon of the Outline view", e); DebriefPlugin.getDefault().getLog().log(status); } } private void removePreferencePages() { PreferenceManager preferenceManager = PlatformUI.getWorkbench().getPreferenceManager(); if (preferenceManager == null) { return; } preferenceManager.remove("org.eclipse.debug.ui.DebugPreferencePage"); preferenceManager.remove("org.eclipse.debug.ui.LaunchingPreferencePage"); preferenceManager .remove("org.eclipse.debug.ui.ViewManagementPreferencePage"); preferenceManager.remove("org.eclipse.debug.ui.ConsolePreferencePage"); preferenceManager .remove("org.eclipse.debug.ui.StringVariablePreferencePage"); preferenceManager.remove("org.eclipse.debug.ui.PerspectivePreferencePage"); preferenceManager.remove("org.eclipse.debug.ui.LaunchConfigurations"); preferenceManager .remove("org.eclipse.debug.ui.LaunchDelegatesPreferencePage"); preferenceManager.remove("org.eclipse.team.ui.TeamPreferences"); preferenceManager .remove("org.eclipse.wst.xml.ui.propertyPage.project.validation"); } private void removePerspective() { IPerspectiveRegistry registry = PlatformUI.getWorkbench().getPerspectiveRegistry(); if (registry == null) { return; } List<IPerspectiveDescriptor> descriptors = new ArrayList<IPerspectiveDescriptor>(); addDescriptor(registry, descriptors, "org.eclipse.debug.ui.DebugPerspective"); addDescriptor(registry, descriptors, "org.eclipse.team.ui.TeamSynchronizingPerspective"); // FIXME this method doesn't work on Eclipse E4 (Juno/Kepler) if (registry instanceof IExtensionChangeHandler && !descriptors.isEmpty()) { IExtensionChangeHandler handler = (IExtensionChangeHandler) registry; handler.removeExtension(null, descriptors.toArray()); } } private void addDescriptor(IPerspectiveRegistry registry, List<IPerspectiveDescriptor> descriptors, String id) { IPerspectiveDescriptor perspectiveDescriptor = registry.findPerspectiveWithId(id); if (perspectiveDescriptor != null) { descriptors.add(perspectiveDescriptor); } } private static class ActionAccessSupport { Method actionAccess; ActionBarAdvisor actionBarAdvisor = null; public ActionAccessSupport() { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); Class<?> clazz = WorkbenchWindow.class; Method method; try { method = clazz.getDeclaredMethod("getActionBarAdvisor", new Class[] {}); method.setAccessible(true); actionBarAdvisor = (ActionBarAdvisor) method.invoke(activeWorkbenchWindow); assert actionBarAdvisor != null : "API CHANGE!"; actionAccess = ActionBarAdvisor.class.getDeclaredMethod("getAction", new Class[] {String.class}); actionAccess.setAccessible(true); assert actionAccess != null : "API CHANGE!"; } catch (Exception e) { e.printStackTrace(); } } IAction getAction(String id) { try { return (IAction) actionAccess.invoke(actionBarAdvisor, id); } catch (Exception e) { e.printStackTrace(); } return null; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import java.util.function.Predicate; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundBooleanFlag MAIN_CHAIN_GRAPH = defineFeatureFlag( "main-chain-graph", true, List.of("hakonhall"), "2022-07-06", "2022-10-05", "Whether to run all tasks in the main task chain up to the one failing to converge (false), or " + "run all tasks in the main task chain whose dependencies have converged (true). And when suspending, " + "whether to run the tasks in sequence (false) or in reverse sequence (true).", "On first tick of the main chain after (re)start of host admin.", ZONE_ID, NODE_TYPE, HOSTNAME); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag QUERY_DISPATCH_POLICY = defineStringFlag( "query-dispatch-policy", "adaptive", List.of("baldersheim"), "2022-08-20", "2023-01-01", "Select query dispatch policy, valid values are adaptive, round-robin, best-of-random-2," + " latency-amortized-over-requests, latency-amortized-over-time", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag PHRASE_OPTIMIZATION = defineStringFlag( "phrase-optimization", "split", List.of("baldersheim"), "2022-08-28", "2023-01-01", "Select phase optimization, valid values are 'split', 'off'.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag( "keep-storage-node-up", true, List.of("hakonhall"), "2022-07-07", "2022-09-07", "Whether to leave the storage node (with wanted state) UP while the node is permanently down.", "Takes effect immediately for nodes transitioning to permanently down.", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", true, List.of("vekterli"), "2020-12-02", "2022-10-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2023-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag( "feed-niceness", 0.0, List.of("baldersheim"), "2022-06-24", "2023-01-01", "How nice feeding shall be", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag MBUS_DISPATCH_ON_ENCODE = defineFeatureFlag( "mbus-dispatch-on-encode", true, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Should we use mbus threadpool on encode", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag MBUS_DISPATCH_ON_DECODE = defineFeatureFlag( "mbus-dispatch-on-decode", true, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Should we use mbus threadpool on decode", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag( "mbus-java-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag( "mbus-cpp-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag( "rpc-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-java-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-cpp-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag( "rpc-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_THREADS = defineIntFlag( "mbus-num-threads", 4, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus threadpool", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag( "mbus-num-network-threads", 1, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus network", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag( "shared-string-repo-no-reclaim", false, List.of("baldersheim"), "2022-06-14", "2023-01-01", "Controls whether we do track usage and reclaim unused enum values in shared string repo", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2023-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag( "load-code-as-hugepages", false, List.of("baldersheim"), "2022-05-13", "2023-01-01", "Will try to map the code segment with huge (2M) pages", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2023-05-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-11-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-10-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 16, List.of("balder", "vekterli"), "2021-06-06", "2022-10-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 100, List.of("balder", "vekterli"), "2021-06-06", "2022-10-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-09-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag( "metricsproxy-num-threads", 2, List.of("balder"), "2021-09-01", "2023-01-01", "Number of threads for metrics proxy", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag AVAILABLE_PROCESSORS = defineIntFlag( "available-processors", 2, List.of("balder"), "2022-01-18", "2023-01-01", "Number of processors the jvm sees in non-application clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2022-10-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag( "unordered-merge-chaining", true, List.of("vekterli", "geirst"), "2021-11-15", "2022-09-01", "Enables the use of unordered merge chains for data merge operations", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-12-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", true, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_SERVER_OCSP_STAPLING = defineFeatureFlag( "enable-server-ocsp-stapling", false, List.of("bjorncs"), "2021-12-17", "2022-09-01", "Enable server OCSP stapling for jdisc containers", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_DATA_HIGHWAY_IN_AWS = defineFeatureFlag( "enable-data-highway-in-aws", false, List.of("hmusum"), "2022-01-06", "2022-10-01", "Enable Data Highway in AWS", "Takes effect on restart of Docker container", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag MERGE_THROTTLING_POLICY = defineStringFlag( "merge-throttling-policy", "STATIC", List.of("vekterli"), "2022-01-25", "2022-10-01", "Sets the policy used for merge throttling on the content nodes. " + "Valid values: STATIC, DYNAMIC", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_DECREMENT_FACTOR = defineDoubleFlag( "persistence-throttling-ws-decrement-factor", 1.2, List.of("vekterli"), "2022-01-27", "2022-10-01", "Sets the dynamic throttle policy window size decrement factor for persistence " + "async throttling. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_BACKOFF = defineDoubleFlag( "persistence-throttling-ws-backoff", 0.95, List.of("vekterli"), "2022-01-27", "2022-10-01", "Sets the dynamic throttle policy window size backoff for persistence " + "async throttling. Only applies if DYNAMIC policy is used. Valid range [0, 1]", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag PERSISTENCE_THROTTLING_WINDOW_SIZE = defineIntFlag( "persistence-throttling-window-size", -1, List.of("vekterli"), "2022-02-23", "2022-09-01", "If greater than zero, sets both min and max window size to the given number, effectively " + "turning dynamic throttling into a static throttling policy. " + "Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_RESIZE_RATE = defineDoubleFlag( "persistence-throttling-ws-resize-rate", 3.0, List.of("vekterli"), "2022-02-23", "2022-09-01", "Sets the dynamic throttle policy resize rate. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag PERSISTENCE_THROTTLING_OF_MERGE_FEED_OPS = defineFeatureFlag( "persistence-throttling-of-merge-feed-ops", true, List.of("vekterli"), "2022-02-24", "2022-09-01", "If true, each put/remove contained within a merge is individually throttled as if it " + "were a put/remove from a client. If false, merges are throttled at a persistence thread " + "level, i.e. per ApplyBucketDiff message, regardless of how many document operations " + "are contained within. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", false, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", true, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_BIT_VECTORS = defineFeatureFlag( "enable-bit-vectors", false, List.of("baldersheim"), "2022-05-03", "2022-12-31", "Enables bit vector by default for fast-search attributes", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag APPLICATION_FILES_WITH_UNKNOWN_EXTENSION = defineStringFlag( "fail-deployment-for-files-with-unknown-extension", "FAIL", List.of("hmusum"), "2022-04-27", "2022-10-01", "Whether to log or fail for deployments when app has a file with unknown extension (valid values: LOG, FAIL)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag( "dispatch-notifications", false, List.of("enygaard"), "2022-05-02", "2022-09-30", "Whether we should send notification for a given tenant", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag( "enable-proxy-protocol-mixed-mode", true, List.of("tokle"), "2022-05-09", "2022-11-01", "Enable or disable proxy protocol mixed mode", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag( "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class, List.of("hmusum"), "2022-07-05", "2022-10-01", "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag( "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class, List.of("hmusum"), "2022-07-05", "2022-10-01", "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag( "use-yumproxy-v2", false, List.of("tokle"), "2022-05-05", "2022-11-01", "Use yumproxy-v2", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag( "log-file-compression-algorithm", "", List.of("arnej"), "2022-06-14", "2024-12-31", "Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd", "Takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag( "separate-metric-check-config", false, List.of("olaa"), "2022-07-04", "2022-11-01", "Determines whether one metrics config check should be written per Vespa node", "Takes effect on next tick", HOSTNAME); public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag( "tls-capabilities-enforcement-mode", "disable", List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01", "Configure Vespa TLS capability enforcement mode", "Takes effect on restart of Docker container", APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION ); public static final UnboundBooleanFlag CLEANUP_TENANT_ROLES = defineFeatureFlag( "cleanup-tenant-roles", false, List.of("olaa"), "2022-08-10", "2022-10-01", "Determines whether old tenant roles should be deleted", "Takes effect next maintenance run" ); public static final UnboundBooleanFlag USE_TWO_PHASE_DOCUMENT_GC = defineFeatureFlag( "use-two-phase-document-gc", false, List.of("vekterli"), "2022-08-24", "2022-11-01", "Use two-phase document GC in content clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return defineStringFlag(flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, value -> true, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, Predicate<String> validator, FetchVector.Dimension... dimensions) { return define((i, d, v) -> new UnboundStringFlag(i, d, v, validator), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultValue, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package org.intermine.web; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Map; /** * A template query, which consists of a PathQuery, description, category, * short name. * * @author Mark Woodbridge * @author Thomas Riley */ public class TemplateQuery { /** Template query name. */ protected String name; /** Template query description. */ protected String description; /** Template query category. */ protected String category; /** Entire query */ protected PathQuery query; /** Nodes with templated constraints */ protected List nodes = new ArrayList(); /** Map from node to editable constraint list */ protected Map constraints = new HashMap(); /** * Construct a new instance of TemplateQuery. * * @param name the name of the template * @param category name of category that this query falls under * @param description the template description * @param query the query itself */ public TemplateQuery(String name, String description, String category, PathQuery query) { this.description = description; this.query = query; this.category = category; this.name = name; // Find the editable constraints in the query. Iterator iter = query.getNodes().entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); PathNode node = (PathNode) entry.getValue(); Iterator citer = node.getConstraints().iterator(); while (citer.hasNext()) { Constraint c = (Constraint) citer.next(); if (c.isEditable()) { List ecs = (List) constraints.get(node); if (ecs == null) { ecs = new ArrayList(); nodes.add(node); constraints.put(node, ecs); } ecs.add(c); } } } } /** * For a PathNode with editable constraints, get all the editable * constraints as a List. * * @param node a PathNode with editable constraints * @return List of Constraints for Node */ public List getConstraints(PathNode node) { return (List) constraints.get(node); } /** * Get the tempalte description. * @return the description */ public String getDescription() { return description; } /** * Get the query (eg. select c from Company as c where c.name = 'CompanyA') * @return the query */ public PathQuery getQuery() { return query; } /** * Get the nodes from the description, in order (eg. {Company.name}) * @return the nodes */ public List getNodes() { return nodes; } /** * Get the query short name. * @return the query identifier string */ public String getName() { return name; } /** * Get the category that this template belongs to. * @return category for template */ public String getCategory() { return category; } }
package org.spoofax.jsglr; import java.io.IOException; import java.util.ArrayList; public class ParserHistory { private final static int MAX_SIZE_NEW_LINE_POINTS = 150; private final static int MIN_SIZE_NEW_LINE_POINTS = 50; private IndentationHandler indentHandler; private ArrayList<IndentInfo> newLinePoints; public char[] recoverTokenStream; private int recoverTokenCount; private int tokenIndex; public int getTokenIndex() { return tokenIndex; } public int getIndexLastToken() { return recoverTokenCount-1; } public void setTokenIndex(int tokenIndex) { this.tokenIndex = tokenIndex; } public ParserHistory(){ newLinePoints=new ArrayList<IndentInfo>(); reset(); } private void reset(){ newLinePoints.clear(); recoverTokenStream = new char[5000]; recoverTokenCount = 0; tokenIndex=0; indentHandler = new IndentationHandler(); } /* * Set current token of parser based on recover tokens or read from new tokens */ public void readRecoverToken(SGLR myParser) throws IOException{ if (hasFinishedRecoverTokens()) { if(myParser.currentToken!=SGLR.EOF){ if(getIndexLastToken()>0 && recoverTokenStream[getIndexLastToken()]!=SGLR.EOF){ myParser.readNextToken(); indentHandler.updateIndentation(myParser.currentToken); keepToken((char)myParser.currentToken); if(indentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, true); } } } myParser.currentToken = recoverTokenStream[tokenIndex]; tokenIndex++; } public boolean hasFinishedRecoverTokens() { return tokenIndex >= recoverTokenCount; } public int getTokensSeenStartLine(int tokPosition){ int tokIndexLine=tokPosition; while (recoverTokenStream[tokIndexLine] != '\n' && tokIndexLine>0) { tokIndexLine-=1; } return tokIndexLine; } public void keepTokenAndState(SGLR myParser) { indentHandler.updateIndentation(myParser.currentToken); keepToken((char)myParser.currentToken); tokenIndex++; if(indentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, false); } public void keepInitialState(SGLR myParser) { IndentInfo newLinePoint= new IndentInfo(0, 0, 0); newLinePoint.fillStackNodes(myParser.activeStacks); newLinePoints.add(newLinePoint); } private void keepToken(char currentToken) { if(getIndexLastToken()>0 && recoverTokenStream[getIndexLastToken()]==SGLR.EOF) return; recoverTokenStream[recoverTokenCount++] = currentToken; if (recoverTokenCount == recoverTokenStream.length) { char[] copy = recoverTokenStream; recoverTokenStream = new char[recoverTokenStream.length * 2]; System.arraycopy(copy, 0, recoverTokenStream, 0, copy.length); } } private void keepNewLinePoint(SGLR myParser, boolean inRecoverMode) { int indent = indentHandler.getIndentValue(); IndentInfo newLinePoint= new IndentInfo(myParser.lineNumber, myParser.tokensSeen-1, indent); newLinePoints.add(newLinePoint); if(!inRecoverMode){ newLinePoint.fillStackNodes(myParser.activeStacks); if(newLinePoints.size()> MAX_SIZE_NEW_LINE_POINTS) removeOldPoints(); } } private void removeOldPoints() { int firstPointIndex = nrOfLines()-MIN_SIZE_NEW_LINE_POINTS; ArrayList<IndentInfo> shrinkedList = new ArrayList<IndentInfo>(); shrinkedList.ensureCapacity(newLinePoints.size()); shrinkedList.addAll(newLinePoints.subList(firstPointIndex, newLinePoints.size()-1)); newLinePoints = shrinkedList; } public String getFragment(int startTok, int endTok) { String fragment=""; for (int i = startTok; i <= endTok; i++) { if(i >= recoverTokenCount) break; fragment+= recoverTokenStream[i]; } return fragment; } public String getFragment(StructureSkipSuggestion skip) { String fragment=""; for (int i = skip.getStartSkip().getTokensSeen(); i <= skip.getEndSkip().getTokensSeen()-1; i++) { if(i >= recoverTokenCount) break; fragment+= recoverTokenStream[i]; } String correctedFragment=fragment.substring(skip.getAdditionalTokens().length); return correctedFragment; } public String readLine(int StartTok) { String fragment=""; int pos=StartTok; char currentTok=' '; while(currentTok!='\n' && currentTok!=SGLR.EOF && pos<recoverTokenCount) { currentTok=recoverTokenStream[pos]; fragment+= currentTok; pos++; } return fragment; } private int nrOfLines(){ return newLinePoints.size(); } public IndentInfo getLine(int index){ if(index < 0 || index > getIndexLastLine()) return null; return newLinePoints.get(index); } public IndentInfo getLastLine(){ return newLinePoints.get(newLinePoints.size()-1); } public int getIndexLastLine(){ return newLinePoints.size()-1; } public ArrayList<IndentInfo> getLinesFromTo(int startIndex, int endLocation) { int indexLine = startIndex; ArrayList<IndentInfo> result=new ArrayList<IndentInfo>(); IndentInfo firstLine = newLinePoints.get(indexLine); while(indexLine < newLinePoints.size()){ firstLine = newLinePoints.get(indexLine); if(firstLine.getTokensSeen() < endLocation){ result.add(firstLine); indexLine++; } else{ indexLine=newLinePoints.size(); } } return result; } }
package org.intermine.web; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.LinkedHashMap; import org.intermine.metadata.Model; import org.intermine.objectstore.query.ResultsInfo; import org.intermine.objectstore.query.BagConstraint; import org.intermine.util.CollectionUtil; /** * Class to represent a path-based query * @author Mark Woodbridge */ public class PathQuery { protected Model model; protected LinkedHashMap nodes = new LinkedHashMap(); protected List view = new ArrayList(); protected ResultsInfo info; protected ArrayList problems = new ArrayList(); /** * Constructor * @param model the Model on which to base this query */ public PathQuery(Model model) { this.model = model; } /** * Gets the value of model * @return the value of model */ public Model getModel() { return model; } /** * Gets the value of nodes * @return the value of nodes */ public Map getNodes() { return nodes; } /** * Sets the value of view * @param view the value of view */ public void setView(List view) { this.view = view; for (Iterator iter = view.iterator(); iter.hasNext(); ) { try { MainHelper.getTypeForPath((String) iter.next(), this); } catch (Exception err) { problems.add(err); } } } /** * Gets the value of view * @return the value of view */ public List getView() { return view; } /** * Get info regarding this query * @return the info */ public ResultsInfo getInfo() { return info; } /** * Set info about this query * @param info the info */ public void setInfo(ResultsInfo info) { this.info = info; } /** * Provide a list of the names of bags mentioned in the query * @return the list of bag names */ public List getBagNames() { List bagNames = new ArrayList(); for (Iterator i = nodes.values().iterator(); i.hasNext();) { PathNode node = (PathNode) i.next(); for (Iterator j = node.getConstraints().iterator(); j.hasNext();) { Constraint c = (Constraint) j.next(); if (BagConstraint.VALID_OPS.contains(c.getOp())) { bagNames.add(c.getValue()); } } } return bagNames; } /** * Add a node to the query using a path, adding parent nodes if necessary * @param path the path for the new Node * @return the PathNode that was added to the nodes Map */ public PathNode addNode(String path) { PathNode node; // the new node will be inserted after this one or at the end if null String previousNodePath = null; if (path.indexOf(".") == -1) { node = new PathNode(path); // Check whether starting point exists try { MainHelper.getQualifiedTypeName(path, model); } catch (ClassNotFoundException err) { problems.add(err); } } else { String prefix = path.substring(0, path.lastIndexOf(".")); if (nodes.containsKey(prefix)) { Iterator pathsIter = nodes.keySet().iterator(); while (pathsIter.hasNext()) { String pathFromMap = (String) pathsIter.next(); if (pathFromMap.startsWith(prefix)) { previousNodePath = pathFromMap; } } PathNode parent = (PathNode) nodes.get(prefix); String fieldName = path.substring(path.lastIndexOf(".") + 1); node = new PathNode(parent, fieldName); try { node.setModel(model); } catch (Exception err) { problems.add(err); } } else { addNode(prefix); return addNode(path); } } nodes = CollectionUtil.linkedHashMapAdd(nodes, previousNodePath, path, node); return node; } /** * Get the exceptions generated while deserialising this path query query. * @return exceptions relating to this path query */ public Exception[] getProblems() { return (Exception[]) problems.toArray(new Exception[0]); } /** * Find out whether the path query is valid against the current model. * @return true if query is valid, false if not */ public boolean isValid() { return (problems.size() == 0); } /** * Clone this PathQuery * @return a PathQuery */ public Object clone() { PathQuery query = new PathQuery(model); for (Iterator i = nodes.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); query.getNodes().put(entry.getKey(), clone(query, (PathNode) entry.getValue())); } query.getView().addAll(view); return query; } /** * Clone a PathNode * @param query PathQuery containing cloned PathNode * @param node a PathNode * @return a copy of the PathNode */ protected PathNode clone(PathQuery query, PathNode node) { PathNode newNode; PathNode parent = (PathNode) nodes.get(node.getPrefix()); if (parent == null) { newNode = new PathNode(node.getType()); } else { newNode = new PathNode(parent, node.getFieldName()); try { newNode.setModel(model); } catch (IllegalArgumentException err) { query.problems.add(err); } newNode.setType(node.getType()); } for (Iterator i = node.getConstraints().iterator(); i.hasNext();) { Constraint constraint = (Constraint) i.next(); newNode.getConstraints().add(new Constraint(constraint.getOp(), constraint.getValue())); } return newNode; } /** * @see Object#equals */ public boolean equals(Object o) { return (o instanceof PathQuery) && model.equals(((PathQuery) o).model) && nodes.equals(((PathQuery) o).nodes) && view.equals(((PathQuery) o).view); } /** * @see Object#hashCode */ public int hashCode() { return 2 * model.hashCode() + 3 * nodes.hashCode() + 5 * view.hashCode(); } /** * @see Object#toString */ public String toString() { return "{PathQuery: " + model + ", " + nodes + ", " + view + "}"; } }
// OMETiffReader.java package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.IFormatReader; import loci.formats.MetadataTools; import loci.formats.meta.IMetadata; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffParser; public class OMETiffReader extends FormatReader { // -- Fields -- /** Mapping from series and plane numbers to files and IFD entries. */ protected OMETiffPlane[][] info; // dimensioned [numSeries][numPlanes] /** List of used files. */ protected String[] used; private int lastPlane; private boolean hasSPW; // -- Constructor -- /** Constructs a new OME-TIFF reader. */ public OMETiffReader() { super("OME-TIFF", new String[] {"ome.tif", "ome.tiff"}); suffixNecessary = false; suffixSufficient = false; domains = FormatTools.ALL_DOMAINS; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFDList ifds = tp.getIFDs(); ras.close(); String xml = ifds.get(0).getComment(); IMetadata meta = MetadataTools.createOMEXMLMetadata(xml); if (meta == null) { throw new FormatException("ome-xml.jar is required to read OME-TIFF " + "files. Please download it from " + "http://loci.wisc.edu/ome/formats-library.html"); } if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } int nImages = 0; for (int i=0; i<meta.getImageCount(); i++) { int nChannels = meta.getLogicalChannelCount(i); if (nChannels == 0) nChannels = 1; for (int p=0; p<meta.getPixelsCount(i); p++) { int z = meta.getPixelsSizeZ(i, p).intValue(); int t = meta.getPixelsSizeT(i, p).intValue(); nImages += z * t * nChannels; } } return nImages <= ifds.size(); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); boolean validHeader = tp.isValidHeader(); if (!validHeader) return false; // look for OME-XML in first IFD's comment IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; String comment = ifd.getComment(); if (comment == null) return false; return comment.trim().endsWith("</OME>"); } /* @see loci.formats.IFormatReader#getDomains() */ public String[] getDomains() { FormatTools.assertId(currentId, true, 1); return hasSPW ? new String[] {FormatTools.HCS_DOMAIN} : FormatTools.NON_HCS_DOMAINS; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { if (info[series][lastPlane] == null || info[series][lastPlane].reader == null || info[series][lastPlane].id == null) { return null; } info[series][lastPlane].reader.setId(info[series][lastPlane].id); return info[series][lastPlane].reader.get8BitLookupTable(); } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { if (info[series][lastPlane] == null || info[series][lastPlane].reader == null || info[series][lastPlane].id == null) { return null; } info[series][lastPlane].reader.setId(info[series][lastPlane].id); return info[series][lastPlane].reader.get16BitLookupTable(); } /* * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); lastPlane = no; int i = info[series][no].ifd; MinimalTiffReader r = (MinimalTiffReader) info[series][no].reader; if (r.getCurrentFile() == null) { r.setId(info[series][no].id); } IFD ifd = r.getIFDs().get(i); RandomAccessInputStream s = new RandomAccessInputStream(info[series][no].id); TiffParser p = new TiffParser(s); p.getSamples(ifd, buf, x, y, w, h); s.close(); return buf; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); return noPixels ? null : used; } /* @see loci.formats.IFormatReader#fileGroupOption() */ public int fileGroupOption(String id) { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { info = null; used = null; lastPlane = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { debug("OMETiffReader.initFile(" + id + ")"); // normalize file name super.initFile(normalizeFilename(null, id)); id = currentId; String dir = new File(id).getParent(); // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFD firstIFD = tp.getFirstIFD(); ras.close(); String xml = firstIFD.getComment(); IMetadata meta = MetadataTools.createOMEXMLMetadata(xml); hasSPW = meta.getPlateCount() > 0; Hashtable originalMetadata = MetadataTools.getOriginalMetadata(meta); if (originalMetadata != null) metadata = originalMetadata; debug(xml, 3); if (meta == null) { throw new FormatException("ome-xml.jar is required to read OME-TIFF " + "files. Please download it from " + "http://loci.wisc.edu/ome/formats-library.html"); } if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } String currentUUID = meta.getUUID(); MetadataTools.convertMetadata(meta, metadataStore); // determine series count from Image and Pixels elements int seriesCount = 0; int imageCount = meta.getImageCount(); for (int i=0; i<imageCount; i++) seriesCount += meta.getPixelsCount(i); core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = new CoreMetadata(); } info = new OMETiffPlane[seriesCount][]; // compile list of file/UUID mappings Hashtable<String, String> files = new Hashtable<String, String>(); boolean needSearch = false; for (int i=0; i<imageCount; i++) { int pixelsCount = meta.getPixelsCount(i); for (int p=0; p<pixelsCount; p++) { int tiffDataCount = meta.getTiffDataCount(i, p); for (int td=0; td<tiffDataCount; td++) { String uuid = meta.getTiffDataUUID(i, p, td); String filename = null; if (uuid == null) { // no UUID means that TiffData element refers to this file uuid = ""; filename = id; } else { filename = meta.getTiffDataFileName(i, p, td); if (!new Location(dir, filename).exists()) filename = null; if (filename == null) { if (uuid.equals(currentUUID)) { // UUID references this file filename = id; } else { // will need to search for this UUID filename = ""; needSearch = true; } } else filename = normalizeFilename(dir, filename); } String existing = files.get(uuid); if (existing == null) files.put(uuid, filename); else if (!existing.equals(filename)) { throw new FormatException("Inconsistent UUID filenames"); } } } } // search for missing filenames if (needSearch) { Enumeration en = files.keys(); while (en.hasMoreElements()) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); if (filename.equals("")) { // TODO search... // should scan only other .ome.tif files // to make this work with OME server may be a little tricky? throw new FormatException("Unmatched UUID: " + uuid); } } } // build list of used files Enumeration en = files.keys(); int numUUIDs = files.size(); HashSet fileSet = new HashSet(); // ensure no duplicate filenames for (int i=0; i<numUUIDs; i++) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); fileSet.add(filename); } used = new String[fileSet.size()]; Iterator iter = fileSet.iterator(); for (int i=0; i<used.length; i++) used[i] = (String) iter.next(); // process TiffData elements Hashtable<String, IFormatReader> readers = new Hashtable<String, IFormatReader>(); int s = 0; for (int i=0; i<imageCount; i++) { debug("Image[" + i + "] {"); debug(" id = " + meta.getImageID(i)); int pixelsCount = meta.getPixelsCount(i); for (int p=0; p<pixelsCount; p++, s++) { debug(" Pixels[" + p + "] {"); debug(" id = " + meta.getPixelsID(i, p)); String order = meta.getPixelsDimensionOrder(i, p); Integer samplesPerPixel = meta.getLogicalChannelSamplesPerPixel(i, 0); int samples = samplesPerPixel == null ? -1 : samplesPerPixel.intValue(); int tiffSamples = firstIFD.getSamplesPerPixel(); if (samples != tiffSamples) { warn("SamplesPerPixel mismatch: OME=" + samples + ", TIFF=" + tiffSamples); samples = tiffSamples; } int effSizeC = meta.getPixelsSizeC(i, p).intValue() / samples; if (effSizeC == 0) effSizeC = 1; if (effSizeC * samples != meta.getPixelsSizeC(i, p).intValue()) { effSizeC = meta.getPixelsSizeC(i, p).intValue(); } int sizeT = meta.getPixelsSizeT(i, p).intValue(); int sizeZ = meta.getPixelsSizeZ(i, p).intValue(); int num = effSizeC * sizeT * sizeZ; OMETiffPlane[] planes = new OMETiffPlane[num]; for (int no=0; no<num; no++) planes[no] = new OMETiffPlane(); int tiffDataCount = meta.getTiffDataCount(i, p); for (int td=0; td<tiffDataCount; td++) { debug(" TiffData[" + td + "] {"); // extract TiffData parameters String filename = meta.getTiffDataFileName(i, p, td); String uuid = meta.getTiffDataUUID(i, p, td); Integer tdIFD = meta.getTiffDataIFD(i, p, td); int ifd = tdIFD == null ? 0 : tdIFD.intValue(); Integer numPlanes = meta.getTiffDataNumPlanes(i, p, td); Integer firstC = meta.getTiffDataFirstC(i, p, td); Integer firstT = meta.getTiffDataFirstT(i, p, td); Integer firstZ = meta.getTiffDataFirstZ(i, p, td); int c = firstC == null ? 0 : firstC.intValue(); int t = firstT == null ? 0 : firstT.intValue(); int z = firstZ == null ? 0 : firstZ.intValue(); // NB: some writers index FirstC, FirstZ and FirstT from 1 if (c >= effSizeC) c if (z >= sizeZ) z if (t >= sizeT) t int index = FormatTools.getIndex(order, sizeZ, effSizeC, sizeT, num, z, c, t); int count = numPlanes == null ? 1 : numPlanes.intValue(); if (count == 0) { core[s] = null; break; } // get reader object for this filename if (filename == null) { if (uuid == null) filename = id; else filename = files.get(uuid); } else filename = normalizeFilename(dir, filename); IFormatReader r = readers.get(filename); if (r == null) { r = new MinimalTiffReader(); readers.put(filename, r); } Location file = new Location(filename); if (!file.exists()) { // if this is an absolute file name, try using a relative name // old versions of OMETiffWriter wrote an absolute path to // UUID.FileName, which causes problems if the file is moved to // a different directory filename = filename.substring(filename.lastIndexOf(File.separator) + 1); filename = dir + File.separator + filename; if (!new Location(filename).exists()) { filename = currentId; } } // populate plane index -> IFD mapping for (int q=0; q<count; q++) { int no = index + q; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = ifd + q; planes[no].certain = true; debug(" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" + planes[no].ifd); } if (numPlanes == null) { // unknown number of planes; fill down for (int no=index+1; no<num; no++) { if (planes[no].certain) break; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = planes[no - 1].ifd + 1; debug(" Plane[" + no + "]: FILLED"); } } else { // known number of planes; clear anything subsequently filled for (int no=index+count; no<num; no++) { if (planes[no].certain) break; planes[no].reader = null; planes[no].id = null; planes[no].ifd = -1; debug(" Plane[" + no + "]: CLEARED"); } } debug(" }"); } if (core[s] == null) continue; // verify that all planes are available debug(" for (int no=0; no<num; no++) { debug(" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" + planes[no].ifd); if (planes[no].reader == null) { warn("Pixels ID '" + meta.getPixelsID(i, p) + "': missing plane no + ". Using TiffReader to determine the number of planes."); TiffReader r = new TiffReader(); r.setId(currentId); planes = new OMETiffPlane[r.getImageCount()]; for (int plane=0; plane<planes.length; plane++) { planes[plane] = new OMETiffPlane(); planes[plane].id = currentId; planes[plane].reader = r; planes[plane].ifd = plane; } num = planes.length; } } debug(" }"); // populate core metadata info[s] = planes; try { core[s].sizeX = meta.getPixelsSizeX(i, p).intValue(); int tiffWidth = (int) firstIFD.getImageWidth(); if (core[s].sizeX != tiffWidth) { warn("SizeX mismatch: OME=" + core[s].sizeX + ", TIFF=" + tiffWidth); } core[s].sizeY = meta.getPixelsSizeY(i, p).intValue(); int tiffHeight = (int) firstIFD.getImageLength(); if (core[s].sizeY != tiffHeight) { warn("SizeY mismatch: OME=" + core[s].sizeY + ", TIFF=" + tiffHeight); } core[s].sizeZ = meta.getPixelsSizeZ(i, p).intValue(); core[s].sizeC = meta.getPixelsSizeC(i, p).intValue(); core[s].sizeT = meta.getPixelsSizeT(i, p).intValue(); core[s].pixelType = FormatTools.pixelTypeFromString( meta.getPixelsPixelType(i, p)); int tiffPixelType = firstIFD.getPixelType(); if (core[s].pixelType != tiffPixelType) { warn("PixelType mismatch: OME=" + core[s].pixelType + ", TIFF=" + tiffPixelType); core[s].pixelType = tiffPixelType; } core[s].imageCount = num; core[s].dimensionOrder = meta.getPixelsDimensionOrder(i, p); core[s].orderCertain = true; int photo = firstIFD.getPhotometricInterpretation(); core[s].rgb = samples > 1 || photo == PhotoInterp.RGB; if ((samples != core[s].sizeC && (samples % core[s].sizeC) != 0 && (core[s].sizeC % samples) != 0) || core[s].sizeC == 1) { core[s].sizeC *= samples; } if (core[s].sizeZ * core[s].sizeT * core[s].sizeC > core[s].imageCount && !core[s].rgb) { if (core[s].sizeZ == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeC = 1; } else if (core[s].sizeT == core[s].imageCount) { core[s].sizeZ = 1; core[s].sizeC = 1; } else if (core[s].sizeC == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeZ = 1; } } core[s].littleEndian = !meta.getPixelsBigEndian(i, p).booleanValue(); boolean tiffLittleEndian = firstIFD.isLittleEndian(); if (core[s].littleEndian != tiffLittleEndian) { warn("BigEndian mismatch: OME=" + !core[s].littleEndian + ", TIFF=" + !tiffLittleEndian); } core[s].interleaved = false; core[s].indexed = photo == PhotoInterp.RGB_PALETTE && firstIFD.getIFDValue(IFD.COLOR_MAP) != null; if (core[s].indexed) { core[s].rgb = false; } core[s].falseColor = false; core[s].metadataComplete = true; } catch (NullPointerException exc) { throw new FormatException("Incomplete Pixels metadata", exc); } } debug("}"); } // remove null CoreMetadata entries Vector<CoreMetadata> series = new Vector<CoreMetadata>(); Vector<OMETiffPlane[]> planeInfo = new Vector<OMETiffPlane[]>(); for (int i=0; i<core.length; i++) { if (core[i] != null) { series.add(core[i]); planeInfo.add(info[i]); } } core = series.toArray(new CoreMetadata[series.size()]); info = planeInfo.toArray(new OMETiffPlane[0][0]); } // -- Helper methods -- private String normalizeFilename(String dir, String name) { File file = new File(dir, name); if (file.exists()) return file.getAbsolutePath(); return new Location(name).getAbsolutePath(); } // -- Helper classes -- /** Structure containing details on where to find a particular image plane. */ private class OMETiffPlane { /** Reader to use for accessing this plane. */ public IFormatReader reader; /** File containing this plane. */ public String id; /** IFD number of this plane. */ public int ifd = -1; /** Certainty flag, for dealing with unspecified NumPlanes. */ public boolean certain = false; } }
package gov.nih.nci.gss.api; import gov.nih.nci.gss.domain.DataService; import gov.nih.nci.gss.domain.DataServiceGroup; import gov.nih.nci.gss.domain.DomainClass; import gov.nih.nci.gss.domain.DomainModel; import gov.nih.nci.gss.domain.GridService; import gov.nih.nci.gss.domain.HostingCenter; import gov.nih.nci.gss.domain.PointOfContact; import gov.nih.nci.gss.domain.SearchExemplar; import gov.nih.nci.gss.util.Cab2bTranslator; import gov.nih.nci.gss.util.Constants; import gov.nih.nci.gss.util.GridServiceDAO; import gov.nih.nci.gss.util.StringUtil; import gov.nih.nci.system.applicationservice.ApplicationException; import gov.nih.nci.system.dao.orm.ORMDAOImpl; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.util.FileCopyUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * Custom JSON API for returning service metadata in bulk and querying services * via caB2B. * * @author <a href="mailto:rokickik@mail.nih.gov">Konrad Rokicki</a> */ public class JSONDataService extends HttpServlet { private static Logger log = Logger.getLogger(JSONDataService.class); private enum Verb { GET, POST }; private enum QueryStatus { RUNNING, EXPIRED, UNKNOWN, FOUND }; /** Date format for serializing dates into JSON. * Must match the data format used by the iPhone client */ public static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz"); /** JSON string describing the usage of this service */ private String usage; /** Hibernate session factory */ private SessionFactory sessionFactory; /** Service that manages background queries and results */ private QueryService queryService; /** Translates caB2B names to GSS names */ private Cab2bTranslator cab2bTranslator; /** Cache for JSON responses */ private Map cache; @Override public void init() throws ServletException { try { WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); this.sessionFactory = ((ORMDAOImpl)ctx.getBean("ORMDAO")).getHibernateTemplate().getSessionFactory(); this.cab2bTranslator = new Cab2bTranslator(sessionFactory); this.queryService = new QueryService(cab2bTranslator); this.cache = (Map)ctx.getBean("memoryCache"); this.usage = FileCopyUtils.copyToString(new InputStreamReader( JSONDataService.class.getResourceAsStream("/rest_api_usage.js"))); } catch (Exception e) { throw new ServletException(e); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doREST(Verb.GET, request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doREST(Verb.POST, request, response); } @Override public void destroy() { queryService.close(); super.destroy(); } /** * * @param verb * @param request * @param response * @throws ServletException * @throws IOException */ private void doREST(Verb verb, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = new PrintWriter(response.getOutputStream()); try { response.setContentType("application/json"); String path = request.getPathInfo(); if (path == null) { pw.print(getJSONUsage()); } else { String[] pathList = path.split("/"); if (pathList.length < 2) { pw.print(getJSONUsage()); } else { String noun = pathList[1]; pw.print(getRESTResponse(verb, noun, pathList, request)); } } } catch (Exception e) { log.error("JSON service error",e); pw.print(getJSONError(e.getClass().getName(), e.getMessage())); } finally { pw.close(); } } /** * Process a REST request for a given noun. * @param noun * @param pathList * @param request * @return */ private String getRESTResponse(Verb verb, String noun, String[] pathList, HttpServletRequest request) throws Exception { // User can specify a delay for debugging purposes. String delay = request.getParameter("delay"); if (delay != null && !"".equals(delay)) { int sleepTime = Integer.parseInt(delay); if (sleepTime < 20000) { // 30 seconds at most Thread.sleep(sleepTime); } } if ("summary".equals(noun)) { // Return a summary of data types return getSummaryJSON(); } else if ("counts".equals(noun)) { // Return a summary of data types boolean aggregate = "1".equals(request.getParameter("aggregate")); return getCountsJSON(aggregate); } else if ("service".equals(noun)) { // Return details about services, or a single service String id = null; if (pathList.length > 2) { id = pathList[2]; } return getServiceJSON(id); } else if ("host".equals(noun)) { // Return details about hosts, or a single hosts String id = null; if (pathList.length > 2) { id = pathList[2]; } boolean includeKey = "1".equals(request.getParameter("key")); return getHostJSON(id, includeKey); } else if ("runQuery".equals(noun)) { // Query grid services using caB2B String clientId = request.getParameter("clientId"); String searchString = request.getParameter("searchString"); String serviceGroup = request.getParameter("serviceGroup"); String serviceIdConcat = request.getParameter("serviceIds"); String[] serviceIds = request.getParameterValues("serviceId"); String[] serviceUrls = request.getParameterValues("serviceUrl"); if (StringUtil.isEmpty(clientId)) { return getJSONError("UsageError", "Specify your clientId."); } if (StringUtil.isEmpty(searchString)) { return getJSONError("UsageError", "Specify a searchString to search on."); } List<String> serviceUrlList = new ArrayList<String>(); if (serviceUrls != null) { for(String serviceUrl : serviceUrls) { serviceUrlList.add(serviceUrl); } } if (serviceIds == null && serviceIdConcat != null) { serviceIds = serviceIdConcat.split(","); } if (serviceIds != null && serviceIds.length > 0) { Session s = sessionFactory.openSession(); for(String serviceId : serviceIds) { List<GridService> services = GridServiceDAO.getServices(serviceId, s); if (services.isEmpty()) { return getJSONError("UsageError", "Unknown service id: "+serviceId); } if (services.size() > 1) { log.error("More than one matching service for service id: "+serviceId); } serviceUrlList.add(services.get(0).getUrl()); } s.close(); } QueryParams queryParams = null; if (!serviceUrlList.isEmpty()) { queryParams = new QueryParams(clientId, searchString, null, serviceUrlList); } else if (!StringUtil.isEmpty(serviceGroup)) { if (serviceGroup == null) { return getJSONError("UsageError", "Unrecognized serviceGroup '"+serviceGroup+"'"); } queryParams = new QueryParams(clientId, searchString, serviceGroup, null); } else { return getJSONError("UsageError", "Specify serviceGroup or serviceId or serviceUrl."); } Cab2bQuery query = queryService.executeQuery(queryParams); log.info("Executing "+queryParams+" as job " +query.getJobId()); JSONObject jsonObj = new JSONObject(); jsonObj.put("status", QueryStatus.RUNNING); jsonObj.put("job_id", query.getJobId()); return jsonObj.toString(); } else if ("query".equals(noun)) { String clientId = request.getParameter("clientId"); String jobId = request.getParameter("jobId"); boolean collapse = "1".equals(request.getParameter("collapse")); if (StringUtil.isEmpty(clientId)) { return getJSONError("UsageError", "Specify your clientId."); } if (StringUtil.isEmpty(jobId)) { return getJSONError("UsageError", "Specify a jobId."); } Cab2bQuery query = queryService.retrieveQuery(jobId); if (query == null) { return getJSONStatus(QueryStatus.UNKNOWN); } if (!query.getQueryParams().getClientId().equals(clientId)) { return getJSONStatus(QueryStatus.UNKNOWN); } log.info("Got query "+jobId+": "+query.getQueryParams()); // What if the query isn't completed? if (!query.isDone()) { // Return nothing and let the client poll if ("1".equals(request.getParameter("async"))) { log.info("Returning asyncronously for query: "+jobId); return getJSONStatus(QueryStatus.RUNNING); } // Block until the query is completed synchronized (query) { try { log.info("Blocking until query is complete: "+jobId); query.wait(); } catch (InterruptedException e) { log.error("Interrupted wait",e); } } } return getQueryResultsJSON(query,collapse); } // If the noun was good we would've returned by now return getJSONError("UsageError", "Unrecognized noun '"+noun+"'"); } /** * Returns a JSON object representing the basic attributes of a service. * @param service * @return * @throws JSONException */ private JSONObject getJSONObjectForService(GridService service) throws JSONException { HostingCenter host = service.getHostingCenter(); JSONObject jsonService = new JSONObject(); jsonService.put("id", service.getIdentifier()); jsonService.put("name", service.getName()); jsonService.put("version", service.getVersion()); jsonService.put("class", service.getClass().getSimpleName()); jsonService.put("simple_name", service.getSimpleName()); jsonService.put("url", service.getUrl()); jsonService.put("publish_date", df.format(service.getPublishDate())); if (service.getHiddenDefault() || service.getHostingCenter().getHiddenDefault()) { jsonService.put("hidden_default", "true"); } if (host != null) { jsonService.put("host_id", host.getIdentifier()); jsonService.put("host_short_name", host.getShortName()); } if (service instanceof DataService) { DataService dataService = (DataService)service; DataServiceGroup group = dataService.getGroup(); if (group != null) jsonService.put("group", group.getName()); if (dataService.getSearchDefault()) { jsonService.put("search_default", "true"); } if (dataService.getAccessible() != null) { jsonService.put("accessible", dataService.getAccessible().toString()); } } return jsonService; } /** * Returns a JSON object representing the basic attributes of a service. * @param service * @return * @throws JSONException */ private JSONObject getJSONObjectForHost(HostingCenter host, boolean includeKey) throws JSONException { JSONObject hostObj = new JSONObject(); // service host details hostObj.put("id", host.getIdentifier()); hostObj.put("short_name", host.getShortName()); hostObj.put("long_name", host.getLongName()); hostObj.put("country_code", host.getCountryCode()); hostObj.put("state_province", host.getStateProvince()); hostObj.put("locality", host.getLocality()); hostObj.put("postal_code", host.getPostalCode()); hostObj.put("street", host.getStreet()); if (host.getHiddenDefault()) { hostObj.put("hidden_default", "true"); } else { // If all its services are hidden, hide the host too boolean allHidden = true; for(GridService service : host.getGridServices()) { if (!service.getHiddenDefault()) allHidden = false; } if (allHidden) { hostObj.put("hidden_default", "true"); } } // check if the host has a custom image String imageName = ImageService.getHostImageName(host); String filePath = ImageService.getHostImageFilePath(imageName); File file = new File(filePath); // TODO: optimize this so that the disk is not accessed each time if (file.exists()) { hostObj.put("image_name", imageName); } if (includeKey) { hostObj.put("assigned_image_name", imageName); } // service host pocs JSONArray jsonPocs = new JSONArray(); for (PointOfContact poc : host.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } hostObj.put("pocs", jsonPocs); return hostObj; } /** * Returns a JSON string with data type summary data. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getSummaryJSON() throws JSONException, ApplicationException { if (cache.containsKey(Constants.SUMMARY_CACHE_KEY)) { log.info("Returning cached summary JSON"); return cache.get(Constants.SUMMARY_CACHE_KEY).toString(); } JSONObject json = new JSONObject(); JSONArray groupsArray = new JSONArray(); for(DataServiceGroup group : cab2bTranslator.getServiceGroups()) { JSONObject groupObj = new JSONObject(); groupObj.put("name",group.getName()); groupObj.put("label",group.getCab2bName()); groupObj.put("primaryKeyAttr",group.getDataPrimaryKey()); groupObj.put("hostAttr",group.getHostPrimaryKey()); groupObj.put("titleAttr",group.getDataTitle()); groupObj.put("descriptionAttr",group.getDataDescription()); groupObj.put("primaryClass",group.getPrimaryClass()); JSONArray exemplarsArray = new JSONArray(); List<SearchExemplar> exemplars = new ArrayList( group.getExemplarCollection()); // order exemplars by id so that they can be prioritized in the database Collections.sort(exemplars, new Comparator<SearchExemplar>() { public int compare(SearchExemplar o1, SearchExemplar o2) { return o1.getId().compareTo(o2.getId()); } }); for(SearchExemplar se : exemplars) { exemplarsArray.put(se.getSearchString()); } groupObj.put("exemplars",exemplarsArray); groupsArray.put(groupObj); } json.put("groups", groupsArray); String jsonStr = json.toString(); cache.put(Constants.SUMMARY_CACHE_KEY, jsonStr); return jsonStr; } /** * Returns a JSON string with class count data. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getCountsJSON(boolean aggregate) throws JSONException, ApplicationException { if (aggregate) { if (cache.containsKey(Constants.COUNTS_AGGR_CACHE_KEY)) { log.info("Returning cached aggregate counts JSON"); return cache.get(Constants.COUNTS_AGGR_CACHE_KEY).toString(); } Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); JSONObject classesObj = new JSONObject(); try { Map<String,Long> counts = GridServiceDAO.getAggregateClassCounts(s); for(String fullClass : counts.keySet()) { Long count = counts.get(fullClass); if ((count != null) && (count>0)) { classesObj.put(fullClass,count.toString()); } } json.put("counts", classesObj); } finally { s.close(); } String jsonStr = json.toString(); cache.put(Constants.COUNTS_AGGR_CACHE_KEY, jsonStr); return jsonStr; } else { if (cache.containsKey(Constants.COUNTS_CACHE_KEY)) { log.info("Returning cached counts JSON"); return cache.get(Constants.COUNTS_CACHE_KEY).toString(); } Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); JSONObject classesObj = new JSONObject(); try { Map<String,Map<String,Long>> counts = GridServiceDAO.getClassCounts(s); for(String fullClass : counts.keySet()) { JSONObject servicesObj = new JSONObject(); Map<String,Long> classCounts = counts.get(fullClass); for(String serviceUrl : classCounts.keySet()) { Long count = classCounts.get(serviceUrl); if ((count != null) && (count>0)) { servicesObj.put(serviceUrl,count.toString()); } } if (servicesObj.length() > 0) { classesObj.put(fullClass, servicesObj); } } if (classesObj.length() > 0) { json.put("counts", classesObj); } } finally { s.close(); } String jsonStr = json.toString(); cache.put(Constants.COUNTS_CACHE_KEY, jsonStr); return jsonStr; } } /** * Returns a JSON string with all the metadata about a particular service. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getServiceJSON(String serviceId) throws JSONException, ApplicationException { if (serviceId == null) { if (cache.containsKey(Constants.SERVICE_CACHE_KEY)) { log.info("Returning cached service JSON"); return cache.get(Constants.SERVICE_CACHE_KEY).toString(); } } Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); try { // Retrieve the list of services Collection<GridService> services = GridServiceDAO.getServices(serviceId, s); JSONArray jsonArray = new JSONArray(); json.put("services", jsonArray); for (GridService service : services) { JSONObject jsonService = getJSONObjectForService(service); jsonArray.put(jsonService); // Add service details jsonService.put("description", service.getDescription()); jsonService.put("status", service.getLastStatus()); // Add service pocs JSONArray jsonPocs = new JSONArray(); for (PointOfContact poc : service.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } jsonService.put("pocs", jsonPocs); if (serviceId != null) { // output more metadata if a service is specified if (service instanceof DataService) { DomainModel model = ((DataService)service).getDomainModel(); // Add domain model JSONObject modelObj = new JSONObject(); jsonService.put("domain_model", modelObj); if (model != null) { modelObj.put("long_name", model.getLongName()); modelObj.put("version", model.getVersion()); modelObj.put("description", model.getDescription()); // Add model classes JSONArray jsonClasses = new JSONArray(); for (DomainClass dc : model.getClasses()) { JSONObject jsonClass = new JSONObject(); jsonClass.put("name", dc.getClassName()); jsonClass.put("package", dc.getDomainPackage()); jsonClass.put("description", dc.getDescription()); jsonClasses.put(jsonClass); } modelObj.put("classes", jsonClasses); } } } } } finally { s.close(); } String jsonStr = json.toString(); if (serviceId == null) { cache.put(Constants.SERVICE_CACHE_KEY, jsonStr); } return jsonStr; } /** * Returns a JSON string with all the metadata about a particular host. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getHostJSON(String hostId, boolean includeKey) throws JSONException, ApplicationException { if (hostId == null) { if (cache.containsKey(Constants.HOST_CACHE_KEY)) { log.info("Returning cached host JSON"); return cache.get(Constants.HOST_CACHE_KEY).toString(); } } Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); try { // Get the list of hosts Collection<HostingCenter> hosts = GridServiceDAO.getHosts(hostId, s); JSONArray jsonArray = new JSONArray(); json.put("hosts", jsonArray); for (HostingCenter host : hosts) { jsonArray.put(getJSONObjectForHost(host, includeKey)); } } finally { s.close(); } String jsonStr = json.toString(); if (hostId == null) { cache.put(Constants.HOST_CACHE_KEY, jsonStr); } return jsonStr; } private String getQueryResultsJSON(Cab2bQuery query, boolean collapse) throws JSONException { if (!query.isDone()) { throw new IllegalStateException("Query has not completed: "+query); } Exception e = query.getException(); if (e != null) { return getJSONError(e.getClass().getName(), e.getMessage()); } JSONObject json = new JSONObject(query.getResultJson()); if (json.has("error")) { return query.getResultJson(); } String modelGroupName = json.getString("modelGroupName"); DataServiceGroup serviceGroup = cab2bTranslator.getServiceGroupForModelGroup(modelGroupName); if (modelGroupName != null) { json.remove("modelGroupName"); json.put("serviceGroup", serviceGroup.getName()); } if (collapse) { Map<String,Map<String,JSONObject>> servers = new LinkedHashMap<String,Map<String,JSONObject>>(); // the key to discriminate on for duplicates String primaryKey = serviceGroup.getDataPrimaryKey(); String hostKey = serviceGroup.getHostPrimaryKey(); JSONObject queries = json.getJSONObject("results"); for(Iterator i = queries.keys(); i.hasNext(); ) { String queryName = (String)i.next(); JSONObject urls = queries.getJSONObject(queryName); for(Iterator j = urls.keys(); j.hasNext(); ) { String url = (String)j.next(); JSONArray objs = urls.getJSONArray(url); Map<String,JSONObject> serverUnique = servers.get(url); if (serverUnique == null) { serverUnique = new LinkedHashMap<String,JSONObject>(); servers.put(url, serverUnique); } for(int k=0; k<objs.length(); k++) { JSONObject obj = objs.getJSONObject(k); String key = null; try { key = obj.getString(hostKey)+"~"+obj.getString(primaryKey); } catch (JSONException x) { log.error("Error getting unique key",x); key = obj.toString(); } if (!serverUnique.containsKey(key)) { serverUnique.put(key, obj); } } } } JSONObject jsonUrls = new JSONObject(); for(String url : servers.keySet()) { JSONArray jsonObjs = new JSONArray(); jsonUrls.put(url, jsonObjs); for (JSONObject obj : servers.get(url).values()) { jsonObjs.put(obj); } } json.put("results", jsonUrls); } return json.toString(); } /** * Returns a JSON string with the given error message. * @return JSON-formatted String */ private String getJSONError(String exception, String message) { return "{\"error\":"+JSONObject.quote(exception)+ ",\"message\":"+JSONObject.quote(message)+"}"; } /** * Get a JSON string with a simple query status message. * @param status * @return * @throws JSONException */ private String getJSONStatus(Object status) throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.put("status", status); return jsonObj.toString(); } /** * Returns a JSON string with usage instructions, or an error if a problem * occurs. * @return JSON-formatted String */ private String getJSONUsage() { return usage; } }
package jadx.core.utils; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import org.jetbrains.annotations.Nullable; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.LoopInfo; import jadx.core.dex.attributes.nodes.PhiListAttr; import jadx.core.dex.instructions.IfNode; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.PhiInsn; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.InsnWrapArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.instructions.mods.TernaryInsn; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.IBlock; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.regions.conditions.IfCondition; import jadx.core.utils.exceptions.JadxRuntimeException; public class BlockUtils { private BlockUtils() { } public static BlockNode getBlockByOffset(int offset, Iterable<BlockNode> casesBlocks) { for (BlockNode block : casesBlocks) { if (block.getStartOffset() == offset) { return block; } } throw new JadxRuntimeException("Can't find block by offset: " + InsnUtils.formatOffset(offset) + " in list " + casesBlocks); } public static BlockNode selectOther(BlockNode node, List<BlockNode> blocks) { List<BlockNode> list = blocks; if (list.size() > 2) { list = cleanBlockList(list); } if (list.size() != 2) { throw new JadxRuntimeException("Incorrect nodes count for selectOther: " + node + " in " + list); } BlockNode first = list.get(0); if (first != node) { return first; } else { return list.get(1); } } public static BlockNode selectOtherSafe(BlockNode node, List<BlockNode> blocks) { int size = blocks.size(); if (size == 1) { BlockNode first = blocks.get(0); return first != node ? first : null; } if (size == 2) { BlockNode first = blocks.get(0); return first != node ? first : blocks.get(1); } return null; } public static boolean isExceptionHandlerPath(BlockNode b) { if (b.contains(AType.EXC_HANDLER) || b.contains(AFlag.EXC_BOTTOM_SPLITTER) || b.contains(AFlag.REMOVE)) { return true; } if (b.contains(AFlag.SYNTHETIC)) { List<BlockNode> s = b.getSuccessors(); return s.size() == 1 && s.get(0).contains(AType.EXC_HANDLER); } return false; } /** * Remove exception handlers from block nodes list */ private static List<BlockNode> cleanBlockList(List<BlockNode> list) { List<BlockNode> ret = new ArrayList<>(list.size()); for (BlockNode block : list) { if (!isExceptionHandlerPath(block)) { ret.add(block); } } return ret; } /** * Remove exception handlers from block nodes bitset */ public static void cleanBitSet(MethodNode mth, BitSet bs) { for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { BlockNode block = mth.getBasicBlocks().get(i); if (isExceptionHandlerPath(block)) { bs.clear(i); } } } public static boolean isBackEdge(BlockNode from, BlockNode to) { if (to == null) { return false; } if (from.getCleanSuccessors().contains(to)) { return false; // already checked } return from.getSuccessors().contains(to); } public static boolean isFollowBackEdge(BlockNode block) { if (block == null) { return false; } if (block.contains(AFlag.LOOP_START)) { List<BlockNode> predecessors = block.getPredecessors(); if (predecessors.size() == 1) { BlockNode loopEndBlock = predecessors.get(0); if (loopEndBlock.contains(AFlag.LOOP_END)) { List<LoopInfo> loops = loopEndBlock.getAll(AType.LOOP); for (LoopInfo loop : loops) { if (loop.getStart().equals(block) && loop.getEnd().equals(loopEndBlock)) { return true; } } } } } return false; } /** * Check if instruction contains in block (use == for comparison, not equals) */ public static boolean blockContains(BlockNode block, InsnNode insn) { for (InsnNode bi : block.getInstructions()) { if (bi == insn) { return true; } } return false; } public static boolean checkFirstInsn(IBlock block, Predicate<InsnNode> predicate) { InsnNode insn = getFirstInsn(block); return insn != null && predicate.test(insn); } public static boolean checkLastInsnType(IBlock block, InsnType expectedType) { InsnNode insn = getLastInsn(block); return insn != null && insn.getType() == expectedType; } public static InsnNode getLastInsnWithType(IBlock block, InsnType expectedType) { InsnNode insn = getLastInsn(block); if (insn != null && insn.getType() == expectedType) { return insn; } return null; } @Nullable public static InsnNode getFirstInsn(@Nullable IBlock block) { if (block == null) { return null; } List<InsnNode> insns = block.getInstructions(); if (insns.isEmpty()) { return null; } return insns.get(0); } @Nullable public static InsnNode getLastInsn(@Nullable IBlock block) { if (block == null) { return null; } List<InsnNode> insns = block.getInstructions(); if (insns.isEmpty()) { return null; } return insns.get(insns.size() - 1); } public static boolean isExitBlock(MethodNode mth, BlockNode block) { BlockNode exitBlock = mth.getExitBlock(); if (block == exitBlock) { return true; } return exitBlock.getPredecessors().contains(block); } public static boolean containsExitInsn(IBlock block) { InsnNode lastInsn = BlockUtils.getLastInsn(block); if (lastInsn == null) { return false; } InsnType type = lastInsn.getType(); return type == InsnType.RETURN || type == InsnType.THROW || type == InsnType.BREAK || type == InsnType.CONTINUE; } @Nullable public static BlockNode getBlockByInsn(MethodNode mth, @Nullable InsnNode insn) { if (insn == null) { return null; } if (insn instanceof PhiInsn) { return searchBlockWithPhi(mth, (PhiInsn) insn); } if (insn.contains(AFlag.WRAPPED)) { return getBlockByWrappedInsn(mth, insn); } for (BlockNode bn : mth.getBasicBlocks()) { if (blockContains(bn, insn)) { return bn; } } return null; } public static BlockNode searchBlockWithPhi(MethodNode mth, PhiInsn insn) { for (BlockNode block : mth.getBasicBlocks()) { PhiListAttr phiListAttr = block.get(AType.PHI_LIST); if (phiListAttr != null) { for (PhiInsn phiInsn : phiListAttr.getList()) { if (phiInsn == insn) { return block; } } } } return null; } private static BlockNode getBlockByWrappedInsn(MethodNode mth, InsnNode insn) { for (BlockNode bn : mth.getBasicBlocks()) { for (InsnNode bi : bn.getInstructions()) { if (bi == insn || foundWrappedInsn(bi, insn) != null) { return bn; } } } return null; } public static InsnNode searchInsnParent(MethodNode mth, InsnNode insn) { InsnArg insnArg = searchWrappedInsnParent(mth, insn); if (insnArg == null) { return null; } return insnArg.getParentInsn(); } public static InsnArg searchWrappedInsnParent(MethodNode mth, InsnNode insn) { if (!insn.contains(AFlag.WRAPPED)) { return null; } for (BlockNode bn : mth.getBasicBlocks()) { for (InsnNode bi : bn.getInstructions()) { InsnArg res = foundWrappedInsn(bi, insn); if (res != null) { return res; } } } return null; } private static InsnArg foundWrappedInsn(InsnNode container, InsnNode insn) { for (InsnArg arg : container.getArguments()) { if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); if (wrapInsn == insn) { return arg; } InsnArg res = foundWrappedInsn(wrapInsn, insn); if (res != null) { return res; } } } if (container instanceof TernaryInsn) { return foundWrappedInsnInCondition(((TernaryInsn) container).getCondition(), insn); } return null; } private static InsnArg foundWrappedInsnInCondition(IfCondition cond, InsnNode insn) { if (cond.isCompare()) { IfNode cmpInsn = cond.getCompare().getInsn(); return foundWrappedInsn(cmpInsn, insn); } for (IfCondition nestedCond : cond.getArgs()) { InsnArg res = foundWrappedInsnInCondition(nestedCond, insn); if (res != null) { return res; } } return null; } public static BitSet newBlocksBitSet(MethodNode mth) { return new BitSet(mth.getBasicBlocks().size()); } public static BitSet copyBlocksBitSet(MethodNode mth, BitSet bitSet) { BitSet copy = new BitSet(mth.getBasicBlocks().size()); if (!bitSet.isEmpty()) { copy.or(bitSet); } return copy; } public static BitSet blocksToBitSet(MethodNode mth, Collection<BlockNode> blocks) { BitSet bs = newBlocksBitSet(mth); for (BlockNode block : blocks) { bs.set(block.getId()); } return bs; } @Nullable public static BlockNode bitSetToOneBlock(MethodNode mth, BitSet bs) { if (bs == null || bs.cardinality() != 1) { return null; } return mth.getBasicBlocks().get(bs.nextSetBit(0)); } public static List<BlockNode> bitSetToBlocks(MethodNode mth, BitSet bs) { if (bs == null || bs == EmptyBitSet.EMPTY) { return Collections.emptyList(); } int size = bs.cardinality(); if (size == 0) { return Collections.emptyList(); } List<BlockNode> blocks = new ArrayList<>(size); for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { BlockNode block = mth.getBasicBlocks().get(i); blocks.add(block); } return blocks; } public static void forEachBlockFromBitSet(MethodNode mth, BitSet bs, Consumer<BlockNode> consumer) { if (bs == null || bs == EmptyBitSet.EMPTY || bs.isEmpty()) { return; } List<BlockNode> blocks = mth.getBasicBlocks(); for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { consumer.accept(blocks.get(i)); } } /** * Return first successor which not exception handler and not follow loop back edge */ public static BlockNode getNextBlock(BlockNode block) { List<BlockNode> s = block.getCleanSuccessors(); return s.isEmpty() ? null : s.get(0); } /** * Return successor on path to 'pathEnd' block */ public static BlockNode getNextBlockToPath(BlockNode block, BlockNode pathEnd) { List<BlockNode> successors = block.getCleanSuccessors(); if (successors.contains(pathEnd)) { return pathEnd; } Set<BlockNode> path = getAllPathsBlocks(block, pathEnd); for (BlockNode s : successors) { if (path.contains(s)) { return s; } } return null; } /** * Visit blocks on any path from start to end. * Only one path will be visited! */ public static boolean visitBlocksOnPath(MethodNode mth, BlockNode start, BlockNode end, Consumer<BlockNode> visitor) { visitor.accept(start); if (start == end) { return true; } if (start.getCleanSuccessors().contains(end)) { visitor.accept(end); return true; } // DFS on clean successors BitSet visited = newBlocksBitSet(mth); Deque<BlockNode> queue = new ArrayDeque<>(); queue.addLast(start); while (true) { BlockNode current = queue.peekLast(); if (current == null) { return false; } boolean added = false; for (BlockNode next : current.getCleanSuccessors()) { if (next == end) { queue.removeFirst(); // start already visited queue.addLast(next); queue.forEach(visitor); return true; } int id = next.getId(); if (!visited.get(id)) { visited.set(id); queue.addLast(next); added = true; break; } } if (!added) { queue.pollLast(); if (queue.isEmpty()) { return false; } } } } public static List<BlockNode> collectPredecessors(MethodNode mth, BlockNode start, Collection<BlockNode> stopBlocks) { BitSet bs = newBlocksBitSet(mth); if (!stopBlocks.isEmpty()) { bs.or(blocksToBitSet(mth, stopBlocks)); } List<BlockNode> list = new ArrayList<>(); traversePredecessors(start, bs, list::add); return list; } /** * Up BFS */ private static void traversePredecessors(BlockNode start, BitSet visited, Consumer<BlockNode> visitor) { Queue<BlockNode> queue = new ArrayDeque<>(); queue.add(start); while (true) { BlockNode current = queue.poll(); if (current == null) { return; } visitor.accept(current); for (BlockNode next : current.getPredecessors()) { int id = next.getId(); if (!visited.get(id)) { visited.set(id); queue.add(next); } } } } /** * Collect blocks from all possible execution paths from 'start' to 'end' */ public static Set<BlockNode> getAllPathsBlocks(BlockNode start, BlockNode end) { Set<BlockNode> set = new HashSet<>(); set.add(start); if (start != end) { addPredecessors(set, end, start); } return set; } private static void addPredecessors(Set<BlockNode> set, BlockNode from, BlockNode until) { set.add(from); for (BlockNode pred : from.getPredecessors()) { if (pred != until && !set.contains(pred)) { addPredecessors(set, pred, until); } } } private static boolean traverseSuccessorsUntil(BlockNode from, BlockNode until, BitSet visited, boolean clean) { List<BlockNode> nodes = clean ? from.getCleanSuccessors() : from.getSuccessors(); for (BlockNode s : nodes) { if (s == until) { return true; } int id = s.getId(); if (!visited.get(id)) { visited.set(id); if (until.isDominator(s)) { return true; } if (traverseSuccessorsUntil(s, until, visited, clean)) { return true; } } } return false; } /** * Search at least one path from startBlocks to end */ public static boolean atLeastOnePathExists(Collection<BlockNode> startBlocks, BlockNode end) { for (BlockNode startBlock : startBlocks) { if (isPathExists(startBlock, end)) { return true; } } return false; } /** * Check if exist path from every startBlocks to end */ public static boolean isAllPathExists(Collection<BlockNode> startBlocks, BlockNode end) { for (BlockNode startBlock : startBlocks) { if (!isPathExists(startBlock, end)) { return false; } } return true; } public static boolean isPathExists(BlockNode start, BlockNode end) { if (start == end || end.isDominator(start) || start.getCleanSuccessors().contains(end)) { return true; } if (start.getPredecessors().contains(end)) { return false; } return traverseSuccessorsUntil(start, end, new BitSet(), true); } public static boolean isAnyPathExists(BlockNode start, BlockNode end) { if (start == end || end.isDominator(start) || start.getSuccessors().contains(end)) { return true; } if (start.getPredecessors().contains(end)) { return false; } return traverseSuccessorsUntil(start, end, new BitSet(), false); } public static BlockNode getTopBlock(List<BlockNode> blocks) { if (blocks.size() == 1) { return blocks.get(0); } for (BlockNode from : blocks) { boolean top = true; for (BlockNode to : blocks) { if (from != to && !isAnyPathExists(from, to)) { top = false; break; } } if (top) { return from; } } return null; } /** * Search last block in control flow graph from input set. */ public static BlockNode getBottomBlock(List<BlockNode> blocks) { if (blocks.size() == 1) { return blocks.get(0); } for (BlockNode bottomCandidate : blocks) { boolean bottom = true; for (BlockNode from : blocks) { if (bottomCandidate != from && !isAnyPathExists(from, bottomCandidate)) { bottom = false; break; } } if (bottom) { return bottomCandidate; } } return null; } public static boolean isOnlyOnePathExists(BlockNode start, BlockNode end) { if (start == end) { return true; } if (!end.isDominator(start)) { return false; } BlockNode currentNode = start; while (currentNode.getCleanSuccessors().size() == 1) { currentNode = currentNode.getCleanSuccessors().get(0); if (currentNode == end) { return true; } } return false; } /** * Search for first node which not dominated by dom, starting from start */ public static BlockNode traverseWhileDominates(BlockNode dom, BlockNode start) { for (BlockNode node : start.getCleanSuccessors()) { if (!node.isDominator(dom)) { return node; } else { BlockNode out = traverseWhileDominates(dom, node); if (out != null) { return out; } } } return null; } /** * Search lowest common ancestor in dominator tree for input set. */ @Nullable public static BlockNode getCommonDominator(MethodNode mth, List<BlockNode> blocks) { BitSet doms = newBlocksBitSet(mth); // collect all dominators from input set doms.set(0, mth.getBasicBlocks().size()); blocks.forEach(b -> doms.and(b.getDoms())); // exclude all dominators of immediate dominator (including self) BitSet combine = newBlocksBitSet(mth); combine.or(doms); forEachBlockFromBitSet(mth, doms, block -> { BlockNode idom = block.getIDom(); if (idom != null) { combine.andNot(idom.getDoms()); combine.clear(idom.getId()); } }); return bitSetToOneBlock(mth, combine); } /** * Return common cross block for input set. * * @return null if cross is a method exit block. */ @Nullable public static BlockNode getPathCross(MethodNode mth, Collection<BlockNode> blocks) { BitSet domFrontBS = newBlocksBitSet(mth); boolean first = true; for (BlockNode b : blocks) { if (first) { domFrontBS.or(b.getDomFrontier()); first = false; } else { domFrontBS.and(b.getDomFrontier()); } } domFrontBS.clear(mth.getExitBlock().getId()); if (domFrontBS.isEmpty()) { return null; } BlockNode oneBlock = bitSetToOneBlock(mth, domFrontBS); if (oneBlock != null) { return oneBlock; } BitSet excluded = newBlocksBitSet(mth); // exclude method exit and loop start blocks excluded.set(mth.getExitBlock().getId()); // exclude loop start blocks mth.getLoops().forEach(l -> excluded.set(l.getStart().getId())); if (!mth.isNoExceptionHandlers()) { // exclude exception handlers paths mth.getExceptionHandlers().forEach(h -> excluded.or(h.getHandlerBlock().getDomFrontier())); } domFrontBS.andNot(excluded); oneBlock = bitSetToOneBlock(mth, domFrontBS); if (oneBlock != null) { return oneBlock; } BitSet combinedDF = newBlocksBitSet(mth); int k = mth.getBasicBlocks().size(); while (true) { // collect dom frontier blocks from current set until only one block left forEachBlockFromBitSet(mth, domFrontBS, block -> { BitSet domFrontier = block.getDomFrontier(); if (!domFrontier.isEmpty()) { combinedDF.or(domFrontier); combinedDF.clear(block.getId()); } }); combinedDF.andNot(excluded); int cardinality = combinedDF.cardinality(); if (cardinality == 1) { return bitSetToOneBlock(mth, combinedDF); } if (cardinality == 0) { return null; } if (k mth.addWarnComment("Path cross not found for " + blocks + ", limit reached: " + mth.getBasicBlocks().size()); return null; } // replace domFrontBS with combinedDF domFrontBS.clear(); domFrontBS.or(combinedDF); combinedDF.clear(); } } public static BlockNode getPathCross(MethodNode mth, BlockNode b1, BlockNode b2) { if (b1 == b2) { return b1; } if (b1 == null || b2 == null) { return null; } return getPathCross(mth, Arrays.asList(b1, b2)); } /** * Collect all block dominated by 'dominator', starting from 'start' */ public static List<BlockNode> collectBlocksDominatedBy(MethodNode mth, BlockNode dominator, BlockNode start) { List<BlockNode> result = new ArrayList<>(); collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), false); return result; } /** * Collect all block dominated by 'dominator', starting from 'start', including exception handlers */ public static Set<BlockNode> collectBlocksDominatedByWithExcHandlers(MethodNode mth, BlockNode dominator, BlockNode start) { Set<BlockNode> result = new LinkedHashSet<>(); collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), true); return result; } private static void collectWhileDominates(BlockNode dominator, BlockNode child, Collection<BlockNode> result, BitSet visited, boolean includeExcHandlers) { if (visited.get(child.getId())) { return; } visited.set(child.getId()); List<BlockNode> successors = includeExcHandlers ? child.getSuccessors() : child.getCleanSuccessors(); for (BlockNode node : successors) { if (node.isDominator(dominator)) { result.add(node); collectWhileDominates(dominator, node, result, visited, includeExcHandlers); } } } /** * Visit blocks on path without branching or merging paths. */ public static void visitSinglePath(BlockNode startBlock, Consumer<BlockNode> visitor) { if (startBlock == null) { return; } visitor.accept(startBlock); BlockNode next = getNextSinglePathBlock(startBlock); while (next != null) { visitor.accept(next); next = getNextSinglePathBlock(next); } } @Nullable public static BlockNode getNextSinglePathBlock(BlockNode block) { if (block == null || block.getPredecessors().size() > 1) { return null; } List<BlockNode> successors = block.getSuccessors(); return successors.size() == 1 ? successors.get(0) : null; } public static List<BlockNode> buildSimplePath(BlockNode block) { if (block == null) { return Collections.emptyList(); } List<BlockNode> list = new ArrayList<>(); if (block.getCleanSuccessors().size() >= 2) { return Collections.emptyList(); } list.add(block); BlockNode currentBlock = getNextBlock(block); while (currentBlock != null && currentBlock.getCleanSuccessors().size() < 2 && currentBlock.getPredecessors().size() == 1) { list.add(currentBlock); currentBlock = getNextBlock(currentBlock); } return list; } /** * Set 'SKIP' flag for all synthetic predecessors from start block. */ public static void skipPredSyntheticPaths(BlockNode block) { for (BlockNode pred : block.getPredecessors()) { if (pred.contains(AFlag.SYNTHETIC) && !pred.contains(AFlag.EXC_TOP_SPLITTER) && !pred.contains(AFlag.EXC_BOTTOM_SPLITTER) && pred.getInstructions().isEmpty()) { pred.add(AFlag.DONT_GENERATE); skipPredSyntheticPaths(pred); } } } /** * Follow empty blocks and return end of path block (first not empty). * Return start block if no such path. */ public static BlockNode followEmptyPath(BlockNode start) { while (true) { BlockNode next = getNextBlockOnEmptyPath(start); if (next == null) { return start; } start = next; } } public static void visitBlocksOnEmptyPath(BlockNode start, Consumer<BlockNode> visitor) { while (true) { BlockNode next = getNextBlockOnEmptyPath(start); if (next == null) { return; } visitor.accept(next); start = next; } } @Nullable private static BlockNode getNextBlockOnEmptyPath(BlockNode block) { if (!block.getInstructions().isEmpty() || block.getPredecessors().size() > 1) { return null; } List<BlockNode> successors = block.getCleanSuccessors(); if (successors.size() != 1) { return null; } return successors.get(0); } /** * Return true if on path from start to end no instructions and no branches. */ public static boolean isEmptySimplePath(BlockNode start, BlockNode end) { if (start == end && start.getInstructions().isEmpty()) { return true; } if (!start.getInstructions().isEmpty() || start.getCleanSuccessors().size() != 1) { return false; } BlockNode block = getNextBlock(start); while (block != null && block != end && block.getCleanSuccessors().size() < 2 && block.getPredecessors().size() == 1 && block.getInstructions().isEmpty()) { block = getNextBlock(block); } return block == end; } /** * Return predecessor of synthetic block or same block otherwise. */ public static BlockNode skipSyntheticPredecessor(BlockNode block) { if (block.isSynthetic() && block.getInstructions().isEmpty() && block.getPredecessors().size() == 1) { return block.getPredecessors().get(0); } return block; } public static boolean isAllBlocksEmpty(List<BlockNode> blocks) { for (BlockNode block : blocks) { if (!block.getInstructions().isEmpty()) { return false; } } return true; } public static List<InsnNode> collectAllInsns(List<BlockNode> blocks) { List<InsnNode> insns = new ArrayList<>(); blocks.forEach(block -> insns.addAll(block.getInstructions())); return insns; } /** * Return limited number of instructions from method. * Return empty list if method contains more than limit. */ public static List<InsnNode> collectInsnsWithLimit(List<BlockNode> blocks, int limit) { List<InsnNode> insns = new ArrayList<>(limit); for (BlockNode block : blocks) { List<InsnNode> blockInsns = block.getInstructions(); int blockSize = blockInsns.size(); if (blockSize == 0) { continue; } if (insns.size() + blockSize > limit) { return Collections.emptyList(); } insns.addAll(blockInsns); } return insns; } /** * Return insn if it is only one instruction in this method. Return null otherwise. */ @Nullable public static InsnNode getOnlyOneInsnFromMth(MethodNode mth) { InsnNode insn = null; for (BlockNode block : mth.getBasicBlocks()) { List<InsnNode> blockInsns = block.getInstructions(); int blockSize = blockInsns.size(); if (blockSize == 0) { continue; } if (blockSize > 1) { return null; } if (insn != null) { return null; } insn = blockInsns.get(0); } return insn; } public static boolean isFirstInsn(MethodNode mth, InsnNode insn) { BlockNode startBlock = followEmptyPath(mth.getEnterBlock()); if (startBlock != null && !startBlock.getInstructions().isEmpty()) { return startBlock.getInstructions().get(0) == insn; } // handle branching with empty blocks BlockNode block = getBlockByInsn(mth, insn); if (block == null) { throw new JadxRuntimeException("Insn not found in method: " + insn); } if (block.getInstructions().get(0) != insn) { return false; } Set<BlockNode> allPathsBlocks = getAllPathsBlocks(mth.getEnterBlock(), block); for (BlockNode pathBlock : allPathsBlocks) { if (!pathBlock.getInstructions().isEmpty() && pathBlock != block) { return false; } } return true; } /** * Replace insn by index i in block, * for proper copy attributes, assume attributes are not overlap */ public static void replaceInsn(MethodNode mth, BlockNode block, int i, InsnNode insn) { InsnNode prevInsn = block.getInstructions().get(i); insn.copyAttributesFrom(prevInsn); insn.inheritMetadata(prevInsn); insn.setOffset(prevInsn.getOffset()); block.getInstructions().set(i, insn); RegisterArg result = insn.getResult(); RegisterArg prevResult = prevInsn.getResult(); if (result != null && prevResult != null && result.sameRegAndSVar(prevResult)) { // Don't unbind result for same register. // Unbind will remove arg from PHI and not add it back on rebind. InsnRemover.unbindAllArgs(mth, prevInsn); } else { InsnRemover.unbindInsn(mth, prevInsn); } insn.rebindArgs(); } public static boolean replaceInsn(MethodNode mth, BlockNode block, InsnNode oldInsn, InsnNode newInsn) { List<InsnNode> instructions = block.getInstructions(); int size = instructions.size(); for (int i = 0; i < size; i++) { InsnNode instruction = instructions.get(i); if (instruction == oldInsn) { replaceInsn(mth, block, i, newInsn); return true; } } return false; } public static boolean insertBeforeInsn(BlockNode block, InsnNode insn, InsnNode newInsn) { int index = getInsnIndexInBlock(block, insn); if (index == -1) { return false; } block.getInstructions().add(index, newInsn); return true; } public static boolean insertAfterInsn(BlockNode block, InsnNode insn, InsnNode newInsn) { int index = getInsnIndexInBlock(block, insn); if (index == -1) { return false; } block.getInstructions().add(index + 1, newInsn); return true; } public static int getInsnIndexInBlock(BlockNode block, InsnNode insn) { List<InsnNode> instructions = block.getInstructions(); int size = instructions.size(); for (int i = 0; i < size; i++) { if (instructions.get(i) == insn) { return i; } } return -1; } public static boolean replaceInsn(MethodNode mth, InsnNode oldInsn, InsnNode newInsn) { for (BlockNode block : mth.getBasicBlocks()) { if (replaceInsn(mth, block, oldInsn, newInsn)) { return true; } } return false; } public static Map<BlockNode, BitSet> calcPostDominance(MethodNode mth) { return calcPartialPostDominance(mth, mth.getBasicBlocks(), mth.getPreExitBlocks().get(0)); } public static Map<BlockNode, BitSet> calcPartialPostDominance(MethodNode mth, Collection<BlockNode> blockNodes, BlockNode exitBlock) { int blocksCount = mth.getBasicBlocks().size(); Map<BlockNode, BitSet> map = new HashMap<>(blocksCount); BitSet initSet = new BitSet(blocksCount); for (BlockNode block : blockNodes) { initSet.set(block.getId()); } for (BlockNode block : blockNodes) { BitSet postDoms = new BitSet(blocksCount); postDoms.or(initSet); map.put(block, postDoms); } BitSet exitBitSet = map.get(exitBlock); exitBitSet.clear(); exitBitSet.set(exitBlock.getId()); BitSet domSet = new BitSet(blocksCount); boolean changed; do { changed = false; for (BlockNode block : blockNodes) { if (block == exitBlock) { continue; } BitSet d = map.get(block); if (!changed) { domSet.clear(); domSet.or(d); } for (BlockNode scc : block.getSuccessors()) { BitSet scPDoms = map.get(scc); if (scPDoms != null) { d.and(scPDoms); } } d.set(block.getId()); if (!changed && !d.equals(domSet)) { changed = true; map.put(block, d); } } } while (changed); blockNodes.forEach(block -> { BitSet postDoms = map.get(block); postDoms.clear(block.getId()); if (postDoms.isEmpty()) { map.put(block, EmptyBitSet.EMPTY); } }); return map; } @Nullable public static BlockNode calcImmediatePostDominator(MethodNode mth, BlockNode block) { BlockNode oneSuccessor = Utils.getOne(block.getSuccessors()); if (oneSuccessor != null) { return oneSuccessor; } return calcImmediatePostDominator(mth, block, calcPostDominance(mth)); } @Nullable public static BlockNode calcPartialImmediatePostDominator(MethodNode mth, BlockNode block, Collection<BlockNode> blockNodes, BlockNode exitBlock) { BlockNode oneSuccessor = Utils.getOne(block.getSuccessors()); if (oneSuccessor != null) { return oneSuccessor; } Map<BlockNode, BitSet> pDomsMap = calcPartialPostDominance(mth, blockNodes, exitBlock); return calcImmediatePostDominator(mth, block, pDomsMap); } @Nullable public static BlockNode calcImmediatePostDominator(MethodNode mth, BlockNode block, Map<BlockNode, BitSet> postDomsMap) { BlockNode oneSuccessor = Utils.getOne(block.getSuccessors()); if (oneSuccessor != null) { return oneSuccessor; } List<BlockNode> basicBlocks = mth.getBasicBlocks(); BitSet postDoms = postDomsMap.get(block); BitSet bs = copyBlocksBitSet(mth, postDoms); for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { BlockNode pdomBlock = basicBlocks.get(i); BitSet pdoms = postDomsMap.get(pdomBlock); if (pdoms != null) { bs.andNot(pdoms); } } return bitSetToOneBlock(mth, bs); } public static BlockNode getTopSplitterForHandler(BlockNode handlerBlock) { BlockNode block = getBlockWithFlag(handlerBlock.getPredecessors(), AFlag.EXC_TOP_SPLITTER); if (block == null) { throw new JadxRuntimeException("Can't find top splitter block for handler:" + handlerBlock); } return block; } @Nullable public static BlockNode getBlockWithFlag(List<BlockNode> blocks, AFlag flag) { for (BlockNode block : blocks) { if (block.contains(flag)) { return block; } } return null; } }
package org.karmaexchange.util; import java.io.UnsupportedEncodingException; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.karmaexchange.dao.User; import org.karmaexchange.dao.User.RegisteredEmail; public class MailUtil { public static void sendMail(User fromUser, User toUser,String subject, String body) { sendMail(getPrimaryEmailForUser(fromUser), getUserName(fromUser), getPrimaryEmailForUser(toUser), getUserName(toUser), subject, body); } private static void sendMail(String fromEmail, String fromName, String toEmail, String toName, String subject, String body) { Session session = Session.getDefaultInstance(null); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEmail, fromName)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail, toName)); msg.setSubject(subject); msg.setText(body); Transport.send(msg); } catch (AddressException e) { } catch (MessagingException e) { } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static String getUserName(User user) { return user.getFirstName() + " " + user.getLastName(); } public static String getPrimaryEmailForUser(User userObj){ for (RegisteredEmail registeredEmail : userObj.getRegisteredEmails()) { if (registeredEmail.isPrimary()) { return registeredEmail.getEmail(); } } return null; } }
package org.wyona.yanel.servlet; import java.io.File; import java.io.BufferedReader; import java.io.InputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.net.URL; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeIdentifier; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.servlet.CreateUsecaseHelper; import org.wyona.yanel.servlet.communication.HttpRequest; import org.wyona.yanel.servlet.communication.HttpResponse; import org.wyona.yanel.util.ResourceAttributeHelper; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.PolicyManager; import org.wyona.security.core.api.Role; import org.apache.log4j.Category; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class YanelServlet extends HttpServlet { private static Category log = Category.getInstance(YanelServlet.class); private ServletConfig config; ResourceTypeRegistry rtr; PolicyManager pm; IdentityManager im; Map map; Yanel yanel; File xsltFile; private static String IDENTITY_KEY = "identity"; private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_OPTIONS = "OPTIONS"; private static final String METHOD_GET = "GET"; private static final String METHOD_POST = "POST"; private static final String METHOD_PUT = "PUT"; private static final String METHOD_DELETE = "DELETE"; private String sslPort = null; public void init(ServletConfig config) throws ServletException { this.config = config; xsltFile = org.wyona.commons.io.FileUtil.file(config.getServletContext().getRealPath("/"), config.getInitParameter("exception-and-info-screen-xslt")); try { yanel = Yanel.getInstance(); yanel.init(); rtr = yanel.getResourceTypeRegistry(); pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager"); im = (IdentityManager) yanel.getBeanFactory().getBean("identityManager"); map = (Map) yanel.getBeanFactory().getBean("map"); //sslPort = "8443"; sslPort = config.getInitParameter("ssl-port"); } catch (Exception e) { log.error(e); throw new ServletException(e.getMessage(), e); } } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); String httpUserAgent = request.getHeader("User-Agent"); log.debug("HTTP User Agent: " + httpUserAgent); String httpAcceptLanguage = request.getHeader("Accept-Language"); log.debug("HTTP Accept Language: " + httpAcceptLanguage); // Logout from Yanel String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("logout")) { if(doLogout(request, response) != null) return; } // Authentication if(doAuthenticate(request, response) != null) return; // Check authorization if(doAuthorize(request, response) != null) return; // Delegate ... String method = request.getMethod(); if (method.equals(METHOD_PROPFIND)) { doPropfind(request, response); } else if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } else if (method.equals(METHOD_PUT)) { doPut(request, response); } else if (method.equals(METHOD_DELETE)) { doDelete(request, response); } else if (method.equals(METHOD_OPTIONS)) { doOptions(request, response); } else { log.error("No such method implemented: " + method); response.sendError(response.SC_NOT_IMPLEMENTED); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check if a new resource shall be created ... String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("create")) { CreateUsecaseHelper creator = new CreateUsecaseHelper(); creator.create(request, response, yanel); return; } getContent(request, response); } private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { View view = null; org.w3c.dom.Document doc = null; javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation(); org.w3c.dom.DocumentType doctype = null; doc = impl.createDocument("http: } catch(Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } Element rootElement = doc.getDocumentElement(); String servletContextRealPath = config.getServletContext().getRealPath("/"); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); //log.deubg("servletContextRealPath: " + servletContextRealPath); //log.debug("contextPath: " + request.getContextPath()); //log.debug("servletPath: " + request.getServletPath()); Element requestElement = (Element) rootElement.appendChild(doc.createElement("request")); requestElement.setAttribute("uri", request.getRequestURI()); requestElement.setAttribute("servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } Realm realm; Path path; ResourceTypeIdentifier rti; try { realm = map.getRealm(request.getServletPath()); path = map.getPath(realm, request.getServletPath()); rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path); } catch (Exception e) { String message = "URL could not be mapped to realm/path " + e.getMessage(); log.error(message, e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } //String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); Resource res = null; long lastModified = -1; long size = -1; if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti.getUniversalName()); if (rtd == null) { String message = "No such resource type registered: " + rti.getUniversalName() + ", check " + rtr.getConfigurationFile(); log.error(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } Element rtiElement = (Element) rootElement.appendChild(doc.createElement("resource-type-identifier")); rtiElement.setAttribute("namespace", rtd.getResourceTypeNamespace()); rtiElement.setAttribute("local-name", rtd.getResourceTypeLocalName()); try { HttpRequest httpRequest = new HttpRequest(request); HttpResponse httpResponse = new HttpResponse(response); res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path, rtd, rti); if (res != null) { Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { log.info("Resource is viewable V1"); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV1) res).getViewDescriptors())); String viewId = request.getParameter("yanel.resource.viewid"); try { view = ((ViewableV1) res).getView(request, viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { // TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ... String message = "No such node exception: " + e; log.warn(e); //log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "404"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); setYanelOutput(request, response, doc); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { log.info("Resource is viewable V2"); String viewId = request.getParameter("yanel.resource.viewid"); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV2) res).getViewDescriptors())); size = ((ViewableV2) res).getSize(); Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size")); sizeElement.appendChild(doc.createTextNode(String.valueOf(size))); view = ((ViewableV2) res).getView(viewId); } else { Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable")); noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // retrieve the revisions, but only in the meta usecase (for performance reasons): if (request.getParameter("yanel.resource.meta") != null) { String[] revisions = ((VersionableV2)res).getRevisions(); Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions")); if (revisions != null) { for (int i=0; i<revisions.length; i++) { Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision")); revisionElement.appendChild(doc.createTextNode(revisions[i])); } } else { Element noRevisionsYetElement = (Element) resourceElement.appendChild(doc.createElement("no-revisions-yet")); } } } else { Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable")); } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else { Element noRTIFoundElement = (Element) rootElement.appendChild(doc.createElement("no-resource-type-identifier-found")); noRTIFoundElement.setAttribute("servlet-path", request.getServletPath()); } String usecase = request.getParameter("yanel.resource.usecase"); if (usecase != null && usecase.equals("checkout")) { log.debug("Checkout data ..."); // TODO: Implement checkout ... log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } String meta = request.getParameter("yanel.resource.meta"); if (meta != null) { if (meta.length() > 0) { log.error("DEBUG: meta length: " + meta.length()); } else { log.error("DEBUG: Show all meta"); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(request, response, doc); return; } if (view != null) { // check if the view contatins the response (otherwise assume that the resource // wrote the response, and just return). if (!view.isResponse()) return; response.setContentType(patchContentType(view.getMimeType(), request)); InputStream is = view.getInputStream(); //BufferedReader reader = new BufferedReader(new InputStreamReader(is)); //String line; //System.out.println("getContentXML: "+path); //while ((line = reader.readLine()) != null) System.out.println(line); byte buffer[] = new byte[8192]; int bytesRead; if (is != null) { // TODO: Yarep does not set returned Stream to null resp. is missing Exception Handling for the constructor. Exceptions should be handled here, but rather within Yarep or whatever repositary layer is being used ... bytesRead = is.read(buffer); if (bytesRead == -1) { String message = "InputStream of view does not seem to contain any data!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag String ifModifiedSince = request.getHeader("If-Modified-Since"); if (ifModifiedSince != null) { log.error("DEBUG: TODO: Implement 304 ..."); } java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified); return; } else { String message = "InputStream of view is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.info("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); if (contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); try { Resource atomEntry = rtr.newResource("<{http: atomEntry.setYanel(yanel); // TODO: Initiate Atom Feed Resource Type to get actual path for saving ... log.error("DEBUG: Atom Feed: " + request.getServletPath() + " " + request.getRequestURI()); Path entryPath = new Path(request.getServletPath() + "/" + new java.util.Date().getTime() + ".xml"); atomEntry.setPath(entryPath); ((ModifiableV2)atomEntry).write(in); byte buffer[] = new byte[8192]; int bytesRead; InputStream resourceIn = ((ModifiableV2)atomEntry).getInputStream(); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } getContent(request, response); } } /** * HTTP PUT implementation */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: Reuse code doPost resp. share code with doPut String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ...!"); // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); if (contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); try { Resource atomEntry = rtr.newResource("<{http: atomEntry.setYanel(yanel); log.error("DEBUG: Atom Entry: " + request.getServletPath() + " " + request.getRequestURI()); Path entryPath = new Path(request.getServletPath()); atomEntry.setPath(entryPath); // TODO: There seems to be a problem ... ((ModifiableV2)atomEntry).write(in); // NOTE: This method does not update updated date /* OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } */ log.info("Atom entry has been saved: " + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } else { save(request, response); /* log.warn("TODO: WebDAV PUT ..."); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); return; */ } } } /** * HTTP DELETE implementation */ public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Resource res = getResource(request, response); res.setPath(new Path(request.getServletPath())); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { if (((ModifiableV2) res).delete()) { log.debug("Resource has been deleted: " + res); response.setStatus(response.SC_OK); return; } else { log.warn("Resource could not be deleted: " + res); response.setStatus(response.SC_FORBIDDEN); return; } } else { log.error("Resource '" + res + "' has interface ModifiableV2 not implemented." ); response.sendError(response.SC_NOT_IMPLEMENTED); return; } } catch (Exception e) { log.error("Could not delete resource with URL " + request.getRequestURL() + " " + e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } private Resource getResource(HttpServletRequest request, HttpServletResponse response) { try { Realm realm = map.getRealm(request.getServletPath()); Path path = map.getPath(realm, request.getServletPath()); HttpRequest httpRequest = new HttpRequest(request); HttpResponse httpResponse = new HttpResponse(response); Resource res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path); return res; } catch(Exception e) { log.error(e.getMessage(), e); return null; } } /** * Save data */ private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Save data ..."); InputStream in = request.getInputStream(); java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); // Check on well-formedness ... String contentType = request.getContentType(); log.debug("Content-Type: " + contentType); if (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0) { log.info("Check well-formedness ..."); javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); // TODO: Get log messages into log4j ... //parser.setErrorHandler(...); // NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also // if isValidating is set to false. // Hence, for performance and network reasons we use a local catalog ... // TODO: What about a resolver factory? parser.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); parser.parse(new java.io.ByteArrayInputStream(memBuffer)); //org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer)); } catch (org.xml.sax.SAXException e) { log.warn("Data is not well-formed: "+e.getMessage()); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Data is not well-formed: "+e.getMessage()+"</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { log.error(e.getMessage(), e); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: //sb.append("<message>" + e.getStackTrace() + "</message>"); //sb.append("<message>" + e.getMessage() + "</message>"); sb.append("<message>" + e + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } log.info("Data seems to be well-formed :-)"); } else { log.info("No well-formedness check required for content type: " + contentType); } java.io.ByteArrayInputStream memIn = new java.io.ByteArrayInputStream(memBuffer); // IMPORTANT TODO: Use ModifiableV2.write(InputStream in) such that resource can modify data during saving resp. check if getOutputStream is equals null and then use write .... OutputStream out = null; Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); write(memIn, out, request, response); return; } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { try { out = ((ModifiableV2) res).getOutputStream(); if (out != null) { write(memIn, out, request, response); } else { ((ModifiableV2) res).write(memIn); } return; } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } else { String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!"; log.warn(message); StringBuffer sb = new StringBuffer(); // TODO: Differentiate between Neutron based and other clients ... sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>" + message + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } } /** * Authorize request (and also authenticate for HTTP BASIC) */ private HttpServletResponse doAuthorize(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Role role = null; // TODO: Replace hardcoded roles by mapping between roles amd query strings ... String value = request.getParameter("yanel.resource.usecase"); String contentType = request.getContentType(); String method = request.getMethod(); if (value != null && value.equals("save")) { log.debug("Save data ..."); role = new Role("write"); } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); role = new Role("write"); } else if (value != null && value.equals("checkout")) { log.debug("Checkout data ..."); role = new Role("open"); } else if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) { // TODO: Is posting atom entries different from a general post (see below)?! log.error("DEBUG: Write/Checkin Atom entry ..."); role = new Role("write"); } else if (method.equals(METHOD_PUT) || method.equals(METHOD_POST)) { log.error("DEBUG: Upload data ..."); role = new Role("write"); } else if (method.equals(METHOD_DELETE)) { log.error("DEBUG: Delete resource ..."); role = new Role("delete"); } else { log.debug("Role will be 'view'!"); role = new Role("view"); } value = request.getParameter("yanel.usecase"); if (value != null && value.equals("create")) { log.debug("Create new resource ..."); role = new Role("create"); } boolean authorized = false; Realm realm = map.getRealm(new Path(request.getServletPath())); // HTTP BASIC Authorization (For clients such as for instance Sunbird, OpenOffice or cadaver) // IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling String authorization = request.getHeader("Authorization"); log.debug("Checking for Authorization Header: " + authorization); if (authorization != null) { if (authorization.toUpperCase().startsWith("BASIC")) { log.debug("Using BASIC authorization ..."); // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorization.substring(6); // Decode it, using any base 64 decoder sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); log.debug("Username and Password Decoded: " + userpassDecoded); String[] up = userpassDecoded.split(":"); String username = up[0]; String password = up[1]; log.debug("username: " + username + ", password: " + password); if (im.authenticate(username, password, realm.getID())) { authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), new Identity(username, null), new Role("view")); if(authorized) { return null; } else { log.warn("HTTP BASIC Authorization failed for " + username + "!"); response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(response.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authorization Failed!"); return response; } } else { log.warn("HTTP BASIC Authentication failed for " + username + "!"); response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(response.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authentication Failed!"); return response; } } else if (authorization.toUpperCase().startsWith("DIGEST")) { log.error("DIGEST is not implemented"); authorized = false; response.sendError(response.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "DIGEST realm=\"" + realm.getName() + "\""); PrintWriter writer = response.getWriter(); writer.print("DIGEST is not implemented!"); return response; } else { log.warn("No such authorization implemented resp. handled by session based authorization: " + authorization); authorized = false; } } // Custom Authorization log.debug("Do session based custom authorization"); //String[] groupnames = {"null", "null"}; HttpSession session = request.getSession(true); Identity identity = (Identity) session.getAttribute(IDENTITY_KEY); if (identity == null) { log.debug("Identity is WORLD"); identity = new Identity(); } authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), identity, role); if(!authorized) { log.warn("Access denied: " + getRequestURLQS(request, null, false)); if(!request.isSecure()) { if(sslPort != null) { log.info("Redirect to SSL ..."); try { URL url = new URL(getRequestURLQS(request, null, false).toString()); url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); response.setHeader("Location", url.toString()); // TODO: Yulup has a bug re TEMPORARY_REDIRECT //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); return response; } catch (Exception e) { log.error(e); } } else { log.warn("SSL does not seem to be configured!"); } } // TODO: Shouldn't this be here instead at the beginning of service() ...? //if(doAuthenticate(request, response) != null) return response; // Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request StringBuffer sb = new StringBuffer(""); String neutronVersions = request.getHeader("Neutron"); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { log.debug("Neutron Versions supported by client: " + neutronVersions); log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true) + "</message>"); sb.append("<authentication>"); sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true) + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter w = response.getWriter(); w.print(sb); } else if (request.getRequestURI().endsWith(".ics")) { log.warn("Somebody seems to ask for a Calendar (ICS) ..."); response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(response.SC_UNAUTHORIZED); } else { getXHTMLAuthenticationForm(request, response, realm, null); } return response; } else { log.info("Access granted: " + getRequestURLQS(request, null, false)); return null; } } private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) { Realm realm = map.getRealm(new Path(request.getServletPath())); // TODO: Handle this exception more gracefully! if (realm == null) log.error("No realm found for path " + new Path(request.getServletPath())); String proxyHostName = realm.getProxyHostName(); String proxyPort = realm.getProxyPort(); String proxyPrefix = realm.getProxyPrefix(); URL url = null; try { url = new URL(request.getRequestURL().toString()); if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } if (proxyPort != null) { if (proxyPort.length() > 0) { url = new URL(url.getProtocol(), url.getHost(), new Integer(proxyPort).intValue(), url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } if(proxyHostName != null || proxyPort != null || proxyPrefix != null) { log.debug("Proxy enabled request: " + url); } } catch (Exception e) { log.error(e); } String urlQS = url.toString(); if (request.getQueryString() != null) { urlQS = urlQS + "?" + request.getQueryString(); if (addQS != null) urlQS = urlQS + "&" + addQS; } else { if (addQS != null) urlQS = urlQS + "?" + addQS; } if (xml) urlQS = urlQS.replaceAll("&", "&amp;"); log.debug("Request: " + urlQS); return urlQS; } public void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String depth = request.getHeader("Depth"); log.error("DEBUG: Depth: " + depth); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<multistatus xmlns=\"DAV:\">"); if (depth.equals("0")) { // TODO: decide if the requested node is a collection or a resource sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype><collection/></resourcetype>"); sb.append(" <getcontenttype>http/unix-directory</getcontenttype>"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); /* sb.append(" <response>"); sb.append(" <href>/yanel/yanel-website/roadmap.html</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype/>"); sb.append(" </prop>"); sb.append(" </propstat>"); sb.append(" </response>"); */ } else if (depth.equals("1")) { log.warn("TODO: List childen of this node"); } else if (depth.equals("infinity")) { log.warn("TODO: List childen and their children and their childre ..."); } else { log.error("No such depth: " + depth); } sb.append("</multistatus>"); //response.setStatus(javax.servlet.http.HttpServletResponse.SC_MULTI_STATUS); response.setStatus(207, "Multi-Status"); PrintWriter w = response.getWriter(); w.print(sb); } public void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("DAV", "1"); // TODO: Is there anything else to do?! } /** * Authentication * @return null when authentication successful, otherwise return response */ public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Realm realm = map.getRealm(new Path(request.getServletPath())); // HTML Form based authentication String loginUsername = request.getParameter("yanel.login.username"); if(loginUsername != null) { HttpSession session = request.getSession(true); if (im.authenticate(loginUsername, request.getParameter("yanel.login.password"), realm.getID())) { log.debug("Realm: " + realm); session.setAttribute(IDENTITY_KEY, new Identity(loginUsername, null)); return null; } else { log.warn("Login failed: " + loginUsername); getXHTMLAuthenticationForm(request, response, realm, "Login failed!"); return response; } } // Neutron-Auth based authentication String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) { log.debug("Neutron Authentication ..."); String username = null; String password = null; String originalRequest = null; DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(); try { Configuration config = builder.build(request.getInputStream()); Configuration originalRequestConfig = config.getChild("original-request"); originalRequest = originalRequestConfig.getAttribute("url", null); Configuration[] paramConfig = config.getChildren("param"); for (int i = 0; i < paramConfig.length; i++) { String paramName = paramConfig[i].getAttribute("name", null); if (paramName != null) { if (paramName.equals("username")) { username = paramConfig[i].getValue(); } else if (paramName.equals("password")) { password = paramConfig[i].getValue(); } } } } catch(Exception e) { log.warn(e); } log.debug("Username: " + username); if (username != null) { HttpSession session = request.getSession(true); log.debug("Realm ID: " + realm.getID()); if (im.authenticate(username, password, realm.getID())) { log.info("Authentication successful: " + username); session.setAttribute(IDENTITY_KEY, new Identity(username, null)); // TODO: send some XML content, e.g. <authentication-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Authentication Successful!"); return response; } else { log.warn("Neutron Authentication failed: " + username); // TODO: Refactor this code with the one from doAuthenticate ... log.debug("Original Request: " + originalRequest); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter w = response.getWriter(); w.print(sb); return response; } } else { // TODO: Refactor resp. reuse response from above ... log.warn("Neutron Authentication failed because username is NULL!"); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed because no username was sent!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter writer = response.getWriter(); writer.print(sb); return response; } } else { log.debug("Neutron Authentication successful."); return null; } } public HttpServletResponse doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("Logout from Yanel ..."); HttpSession session = request.getSession(true); session.setAttribute(IDENTITY_KEY, null); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { // TODO: send some XML content, e.g. <logout-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Logout Successful!"); return response; } return null; } public String patchContentType(String contentType, HttpServletRequest request) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); if (contentType != null && contentType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) { log.error("DEBUG: Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml"); return "text/html"; } return contentType; } /** * Intercept InputStream and log content ... */ public InputStream intercept(InputStream in) throws IOException { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); log.error("DEBUG: InputStream: " + baos); return new java.io.ByteArrayInputStream(memBuffer); } private void setYanelOutput(HttpServletRequest request, HttpServletResponse response, Document doc) throws ServletException { try { String yanelFormat = request.getParameter("yanel.format"); if(yanelFormat != null && yanelFormat.equals("xml")) { response.setContentType("application/xml"); OutputStream out = response.getOutputStream(); javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); out.close(); } else { response.setContentType("application/xhtml+xml"); Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFile)); transformer.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(response.getWriter())); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } } /** * Custom XHTML Form for authentication */ public void getXHTMLAuthenticationForm(HttpServletRequest request, HttpServletResponse response, Realm realm, String message) throws ServletException, IOException { // TODO: Use configurable XSLT for layout, whereas each realm should be able to overwrite ... StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http: sb.append("<body>"); if (message != null) { sb.append("<p>NOTE: " + message + "</p>"); } sb.append("<p>Authorization denied: " + getRequestURLQS(request, null, true) + "</p>"); sb.append("<p>Enter username and password for realm \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\" (Context Path: " + request.getContextPath() + ")</p>"); sb.append("<form method=\"POST\">"); sb.append("<p>"); sb.append("<table>"); sb.append("<tr><td>Username:</td><td>&#160;</td><td><input type=\"text\" name=\"yanel.login.username\"/></td></tr>"); sb.append("<tr><td>Password:</td><td>&#160;</td><td><input type=\"password\" name=\"yanel.login.password\"/></td></tr>"); sb.append("<tr><td colspan=\"2\">&#160;</td><td align=\"right\"><input type=\"submit\" value=\"Login\"/></td></tr>"); sb.append("</table>"); sb.append("</p>"); sb.append("</form>"); sb.append("</body>"); sb.append("</html>"); response.setContentType("application/xhtml+xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); PrintWriter w = response.getWriter(); w.print(sb); } /** * Write to output stream of modifiable resource */ private void write(InputStream in, OutputStream out, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (out != null) { log.debug("Content-Type: " + request.getContentType()); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); out.close(); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml"); PrintWriter w = response.getWriter(); w.print(sb); log.info("Data has been saved ..."); return; } else { log.error("OutputStream is null!"); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Exception: OutputStream is null!</p>"); sb.append("</body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xhtml+xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } }
package org.homelinux.murray.scorekeep; import java.util.ArrayList; import org.homelinux.murray.scorekeep.provider.Player; import org.homelinux.murray.scorekeep.provider.Score; import android.app.AlertDialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.net.Uri; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.LinearLayout; public final class PlayerData implements OnClickListener { private static final String DEBUG_TAG = "ScoreKeep:PlayerData"; final long id; final String name; final long color; final GameData game; private long total; private String currentContext = null; private final ArrayList<ScoreData> scores = new ArrayList<ScoreData>(); private final Context appContext; /** * Load player data from the DB with scores from a game * * @param context The context to run a query * @param playerId Unique player identifier * @param gameId Unique id for game to get scores from */ public PlayerData(Context context, long playerId, GameData game) { id = playerId; this.game = game; appContext = context.getApplicationContext(); Cursor pc = appContext.getContentResolver().query(ContentUris.withAppendedId(Player.CONTENT_ID_URI_BASE, playerId), null, null, null, null); pc.moveToFirst(); name = pc.getString(pc.getColumnIndex(Player.COLUMN_NAME_NAME)); color = pc.getLong(pc.getColumnIndex(Player.COLUMN_NAME_COLOR)); String selection = Score.COLUMN_NAME_GAME_ID + "=" + game.id + " AND " + Score.COLUMN_NAME_PLAYER_ID + "=" + playerId; Cursor sc = appContext.getContentResolver().query(Score.CONTENT_URI, null, selection, null, null); int scoreColumn = sc.getColumnIndex(Score.COLUMN_NAME_SCORE); int idColumn = sc.getColumnIndex(Score._ID); int contextColumn = sc.getColumnIndex(Score.COLUMN_NAME_CONTEXT); int createdColumn = sc.getColumnIndex(Score.COLUMN_NAME_CREATE_DATE); total = 0; //TODO starting score long id, created; Long score; String scoreContext = null; while(sc.moveToNext()) { id = sc.getLong(idColumn); if(sc.isNull(scoreColumn)) { score = null; } else { score = new Long(sc.getLong(scoreColumn)); } if(!sc.isNull(contextColumn)) { scoreContext = sc.getString(contextColumn); currentContext = scoreContext; } created = sc.getLong(createdColumn); scores.add(new ScoreData(id, score, scoreContext, created)); total += score; } } public long addScore(long score) { return addScoreAndContext(Long.toString(score), null); } public void addContext(String context) { addScoreAndContext(null,context); } public long addScoreAndContext(String score, String context) { // insert to the DB ContentValues values = new ContentValues(); values.put(Score.COLUMN_NAME_GAME_ID, game.id); values.put(Score.COLUMN_NAME_PLAYER_ID, id); Long scoreObject = null; if(score==null&&context==null) { Log.d(DEBUG_TAG, "Score and Context are null, WTH?"); } if(score != null) { long ls = evaluate(score); scoreObject = new Long(ls); values.put(Score.COLUMN_NAME_SCORE, ls); } if(context != null) { values.put(Score.COLUMN_NAME_CONTEXT, context); currentContext = context; } Long now = Long.valueOf(System.currentTimeMillis()); values.put(Score.COLUMN_NAME_CREATE_DATE, now); Uri uri = appContext.getContentResolver().insert(Score.CONTENT_URI, values); // add to history scores.add(new ScoreData(ContentUris.parseId(uri), scoreObject, context, now)); // add to total total += total; game.notifyDataSetChanged(); return total; } /** * Evaluates the string as a math formula * * @param math Math formula to evaluate * @return returns result */ private static long evaluate(String math) { MathEval me = new MathEval(); double result = me.evaluate(math); return Math.round(result); } public long getTotal() { return total; } public String getCurrentContext() { return currentContext; } public void onClick(View v) { int vid = v.getId(); switch(vid) { case R.id.badge_add: final AlertDialog.Builder addScoreDialog = new AlertDialog.Builder(v.getContext()); addScoreDialog.setTitle("Enter Score"); LinearLayout ll = new LinearLayout(v.getContext()); ll.setOrientation(LinearLayout.VERTICAL); final EditText scoreInput = new EditText(v.getContext()); scoreInput.setHint("Score"); ll.addView(scoreInput); final EditText contextText = new EditText(v.getContext()); contextText.setHint("Context"); ll.addView(contextText); addScoreDialog.setView(ll); addScoreDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = scoreInput.getText().toString().trim(); addScoreAndContext(value, contextText.getText().toString()); } }); addScoreDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); addScoreDialog.show(); return; case R.id.badge_history: System.out.println("Score History button clicked."); } } }
package org.jgroups.blocks; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.ChannelException; import org.jgroups.MembershipListener; import org.jgroups.View; import org.jgroups.Address; import org.jgroups.blocks.VotingAdapter.FailureVoteResult; import org.jgroups.blocks.VotingAdapter.VoteResult; import org.jgroups.util.Rsp; import org.jgroups.util.RspList; import java.io.Serializable; import java.util.*; /** * Distributed lock manager is responsible for maintaining the lock information * consistent on all participating nodes. * * @author Roman Rokytskyy (rrokytskyy@acm.org) * @author Robert Schaffar-Taurok (robert@fusion.at) * @version $Id: DistributedLockManager.java,v 1.8 2006/08/15 09:18:53 belaban Exp $ */ public class DistributedLockManager implements TwoPhaseVotingListener, LockManager, VoteResponseProcessor, MembershipListener { /** * Definitions for the implementation of the VoteResponseProcessor */ private static final int PROCESS_CONTINUE = 0; private static final int PROCESS_SKIP = 1; private static final int PROCESS_BREAK = 2; /** * This parameter means that lock acquisition expires after 5 seconds. * If there were no "commit" operation on prepared lock, then it * is treated as expired and is removed from the prepared locks table. */ private static final long ACQUIRE_EXPIRATION = 5000; /** * This parameter is used during lock releasing. If group fails to release * the lock during the specified period of time, unlocking fails. */ private static final long VOTE_TIMEOUT = 10000; /** HashMap<Object,LockDecree>. List of all prepared locks */ private final HashMap preparedLocks = new HashMap(); /** HashMap<Object,LockDecree>. List of all prepared releases */ private final HashMap preparedReleases = new HashMap(); /* HashMap<Object,LockDecree>. List of locks on the node */ private final HashMap heldLocks = new HashMap(); private final TwoPhaseVotingAdapter votingAdapter; private final Object id; final Vector current_members=new Vector(); protected final Log log=LogFactory.getLog(getClass()); /** * Create instance of this class. * * @param voteChannel instance of {@link VotingAdapter} that will be used * for voting purposes on the lock decrees. <tt>voteChannel()</tt> will * be wrapped by the instance of the {@link TwoPhaseVotingAdapter}. * * @param id the unique identifier of this lock manager. * * todo check if the node with the same id is already in the group. */ public DistributedLockManager(VotingAdapter voteChannel, Object id) { this(new TwoPhaseVotingAdapter(voteChannel), id); } /** * Constructor for the DistributedLockManager_cl object. * * @param channel instance of {@link TwoPhaseVotingAdapter} * that will be used for voting purposes on the lock decrees. * * @param id the unique identifier of this lock manager. * * @todo check if the node with the same id is already in the group. */ public DistributedLockManager(TwoPhaseVotingAdapter channel, Object id) { this.id = id; this.votingAdapter = channel; this.votingAdapter.addListener(this); if(votingAdapter != null && votingAdapter.getVoteChannel() != null) votingAdapter.getVoteChannel().addMembershipListener(this); setInitialMembership(votingAdapter.getVoteChannel().getMembers()); } private void setInitialMembership(Collection members) { if(members != null) { current_members.clear(); current_members.addAll(members); } } /** * Performs local lock. This method also performs the clean-up of the lock * table, all expired locks are removed. */ private boolean localLock(LockDecree lockDecree) { // remove expired locks removeExpired(lockDecree); LockDecree localLock = (LockDecree) heldLocks.get(lockDecree.getKey()); if (localLock == null) { // promote lock into commited state lockDecree.commit(); // no lock exist, perform local lock, note: // we do not store locks that were requested by other manager. if (lockDecree.managerId.equals(id)) heldLocks.put(lockDecree.getKey(), lockDecree); // everything is fine :) return true; } else return localLock.requester.equals(lockDecree.requester); } /** * Returns <code>true</code> if the requested lock can be granted by the * current node. * * @param decree instance of <code>LockDecree</code> containing information * about the lock. */ private boolean canLock(LockDecree decree) { // clean expired locks removeExpired(decree); LockDecree lock = (LockDecree)heldLocks.get(decree.getKey()); if (lock == null) return true; else return lock.requester.equals(decree.requester); } /** * Returns <code>true</code> if the requested lock can be released by the * current node. * * @param decree instance of {@link LockDecree} containing information * about the lock. */ private boolean canRelease(LockDecree decree) { // clean expired locks removeExpired(decree); // we need to check only hold locks, because // prepared locks cannot contain the lock LockDecree lock = (LockDecree)heldLocks.get(decree.getKey()); if (lock == null) // check if this holds... return true; else return lock.requester.equals(decree.requester); } /** * Removes expired locks. * * @param decree instance of {@link LockDecree} describing the lock. */ private void removeExpired(LockDecree decree) { // remove the invalid (expired) lock LockDecree localLock = (LockDecree)heldLocks.get(decree.getKey()); if (localLock != null && !localLock.isValid()) heldLocks.remove(localLock.getKey()); } /** * Releases lock locally. * * @param lockDecree instance of {@link LockDecree} describing the lock. */ private boolean localRelease(LockDecree lockDecree) { // remove expired locks removeExpired(lockDecree); LockDecree localLock= (LockDecree) heldLocks.get(lockDecree.getKey()); if(localLock == null) { // no lock exist return true; } else if(localLock.requester.equals(lockDecree.requester)) { // requester owns the lock, release the lock heldLocks.remove(lockDecree.getKey()); return true; } else // lock does not belong to requester return false; } /** * Locks an object with <code>lockId</code> on behalf of the specified * <code>owner</code>. * * @param lockId <code>Object</code> representing the object to be locked. * @param owner object that requests the lock. This should be the Address of a JGroups member, otherwise we cannot * release the locks for a crashed member ! * @param timeout time during which group members should decide * whether to grant a lock or not. * * @throws LockNotGrantedException when the lock cannot be granted. * * @throws ClassCastException if lockId or owner are not serializable. * * @throws ChannelException if something bad happened to underlying channel. */ public void lock(Object lockId, Object owner, int timeout) throws LockNotGrantedException, ChannelException { if (!(lockId instanceof Serializable) || !(owner instanceof Serializable)) throw new ClassCastException("DistributedLockManager works only with serializable objects."); boolean acquired = votingAdapter.vote( new AcquireLockDecree(lockId, owner, id), timeout); if (!acquired) throw new LockNotGrantedException("Lock " + lockId + " cannot be granted."); } /** * Unlocks an object with <code>lockId</code> on behalf of the specified * <code>owner</code>. * * since 2.2.9 this method is only a wrapper for * unlock(Object lockId, Object owner, boolean releaseMultiLocked). * Use that with releaseMultiLocked set to true if you want to be able to * release multiple locked locks (for example after a merge) * * @param lockId <code>long</code> representing the object to be unlocked. * @param owner object that releases the lock. * * @throws LockNotReleasedException when the lock cannot be released. * @throws ClassCastException if lockId or owner are not serializable. * */ public void unlock(Object lockId, Object owner) throws LockNotReleasedException, ChannelException { try { unlock(lockId, owner, false, VOTE_TIMEOUT); } catch (LockMultiLockedException e) { // This should never happen when releaseMultiLocked is false log.error("Caught MultiLockedException but releaseMultiLocked is false", e); } } public void unlock(Object lockId, Object owner, long timeout) throws LockNotReleasedException, ChannelException { try { unlock(lockId, owner, false, timeout); } catch (LockMultiLockedException e) { // This should never happen when releaseMultiLocked is false log.error("Caught MultiLockedException but releaseMultiLocked is false", e); } } /** * Unlocks an object with <code>lockId</code> on behalf of the specified * <code>owner</code>. * @param lockId <code>long</code> representing the object to be unlocked. * @param owner object that releases the lock. * @param releaseMultiLocked releases also multiple locked locks. (eg. locks that are locked by another DLM after a merge) * * @throws LockNotReleasedException when the lock cannot be released. * @throws ClassCastException if lockId or owner are not serializable. * @throws LockMultiLockedException if releaseMultiLocked is true and a multiple locked lock has been released. */ public void unlock(Object lockId, Object owner, boolean releaseMultiLocked) throws LockNotReleasedException, ChannelException, LockMultiLockedException { unlock(lockId, owner, releaseMultiLocked, VOTE_TIMEOUT); } public void unlock(Object lockId, Object owner, boolean releaseMultiLocked, long timeout) throws LockNotReleasedException, ChannelException, LockMultiLockedException { if (!(lockId instanceof Serializable) || !(owner instanceof Serializable)) throw new ClassCastException("DistributedLockManager " + "works only with serializable objects."); ReleaseLockDecree releaseLockDecree = new ReleaseLockDecree(lockId, owner, id); boolean released = false; if (releaseMultiLocked) { released = votingAdapter.vote(releaseLockDecree, timeout, this); if (releaseLockDecree.isMultipleLocked()) { throw new LockMultiLockedException("Lock was also locked by other DistributedLockManager(s)"); } } else { released = votingAdapter.vote(releaseLockDecree, timeout); } if (!released) throw new LockNotReleasedException("Lock cannot be unlocked."); } /** * Checks the list of prepared locks/unlocks to determine if we are in the * middle of the two-phase commit process for the lock acqusition/release. * Here we do not tolerate if the request comes from the same node on behalf * of the same owner. * * @param preparedContainer either <code>preparedLocks</code> or * <code>preparedReleases</code> depending on the situation. * * @param requestedDecree instance of <code>LockDecree</code> representing * the lock. */ private boolean checkPrepared(HashMap preparedContainer, LockDecree requestedDecree) { LockDecree preparedDecree = (LockDecree)preparedContainer.get(requestedDecree.getKey()); // if prepared lock is not valid, remove it from the list if ((preparedDecree != null) && !preparedDecree.isValid()) { preparedContainer.remove(preparedDecree.getKey()); preparedDecree = null; } if (preparedDecree != null) { return requestedDecree.requester.equals(preparedDecree.requester); } else // it was not prepared... sorry... return true; } /** * Prepare phase for the lock acquisition or release. * * @param decree should be an instance <code>LockDecree</code>, if not, * we throw <code>VoteException</code> to be ignored by the * <code>VoteChannel</code>. * * @return <code>true</code> when preparing the lock operation succeeds. * * @throws VoteException if we should be ignored during voting. */ public synchronized boolean prepare(Object decree) throws VoteException { if (!(decree instanceof LockDecree)) throw new VoteException("Uknown decree type. Ignore me."); if (decree instanceof AcquireLockDecree) { AcquireLockDecree acquireDecree = (AcquireLockDecree)decree; if(log.isDebugEnabled()) log.debug("Preparing to acquire decree " + acquireDecree.lockId); if (!checkPrepared(preparedLocks, acquireDecree)) // there is a prepared lock owned by third party return false; if (canLock(acquireDecree)) { preparedLocks.put(acquireDecree.getKey(), acquireDecree); return true; } else // we are unable to aquire local lock return false; } else if (decree instanceof ReleaseLockDecree) { ReleaseLockDecree releaseDecree = (ReleaseLockDecree)decree; if(log.isDebugEnabled()) log.debug("Preparing to release decree " + releaseDecree.lockId); if (!checkPrepared(preparedReleases, releaseDecree)) // there is a prepared release owned by third party return false; if (canRelease(releaseDecree)) { preparedReleases.put(releaseDecree.getKey(), releaseDecree); // we have local lock and the prepared lock return true; } else // we were unable to aquire local lock return false; } else if (decree instanceof MultiLockDecree) { // Here we abuse the voting mechanism for notifying the other lockManagers of multiple locked objects. MultiLockDecree multiLockDecree = (MultiLockDecree)decree; if(log.isDebugEnabled()) { log.debug("Marking " + multiLockDecree.getKey() + " as multilocked"); } LockDecree lockDecree = (LockDecree)heldLocks.get(multiLockDecree.getKey()); if (lockDecree != null) { lockDecree.setMultipleLocked(true); } return true; } // we should not be here return false; } /** * Commit phase for the lock acquisition or release. * * @param decree should be an instance <code>LockDecree</code>, if not, * we throw <code>VoteException</code> to be ignored by the * <code>VoteChannel</code>. * * @return <code>true</code> when commiting the lock operation succeeds. * * @throws VoteException if we should be ignored during voting. */ public synchronized boolean commit(Object decree) throws VoteException { if (!(decree instanceof LockDecree)) throw new VoteException("Uknown decree type. Ignore me."); if (decree instanceof AcquireLockDecree) { if(log.isDebugEnabled()) log.debug("Committing decree acquisition " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedLocks, (LockDecree)decree)) // there is a prepared lock owned by third party return false; if (localLock((LockDecree)decree)) { preparedLocks.remove(((LockDecree)decree).getKey()); return true; } else return false; } else if (decree instanceof ReleaseLockDecree) { if(log.isDebugEnabled()) log.debug("Committing decree release " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedReleases, (LockDecree)decree)) // there is a prepared release owned by third party return false; if (localRelease((LockDecree)decree)) { preparedReleases.remove(((LockDecree)decree).getKey()); return true; } else return false; } else if (decree instanceof MultiLockDecree) { return true; } // we should not be here return false; } /** * Abort phase for the lock acquisition or release. * * @param decree should be an instance <code>LockDecree</code>, if not, * we throw <code>VoteException</code> to be ignored by the * <code>VoteChannel</code>. * * @throws VoteException if we should be ignored during voting. */ public synchronized void abort(Object decree) throws VoteException { if (!(decree instanceof LockDecree)) throw new VoteException("Uknown decree type. Ignore me."); if (decree instanceof AcquireLockDecree) { if(log.isDebugEnabled()) log.debug("Aborting decree acquisition " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedLocks, (LockDecree)decree)) // there is a prepared lock owned by third party return; preparedLocks.remove(((LockDecree)decree).getKey()); } else if (decree instanceof ReleaseLockDecree) { if(log.isDebugEnabled()) log.debug("Aborting decree release " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedReleases, (LockDecree)decree)) // there is a prepared release owned by third party return; preparedReleases.remove(((LockDecree)decree).getKey()); } } /** * Processes the response list and votes like the default processResponses method with the consensusType VOTE_ALL * If the result of the voting is false, but this DistributedLockManager owns the lock, the result is changed to * true and the lock is released, but marked as multiple locked. (only in the prepare state to reduce traffic) * <p> * Note: we do not support voting in case of Byzantine failures, i.e. * when the node responds with the fault message. */ public boolean processResponses(RspList responses, int consensusType, Object decree) throws ChannelException { if (responses == null) { return false; } int totalPositiveVotes = 0; int totalNegativeVotes = 0; for (int i = 0; i < responses.size(); i++) { Rsp response = (Rsp) responses.elementAt(i); switch (checkResponse(response)) { case PROCESS_SKIP: continue; case PROCESS_BREAK: return false; } VoteResult result = (VoteResult) response.getValue(); totalPositiveVotes += result.getPositiveVotes(); totalNegativeVotes += result.getNegativeVotes(); } boolean voteResult = (totalNegativeVotes == 0 && totalPositiveVotes > 0); if (decree instanceof TwoPhaseVotingAdapter.TwoPhaseWrapper) { TwoPhaseVotingAdapter.TwoPhaseWrapper wrappedDecree = (TwoPhaseVotingAdapter.TwoPhaseWrapper)decree; if (wrappedDecree.isPrepare()) { Object unwrappedDecree = wrappedDecree.getDecree(); if (unwrappedDecree instanceof ReleaseLockDecree) { ReleaseLockDecree releaseLockDecree = (ReleaseLockDecree)unwrappedDecree; LockDecree lock = null; if ((lock = (LockDecree)heldLocks.get(releaseLockDecree.getKey())) != null) { // If there is a local lock... if (!voteResult) { // ... and another DLM voted negatively, but this DLM owns the lock // we inform the other node, that it's lock is multiple locked if (informLockingNodes(releaseLockDecree)) { // we set the local lock to multiple locked lock.setMultipleLocked(true); voteResult = true; } } if (lock.isMultipleLocked()) { //... and the local lock is marked as multilocked // we mark the releaseLockDecree als multiple locked for evaluation when unlock returns releaseLockDecree.setMultipleLocked(true); } } } } } return voteResult; } /** * This method checks the response and says the processResponses() method * what to do. * @return PROCESS_CONTINUE to continue calculating votes, * PROCESS_BREAK to stop calculating votes from the nodes, * PROCESS_SKIP to skip current response. * @throws ChannelException when the response is fatal to the * current voting process. */ private int checkResponse(Rsp response) throws ChannelException { if (!response.wasReceived()) { if (log.isDebugEnabled()) log.debug("Response from node " + response.getSender() + " was not received."); throw new ChannelException("Node " + response.getSender() + " failed to respond."); } if (response.wasSuspected()) { if (log.isDebugEnabled()) log.debug("Node " + response.getSender() + " was suspected."); return PROCESS_SKIP; } Object object = response.getValue(); // we received exception/error, something went wrong // on one of the nodes... and we do not handle such faults if (object instanceof Throwable) { throw new ChannelException("Node " + response.getSender() + " is faulty."); } if (object == null) { return PROCESS_SKIP; } // it is always interesting to know the class that caused failure... if (!(object instanceof VoteResult)) { String faultClass = object.getClass().getName(); // ...but we do not handle byzantine faults throw new ChannelException("Node " + response.getSender() + " generated fault (class " + faultClass + ')'); } // what if we received the response from faulty node? if (object instanceof FailureVoteResult) { if (log.isErrorEnabled()) log.error(((FailureVoteResult) object).getReason()); return PROCESS_BREAK; } // everything is fine :) return PROCESS_CONTINUE; } private boolean informLockingNodes(ReleaseLockDecree releaseLockDecree) throws ChannelException { return votingAdapter.vote(new MultiLockDecree(releaseLockDecree), VOTE_TIMEOUT); } /** Remove all locks held by members who left the previous view */ public void viewAccepted(View new_view) { Vector prev_view=new Vector(current_members); current_members.clear(); current_members.addAll(new_view.getMembers()); System.out.println("-- VIEW: " + current_members + ", old view: " + prev_view); prev_view.removeAll(current_members); if(prev_view.size() > 0) { // we have left members, so we need to check for locks which are still held by them for(Iterator it=prev_view.iterator(); it.hasNext();) { Object mbr=it.next(); removeLocksHeldBy(preparedLocks, mbr); removeLocksHeldBy(preparedReleases, mbr); removeLocksHeldBy(heldLocks, mbr); } } } /** Remove from preparedLocks, preparedReleases and heldLocks */ private void removeLocksHeldBy(Map lock_table, Object mbr) { Map.Entry entry; LockDecree val; Object holder; for(Iterator it=lock_table.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); val=(LockDecree)entry.getValue(); holder=val.requester; if(holder != null && holder.equals(mbr)) { if(log.isTraceEnabled()) log.trace("removing a leftover lock held by " + mbr + " for " + entry.getKey() + ": " + val); it.remove(); } } } public void suspect(Address suspected_mbr) { } public void block() { } /** * This class represents the lock */ public static class LockDecree implements Serializable { protected final Object lockId; protected final Object requester; protected final Object managerId; protected boolean commited; private boolean multipleLocked = false; private static final long serialVersionUID = 7264104838035219212L; private LockDecree(Object lockId, Object requester, Object managerId) { this.lockId = lockId; this.requester = requester; this.managerId = managerId; } /** * Returns the key that should be used for Map lookup. */ public Object getKey() { return lockId; } /** * This is a place-holder for future lock expiration code. */ public boolean isValid() { return true; } public void commit() { this.commited = true; } /** * @return Returns the multipleLocked. */ public boolean isMultipleLocked() { return multipleLocked; } /** * @param multipleLocked The multipleLocked to set. */ public void setMultipleLocked(boolean multipleLocked) { this.multipleLocked = multipleLocked; } /** * This is hashcode from the java.lang.Long class. */ public int hashCode() { return lockId.hashCode(); } public boolean equals(Object other) { if (other instanceof LockDecree) { return ((LockDecree)other).lockId.equals(this.lockId); } else { return false; } } } /** * This class represents the lock to be released. */ public static class AcquireLockDecree extends LockDecree { private final long creationTime; private AcquireLockDecree(Object lockId, Object requester, Object managerId) { super(lockId, requester, managerId); this.creationTime = System.currentTimeMillis(); } /** * Lock aquire decree is valid for a <code>ACQUIRE_EXPIRATION</code> * time after creation and if the lock is still valid (in the * future locks will be leased for a predefined period of time). */ public boolean isValid() { boolean result = super.isValid(); if (!commited && result) result = ((creationTime + ACQUIRE_EXPIRATION) > System.currentTimeMillis()); return result; } } /** * This class represents the lock to be released. */ public static class ReleaseLockDecree extends LockDecree { ReleaseLockDecree(Object lockId, Object requester, Object managerId) { super(lockId, requester, managerId); } } /** * This class represents the lock that has to be marked as multilocked */ public static class MultiLockDecree extends LockDecree { MultiLockDecree(Object lockId, Object requester, Object managerId) { super(lockId, requester, managerId); } MultiLockDecree(ReleaseLockDecree releaseLockDecree) { super(releaseLockDecree.lockId, releaseLockDecree.requester, releaseLockDecree.managerId); } } }
package org.ccnx.ccn.impl.repo; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.config.ConfigurationException; import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.MalformedContentNameStringException; /** * MemoryRepoStore is a transient, in-memory store for applications that * wish to provide a repo for their own content as long as they are running. * Given that it is transient, this implementation breaks the usual convention * that a repository provides persistent storage. * */ public class MemoryRepoStore extends RepositoryStoreBase implements RepositoryStore, ContentTree.ContentGetter { public final static String CURRENT_VERSION = "1.0"; protected ContentTree _index; protected ContentName _namespace = null; // Prinmary/initial namespace // For in-memory repo, we just hold onto each ContentObject directly in the ref static class MemRef extends ContentRef { ContentObject co; public MemRef(ContentObject content) { co = content; } } public MemoryRepoStore(ContentName namespace) { _namespace = namespace; } public String getVersion() { return CURRENT_VERSION; } public void initialize(String repositoryRoot, File policyFile, String localName, String globalPrefix, String nameSpace, CCNHandle handle) throws RepositoryException { if (null == handle) { // use the default user credentials try { handle = CCNHandle.open(); } catch (IOException e) { throw new RepositoryException("IOException opening a CCNHandle!", e); } catch (ConfigurationException e) { throw new RepositoryException("ConfigurationException opening a CCNHandle!", e); } } _handle = handle; if (null != _index) { throw new RepositoryException("Attempt to re-initialize " + this.getClass().getName()); } _index = new ContentTree(); if (null != _namespace) { ArrayList<ContentName> ns = new ArrayList<ContentName>(); ns.add(_namespace); _policy = new BasicPolicy(null, ns); _policy.setVersion(CURRENT_VERSION); } else { startInitPolicy(policyFile, nameSpace); } // We never have any persistent content so don't try to read policy from there with readPolicy() try { finishInitPolicy(localName, globalPrefix); } catch (MalformedContentNameStringException e) { throw new RepositoryException(e.getMessage()); } } public ContentObject get(ContentRef ref) { if (null == ref) { return null; } else { // This is a call back based on what we put in ContentTree, so it must be // using our subtype of ContentRef MemRef mref = (MemRef)ref; return mref.co; } } public NameEnumerationResponse saveContent(ContentObject content) throws RepositoryException { // Note: we're trusting the app to store what it wants and not implementing any // namespace restrictions here MemRef ref = new MemRef(content); NameEnumerationResponse ner = new NameEnumerationResponse(); _index.insert(content, ref, System.currentTimeMillis(), this, ner); return ner; } public ContentObject getContent(Interest interest) throws RepositoryException { return _index.get(interest, this); } public boolean hasContent(ContentName name) throws RepositoryException { return _index.matchContent(name); } public NameEnumerationResponse getNamesWithPrefix(Interest i, ContentName responseName) { return _index.getNamesWithPrefix(i, responseName); } public void shutDown() { // no-op } public Object getStatus(String type) { return null; } public boolean bulkImport(String name) throws RepositoryException { return false; // not supported } }
package com.bot.babyfoodplanner.model; import android.content.Context; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import android.util.Log; public class FoodManager { final String TAG = this.getClass().getSimpleName(); private static FoodManagerHelper mHelper = null; private static Context mContext = null; private static String[] foodGroups; private static String[][] foodNames; private static HashMap<Integer, ArrayList<String>> foodBankMap = new HashMap<Integer, ArrayList<String>>(); private static Integer foodBankSize = 0; public FoodManager(Context context) { mContext = context; mHelper = FoodManagerHelper.getInstance(context); } public void parseFoodGroups() throws JSONException { JSONArray foodBank = mHelper.retrieveFoodBank(); foodGroups = new String[foodBank.length()]; foodBankSize = foodBank.length(); for (int i=0; i < foodBankSize; i++) { JSONObject fg = foodBank.getJSONObject(i); if (fg.has(FoodLiterals.FG_LENTILS)) { String fgKey = FoodLiterals.FG_LENTILS; //foodGroups = key; assign(fg, fgKey, i); } else if (fg.has(FoodLiterals.FG_VEGGIES)) { String fgKey = FoodLiterals.FG_VEGGIES; assign(fg, fgKey, i); } else if (fg.has(FoodLiterals.FG_FRUITS)) { String fgKey = FoodLiterals.FG_FRUITS; assign(fg, fgKey, i); } else if (fg.has(FoodLiterals.FG_DAIRY)) { String fgKey = FoodLiterals.FG_DAIRY; assign(fg, fgKey, i); } else if (fg.has(FoodLiterals.FG_GRAINS)) { String fgKey = FoodLiterals.FG_GRAINS; assign(fg, fgKey, i); } } } //TODO public void addFoodItem(int foodGroup, String foodName) { if (foodBankMap.containsKey(foodGroup)) { ArrayList<String> foodNames = foodBankMap.get(foodGroup); foodNames.add(foodName); foodBankMap.put(foodGroup, foodNames); } else { //Food Group doesn't exist Log.e(TAG, "Food group doesn't exist"); } } private void assign(JSONObject foodGroup, String foodGroupKey, int groupIndex) throws JSONException { JSONObject foodItems = foodGroup.getJSONObject(foodGroupKey); Iterator<String> keys = foodItems.keys(); ArrayList<String> foodNamesList = new ArrayList<String>(); foodNames = new String[foodBankSize][foodItems.length()]; String foods[] = new String[foodItems.length()]; int counter = 0; while(keys.hasNext() ){ String key = (String)keys.next(); if(foodItems.get(key) instanceof String ){ foods[counter++] = foodItems.getString(key); foodNamesList.add(foodItems.getString(key)); } } foodGroups[groupIndex] = foodGroupKey; foodBankMap.put(groupIndex, foodNamesList); } public String[] getFoodGroups() { return foodGroups; } public ArrayList<String> getFoodGroupsList() { return new ArrayList<String>(Arrays.asList(foodGroups)); } public String[][] getFoodNames() { Iterator<?> iterator = foodBankMap.keySet().iterator(); int counter = 0; for (Map.Entry pair : foodBankMap.entrySet()) { Integer key = (Integer)pair.getKey(); ArrayList<String> foodList = (ArrayList<String>)pair.getValue(); for(int i=0; i < foodList.size(); i++) { foodNames[key][i] = (String)foodList.get(i); } } return foodNames; } public void persistFoodBank( HashMap<Integer, ArrayList<String>> foodBankMap) { } }
package com.chariotsolutions.nfc.plugin; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.nfc.*; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.os.Parcelable; import android.util.Log; import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; public class NfcPlugin extends Plugin { private static final String REGISTER_MIME_TYPE = "registerMimeType"; private static final String REGISTER_NDEF = "registerNdef"; private static final String REGISTER_NDEF_FORMATABLE = "registerNdefFormatable"; private static final String REGISTER_DEFAULT_TAG = "registerTag"; private static final String WRITE_TAG = "writeTag"; private static final String SHARE_TAG = "shareTag"; private static final String UNSHARE_TAG = "unshareTag"; private static final String INIT = "init"; private static final String NDEF = "ndef"; private static final String NDEF_MIME = "ndef-mime"; private static final String NDEF_FORMATABLE = "ndef-formatable"; private static final String TAG_DEFAULT = "tag"; private static final String TAG = "NfcPlugin"; private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>(); private final ArrayList<String[]> techLists = new ArrayList<String[]>(); private NdefMessage p2pMessage = null; private PendingIntent pendingIntent = null; private Intent savedIntent = null; @Override public PluginResult execute(String action, JSONArray data, String callbackId) { Log.d(TAG, "execute " + action); createPendingIntent(); if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) { try { String mimeType = data.getString(0); intentFilters.add(createIntentFilter(mimeType)); } catch (MalformedMimeTypeException e) { return new PluginResult(Status.ERROR, "Invalid MIME Type"); } catch (JSONException e) { return new PluginResult(Status.JSON_EXCEPTION, "Invalid MIME Type"); } startNfc(); return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(REGISTER_NDEF)) { addTechList(new String[]{Ndef.class.getName()}); startNfc(); return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATABLE)) { addTechList(new String[]{NdefFormatable.class.getName()}); startNfc(); return new PluginResult(Status.OK); } else if (action.equals(REGISTER_DEFAULT_TAG)) { addTagFilter(); startNfc(); return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(WRITE_TAG)) { if (getIntent() == null) { // TODO remove this and handle LostTag return new PluginResult(Status.ERROR, "Failed to write tag, received null intent"); } try { Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0)); writeTag(new NdefMessage(records), tag); } catch (JSONException e) { e.printStackTrace(); return new PluginResult(Status.JSON_EXCEPTION, e.getMessage()); } catch (Exception e) { e.printStackTrace(); return new PluginResult(Status.ERROR, e.getMessage()); } return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(SHARE_TAG)) { try { NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0)); this.p2pMessage = new NdefMessage(records); startNdefPush(); } catch (JSONException e) { return new PluginResult(Status.JSON_EXCEPTION, "Error reading NDEF message from JSON"); } return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(UNSHARE_TAG)) { p2pMessage = null; stopNdefPush(); return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(INIT)) { Log.d(TAG, "Enabling plugin " + getIntent()); startNfc(); if (!recycledIntent()) { parseMessage(); } return new PluginResult(Status.OK); } Log.d(TAG, "no result"); return new PluginResult(Status.NO_RESULT); } private void createPendingIntent() { if (pendingIntent == null) { Activity activity = getActivity(); Intent intent = new Intent(activity, activity.getClass()); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0); } } private void addTechList(String[] list) { this.addTechFilter(); this.addToTechList(list); } private void addTechFilter() { intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)); } private void addTagFilter() { intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)); } private void startNfc() { createPendingIntent(); // onResume can call startNfc before execute this.ctx.runOnUiThread(new Runnable() { public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(ctx.getContext()); if (nfcAdapter != null) { nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists()); if (p2pMessage != null) { nfcAdapter.enableForegroundNdefPush(getActivity(), p2pMessage); } } } }); } private void stopNfc() { this.ctx.runOnUiThread(new Runnable() { public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(ctx.getContext()); if (nfcAdapter != null) { nfcAdapter.disableForegroundDispatch(getActivity()); nfcAdapter.disableForegroundNdefPush(getActivity()); } } }); } private void startNdefPush() { this.ctx.runOnUiThread(new Runnable() { public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(ctx.getContext()); if (nfcAdapter != null) { nfcAdapter.enableForegroundNdefPush(getActivity(), p2pMessage); } } }); } private void stopNdefPush() { this.ctx.runOnUiThread(new Runnable() { public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(ctx.getContext()); if (nfcAdapter != null) { nfcAdapter.disableForegroundNdefPush(getActivity()); } } }); } private void addToTechList(String[] techs) { techLists.add(techs); } private IntentFilter createIntentFilter(String mimeType) throws MalformedMimeTypeException { IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); intentFilter.addDataType(mimeType); return intentFilter; } private PendingIntent getPendingIntent() { return pendingIntent; } private IntentFilter[] getIntentFilters() { return intentFilters.toArray(new IntentFilter[intentFilters.size()]); } private String[][] getTechLists() { //noinspection ToArrayCallWithZeroLengthArrayArgument return techLists.toArray(new String[0][0]); } void parseMessage() { Log.d(TAG, "parseMessage " + getIntent()); Intent intent = getIntent(); String action = intent.getAction(); Log.d(TAG, "action " + action); if (action == null) { return; } Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES)); if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { Ndef ndef = Ndef.get(tag); fireNdefEvent(NDEF_MIME, ndef, messages); } else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) { for (String tagTech : tag.getTechList()) { Log.d(TAG, tagTech); if (tagTech.equals(NdefFormatable.class.getName())) { fireNdefEvent(NDEF_FORMATABLE, null, null); } else if (tagTech.equals(Ndef.class.getName())) { Ndef ndef = Ndef.get(tag); fireNdefEvent(NDEF, ndef, messages); } } } if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) { fireTagEvent(tag); } setIntent(new Intent()); } private void fireNdefEvent(String type, Ndef ndef, Parcelable[] messages) { String javascriptTemplate = "var e = document.createEvent(''Events'');\n" + "e.initEvent(''{0}'');\n" + "e.tag = {1};\n" + "document.dispatchEvent(e);"; JSONObject jsonObject = buildNdefJSON(ndef, messages); String tag = jsonObject.toString(); String command = MessageFormat.format(javascriptTemplate, type, tag); Log.v(TAG, command); this.sendJavascript(command); } private void fireTagEvent (Tag tag) { String javascriptTemplate = "var e = document.createEvent(''Events'');\n" + "e.initEvent(''{0}'');\n" + "e.tag = {1};\n" + "document.dispatchEvent(e);"; String command = MessageFormat.format(javascriptTemplate, TAG_DEFAULT, Util.tagToJSON(tag)); Log.v(TAG, command); this.sendJavascript(command); } JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) { JSONObject json = Util.ndefToJSON(ndef); // ndef is null for peer-to-peer // ndef and messages are null for ndef format-able if (ndef == null && messages != null) { try { if (messages.length > 0) { NdefMessage message = (NdefMessage) messages[0]; json.put("ndefMessage", Util.messageToJSON(message)); // guessing type, would prefer a more definitive way to determine type json.put("type", "NDEF Push Protocol"); } if (messages.length > 1) { Log.wtf(TAG, "Expected one ndefMessage but found " + messages.length); } } catch (JSONException e) { // shouldn't happen Log.e(Util.TAG, "Failed to convert ndefMessage into json", e); } } return json; } private void writeTag(NdefMessage message, Tag tag) throws TagWriteException, IOException, FormatException { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { throw new TagWriteException("Tag is read only"); } int size = message.toByteArray().length; if (ndef.getMaxSize() < size) { String errorMessage = "Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes."; throw new TagWriteException(errorMessage); } ndef.writeNdefMessage(message); } else { NdefFormatable formatable = NdefFormatable.get(tag); if (formatable != null) { formatable.connect(); formatable.format(message); } else { throw new TagWriteException("Tag doesn't support NDEF"); } } } private boolean recycledIntent() { // TODO this is a kludge, find real solution int flags = getIntent().getFlags(); if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) { Log.i(TAG, "Launched from history, killing recycled intent"); setIntent(new Intent()); return true; } return false; } @Override public void onPause(boolean multitasking) { Log.d(TAG, "onPause " + getIntent()); super.onPause(multitasking); stopNfc(); } @Override public void onResume(boolean multitasking) { Log.d(TAG, "onResume " + getIntent()); super.onResume(multitasking); startNfc(); } @Override public void onNewIntent(Intent intent) { Log.d(TAG, "onNewIntent " + intent); super.onNewIntent(intent); setIntent(intent); savedIntent = intent; parseMessage(); } private Activity getActivity() { return (Activity)ctx; } private Intent getIntent() { return ((Activity)ctx).getIntent(); } private void setIntent(Intent intent) { ((Activity)ctx).setIntent(intent); } }
package com.digi.xbee.api.packet; import java.io.IOException; import java.io.InputStream; import java.util.Date; import com.digi.xbee.api.exceptions.InvalidPacketException; import com.digi.xbee.api.models.ATCommandStatus; import com.digi.xbee.api.models.SpecialByte; import com.digi.xbee.api.models.XBee16BitAddress; import com.digi.xbee.api.models.XBee64BitAddress; import com.digi.xbee.api.models.XBeeDiscoveryStatus; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.models.XBeeTransmitStatus; import com.digi.xbee.api.packet.common.ATCommandPacket; import com.digi.xbee.api.packet.common.ATCommandResponsePacket; import com.digi.xbee.api.packet.common.IODataSampleRxIndicatorPacket; import com.digi.xbee.api.packet.common.ReceivePacket; import com.digi.xbee.api.packet.common.RemoteATCommandPacket; import com.digi.xbee.api.packet.common.RemoteATCommandResponsePacket; import com.digi.xbee.api.packet.common.TransmitPacket; import com.digi.xbee.api.packet.common.TransmitStatusPacket; import com.digi.xbee.api.packet.raw.RX16IOPacket; import com.digi.xbee.api.packet.raw.RX16Packet; import com.digi.xbee.api.packet.raw.RX64IOPacket; import com.digi.xbee.api.packet.raw.RX64Packet; import com.digi.xbee.api.packet.raw.TX16Packet; import com.digi.xbee.api.packet.raw.TX64Packet; import com.digi.xbee.api.packet.raw.TXStatusPacket; /** * This class reads and parses XBee packets from the input stream returning * a generic {@code XBeeAPIPacket} which can be casted later to the * corresponding high level specific API packet. * * <p>All the API and API2 logic is already included so all packet reads from * the input stream are independent of the XBee working mode.</p> * * @see XBeeAPIPacket */ public class XBeePacketParser { private static int DEFAULT_TIMEOUT = 2000; // Variables private InputStream inputStream; private OperatingMode mode; private boolean lengthRead; private int readBytes = 0; private int length = 0; private XBeeChecksum checksum; public XBeePacketParser(InputStream inputStream, OperatingMode mode) { if (inputStream == null) throw new NullPointerException("Input stream cannot be null."); if (mode == null) throw new NullPointerException("Operating mode cannot be null."); if (mode != OperatingMode.API && mode != OperatingMode.API_ESCAPE) throw new IllegalArgumentException("Operating mode must be API or API Escaped."); this.inputStream = inputStream; this.mode = mode; } /** * Parses a packet from the input stream depending on the working mode and * returns it. * * @return Parsed packet. * * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ public XBeePacket parsePacket() throws InvalidPacketException { try { // Reset variables. readBytes = 0; lengthRead = false; // Initialize checksum. checksum = new XBeeChecksum(); // Read packet size. int hSize = readByte(); int lSize = readByte(); length = hSize << 8 | lSize; lengthRead = true; // Read API ID int apiID = readByte(); APIFrameType apiType = APIFrameType.get(apiID); // Parse API payload depending on API ID. XBeePacket packet = null; if (apiType == null) { // Parse unknown packet. // Read payload. byte[] payload = readBytes(length - 1); // Create packet. packet = new UnknownXBeePacket(apiID, payload); } else { switch (apiType) { case TX_64: packet = parseTX64Packet(); break; case TX_16: packet = parseTX16Packet(); break; case AT_COMMAND: packet = parseATCommandPacket(); break; case TRANSMIT_REQUEST: packet = parseTransmitRequestPacket(); break; case REMOTE_AT_COMMAND_REQUEST: packet = parseRemoteATCommandRequestPacket(); break; case RX_64: packet = parseRX64Packet(); break; case RX_16: packet = parseRX16Packet(); break; case RX_IO_64: packet = parseRXIO64Packet(); break; case RX_IO_16: packet = parseRXIO16Packet(); break; case AT_COMMAND_RESPONSE: packet = parseATCommandResponsePacket(); break; case REMOTE_AT_COMMAND_RESPONSE: packet = parseRemoteATCommandResponsePacket(); break; case TX_STATUS: packet = parseTXStatusPacket(); break; case TRANSMIT_STATUS: packet = parseTransmitStatusPacket(); break; case RECEIVE_PACKET: packet = parseZigBeeReceivePacket(); break; case IO_DATA_SAMPLE_RX_INDICATOR: packet = parseIODataSampleRxIndicatorPacket(); break; case GENERIC: default: packet = parseGenericPacket(); } } // Read single byte (checksum) which is automatically verified. readByte(); return packet; } catch (IOException e) { throw new InvalidPacketException("Error parsing packet: " + e.getMessage(), e); } } /** * Reads one byte from the input stream. * * <p>This operation checks several things like the working mode in order * to consider escaped bytes.</p> * * @return The read byte. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private int readByte() throws IOException, InvalidPacketException { // Give a bit of time to fill stream if read byte is -1. long deadline = new Date().getTime() + 200; int b = inputStream.read(); while (b == -1 && new Date().getTime() < deadline) { b = inputStream.read(); try { Thread.sleep(10); } catch (InterruptedException e) {} } if (b == -1) throw new InvalidPacketException("Error parsing packet: Incomplete packet."); if (mode == OperatingMode.API_ESCAPE) { // Check if the byte is special. if (SpecialByte.isSpecialByte(b)) { // Check if the byte is ESCAPE if (b == SpecialByte.ESCAPE_BYTE.getValue()) { // Read next byte and unescape it. // Give a bit of time to fill stream if read byte is -1. deadline = new Date().getTime() + 200; b = inputStream.read(); while (b == -1 && new Date().getTime() < deadline) { b = inputStream.read(); try { Thread.sleep(10); } catch (InterruptedException e) {} } if (b == -1) throw new InvalidPacketException("Error parsing packet: Incomplete packet."); b ^= 0x20; } else { throw new InvalidPacketException("Expecting a " + SpecialByte.ESCAPE_BYTE.getValue() + ", but got " + b); // This should NEVER occur! // rebootTheMatrix(); } } } // If length was already read add byte to read bytes and checksum computing. if (lengthRead) { checksum.add(b); readBytes += 1; // Check if packet is fully read. if (readBytes >= length + 1) { // Was checksum byte, verify it! if (!checksum.validate()) throw new InvalidPacketException("Error verifying packet checksum."); } } return b; } /** * Reads the given amount of bytes from the input stream. * * <p>This operation checks several things like the working mode in order * to consider escaped bytes.</p> * * @param numBytes Number of bytes to read. * * @return The read byte array. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private byte[] readBytes(int numBytes) throws IOException, InvalidPacketException { byte[] data = new byte[numBytes]; switch (mode) { case API: int numBytesRead = 0; int currentRead = 0; long deadline = new Date().getTime() + DEFAULT_TIMEOUT; while (new Date().getTime() < deadline) { currentRead = inputStream.read(data, numBytesRead, numBytes - numBytesRead); if (currentRead == -1) throw new InvalidPacketException("Error parsing packet: Incomplete packet."); numBytesRead = numBytesRead + currentRead; if (numBytesRead < numBytes) { try { Thread.sleep(50); } catch (InterruptedException e) {} } else break; } if (numBytesRead < numBytes) throw new InvalidPacketException("Not enough data in the stream."); if (lengthRead) { checksum.add(data); readBytes += numBytes; // Check if packet is fully read. if (readBytes >= length + 1) { // Was checksum byte, verify it! if (!checksum.validate()) throw new InvalidPacketException("Error verifying packet checksum."); } } break; case API_ESCAPE: for (int i = 0; i < numBytes; i++) data[i] = (byte)readByte(); break; default: break; } return data; } /** * Reads an XBee 64 bit address from the input stream. * * @return The read XBee 64 bit address, {@code null} if error. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBee64BitAddress readXBee64BitAddress() throws IOException, InvalidPacketException { byte[] address = new byte[8]; for (int i = 0; i < 8; i++) address[i] = (byte)readByte(); return new XBee64BitAddress(address); } /** * Reads an XBee 16 bit address from the input stream. * * @return The read XBee 16 bit address, {@code null} if error. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBee16BitAddress readXBee16BitAddress() throws IOException, InvalidPacketException { int hsb = readByte(); int lsb = readByte(); return new XBee16BitAddress(hsb, lsb); } /** * Parses the input stream and returns a packet of type Generic. * * @return Parsed Generic packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseGenericPacket() throws IOException, InvalidPacketException { byte[] commandData = null; if (readBytes < length) commandData = readBytes(length - readBytes); return new GenericXBeePacket(commandData); } /** * Parses the input stream and returns a packet of type TX (transmit) 16 * Request. * * @return Parsed TX (transmit) 16 Request packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseTX16Packet() throws IOException, InvalidPacketException { int frameID = readByte(); XBee16BitAddress destAddress16 = readXBee16BitAddress(); int transmitOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new TX16Packet(frameID, destAddress16, transmitOptions, data); } /** * Parses the input stream and returns a packet of type TX (transmit) 64 * Request. * * @return Parsed TX (transmit) 64 Request packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseTX64Packet() throws IOException, InvalidPacketException { int frameID = readByte(); XBee64BitAddress destAddress64 = readXBee64BitAddress(); int transmitOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new TX64Packet(frameID, destAddress64, transmitOptions, data); } /** * Parses the input stream and returns a packet of type AT Command. * * @return Parsed AT Command packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, * or if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseATCommandPacket() throws IOException, InvalidPacketException { int frameID = readByte(); String command = new String(readBytes(2)); byte[] parameterData = null; if (readBytes < length) parameterData = readBytes(length - readBytes); return new ATCommandPacket(frameID, command, parameterData); } /** * Parses the input stream and returns a packet of type Transmit Request. * * @return Parsed Transmit Request packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseTransmitRequestPacket() throws IOException, InvalidPacketException { int frameID = readByte(); XBee64BitAddress destAddress64 = readXBee64BitAddress(); XBee16BitAddress destAddress16 = readXBee16BitAddress(); int broadcastRadius = readByte(); int options = readByte(); byte[] rfData = null; if (readBytes < length) rfData = readBytes(length - readBytes); return new TransmitPacket(frameID, destAddress64, destAddress16, broadcastRadius, options, rfData); } /** * Parses the input stream and returns a packet of type AT Command Response. * * @return Parsed AT Command Response packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseATCommandResponsePacket() throws IOException, InvalidPacketException { int frameID = readByte(); String command = new String(readBytes(2)); int status = readByte(); byte[] commandData = null; if (readBytes < length) commandData = readBytes(length - readBytes); return new ATCommandResponsePacket(frameID, ATCommandStatus.get(status), command, commandData); } /** * Parses the input stream and returns a packet of type TX status. * * @return Parsed TX status packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseTXStatusPacket() throws IOException, InvalidPacketException { int frameID = readByte(); int status = readByte(); return new TXStatusPacket(frameID, XBeeTransmitStatus.get(status)); } /** * Parses the input stream and returns a packet of type Transmit Status. * * @return Parsed Transmit Status packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseTransmitStatusPacket() throws IOException, InvalidPacketException { int frameID = readByte(); XBee16BitAddress address = readXBee16BitAddress(); int retryCount = readByte(); int deliveryStatus = readByte(); int discoveryStatus = readByte(); return new TransmitStatusPacket(frameID, address, retryCount, XBeeTransmitStatus.get(deliveryStatus), XBeeDiscoveryStatus.get(discoveryStatus)); } /** * Parses the input stream and returns a packet of type ZigBee Receive. * * @return Parsed ZigBee Receive packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseZigBeeReceivePacket() throws IOException, InvalidPacketException { XBee64BitAddress sourceAddress64 = readXBee64BitAddress(); XBee16BitAddress sourceAddress16 = readXBee16BitAddress(); int receiveOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new ReceivePacket(sourceAddress64, sourceAddress16, receiveOptions, data); } /** * Parses the input stream and returns a packet of type RX 16. * * @return Parsed RX 16 packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseRX16Packet() throws IOException, InvalidPacketException { XBee16BitAddress sourceAddress16 = readXBee16BitAddress(); int signalStrength = readByte(); int receiveOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new RX16Packet(sourceAddress16, signalStrength, receiveOptions, data); } /** * Parses the input stream and returns a packet of type RX 64. * * @return Parsed RX 64 packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseRX64Packet() throws IOException, InvalidPacketException { XBee64BitAddress sourceAddress64 = readXBee64BitAddress(); int signalStrength = readByte(); int receiveOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new RX64Packet(sourceAddress64, signalStrength, receiveOptions, data); } /** * Parses the input stream and returns a packet of type RX IO 64. * * @return Parsed RX IO 64 packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, * or if the input stream has been closed, or if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseRXIO64Packet() throws IOException, InvalidPacketException { XBee64BitAddress sourceAddress64 = readXBee64BitAddress(); int rssi = readByte(); int receiveOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new RX64IOPacket(sourceAddress64, rssi, receiveOptions, data); } /** * Parses the input stream and returns a packet of type RX IO 16. * * @return Parsed RX IO 16 packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, * or if the input stream has been closed, or if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseRXIO16Packet() throws IOException, InvalidPacketException { XBee16BitAddress sourceAddress16 = readXBee16BitAddress(); int rssi = readByte(); int receiveOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new RX16IOPacket(sourceAddress16, rssi, receiveOptions, data); } /** * Parses the input stream and returns a packet of type IO data sample RX indicator. * * @return Parsed IO data sample RX indicator packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, * or if the input stream has been closed, or if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseIODataSampleRxIndicatorPacket() throws IOException, InvalidPacketException { XBee64BitAddress sourceAddress64 = readXBee64BitAddress(); XBee16BitAddress sourceAddress16 = readXBee16BitAddress(); int receiveOptions = readByte(); byte[] data = null; if (readBytes < length) data = readBytes(length - readBytes); return new IODataSampleRxIndicatorPacket(sourceAddress64, sourceAddress16, receiveOptions, data); } /** * Parses the input stream and returns a packet of type Remote AT Command. * * @return Parsed Remote AT Command packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, * or if the input stream has been closed, or if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseRemoteATCommandRequestPacket() throws IOException, InvalidPacketException { int frameID = readByte(); XBee64BitAddress destAddress64 = readXBee64BitAddress(); XBee16BitAddress destAddress16 = readXBee16BitAddress(); int transmitOptions = readByte(); String command = new String(readBytes(2)); byte[] parameterData = null; if (readBytes < length) parameterData = readBytes(length - readBytes); return new RemoteATCommandPacket(frameID, destAddress64, destAddress16, transmitOptions, command, parameterData); } /** * Parses the input stream and returns a packet of type Remote AT Command. * * @return Parsed Remote AT Command packet. * * @throws IOException if the first byte cannot be read for any reason other than end of file, * or if the input stream has been closed, or if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private XBeePacket parseRemoteATCommandResponsePacket() throws IOException, InvalidPacketException { int frameID = readByte(); XBee64BitAddress sourceAddress64 = readXBee64BitAddress(); XBee16BitAddress sourceAddress16 = readXBee16BitAddress(); String command = new String(readBytes(2)); int status = readByte(); byte[] commandData = null; if (readBytes < length) commandData = readBytes(length - readBytes); return new RemoteATCommandResponsePacket(frameID, sourceAddress64, sourceAddress16, command, ATCommandStatus.get(status), commandData); } }
package com.ecyrd.jspwiki.ui.admin.beans; import java.util.Date; import javax.management.NotCompliantMBeanException; import javax.servlet.http.HttpServletRequest; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiSession; import com.ecyrd.jspwiki.auth.NoSuchPrincipalException; import com.ecyrd.jspwiki.auth.UserManager; import com.ecyrd.jspwiki.auth.WikiSecurityException; import com.ecyrd.jspwiki.auth.user.UserProfile; import com.ecyrd.jspwiki.ui.admin.AdminBean; import com.ecyrd.jspwiki.ui.admin.SimpleAdminBean; public class UserBean extends SimpleAdminBean { public UserBean( WikiEngine engine ) throws NotCompliantMBeanException { super(); } public String[] getAttributeNames() { return new String[0]; } // FIXME: We don't yet support MBean for this kind of stuff. public String[] getMethodNames() { return new String[0]; } public String doPost(WikiContext context) { HttpServletRequest request = context.getHttpRequest(); WikiSession session = context.getWikiSession(); UserManager mgr = context.getEngine().getUserManager(); String loginid = request.getParameter("loginid"); String loginname = request.getParameter("loginname"); String fullname = request.getParameter("fullname"); String password = request.getParameter("password"); String password2 = request.getParameter("password2"); String email = request.getParameter("email"); if( request.getParameter("action").equalsIgnoreCase("remove") ) { try { mgr.getUserDatabase().deleteByLoginName(loginid); session.addMessage("User profile "+loginid+" ("+fullname+") has been deleted"); } catch (NoSuchPrincipalException e) { session.addMessage("User profile has already been removed"); } catch (WikiSecurityException e) { session.addMessage("Security problem: "+e); } return ""; } if( password != null && password.length() > 0 && !password.equals(password2) ) { session.addMessage("Passwords do not match!"); return ""; } UserProfile p; if( loginid.equals("--New { // Create new user p = mgr.getUserDatabase().newProfile(); p.setCreated( new Date() ); } else { try { p = mgr.getUserDatabase().findByLoginName( loginid ); } catch (NoSuchPrincipalException e) { session.addMessage("I could not find user profile "+loginid); return ""; } } p.setEmail(email); p.setFullname(fullname); if( password.length() > 0 ) p.setPassword(password); p.setLoginName(loginname); try { mgr.getUserDatabase().save( p ); } catch( WikiSecurityException e ) { session.addMessage("Unable to save "+e.getMessage()); } session.addMessage("User profile has been updated"); return ""; } public String getTitle() { return "User administration"; } public int getType() { return AdminBean.UNKNOWN; } }
package com.example.basiccameraapp; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.os.AsyncTask; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import com.example.basiccameraapp.application.BasicCameraApplication; public class GalleryAdapter extends BaseAdapter { static String TAG = GalleryAdapter.class.getName(); static int refreshRate = 500; static int initialDelay = 2000; Activity mActivity; BasicCameraApplication mApp; SharedPreferences mPrefs; GridView mGallery; ImageCache mImageCache; String[] mImagePaths; View.OnClickListener mImageViewListener; HashMap<String, ImageLoader> mImageLoadersByPath; ArtifactInducer mArtifactInducer; Timer mThumbnailsUpdateTimer; int mDisplayHeight, mDisplayWidth; HashMap<String, Integer> mImageViewTimesCache; public GalleryAdapter(Activity activity, GridView gallery, String[] imagePaths, ImageCache imageCache) { mActivity = activity; mGallery = gallery; mImagePaths = imagePaths; mImageCache = imageCache; mImageLoadersByPath = new HashMap<String, ImageLoader>(); mGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> gallery, View view, int pos, long id) { String path = (String) view.getTag(); if (path != null) { GalleryActivity.viewImage(GalleryAdapter.this.mActivity, path); } } }); mImageViewTimesCache = new HashMap<String, Integer>(); mArtifactInducer = new BlurArtifactInducer(); mPrefs = activity.getSharedPreferences(MainActivity.DEFAULT_PREFS_NAME, Context.MODE_PRIVATE); if (! mPrefs.contains(MainActivity.PREFS_KEY_SCREEN_HEIGHT)) { DisplayMetrics metrics = mActivity.getResources().getDisplayMetrics(); Editor prefsEditor = mPrefs.edit(); mDisplayHeight = metrics.heightPixels; mDisplayWidth = metrics.widthPixels; prefsEditor.putInt(MainActivity.PREFS_KEY_SCREEN_HEIGHT, metrics.heightPixels); prefsEditor.putInt(MainActivity.PREFS_KEY_SCREEN_WIDTH, metrics.widthPixels); prefsEditor.commit(); } else { mDisplayHeight = mPrefs.getInt(MainActivity.PREFS_KEY_SCREEN_HEIGHT, -1); mDisplayWidth = mPrefs.getInt(MainActivity.PREFS_KEY_SCREEN_WIDTH, -1); } } public void startRefresh() { populateImageViewTimesCache(); mThumbnailsUpdateTimer = new Timer(); mThumbnailsUpdateTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { updateImageTimesInCache(refreshRate); notifyDataSetChanged(); } }); } }, initialDelay, refreshRate); } public void stopRefresh() { commitTimeUpdatesToCache(); } public void populateImageViewTimesCache() { mImageViewTimesCache.clear(); for (String path : mImagePaths) { mImageViewTimesCache.put(path, mPrefs.getInt(path, 0)); } } public void updateImageTimesInCache(int updateMs) { for (Map.Entry<String, Integer> entry : mImageViewTimesCache.entrySet()) { String path = entry.getKey(); int currentTime = mImageViewTimesCache.get(path); mImageViewTimesCache.put(path, Math.min(MainActivity.sTimeToImageDeath, currentTime + updateMs)); } } public void commitTimeUpdatesToCache() { Editor prefsEditor = mPrefs.edit(); for (Map.Entry<String, Integer> image : mImageViewTimesCache.entrySet()) { prefsEditor.putInt(image.getKey(), image.getValue().intValue()); } prefsEditor.commit(); } @Override public Object getItem(int position) { return mImagePaths[position]; } @Override public long getItemId(int position) { // Android calls this when an item is clicked so an id can be passed // to onItemClickListener. But we ignore the id currently. return -1; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; String path = (String) getItem(position); if (convertView == null) { imageView = new ImageView(mActivity); imageView.setTag(path); imageView.setLayoutParams(new GridView.LayoutParams(200, 200)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(0,10,0,10); } else { imageView = (ImageView) convertView; imageView.setTag(path); } Bitmap cached = mImageCache.get(path); if (cached == null) { if (! mImageLoadersByPath.containsKey(path)) { ImageLoader loader = new ImageLoader(); loader.execute(path); mImageLoadersByPath.put(path, loader); } } else { setArtifactInducedBitmap(imageView, cached); } return imageView; } @Override public int getCount() { return mImagePaths.length; } public void setArtifactInducedBitmap(ImageView iv, Bitmap bmp) { int timeViewed = mImageViewTimesCache.get(iv.getTag()).intValue(); bmp = mArtifactInducer.induceArtifacts(bmp, mDisplayWidth, mDisplayHeight, (float) timeViewed/MainActivity.sTimeToImageDeath); iv.setImageBitmap(bmp); } class ImageLoader extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... paths) { String path = paths[0]; Bitmap bmp = GalleryActivity.decodeSampledBitmapFromPath( GalleryAdapter.this.mActivity, path, 100, 100); GalleryAdapter.this.mImageCache.put(path, bmp); return null; } @Override protected void onPostExecute(Void result) { GalleryAdapter.this.notifyDataSetChanged(); } } }
package info.u_team.u_team_core.api.gui; import com.mojang.blaze3d.matrix.MatrixStack; import info.u_team.u_team_core.util.RGBA; import net.minecraft.util.text.ITextComponent; public interface ITextProvider { ITextComponent getCurrentText(); RGBA getCurrentTextColor(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks); }
package davenkin.wanghushengri.about; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("local") public class AboutApiTest { @Autowired private TestRestTemplate restTemplate; @Test public void shouldSayAnotherHelloWorld() { String result = restTemplate.getForObject("/about", String.class); assertNotNull(result); } }
/* * LocationLogger.java * * Simple class to record obtained locations in external * storage (usually SD card) for debugging/testing purposes * */ package com.incidentlocator.client; import android.content.Context; import android.util.Log; import android.os.Environment; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class LocationLogger { private static final String TAG = "IncidentLocatorExternalLogger"; private static final String extFile = "locations.log"; public void saveLocation(String data, Context context) { File extDir = context.getExternalFilesDir(null); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { try { File fp = new File(extDir, extFile); // open file for append FileWriter fw = new FileWriter(fp, true); BufferedWriter f = new BufferedWriter(fw); f.write(data + "\n"); f.close(); Log.d(TAG, "wrote to external log"); } catch (IOException e) { Log.w(TAG, e); } } else { Log.w(TAG, "external storage not mounted"); } } }
package com.itboye.banma.welcome; import org.json.JSONException; import org.json.JSONObject; import com.android.volley.VolleyError; import com.itboye.banma.R; import com.itboye.banma.activities.HomePageActivity; import com.itboye.banma.api.StrUIDataListener; import com.itboye.banma.api.StrVolleyInterface; import com.itboye.banma.app.AppContext; import com.itboye.banma.service.TokenIntentService; import com.itboye.banma.utils.SharedConfig; import com.umeng.analytics.AnalyticsConfig; import com.umeng.analytics.MobclickAgent; import com.umeng.message.PushAgent; import com.umeng.message.UmengRegistrar; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Animation.AnimationListener; import android.widget.Toast; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; public class AppStartActivity extends Activity implements StrUIDataListener{ private boolean first; private View view; private Context context; private Animation animation; private SharedPreferences shared; private static int TIME = 500; private AppContext appContext; private StrVolleyInterface networkHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); view = View.inflate(this, R.layout.activity_main, null); appContext = (AppContext) getApplication(); networkHelper = new StrVolleyInterface(this); networkHelper.setStrUIDataListener(this); // MobclickAgent.updateOnlineConfig( this ); // String value = MobclickAgent.getConfigParams( this, "xxxx" ); setContentView(view); MobclickAgent.updateOnlineConfig( this ); AnalyticsConfig.enableEncrypt(true); MobclickAgent.setDebugMode( true ); PushAgent mPushAgent = PushAgent.getInstance(getApplicationContext()); mPushAgent.enable(); PushAgent.getInstance(getApplicationContext()).onAppStart(); //Device Token String device_token = UmengRegistrar.getRegistrationId(this); System.out.println(device_token+""); new SharedConfig(this); shared = SharedConfig.GetConfig(); into(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } public void onPause() { super.onPause(); MobclickAgent.onPause(this); } private void into() { //token if (appContext.isNetworkConnected()==false) { Toast.makeText(AppStartActivity.this, "", Toast.LENGTH_LONG).show(); } try { appContext.getToken(AppStartActivity.this, "client_credentials", "by559a8de1c325c1", "aedd16f80c192661016eebe3ac35a6e7",networkHelper); } catch (Exception e) { Toast.makeText(AppStartActivity.this, "" + e, Toast.LENGTH_LONG).show(); e.printStackTrace(); Log.v("token",e+"" ); } first = shared.getBoolean("First", false); animation = AnimationUtils.loadAnimation(this, R.anim.alpha); view.startAnimation(animation); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent; if (first) { intent = new Intent(AppStartActivity.this, WelcomeActivity.class); } else { intent = new Intent(AppStartActivity.this, HomePageActivity.class); } startActivity(intent); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); AppStartActivity.this.finish(); } }, TIME); } }); } @Override public void onErrorHappened(VolleyError error) { // TODO Auto-generated method stub Toast.makeText(AppStartActivity.this, "" + error, Toast.LENGTH_LONG) .show(); this.startService(new Intent(this,TokenIntentService.class)); AppContext.setTokenSuccess(false); Log.v("token",error.toString() ); } @Override public void onDataChanged(String data) { // TODO Auto-generated method stub String access_token = null; JSONObject jsonObject = null; int code = -1; try { jsonObject=new JSONObject(data); code = jsonObject.getInt("code"); } catch (JSONException e1) { e1.printStackTrace(); } if (code == 0) { try { JSONObject tempdata=(JSONObject) jsonObject.get("data"); access_token = tempdata.getString("access_token"); Log.v("token",access_token+"1"); AppContext.setAccess_token(access_token); AppContext.setTokenSuccess(true); this.startService(new Intent(this,TokenIntentService.class)); } catch (JSONException e) { e.printStackTrace(); } Toast.makeText(AppStartActivity.this, "token" + access_token, Toast.LENGTH_LONG) .show(); } else { AppContext.setTokenSuccess(false); this.startService(new Intent(this,TokenIntentService.class)); Toast.makeText(AppStartActivity.this, "tokencode=" + code, Toast.LENGTH_LONG) .show(); } } }
package com.robrua.orianna.api.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.robrua.orianna.api.Utils; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.api.LoadPolicy; import com.robrua.orianna.type.core.staticdata.Champion; import com.robrua.orianna.type.core.staticdata.Item; import com.robrua.orianna.type.core.staticdata.MapDetails; import com.robrua.orianna.type.core.staticdata.Mastery; import com.robrua.orianna.type.core.staticdata.Realm; import com.robrua.orianna.type.core.staticdata.Rune; import com.robrua.orianna.type.core.staticdata.SummonerSpell; import com.robrua.orianna.type.dto.staticdata.ChampionList; import com.robrua.orianna.type.dto.staticdata.ItemList; import com.robrua.orianna.type.dto.staticdata.MapData; import com.robrua.orianna.type.dto.staticdata.MasteryList; import com.robrua.orianna.type.dto.staticdata.RuneList; import com.robrua.orianna.type.dto.staticdata.SummonerSpellList; public abstract class StaticDataAPI { private static Set<Long> IGNORE_ITEMS = new HashSet<>(Arrays.asList(new Long[] {0L, 2037L, 2039L, 2040L, 3005L, 3039L, 3128L, 3131L, 3160L, 3167L, 3168L, 3169L, 3175L, 3176L, 3171L, 3186L, 3188L, 3206L, 3207L, 3209L, 3210L, 3405L, 3406L, 3407L, 3408L, 3409L, 3413L, 3414L, 3415L, 3419L, 3420L})); /** * @param ID * the ID of the champion to get * @return the champion */ public synchronized static Champion getChampionByID(final long ID) { Champion champion = RiotAPI.store.get(Champion.class, (int)ID); if(champion != null) { return champion; } final com.robrua.orianna.type.dto.staticdata.Champion champ = BaseRiotAPI.getChampion(ID); if(champ == null) { return null; } champion = new Champion(champ); if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getItems(new ArrayList<>(champ.getItemIDs())); } RiotAPI.store.store(champion, (int)ID); return champion; } /** * @param name * the name of the champion to get * @return the champion */ public static Champion getChampionByName(final String name) { final List<Champion> champions = getChampions(); for(final Champion champion : champions) { if(champion.getName().equals(name)) { return champion; } } return null; } /** * @return all the champions */ public synchronized static List<Champion> getChampions() { if(RiotAPI.store.hasAll(Champion.class)) { return RiotAPI.store.getAll(Champion.class); } final ChampionList champs = BaseRiotAPI.getChampions(); final List<Champion> champions = new ArrayList<>(champs.getData().size()); final List<Long> IDs = new ArrayList<>(champions.size()); for(final com.robrua.orianna.type.dto.staticdata.Champion champ : champs.getData().values()) { champions.add(new Champion(champ)); IDs.add(champ.getId().longValue()); } if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getItems(new ArrayList<>(champs.getItemIDs())); } RiotAPI.store.store(champions, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(champions); } /** * @param IDs * the IDs of the champions to get * @return the champions */ public synchronized static List<Champion> getChampionsByID(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Champion> champions = RiotAPI.store.get(Champion.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(champions.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return champions; } if(toGet.size() == 1) { champions.set(index.get(0), getChampionByID(toGet.get(0))); return champions; } getChampions(); final List<Champion> gotten = RiotAPI.store.get(Champion.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { champions.set(id, gotten.get(count++)); } return Collections.unmodifiableList(champions); } /** * @param IDs * the IDs of the champions to get * @return the champions */ public static List<Champion> getChampionsByID(final long... IDs) { return getChampionsByID(Utils.convert(IDs)); } /** * @param names * the names of the champions to get * @return the champions */ public static List<Champion> getChampionsByName(final List<String> names) { final Map<String, Integer> indices = new HashMap<>(); final List<Champion> result = new ArrayList<>(names.size()); int i = 0; for(final String name : names) { indices.put(name, i++); result.add(null); } final List<Champion> champions = getChampions(); for(final Champion champ : champions) { final Integer index = indices.get(champ.getName()); if(index != null) { result.set(index, champ); } } return result; } /** * @param names * the names of the champions to get * @return the champions */ public static List<Champion> getChampionsByName(final String... names) { return getChampionsByName(Arrays.asList(names)); } /** * @param ID * the ID of the item to get * @return the item */ public synchronized static Item getItem(final long ID) { if(IGNORE_ITEMS.contains(ID)) { return null; } Item item = RiotAPI.store.get(Item.class, (int)ID); if(item != null) { return item; } final com.robrua.orianna.type.dto.staticdata.Item it = BaseRiotAPI.getItem(ID); item = new Item(it); RiotAPI.store.store(item, (int)ID); return item; } /** * @return all the items */ public synchronized static List<Item> getItems() { if(RiotAPI.store.hasAll(Item.class)) { return RiotAPI.store.getAll(Item.class); } final ItemList its = BaseRiotAPI.getItems(); final List<Item> items = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(items.size()); for(final com.robrua.orianna.type.dto.staticdata.Item item : its.getData().values()) { items.add(new Item(item)); IDs.add(item.getId().longValue()); } RiotAPI.store.store(items, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(items); } /** * @param IDs * the IDs of the items to get * @return the items */ public synchronized static List<Item> getItems(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Item> items = RiotAPI.store.get(Item.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(items.get(i) == null && !IGNORE_ITEMS.contains(IDs.get(i))) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return items; } if(toGet.size() == 1) { items.set(index.get(0), getItem(toGet.get(0))); return items; } getItems(); final List<Item> gotten = RiotAPI.store.get(Item.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { items.add(id, gotten.get(count++)); } return Collections.unmodifiableList(items); } /** * @param IDs * the IDs of the items to get * @return the items */ public static List<Item> getItems(final long... IDs) { return getItems(Utils.convert(IDs)); } /** * @return the languages */ public static List<String> getLanguages() { return BaseRiotAPI.getLanguages(); } /** * @return the language strings */ public static Map<String, String> getLanguageStrings() { final com.robrua.orianna.type.dto.staticdata.LanguageStrings str = BaseRiotAPI.getLanguageStrings(); return str.getData(); } /** * @return information for the maps */ public synchronized static List<MapDetails> getMapInformation() { if(RiotAPI.store.hasAll(MapDetails.class)) { return RiotAPI.store.getAll(MapDetails.class); } final MapData inf = BaseRiotAPI.getMapInformation(); final List<MapDetails> info = new ArrayList<>(inf.getData().size()); final List<Long> IDs = new ArrayList<>(info.size()); for(final com.robrua.orianna.type.dto.staticdata.MapDetails map : inf.getData().values()) { info.add(new MapDetails(map)); IDs.add(map.getMapId().longValue()); } RiotAPI.store.store(info, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(info); } /** * @return all the masteries */ public synchronized static List<Mastery> getMasteries() { if(RiotAPI.store.hasAll(Mastery.class)) { return RiotAPI.store.getAll(Mastery.class); } final MasteryList its = BaseRiotAPI.getMasteries(); final List<Mastery> masteries = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(masteries.size()); for(final com.robrua.orianna.type.dto.staticdata.Mastery mastery : its.getData().values()) { masteries.add(new Mastery(mastery)); IDs.add(mastery.getId().longValue()); } RiotAPI.store.store(masteries, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(masteries); } /** * @param IDs * the IDs of the masteries to get * @return the masteries */ public synchronized static List<Mastery> getMasteries(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Mastery> masteries = RiotAPI.store.get(Mastery.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(masteries.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return masteries; } if(toGet.size() == 1) { masteries.set(index.get(0), getMastery(toGet.get(0))); return masteries; } getMasteries(); final List<Mastery> gotten = RiotAPI.store.get(Mastery.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { masteries.set(id, gotten.get(count++)); } return Collections.unmodifiableList(masteries); } /** * @param IDs * the IDs of the masteries to get * @return the masteries */ public static List<Mastery> getMasteries(final long... IDs) { return getMasteries(Utils.convert(IDs)); } /** * @param ID * the ID of the mastery to get * @return the mastery */ public synchronized static Mastery getMastery(final long ID) { Mastery mastery = RiotAPI.store.get(Mastery.class, (int)ID); if(mastery != null) { return mastery; } final com.robrua.orianna.type.dto.staticdata.Mastery mast = BaseRiotAPI.getMastery(ID); mastery = new Mastery(mast); RiotAPI.store.store(mastery, (int)ID); return mastery; } /** * @return the realm */ public synchronized static Realm getRealm() { Realm realm = RiotAPI.store.get(Realm.class, 0L); if(realm != null) { return realm; } realm = new Realm(BaseRiotAPI.getRealm()); RiotAPI.store.store(realm, 0); return realm; } /** * @param ID * the ID of the rune to get * @return the rune */ public synchronized static Rune getRune(final long ID) { Rune rune = RiotAPI.store.get(Rune.class, (int)ID); if(rune != null) { return rune; } final com.robrua.orianna.type.dto.staticdata.Rune run = BaseRiotAPI.getRune(ID); rune = new Rune(run); RiotAPI.store.store(rune, (int)ID); return rune; } /** * @return all the runes */ public synchronized static List<Rune> getRunes() { if(RiotAPI.store.hasAll(Rune.class)) { return RiotAPI.store.getAll(Rune.class); } final RuneList its = BaseRiotAPI.getRunes(); final List<Rune> runes = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(runes.size()); for(final com.robrua.orianna.type.dto.staticdata.Rune rune : its.getData().values()) { runes.add(new Rune(rune)); IDs.add(rune.getId().longValue()); } RiotAPI.store.store(runes, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(runes); } /** * @param IDs * the IDs of the runes to get * @return the runes */ public synchronized static List<Rune> getRunes(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Rune> runes = RiotAPI.store.get(Rune.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(runes.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return runes; } if(toGet.size() == 1) { runes.set(index.get(0), getRune(toGet.get(0))); return runes; } getRunes(); final List<Rune> gotten = RiotAPI.store.get(Rune.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { runes.set(id, gotten.get(count++)); } return Collections.unmodifiableList(runes); } /** * @param IDs * the IDs of the runes to get * @return the runes */ public static List<Rune> getRunes(final long... IDs) { return getRunes(Utils.convert(IDs)); } /** * @param ID * the ID of the summoner spell to get * @return the summoner spell */ public synchronized static SummonerSpell getSummonerSpell(final long ID) { SummonerSpell spell = RiotAPI.store.get(SummonerSpell.class, (int)ID); if(spell != null) { return spell; } final com.robrua.orianna.type.dto.staticdata.SummonerSpell spl = BaseRiotAPI.getSummonerSpell(ID); spell = new SummonerSpell(spl); RiotAPI.store.store(spell, (int)ID); return spell; } /** * @return all the summoner spells */ public synchronized static List<SummonerSpell> getSummonerSpells() { if(RiotAPI.store.hasAll(SummonerSpell.class)) { return RiotAPI.store.getAll(SummonerSpell.class); } final SummonerSpellList its = BaseRiotAPI.getSummonerSpells(); final List<SummonerSpell> spells = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(spells.size()); for(final com.robrua.orianna.type.dto.staticdata.SummonerSpell spell : its.getData().values()) { spells.add(new SummonerSpell(spell)); IDs.add(spell.getId().longValue()); } RiotAPI.store.store(spells, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(spells); } /** * @param IDs * the IDs of the summoner spells to get * @return the summoner spells */ public synchronized static List<SummonerSpell> getSummonerSpells(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<SummonerSpell> spells = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(spells.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return spells; } if(toGet.size() == 1) { spells.set(index.get(0), getSummonerSpell(toGet.get(0))); return spells; } getSummonerSpells(); final List<SummonerSpell> gotten = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { spells.set(id, gotten.get(count++)); } return Collections.unmodifiableList(spells); } /** * @param IDs * the IDs of the summoner spells to get * @return the summoner spells */ public static List<SummonerSpell> getSummonerSpells(final long... IDs) { return getSummonerSpells(Utils.convert(IDs)); } /** * @return the versions */ public static List<String> getVersions() { return BaseRiotAPI.getVersions(); } }
package de.unipaderborn.visuflow.ui.graph; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_FILTER_GRAPH; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_MODEL_CHANGED; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_SELECTION; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_UNIT_CHANGED; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Image; import java.awt.Label; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import org.apache.commons.lang.StringEscapeUtils; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.graphstream.algorithm.Toolkit; import org.graphstream.graph.Edge; import org.graphstream.graph.Graph; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.MultiGraph; import org.graphstream.ui.geom.Point3; import org.graphstream.ui.graphicGraph.GraphicElement; import org.graphstream.ui.layout.Layout; import org.graphstream.ui.layout.springbox.implementations.SpringBox; import org.graphstream.ui.swingViewer.ViewPanel; import org.graphstream.ui.view.Viewer; import org.graphstream.ui.view.ViewerListener; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import com.google.common.base.Optional; import de.unipaderborn.visuflow.Logger; import de.unipaderborn.visuflow.ProjectPreferences; import de.unipaderborn.visuflow.Visuflow; import de.unipaderborn.visuflow.builder.GlobalSettings; import de.unipaderborn.visuflow.debug.handlers.NavigationHandler; import de.unipaderborn.visuflow.model.DataModel; import de.unipaderborn.visuflow.model.VFClass; import de.unipaderborn.visuflow.model.VFEdge; import de.unipaderborn.visuflow.model.VFMethod; import de.unipaderborn.visuflow.model.VFMethodEdge; import de.unipaderborn.visuflow.model.VFNode; import de.unipaderborn.visuflow.model.VFUnit; import de.unipaderborn.visuflow.model.graph.ControlFlowGraph; import de.unipaderborn.visuflow.model.graph.ICFGStructure; import de.unipaderborn.visuflow.ui.graph.formatting.UnitFormatter; import de.unipaderborn.visuflow.ui.graph.formatting.UnitFormatterFactory; import de.unipaderborn.visuflow.ui.view.filter.ReturnPathFilter; import de.unipaderborn.visuflow.util.ServiceUtil; import scala.collection.mutable.HashSet; import soot.Unit; import soot.jimple.ReturnStmt; import soot.jimple.ReturnVoidStmt; import soot.jimple.Stmt; /** * @author Shashank B S * */ public class GraphManager implements Runnable, ViewerListener, EventHandler { private static final transient Logger logger = Visuflow.getDefault().getLogger(); /** * Instance of {@link org.graphstream.graph.Graph} object. */ Graph graph; /** * Path to the style sheet of the graph. */ String styleSheetPath; /** * Limit on the number of characters of the node attributes. */ int maxLength; private Viewer viewer; private ViewPanel view; List<VFClass> analysisData; static Node start = null; static Node end, previous = null; static Map<Node, Node> map = new HashMap<>(); static HashSet<Node> setOfNode = new HashSet<>(); Container panel; JApplet applet; JButton zoomInButton, zoomOutButton, showICFGButton, colorSettingsButton; JToolBar headerBar, settingsBar; JTextField searchTextField; JLabel header; JDialog dialog; JPanel panelColor; JColorChooser jcc; List<JButton> stmtTypes; double zoomInDelta, zoomOutDelta, maxZoomPercent, minZoomPercent, panXDelta, panYDelta; Layout graphLayout = new SpringBox(); private JButton panLeftButton; private JButton panRightButton; private JButton panUpButton; private JButton panDownButton; private JPopupMenu popUp; private BufferedImage imgLeft; private BufferedImage imgRight; private BufferedImage imgUp; private BufferedImage imgDown; private BufferedImage imgPlus; private BufferedImage imgMinus; /** * The X coordinate of the pop up window to be displayed. */ private int x = 0; /** * The Y coordinate of the pop up window to be displayed. */ private int y = 0; /** * Flag that determines the type of the displayed graph. */ private boolean CFG; // following 3 variables are used for graph dragging with the mouse private boolean draggingGraph = false; private Point mouseDraggedFrom; private Point mouseDraggedTo; private JMenuItem navigateToJimple; private JMenuItem navigateToJava; private JMenuItem showInUnitView; private JMenuItem followCall; private JMenuItem followReturn; private JMenuItem setCustomAttribute; private JMenu callGraphOption; private JMenuItem cha; private JMenuItem spark; private String nodeAttributesString = "nodeData.attributes"; /** * Creates a new instance of graph manager used for rendering ICFG and CFG. * * @param graphName - name of the graph * @param - styleSheet path to the style sheet file * @author Shashank B S */ public GraphManager(String graphName, String styleSheet) { this.panXDelta = 2; this.panYDelta = 2; this.zoomInDelta = .075; this.zoomOutDelta = .075; this.maxZoomPercent = 0.1; this.minZoomPercent = 3.0; this.maxLength = 55; this.styleSheetPath = styleSheet; createGraph(graphName); createUI(); renderICFG(ServiceUtil.getService(DataModel.class).getIcfg()); adjustToolbarButtonHeights(); } private void adjustToolbarButtonHeights() { Dimension d = new Dimension(90, 32); showICFGButton.setSize(d); showICFGButton.setPreferredSize(d); showICFGButton.setMinimumSize(d); showICFGButton.setMaximumSize(d); d = new Dimension(100, 32); colorSettingsButton.setSize(d); colorSettingsButton.setPreferredSize(d); colorSettingsButton.setMinimumSize(d); colorSettingsButton.setMaximumSize(d); } /** * @return JRootPane which can be used as a container to be rendered in a view * @author Shashank B S */ public Container getApplet() { return applet.getRootPane(); } /** * Registers the event topics for which this class is to be notified about. Refer to {@link DataModel#EA_TOPIC_DATA} * @author Shashank B S */ private void registerEventHandler() { String[] topics = new String[] { EA_TOPIC_DATA_FILTER_GRAPH, EA_TOPIC_DATA_SELECTION, EA_TOPIC_DATA_MODEL_CHANGED, EA_TOPIC_DATA_UNIT_CHANGED, "GraphReady" }; Hashtable<String, Object> properties = new Hashtable<>(); properties.put(EventConstants.EVENT_TOPIC, topics); ServiceUtil.registerService(EventHandler.class, this, properties); } /** * Creates a new MultiGraph in the GUI thread and sets the attributes of styleSheet, quality and antialias to true. This method is called from {@link #GraphManager(String, String)} * @param graphName - name of the graph * @author Shashank B S */ void createGraph(String graphName) { graph = new MultiGraph(graphName); graph.addAttribute("ui.stylesheet", styleSheetPath); graph.setStrict(true); graph.setAutoCreate(true); graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD); viewer.setCloseFramePolicy(Viewer.CloseFramePolicy.CLOSE_VIEWER); view = viewer.addDefaultView(false); view.getCamera().setAutoFitView(true); } /** * Reinitializes the graph by deleting the existing nodes and resets the attributes. * * @throws Exception when graph is null * @author Shashank B S */ private void reintializeGraph() throws Exception { if (graph != null) { graph.clear(); graph.addAttribute("ui.stylesheet", styleSheetPath); graph.setStrict(true); graph.setAutoCreate(true); graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); } else { throw new Exception("Graph is null"); } } /** * Creates the all the necessary components and the necessary handlers for the CFG view. * @author Shashank B S */ private void createUI() { createIcons(); createZoomControls(); createShowICFGButton(); createPanningButtons(); createPopUpMenuItemsAndListeners(); createViewListeners(); createSearchTextBar(); createHeaderBar(); createSettingsBar(); createPanel(); createAppletContainer(); } /** * Pans the CFG view up by {@link #panYDelta} points. * @author Shashank B S */ private void panUp() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x, currCenter.y + panYDelta, 0); } /** * Pans the CFG view down by {@link #panYDelta} points. * @author Shashank B S */ private void panDown() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x, currCenter.y - panYDelta, 0); } /** * Pans the CFG view left by {@link #panXDelta} points. * @author Shashank B S */ private void panLeft() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x - panXDelta, currCenter.y, 0); } /** * Pans the CFG view right by {@link #panXDelta} points. * @author Shashank B S */ private void panRight() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x + panXDelta, currCenter.y, 0); } /** * Pans the graph to the view of the node with the {@code nodeId}. * @param nodeId - Id of the node to pan the graph * @author Shashank B S */ private void panToNode(String nodeId) { Node panToNode = graph.getNode(nodeId); double[] pos = Toolkit.nodePosition(panToNode); double currPosition = view.getCamera().getViewCenter().y; Point3 viewCenter = view.getCamera().getViewCenter(); double diff = pos[1] - viewCenter.y; double sign = Math.signum(diff); double steps = 15; double stepWidth = Math.abs(diff) / steps; for (int i = 0; i < steps; i++) { try { Thread.sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } currPosition += sign * stepWidth; view.getCamera().setViewCenter(pos[0], currPosition, 0.0); } } /** * Performs the default panning and zooming with animation based on the number of nodes in the graph. * @author Shashank B S */ private void defaultPanZoom() { int count = 0; if (graph.getNodeCount() > 10) count = 10; for (int i = 0; i < count; i++) { try { Thread.sleep(40); zoomOut(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Creates instances of buttons {@link #panLeftButton}, {@link #panRightButton}, {@link #panUpButton} and {@link #panDownButton} and its action listeners. * @author Shashank B S */ private void createPanningButtons() { panLeftButton = new JButton(""); panRightButton = new JButton(""); panUpButton = new JButton(""); panDownButton = new JButton(""); panLeftButton.setToolTipText("shift + arrow key left"); panRightButton.setToolTipText("shift + arrow key right"); panUpButton.setToolTipText("shift + arrow key up"); panDownButton.setToolTipText("shift + arrow key down"); panLeftButton.setIcon(new ImageIcon(getScaledImage(imgLeft, 20, 20))); panRightButton.setIcon(new ImageIcon(getScaledImage(imgRight, 20, 20))); panUpButton.setIcon(new ImageIcon(getScaledImage(imgUp, 20, 20))); panDownButton.setIcon(new ImageIcon(getScaledImage(imgDown, 20, 20))); panLeftButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panLeft(); } }); panRightButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panRight(); } }); panUpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panUp(); } }); panDownButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panDown(); } }); } /** * creates JMenuItems {@link #navigateToJimple}, {@link #navigateToJava}, {@link #showInUnitView}, {@link #setCustomAttribute}, {@link #followCall}, {@link #followReturn}, {@link #cha}, {@link #spark} and their handlers. * @author Shashank B S */ private void createPopUpMenuItemsAndListeners() { navigateToJimple = new JMenuItem("Navigate to Jimple"); navigateToJava = new JMenuItem("Navigate to Java"); showInUnitView = new JMenuItem("Highlight on Units view"); setCustomAttribute = new JMenuItem("Set custom attribute"); followCall = new JMenuItem("Follow the Call"); followReturn = new JMenuItem("Follow the Return"); callGraphOption = new JMenu("Call Graph Option"); cha = new JMenuItem("CHA"); spark = new JMenuItem("SPARK"); callGraphOption.add(cha); callGraphOption.add(spark); followCall.setVisible(false); followReturn.setVisible(false); navigateToJimple.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); NavigationHandler handler = new NavigationHandler(); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); handler.highlightJimpleSource(units); } } }); setCustomAttribute.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) { return; } Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { VFUnit selectedVF = ((VFNode) node).getVFUnit(); setCustomAttribute(selectedVF, curr); // curr.setAttribute("ui.color", jcc.getColor()); } } }); navigateToJava.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); NavigationHandler handler = new NavigationHandler(); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); handler.highlightJavaSource(units.get(0)); } } }); showInUnitView.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { DataModel dataModel = ServiceUtil.getService(DataModel.class); GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); ArrayList<VFNode> nodes = new ArrayList<>(); nodes.add((VFNode) node); try { dataModel.filterGraph(nodes, true, true, null); } catch (Exception e1) { e1.printStackTrace(); } } } }); followCall.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if(curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { if (((Stmt) ((VFNode) node).getUnit()).containsInvokeExpr()){ List<VFUnit> list = new ArrayList<>(); for(VFUnit edge : ((VFNode) node).getVFUnit().getOutgoingEdges()){ list.add(edge); } if(list.size() == 1) { returnToCaller(list.get(0)); } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { ReturnPathFilter callFilter = new ReturnPathFilter(Display.getDefault().getActiveShell()); callFilter.setPaths(list); callFilter.setInitialPattern("?"); callFilter.open(); if(callFilter.getFirstResult() != null){ jumpToCallee((VFUnit) callFilter.getFirstResult()); } } }); } } } } }); followReturn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { if (((VFNode) node).getUnit() instanceof ReturnStmt || ((VFNode) node).getUnit() instanceof ReturnVoidStmt) { List<VFUnit> list = new ArrayList<>(); for (VFUnit edge : ((VFNode) node).getVFUnit().getVfMethod().getIncomingEdges()) { list.add(edge); } if(list.size() == 1) { returnToCaller(list.get(0)); } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { Shell shell = Display.getDefault().getActiveShell(); ReturnPathFilter returnFilter = new ReturnPathFilter(shell); returnFilter.setPaths(list); returnFilter.setInitialPattern("?"); returnFilter.open(); if (returnFilter.getFirstResult() != null) { returnToCaller((VFUnit) returnFilter.getFirstResult()); } } }); } } } } }); cha.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GlobalSettings.put("CallGraphOption", "CHA"); ServiceUtil.getService(DataModel.class).triggerProjectRebuild(); header.setText(header.getText() + " } }); spark.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GlobalSettings.put("CallGraphOption", "SPARK"); ServiceUtil.getService(DataModel.class).triggerProjectRebuild(); header.setText(header.getText() + " } }); } /** * Creates icons {@link #imgLeft}, {@link #imgRight}, {@link #imgUp}, {@link #imgDown}, {@link #imgPlus}, {@link #imgMinus} to be added to the {@link #settingsBar}. * @author Shashank B S */ private void createIcons() { try { ClassLoader loader = GraphManager.class.getClassLoader(); imgLeft = ImageIO.read(loader.getResource("/icons/left.png")); imgRight = ImageIO.read(loader.getResource("/icons/right.png")); imgUp = ImageIO.read(loader.getResource("/icons/up.png")); imgDown = ImageIO.read(loader.getResource("/icons/down.png")); imgPlus = ImageIO.read(loader.getResource("/icons/plus.png")); imgMinus = ImageIO.read(loader.getResource("/icons/minus.png")); } catch (IOException e) { e.printStackTrace(); } } /** * Resizes and returns the {@code image} to the dimensions of {@code width} and {@code height}. * * @param image - the source image to be resized * @param width - the new width * @param height - the new height * @return resized image - the resized image to the provided width and height * * @author Shashank B S */ private Image getScaledImage(Image image, int width, int height) { BufferedImage resizedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, width, height, null); g2.dispose(); return resizedImg; } /** * Create and add the handler to the {@link #showICFGButton}. * @author Shashank B S */ private void createShowICFGButton() { showICFGButton = new JButton("Show ICFG"); showICFGButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { renderICFG(ServiceUtil.getService(DataModel.class).getIcfg()); } }); } /** * Creates JTextFiled, focus and action listeners for the graph search functionality. * @author Shashank B S */ private void createSearchTextBar() { this.searchTextField = new JTextField("Search graph"); searchTextField.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { searchTextField.setText("Search graph"); } @Override public void focusGained(FocusEvent e) { searchTextField.setText(""); } }); searchTextField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String searchString = searchTextField.getText().toLowerCase(); if(searchString.isEmpty()) return; ArrayList<VFNode> vfNodes = new ArrayList<>(); ArrayList<VFUnit> vfUnits = new ArrayList<>(); for (Node node : graph) { if (node.getAttribute("ui.label").toString().toLowerCase().contains((searchString)) || (node.hasAttribute(nodeAttributesString) && node.getAttribute(nodeAttributesString).toString().toLowerCase().contains(searchString))) { vfNodes.add((VFNode) node.getAttribute("nodeUnit")); vfUnits.add(((VFNode) node.getAttribute("nodeUnit")).getVFUnit()); } } try { DataModel model = ServiceUtil.getService(DataModel.class); model.filterGraph(vfNodes, true, true, "filter"); } catch (Exception e1) { e1.printStackTrace(); } NavigationHandler handler = new NavigationHandler(); handler.highlightJimpleSource(vfUnits); } }); } /** * Creates an instance of JAppletContainer {@link #applet} and adds the container {@link #panel} to it. * @author Shashank B S */ private void createAppletContainer() { applet = new JApplet(); applet.add(panel); } /** * Creates an instance of JToolBar {@link #settingsBar} and adds {@link #zoomInButton}, {@link #zoomOutButton}, {@link #showICFGButton}, {@link #colorSettingsButton}, {@link #panLeftButton}, {@link #panRightButton}, {@link #panUpButton}, {@link #panDownButton}, {@link #searchTextField} components to it. * @author Shashank B S */ private void createSettingsBar() { settingsBar = new JToolBar("ControlsBar", JToolBar.HORIZONTAL); settingsBar.add(zoomInButton); settingsBar.add(zoomOutButton); settingsBar.add(showICFGButton); settingsBar.add(colorSettingsButton); settingsBar.add(panLeftButton); settingsBar.add(panRightButton); settingsBar.add(panUpButton); settingsBar.add(panDownButton); settingsBar.add(searchTextField); } /** * Creates an instance of JToolBar {@link #headerBar} and adds an instance of JLabel {@link #header} to it. * @author Shashank B S */ private void createHeaderBar() { this.headerBar = new JToolBar("Header"); this.headerBar.setFloatable(false); this.header = new JLabel("ICFG"); this.headerBar.add(header); } /** * Creates an instance of JFrame {@link #panel} and adds the graph view {@link #view} to the {@link #panel}. * @author Shashank B S */ private void createPanel() { JFrame temp = new JFrame(); temp.setLayout(new BorderLayout()); panel = temp.getContentPane(); panel.add(headerBar,BorderLayout.PAGE_START); panel.add(view); panel.add(settingsBar, BorderLayout.PAGE_END); } /** * Creates mouse listeners and keyboard listeners for the CFG view. * @author Shashank B S */ private void createViewListeners() { MouseMotionListener defaultListener = view.getMouseMotionListeners()[0]; view.removeMouseMotionListener(defaultListener); view.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { int rotationDirection = e.getWheelRotation(); if (rotationDirection > 0) zoomIn(); else zoomOut(); } }); view.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent event) { GraphicElement curElement = view.findNodeOrSpriteAt(event.getX(), event.getY()); if (curElement == null) { view.setToolTipText(null); } if (curElement != null) { Node node = graph.getNode(curElement.getId()); String result = "<html><table>"; int maxToolTipLength = 0; for (String key : node.getEachAttributeKey()) { if (key.startsWith("nodeData")) { Object value = node.getAttribute(key); String tempVal = key.substring(key.lastIndexOf(".") + 1) + " : " + value.toString(); if (tempVal.length() > maxToolTipLength) { maxToolTipLength = tempVal.length(); } result += "<tr><td>" + key.substring(key.lastIndexOf(".") + 1) + "</td>" + "<td>" + value.toString() + "</td></tr>"; } } result += "</table></html>"; view.setToolTipText(result); } } @Override public void mouseDragged(MouseEvent e) { if (draggingGraph) { dragGraph(e); } else { defaultListener.mouseDragged(e); } } private void dragGraph(MouseEvent e) { if (mouseDraggedFrom == null) { mouseDraggedFrom = e.getPoint(); } else { if (mouseDraggedTo != null) { mouseDraggedFrom = mouseDraggedTo; } mouseDraggedTo = e.getPoint(); Point3 from = view.getCamera().transformPxToGu(mouseDraggedFrom.x, mouseDraggedFrom.y); Point3 to = view.getCamera().transformPxToGu(mouseDraggedTo.x, mouseDraggedTo.y); double deltaX = from.x - to.x; double deltaY = from.y - to.y; double deltaZ = from.z - to.z; Point3 viewCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(viewCenter.x + deltaX, viewCenter.y + deltaY, viewCenter.z + deltaZ); } } }); view.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { draggingGraph = false; } @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { // reset mouse drag tracking mouseDraggedFrom = null; mouseDraggedTo = null; draggingGraph = true; } } @Override public void mouseExited(MouseEvent e) { // noop } @Override public void mouseEntered(MouseEvent e) { // noop } @Override public void mouseClicked(MouseEvent e) { DataModel dataModel = ServiceUtil.getService(DataModel.class); GraphicElement curElement = view.findNodeOrSpriteAt(e.getX(), e.getY()); if (e.getButton() == MouseEvent.BUTTON3 && !CFG) { x = e.getX(); y = e.getY(); popUp = new JPopupMenu("right click menu"); popUp.add(callGraphOption); popUp.show(e.getComponent(), x, y); } if (e.getButton() == MouseEvent.BUTTON3 && CFG) { x = e.getX(); y = e.getY(); if (curElement != null) { popUp = new JPopupMenu("right click menu"); popUp.add(navigateToJimple); popUp.add(navigateToJava); popUp.add(showInUnitView); popUp.add(setCustomAttribute); popUp.add(followCall); popUp.add(followReturn); popUp.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) { return; } Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { if (((Stmt) ((VFNode) node).getUnit()).containsInvokeExpr()) { followCall.setVisible(true); followReturn.setVisible(false); } else if (((VFNode) node).getUnit() instanceof ReturnStmt || ((VFNode) node).getUnit() instanceof ReturnVoidStmt) { followCall.setVisible(false); followReturn.setVisible(true); } else { followCall.setVisible(false); followReturn.setVisible(false); } } } @Override public void popupMenuCanceled(PopupMenuEvent arg0) { followCall.setVisible(false); followReturn.setVisible(false); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) { followCall.setVisible(false); followReturn.setVisible(false); } }); popUp.show(e.getComponent(), x, y); } } if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); if (e.getButton() == MouseEvent.BUTTON1 && !CFG && !((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK)) { Object node = curr.getAttribute("nodeMethod"); if (node instanceof VFMethod) { VFMethod selectedMethod = (VFMethod) node; try { if (selectedMethod.getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { dataModel.setSelectedMethod(selectedMethod, true); } } catch (Exception e1) { e1.printStackTrace(); } } } else if (e.getButton() == MouseEvent.BUTTON1 && CFG && !((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK)) { Object node = curr.getAttribute("nodeUnit"); NavigationHandler handler = new NavigationHandler(); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); handler.highlightJimpleSource(units); handler.highlightJavaSource(units.get(0)); ArrayList<VFNode> nodes = new ArrayList<>(); nodes.add((VFNode) node); try { dataModel.filterGraph(nodes, true, true, null); } catch (Exception e1) { e1.printStackTrace(); } } } else if (e.getButton() == MouseEvent.BUTTON1 && (e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { String id = curr.getId(); if (id != null) toggleNode(id); } if (e.getButton() == MouseEvent.BUTTON3 && CFG) { x = e.getX(); y = e.getY(); if (curElement != null) popUp.show(e.getComponent(), x, y); } } }); view.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (e.isShiftDown()) { switch (keyCode) { case KeyEvent.VK_UP: // handle up panUp(); break; case KeyEvent.VK_DOWN: // handle down panDown(); break; case KeyEvent.VK_LEFT: // handle left panLeft(); break; case KeyEvent.VK_RIGHT: // handle right panRight(); break; } } } }); } private void returnToCaller(VFUnit unit) { if (unit == null) return; DataModel dataModel = ServiceUtil.getService(DataModel.class); try { if (unit.getVfMethod().getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { VFNode node = new VFNode(unit, 0); List<VFNode> nodes = Collections.singletonList(node); dataModel.filterGraph(nodes, true, true, "filter"); } } catch (Exception e1) { e1.printStackTrace(); } } private void jumpToCallee(VFUnit unit){ if(unit == null) return; DataModel dataModel = ServiceUtil.getService(DataModel.class); try { if(unit.getVfMethod().getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { dataModel.setSelectedMethod(unit.getVfMethod(), true); } } catch (Exception e1) { e1.printStackTrace(); } } /** * zooms out the graph by decreasing the view percent by {@link #zoomInDelta} points. * @author Shashank B S */ private void zoomOut() { double viewPercent = view.getCamera().getViewPercent(); if (viewPercent > maxZoomPercent) view.getCamera().setViewPercent(viewPercent - zoomInDelta); } /** * zooms in the graph by decreasing the view percent by {@link #zoomOutDelta} points. * @author Shashank B S */ private void zoomIn() { double viewPercent = view.getCamera().getViewPercent(); if (viewPercent < minZoomPercent) view.getCamera().setViewPercent(viewPercent + zoomOutDelta); } /** * Create zoom control buttons {@link #zoomInButton}, {@link #zoomOutButton} and action listeners. * @author Shashank B S */ private void createZoomControls() { zoomInButton = new JButton(); zoomOutButton = new JButton(); zoomInButton.setIcon(new ImageIcon(getScaledImage(imgPlus, 20, 20))); zoomOutButton.setIcon(new ImageIcon(getScaledImage(imgMinus, 20, 20))); zoomInButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomOut(); } }); zoomOutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomIn(); } }); createColorSettingsDialogButton(); } private void createColorSettingsDialogButton() { jcc = new JColorChooser(Color.RED); jcc.getSelectionModel().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // Color color = jcc.getColor(); } }); dialog = JColorChooser.createDialog(null, "Color Chooser", true, jcc, null, null); panelColor = new JPanel(new GridLayout(0, 2)); colorSettingsButton = new JButton("Color Settings"); colorSettingsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createColorSettingsDialogue(); } }); } /** * Filters and highlights the graph by setting the {@code uiClassForFilteredNodes} class on the filtered nodes based on the boolean value {@code selection} and also pans the view to the last filtered node based on the value of {@code panToNode}. * @param nodes - nodes to be filtered * @param selection - flag to determine whether the nodes have to be highlighted * @param panToNode - flag to determine whether to pan the graph to the last filtered node * @param uiClassForFilteredNodes - class name to be set on filtered nodes, defaults to <b>filter</b> if the passed in value is null * @author Shashank B S */ private void filterGraphNodes(List<VFNode> nodes, boolean selection, boolean panToNode, String uiClassForFilteredNodes) { boolean panned = false; if (uiClassForFilteredNodes == null) { uiClassForFilteredNodes = "filter"; } Iterable<? extends Node> graphNodes = graph.getEachNode(); for (Node node : graphNodes) { if (node.hasAttribute("ui.class")) { node.removeAttribute("ui.class"); } for (VFNode vfNode : nodes) { if (node.getAttribute("unit").toString().contentEquals(vfNode.getUnit().toString())) { if (selection) { node.removeAttribute("ui.color"); node.addAttribute("ui.class", uiClassForFilteredNodes); } if (!panned && panToNode) { this.panToNode(node.getId()); panned = true; } } } } } /** * Creates the ICFG, sets {@link #header} to <b>ICFG</b> sets {@link #CFG} to false and sets the layout of the graph. * @param icfg * @author Shashank B S */ private void renderICFG(ICFGStructure icfg) { if (icfg == null) { return; } Iterator<VFMethodEdge> iterator = icfg.listEdges.iterator(); try { reintializeGraph(); } catch (Exception e) { e.printStackTrace(); } while (iterator.hasNext()) { VFMethodEdge curr = iterator.next(); VFMethod src = curr.getSourceMethod(); VFMethod dest = curr.getDestMethod(); createGraphMethodNode(src); createGraphMethodNode(dest); createGraphMethodEdge(src, dest); } this.CFG = false; this.header.setText("ICFG"); experimentalLayout(); } /** * Creates an edge between the graph method nodes. * * @param src * @param dest * @author Shashank B S */ private void createGraphMethodEdge(VFMethod src, VFMethod dest) { if (graph.getEdge("" + src.getId() + dest.getId()) == null) { graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true); } } /** * Creates the graph method node and sets the label, methodName, methodSignature, methodBody and nodeMethod attributes on the node. * * @param src * @author Shashank B S */ private void createGraphMethodNode(VFMethod src) { if (graph.getNode(src.getId() + "") == null) { Node createdNode = graph.addNode(src.getId() + ""); String methodName = src.getSootMethod().getName(); String escapedMethodName = StringEscapeUtils.escapeHtml(methodName); String escapedMethodSignature = StringEscapeUtils.escapeHtml(src.getSootMethod().getSignature()); createdNode.setAttribute("ui.label", methodName); createdNode.setAttribute("nodeData.methodName", escapedMethodName); createdNode.setAttribute("nodeData.methodSignature", escapedMethodSignature); String methodBody = src.getBody().toString(); methodBody = Pattern.compile("^[ ]{4}", Pattern.MULTILINE).matcher(methodBody).replaceAll(""); // remove indentation at line start methodBody = methodBody.replaceAll("\n{2,}", "\n"); // replace empty lines String escapedMethodBody = StringEscapeUtils.escapeHtml(methodBody); String hexColor = getCodeBackgroundColor(); createdNode.setAttribute("nodeData.methodBody", "<code><pre style=\"color: #000000; background-color: #"+hexColor+"\">" + escapedMethodBody + "</pre></code>"); createdNode.setAttribute("nodeMethod", src); } } private String getCodeBackgroundColor() { Color tooltipBackground = UIManager.getColor("ToolTip.background"); float[] hsb = new float[3]; hsb = Color.RGBtoHSB(tooltipBackground.getRed(), tooltipBackground.getGreen(), tooltipBackground.getBlue(), hsb); hsb[2] = hsb[2] * 0.95f; Color codeBackground = new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2])); String hexColor = Integer.toHexString(codeBackground.getRGB() & 0xffffff); return hexColor; } /** * Renders the method CFG, sets the {@link #CFG} to true and pans the graph to the first node of the graph based on the value of {@code panToNode}. * * @param cfg * @param panToNode * @throws Exception * @author Shashank B S */ private void renderMethodCFG(ControlFlowGraph cfg, boolean panToNode) throws Exception { if (cfg == null) throw new Exception("GraphStructure is null"); this.reintializeGraph(); ListIterator<VFEdge> edgeIterator = cfg.listEdges.listIterator(); while (edgeIterator.hasNext()) { VFEdge currEdgeIterator = edgeIterator.next(); VFNode src = currEdgeIterator.getSource(); VFNode dest = currEdgeIterator.getDestination(); createControlFlowGraphNode(src); createControlFlowGraphNode(dest); createControlFlowGraphEdge(src, dest); } if (cfg.listEdges.size() == 1) { VFNode node = cfg.listNodes.get(0); createControlFlowGraphNode(node); } this.CFG = true; experimentalLayout(); if (panToNode) { defaultPanZoom(); panToNode(graph.getNodeIterator().next().getId()); } this.header.setText("Method CFG ----> " + ServiceUtil.getService(DataModel.class).getSelectedMethod().toString()); } /** * Creates an edge between two CFG nodes. * * @param src * @param dest * @author Shashank B S */ private void createControlFlowGraphEdge(VFNode src, VFNode dest) { if (graph.getEdge("" + src.getId() + dest.getId()) == null) { Edge createdEdge = graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true); VFUnit unit = src.getVFUnit(); createdEdge.addAttribute("ui.label", Optional.fromNullable(unit.getOutSet()).or("").toString()); createdEdge.addAttribute("edgeData.outSet", Optional.fromNullable(unit.getInSet()).or("").toString()); } } /** * Creates the CFG node and sets the label, unit, escapedHTMLunit, unitType, inSet, outSet, color attributes. * * @param node * @author Shashank B S */ private void createControlFlowGraphNode(VFNode node) { if (graph.getNode(node.getId() + "") == null) { Node createdNode = graph.addNode(node.getId() + ""); Unit unit = node.getUnit(); String label = unit.toString(); try { UnitFormatter formatter = UnitFormatterFactory.createFormatter(unit); //UnitFormatter formatter = new DefaultFormatter(); label = formatter.format(unit, maxLength); } catch (Exception e) { logger.error("Unit formatting failed", e); } createdNode.setAttribute("ui.label", label); String str = unit.toString(); String escapedNodename = StringEscapeUtils.escapeHtml(str); createdNode.setAttribute("unit", str); createdNode.setAttribute("nodeData.unit", escapedNodename); createdNode.setAttribute("nodeData.unitType", node.getUnit().getClass()); String str1 = Optional.fromNullable(node.getVFUnit().getInSet()).or("n/a").toString(); String nodeInSet = StringEscapeUtils.escapeHtml(str1); String str2 = Optional.fromNullable(node.getVFUnit().getInSet()).or("n/a").toString(); String nodeOutSet = StringEscapeUtils.escapeHtml(str2); createdNode.setAttribute("nodeData.inSet", nodeInSet); createdNode.setAttribute("nodeData.outSet", nodeOutSet); Map<String, String> customAttributes = node.getVFUnit().getHmCustAttr(); String attributeData = ""; if(!customAttributes.isEmpty()) { Iterator<Entry<String, String>> customAttributeIterator = customAttributes.entrySet().iterator(); while(customAttributeIterator.hasNext()) { Entry<String, String> curr = customAttributeIterator.next(); attributeData += curr.getKey() + " : " + curr.getValue(); attributeData += "<br />"; } createdNode.setAttribute(nodeAttributesString, attributeData); } createdNode.setAttribute("nodeUnit", node); Color nodeColor = new Color(new ProjectPreferences().getColorForNode(node.getUnit().getClass().getName().toString())); createdNode.addAttribute("ui.color", nodeColor); } } /** * Layout the graph by setting the coordinates on the nodes. <br> * Refer to {@link de.unipaderborn.visuflow.ui.graph.HierarchicalLayout} */ private void experimentalLayout() { if (!CFG) { viewer.enableAutoLayout(new SpringBox()); view.getCamera().resetView(); return; } viewer.disableAutoLayout(); HierarchicalLayout.layout(graph); } /** * Toggles the visibility of the node and its children. * * @param nodeId * @author Shashank B S */ void toggleNode(String nodeId) { Node n = graph.getNode(nodeId); Object[] pos = n.getAttribute("xyz"); Iterator<Node> it = n.getBreadthFirstIterator(true); if (n.hasAttribute("collapsed")) { n.removeAttribute("collapsed"); while (it.hasNext()) { Node m = it.next(); for (Edge e : m.getLeavingEdgeSet()) { e.removeAttribute("ui.hide"); } m.removeAttribute("layout.frozen"); m.setAttribute("x", ((double) pos[0]) + Math.random() * 0.0001); m.setAttribute("y", ((double) pos[1]) + Math.random() * 0.0001); m.removeAttribute("ui.hide"); } n.removeAttribute("ui.class"); } else { n.setAttribute("ui.class", "plus"); n.setAttribute("collapsed"); while (it.hasNext()) { Node m = it.next(); for (Edge e : m.getLeavingEdgeSet()) { e.setAttribute("ui.hide"); } if (n != m) { m.setAttribute("layout.frozen"); // m.setAttribute("x", ((double) pos[0]) + Math.random() * 0.0001); // m.setAttribute("y", ((double) pos[1]) + Math.random() * 0.0001); m.setAttribute("xyz", ((double) pos[0]) + Math.random() * 0.0001, ((double) pos[1]) + Math.random() * 0.0001, 0.0); m.setAttribute("ui.hide"); } } } experimentalLayout(); panToNode(nodeId); } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { this.registerEventHandler(); } /* (non-Javadoc) * @see org.graphstream.ui.view.ViewerListener#buttonPushed(java.lang.String) */ @Override public void buttonPushed(String id) { // noop } /* (non-Javadoc) * @see org.graphstream.ui.view.ViewerListener#buttonReleased(java.lang.String) */ @Override public void buttonReleased(String id) { toggleNode(id); experimentalLayout(); } /* (non-Javadoc) * @see org.graphstream.ui.view.ViewerListener#viewClosed(java.lang.String) */ @Override public void viewClosed(String id) { // noop } /* (non-Javadoc) * @see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event) */ @SuppressWarnings("unchecked") @Override public void handleEvent(Event event) { if (event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_MODEL_CHANGED)) { renderICFG((ICFGStructure) event.getProperty("icfg")); } if (event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_SELECTION)) { VFMethod selectedMethod = (VFMethod) event.getProperty("selectedMethod"); boolean panToNode = (boolean) event.getProperty("panToNode"); try { renderMethodCFG(selectedMethod.getControlFlowGraph(), panToNode); } catch (Exception e) { e.printStackTrace(); } } if (event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_FILTER_GRAPH)) { filterGraphNodes((List<VFNode>) event.getProperty("nodesToFilter"), (boolean) event.getProperty("selection"), (boolean) event.getProperty("panToNode"), (String) event.getProperty("uiClassName")); } if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_UNIT_CHANGED)) { VFUnit unit = (VFUnit) event.getProperty("unit"); for (Edge edge : graph.getEdgeSet()) { Node src = edge.getSourceNode(); VFNode vfNode = src.getAttribute("nodeUnit"); if (vfNode != null) { VFUnit currentUnit = vfNode.getVFUnit(); if (unit.getFullyQualifiedName().equals(currentUnit.getFullyQualifiedName())) { String outset = Optional.fromNullable(unit.getOutSet()).or("").toString(); edge.setAttribute("ui.label", outset); edge.setAttribute("edgeData.outSet", outset); src.addAttribute("nodeData.inSet", unit.getInSet()); src.addAttribute("nodeData.outSet", unit.getOutSet()); } } } } } public void createColorSettingsDialogue() { panelColor.removeAll(); ProjectPreferences pref = new ProjectPreferences(); DataModel dataModel = ServiceUtil.getService(DataModel.class); for (JButton bt : createStmtTypes(stmtTypes)) { panelColor.add(new Label(bt.getName())); bt.setText("change color"); bt.setBackground(new Color(pref.getColorForNode(bt.getName()))); panelColor.add(bt); bt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(true); int color = jcc.getColor().getRGB(); JButton button = (JButton) e.getSource(); pref.updateColorPreferences(bt.getName(),color); button.setBackground(new Color(pref.getColorForNode(button.getName()))); if(CFG) dataModel.setSelectedMethod(dataModel.getSelectedMethod(), false); } }); } JButton resetDefaultColorSettingsButton = new JButton("Reset Defaults"); resetDefaultColorSettingsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pref.createPreferences(); dataModel.setSelectedMethod(dataModel.getSelectedMethod(), false); } }); panelColor.add(resetDefaultColorSettingsButton); JOptionPane.showConfirmDialog(null, panelColor, "Color Settings", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); } @SuppressWarnings("rawtypes") public void setCustomAttribute(VFUnit selectedVF, Node curr) { JPanel panel = new JPanel(new GridLayout(0, 2)); JTextField attributeName = new JTextField(""); JTextField attributeValue = new JTextField(""); panel.add(attributeName); panel.add(new JLabel("Attribute: ")); panel.add(attributeValue); panel.add(new JLabel("Attribute value: ")); int result = JOptionPane.showConfirmDialog(null, panel, "Setting custom attribute", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { Map<String, String> hmCustAttr = new HashMap<>(); // Get actual customized attributes Set set = selectedVF.getHmCustAttr().entrySet(); Iterator i = set.iterator(); String attributeString = ""; if(curr.hasAttribute(nodeAttributesString)) { attributeString += curr.getAttribute(nodeAttributesString) + "<br>"; curr.removeAttribute(nodeAttributesString); } else attributeString += ""; // Display elements while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); hmCustAttr.put((String) me.getKey(), (String) me.getValue()); } if ((attributeName.getText().length() > 0) && (attributeValue.getText().length() > 0)) { try { hmCustAttr.put(attributeName.getText(), attributeValue.getText()); selectedVF.setHmCustAttr(hmCustAttr); ArrayList<VFUnit> units = new ArrayList<>(); units.add(selectedVF); attributeString += attributeName.getText() + ":" + attributeValue.getText(); curr.setAttribute(nodeAttributesString, attributeString); curr.addAttribute("ui.color", Color.red.getRGB()); } catch (Exception e) { e.printStackTrace(); } } else { JOptionPane.showMessageDialog(new JPanel(), "Please make sure all fields are correctly filled out", "Warning", JOptionPane.WARNING_MESSAGE); } } } private List<JButton> createStmtTypes(List<JButton> stmtTypes) { stmtTypes = new ArrayList<>(); // All button JButton btJNopStmt, btJIdentityStmt, btJAssignStmt, btJIfStmt, btJGotoStmt, btJTableSwitchStmt, btJLookupSwitchStmt, btJInvokeStmt, btJReturnStmt, JReturnVoidStmt, btJThrowStmt, btJRetStmt, btJEnterMonitorSmt, btJExitMonitorStmt; btJNopStmt = new JButton("soot.jimple.internal.JNopStmt"); btJNopStmt.setName("soot.jimple.internal.JNopStmt"); btJIdentityStmt = new JButton("soot.jimple.internal.JIdentityStmt"); btJIdentityStmt.setName("soot.jimple.internal.JIdentityStmt"); btJAssignStmt = new JButton("soot.jimple.internal.JAssignStmt"); btJAssignStmt.setName("soot.jimple.internal.JAssignStmt"); btJIfStmt = new JButton("soot.jimple.internal.JIfStmt"); btJIfStmt.setName("soot.jimple.internal.JIfStmt"); btJGotoStmt = new JButton("soot.jimple.internal.JGotoStmt"); btJGotoStmt.setName("soot.jimple.internal.JGotoStmt"); btJTableSwitchStmt = new JButton("soot.jimple.internal.JTableSwitchStmt"); btJTableSwitchStmt.setName("soot.jimple.internal.JTableSwitchStmt"); btJLookupSwitchStmt = new JButton("soot.jimple.internal.JLookupSwitchStmt"); btJLookupSwitchStmt.setName("soot.jimple.internal.JLookupSwitchStmt"); btJInvokeStmt = new JButton("soot.jimple.internal.JInvokeStmt"); btJInvokeStmt.setName("soot.jimple.internal.JInvokeStmt"); btJReturnStmt = new JButton("soot.jimple.internal.JReturnStmt"); btJReturnStmt.setName("soot.jimple.internal.JReturnStmt"); JReturnVoidStmt = new JButton("soot.jimple.internal.JReturnVoidStmt"); JReturnVoidStmt.setName("soot.jimple.internal.JReturnVoidStmt"); btJThrowStmt = new JButton("soot.jimple.internal.JThrowStmt"); btJThrowStmt.setName("soot.jimple.internal.JThrowStmt"); btJRetStmt = new JButton("soot.jimple.internal.JRetStmt"); btJRetStmt.setName("soot.jimple.internal.JRetStmt"); btJEnterMonitorSmt = new JButton("soot.jimple.internal.JEnterMonitorStmt"); btJEnterMonitorSmt.setName("soot.jimple.internal.JEnterMonitorStmt"); btJExitMonitorStmt = new JButton("soot.jimple.internal.JExitMonitorStmt"); btJExitMonitorStmt.setName("soot.jimple.internal.JExitMonitorStmt"); // Add buttons to the list stmtTypes.add(btJNopStmt); stmtTypes.add(btJIdentityStmt); stmtTypes.add(btJAssignStmt); stmtTypes.add(btJIfStmt); stmtTypes.add(btJGotoStmt); stmtTypes.add(btJTableSwitchStmt); stmtTypes.add(btJLookupSwitchStmt); stmtTypes.add(btJInvokeStmt); stmtTypes.add(btJReturnStmt); stmtTypes.add(JReturnVoidStmt); stmtTypes.add(btJThrowStmt); stmtTypes.add(btJRetStmt); stmtTypes.add(btJEnterMonitorSmt); stmtTypes.add(btJExitMonitorStmt); return stmtTypes; } }
package com.vav.CTCI.Common.LinkedList; public class LinkedList<T> { private Link head; public LinkedList(){ head=null; } public void insertAtEnd(T data){ Link<T> node = new Link(data); node.setNext(null); if(head==null){ head = node; return; } Link current = head; while(current.getNext()!=null){ current = current.getNext(); } current.setNext(node); } public void insertAtStart(T data){ Link<T> node = new Link(data); node.setNext(null); if(head==null){ head = node; }else{ node.setNext(head); head = node; } } public void insertAtPosition(T data, int position){ Link<T> node = new Link(data); node.setNext(null); Link current = head; Link previous = null; int count=0; if(head == null){ head = node; return; } if(position ==0){ node.setNext(head); head =node; return; } while(current!=null && count<position){ previous = current; current = current.getNext(); count++; } previous.setNext(node); node.setNext(current); } public void printList(){ Link current = head; while(current!=null){ System.out.print(current.getData()+"->"); current=current.getNext(); } } public void deleteAtPosition(int position){ if(head==null){ System.out.println("List is empty!"); return; } if(position==0){ head = head.getNext(); return; } Link current=head,previous=null; int count=0; while(current.getNext()!=null &&count<position){ previous = current; current = current.getNext(); count++; } previous.setNext(current.getNext()); } //Works for integers public Link deleteWithValue(T value){ Link current = head; Link previous = current; //this may not work for strings or objects if(head.getData().equals(value)){ head = head.getNext(); return head; }else{ current = current.getNext(); } while (current.getData()!=null){ if(current.getData().equals(value)){ previous.setNext(current.getNext()); return head; } previous = current; current = current.getNext(); } return head; } public Link getHead(){ return head; } public void setHead(Link head){ this.head = head; } }
package me.nallar.patched.world; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.google.common.collect.ImmutableSetMultimap; import javassist.is.faulty.ThreadLocals; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.collections.ForcedChunksRedirectMap; import me.nallar.tickthreading.minecraft.entitylist.EntityList; import me.nallar.tickthreading.minecraft.entitylist.LoadedTileEntityList; import me.nallar.tickthreading.patcher.Declare; import net.minecraft.block.Block; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityTracker; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.profiler.Profiler; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldServer; import net.minecraft.world.WorldSettings; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.gen.ChunkProviderServer; import net.minecraft.world.storage.ISaveHandler; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; @SuppressWarnings ("unchecked") public abstract class PatchWorld extends World { private int forcedUpdateCount; @Declare public org.cliffc.high_scale_lib.NonBlockingHashMapLong<Integer> redstoneBurnoutMap_; @Declare public Set<Entity> unloadedEntitySet_; @Declare public Set<TileEntity> tileEntityRemovalSet_; @Declare public com.google.common.collect.ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> forcedChunks_; @Declare public int tickCount_; public void construct() { tickCount = rand.nextInt(240); // So when different worlds do every N tick actions, // they won't all happen at the same time even if the worlds loaded at the same time tileEntityRemovalSet = new HashSet<TileEntity>(); unloadedEntitySet = new HashSet<Entity>(); redstoneBurnoutMap = new NonBlockingHashMapLong<Integer>(); } public PatchWorld(ISaveHandler par1ISaveHandler, String par2Str, WorldProvider par3WorldProvider, WorldSettings par4WorldSettings, Profiler par5Profiler) { super(par1ISaveHandler, par2Str, par3WorldProvider, par4WorldSettings, par5Profiler); } @Override public void removeEntity(Entity entity) { if (entity == null) { return; } try { if (entity.riddenByEntity != null) { entity.riddenByEntity.mountEntity(null); } if (entity.ridingEntity != null) { entity.mountEntity(null); } entity.setDead(); // The next instanceof, somehow, seems to throw NPEs. I don't even. :( if (entity instanceof EntityPlayer) { this.playerEntities.remove(entity); this.updateAllPlayersSleepingFlag(); } } catch (Exception e) { Log.severe("Exception removing a player entity", e); } } @Override public int getBlockId(int x, int y, int z) { if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y > 0 && y < 256) { try { return getChunkFromChunkCoords(x >> 4, z >> 4).getBlockID(x & 15, y, z & 15); } catch (Throwable t) { Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t); } } return 0; } @Override @Declare public int getBlockIdWithoutLoad(int x, int y, int z) { if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y > 0 && y < 256) { try { Chunk chunk = ((ChunkProviderServer) chunkProvider).getChunkIfExists(x >> 4, z >> 4); return chunk == null ? -1 : chunk.getBlockID(x & 15, y, z & 15); } catch (Throwable t) { Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t); } } return 0; } @Override public EntityPlayer getClosestPlayer(double x, double y, double z, double maxRange) { double closestRange = Double.MAX_VALUE; EntityPlayer target = null; for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) { if (!playerEntity.capabilities.disableDamage && playerEntity.isEntityAlive()) { double distanceSq = playerEntity.getDistanceSq(x, y, z); if ((maxRange < 0.0D || distanceSq < (maxRange * maxRange)) && (distanceSq < closestRange)) { closestRange = distanceSq; target = playerEntity; } } } return target; } @SuppressWarnings ("ConstantConditions") @Override public EntityPlayer getClosestVulnerablePlayer(double x, double y, double z, double maxRange) { double closestRange = Double.MAX_VALUE; EntityPlayer target = null; for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) { if (!playerEntity.capabilities.disableDamage && playerEntity.isEntityAlive()) { double distanceSq = playerEntity.getDistanceSq(x, y, z); double effectiveMaxRange = maxRange; if (playerEntity.isSneaking()) { effectiveMaxRange = maxRange * 0.800000011920929D; } if (playerEntity.getHasActivePotion()) { float var18 = playerEntity.func_82243_bO(); if (var18 < 0.1F) { var18 = 0.1F; } effectiveMaxRange *= (double) (0.7F * var18); } if ((maxRange < 0.0D || distanceSq < (effectiveMaxRange * effectiveMaxRange)) && (distanceSq < closestRange)) { closestRange = distanceSq; target = playerEntity; } } } return target; } @Override public EntityPlayer getPlayerEntityByName(String name) { for (EntityPlayer player : (Iterable<EntityPlayer>) playerEntities) { if (name.equals(player.username)) { return player; } } return null; } @Override protected void notifyBlockOfNeighborChange(int x, int y, int z, int par4) { if (!this.editingBlocks && !this.isRemote) { int var5 = this.getBlockIdWithoutLoad(x, y, z); Block var6 = var5 < 1 ? null : Block.blocksList[var5]; if (var6 != null) { try { var6.onNeighborBlockChange(this, x, y, z, par4); } catch (Throwable t) { Log.severe("Exception while updating block neighbours", t); } } } } @Override public ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> getPersistentChunks() { return forcedChunks == null ? ForcedChunksRedirectMap.emptyMap : forcedChunks; } @Override public TileEntity getBlockTileEntity(int x, int y, int z) { if (y >= 256) { return null; } else { Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4); return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15); } } @Override @Declare public TileEntity getTEWithoutLoad(int x, int y, int z) { if (y >= 256) { return null; } else { Chunk chunk = ((ChunkProviderServer) this.chunkProvider).getChunkIfExists(x >> 4, z >> 4); return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15); } } @Override public void updateEntityWithOptionalForce(Entity par1Entity, boolean par2) { int x = MathHelper.floor_double(par1Entity.posX); int z = MathHelper.floor_double(par1Entity.posZ); Boolean isForced = par1Entity.isForced; if (isForced == null || forcedUpdateCount++ % 7 == 0) { par1Entity.isForced = isForced = getPersistentChunks().containsKey(new ChunkCoordIntPair(x >> 4, z >> 4)); } byte range = isForced ? (byte) 0 : 32; boolean canUpdate = !par2 || this.checkChunksExist(x - range, 0, z - range, x + range, 0, z + range); if (canUpdate) { par1Entity.lastTickPosX = par1Entity.posX; par1Entity.lastTickPosY = par1Entity.posY; par1Entity.lastTickPosZ = par1Entity.posZ; par1Entity.prevRotationYaw = par1Entity.rotationYaw; par1Entity.prevRotationPitch = par1Entity.rotationPitch; if (par2 && par1Entity.addedToChunk) { if (par1Entity.ridingEntity != null) { par1Entity.updateRidden(); } else { ++par1Entity.ticksExisted; par1Entity.onUpdate(); } } this.theProfiler.startSection("chunkCheck"); if (Double.isNaN(par1Entity.posX) || Double.isInfinite(par1Entity.posX)) { par1Entity.posX = par1Entity.lastTickPosX; } if (Double.isNaN(par1Entity.posY) || Double.isInfinite(par1Entity.posY)) { par1Entity.posY = par1Entity.lastTickPosY; } if (Double.isNaN(par1Entity.posZ) || Double.isInfinite(par1Entity.posZ)) { par1Entity.posZ = par1Entity.lastTickPosZ; } if (Double.isNaN((double) par1Entity.rotationPitch) || Double.isInfinite((double) par1Entity.rotationPitch)) { par1Entity.rotationPitch = par1Entity.prevRotationPitch; } if (Double.isNaN((double) par1Entity.rotationYaw) || Double.isInfinite((double) par1Entity.rotationYaw)) { par1Entity.rotationYaw = par1Entity.prevRotationYaw; } int var6 = MathHelper.floor_double(par1Entity.posX / 16.0D); int var7 = MathHelper.floor_double(par1Entity.posY / 16.0D); int var8 = MathHelper.floor_double(par1Entity.posZ / 16.0D); if (!par1Entity.addedToChunk || par1Entity.chunkCoordX != var6 || par1Entity.chunkCoordY != var7 || par1Entity.chunkCoordZ != var8) { if (par1Entity.addedToChunk) { Chunk chunk = getChunkIfExists(par1Entity.chunkCoordX, par1Entity.chunkCoordZ); if (chunk != null) { chunk.removeEntityAtIndex(par1Entity, par1Entity.chunkCoordY); } } Chunk chunk = getChunkIfExists(var6, var8); if (chunk != null) { par1Entity.addedToChunk = true; chunk.addEntity(par1Entity); } else { par1Entity.addedToChunk = false; } } this.theProfiler.endSection(); if (par2 && par1Entity.addedToChunk && par1Entity.riddenByEntity != null) { if (!par1Entity.riddenByEntity.isDead && par1Entity.riddenByEntity.ridingEntity == par1Entity) { this.updateEntity(par1Entity.riddenByEntity); } else { par1Entity.riddenByEntity.ridingEntity = null; par1Entity.riddenByEntity = null; } } } } @Override public void addLoadedEntities(List par1List) { EntityTracker entityTracker = null; //noinspection RedundantCast if (((Object) this instanceof WorldServer)) { entityTracker = ((WorldServer) (Object) this).getEntityTracker(); } for (int var2 = 0; var2 < par1List.size(); ++var2) { Entity entity = (Entity) par1List.get(var2); if (MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(entity, this))) { par1List.remove(var2 } else if (entityTracker == null || !entityTracker.isTracking(entity.entityId)) { loadedEntityList.add(entity); this.obtainEntitySkin(entity); } } } @Override @Declare public boolean hasCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) { List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get(); collidingBoundingBoxes.clear(); int minX = MathHelper.floor_double(par2AxisAlignedBB.minX); int maxX = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D); int minY = MathHelper.floor_double(par2AxisAlignedBB.minY); int maxY = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D); int minZ = MathHelper.floor_double(par2AxisAlignedBB.minZ); int maxZ = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D); int ystart = ((minY - 1) < 0) ? 0 : (minY - 1); for (int chunkx = (minX >> 4); chunkx <= ((maxX - 1) >> 4); chunkx++) { int cx = chunkx << 4; for (int chunkz = (minZ >> 4); chunkz <= ((maxZ - 1) >> 4); chunkz++) { Chunk chunk = this.getChunkIfExists(chunkx, chunkz); if (chunk == null) { continue; } // Compute ranges within chunk int cz = chunkz << 4; int xstart = (minX < cx) ? cx : minX; int xend = (maxX < (cx + 16)) ? maxX : (cx + 16); int zstart = (minZ < cz) ? cz : minZ; int zend = (maxZ < (cz + 16)) ? maxZ : (cz + 16); // Loop through blocks within chunk for (int x = xstart; x < xend; x++) { for (int z = zstart; z < zend; z++) { for (int y = ystart; y < maxY; y++) { int blkid = chunk.getBlockID(x - cx, y, z - cz); if (blkid > 0) { Block block = Block.blocksList[blkid]; if (block != null) { block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity); } if (!collidingBoundingBoxes.isEmpty()) { return true; } } } } } } } double var14 = 0.25D; List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), 100); for (Entity aVar16 : var16) { AxisAlignedBB var13 = aVar16.getBoundingBox(); if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) { return true; } var13 = par1Entity.getCollisionBox(aVar16); if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) { return true; } } return false; } @Override @Declare public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) { List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get(); collidingBoundingBoxes.clear(); int var3 = MathHelper.floor_double(par2AxisAlignedBB.minX); int var4 = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D); int var5 = MathHelper.floor_double(par2AxisAlignedBB.minY); int var6 = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D); int var7 = MathHelper.floor_double(par2AxisAlignedBB.minZ); int var8 = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D); int ystart = ((var5 - 1) < 0) ? 0 : (var5 - 1); for (int chunkx = (var3 >> 4); chunkx <= ((var4 - 1) >> 4); chunkx++) { int cx = chunkx << 4; for (int chunkz = (var7 >> 4); chunkz <= ((var8 - 1) >> 4); chunkz++) { Chunk chunk = this.getChunkIfExists(chunkx, chunkz); if (chunk == null) { continue; } // Compute ranges within chunk int cz = chunkz << 4; // Compute ranges within chunk int xstart = (var3 < cx) ? cx : var3; int xend = (var4 < (cx + 16)) ? var4 : (cx + 16); int zstart = (var7 < cz) ? cz : var7; int zend = (var8 < (cz + 16)) ? var8 : (cz + 16); // Loop through blocks within chunk for (int x = xstart; x < xend; x++) { for (int z = zstart; z < zend; z++) { for (int y = ystart; y < var6; y++) { int blkid = chunk.getBlockID(x - cx, y, z - cz); if (blkid > 0) { Block block = Block.blocksList[blkid]; if (block != null) { block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity); } } } } } } } double var14 = 0.25D; List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), limit); for (Entity aVar16 : var16) { AxisAlignedBB var13 = aVar16.getBoundingBox(); if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) { collidingBoundingBoxes.add(var13); } var13 = par1Entity.getCollisionBox(aVar16); if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) { collidingBoundingBoxes.add(var13); } } return collidingBoundingBoxes; } @Override public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) { return getCollidingBoundingBoxes(par1Entity, par2AxisAlignedBB, 2000); } @Override public void addTileEntity(Collection tileEntities) { List dest = scanningTileEntities ? addedTileEntityList : loadedTileEntityList; for (TileEntity tileEntity : (Iterable<TileEntity>) tileEntities) { tileEntity.validate(); if (tileEntity.canUpdate()) { dest.add(tileEntity); } } } @Override @Declare public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) { List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get(); entitiesWithinAABBExcludingEntity.clear(); int minX = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D); int maxX = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D); int minZ = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D); int maxZ = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D); for (int x = minX; x <= maxX; ++x) { for (int z = minZ; z <= maxZ; ++z) { Chunk chunk = getChunkIfExists(x, z); if (chunk != null) { chunk.getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity, limit); } } } return entitiesWithinAABBExcludingEntity; } @Override public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) { List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get(); entitiesWithinAABBExcludingEntity.clear(); int var3 = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D); int var4 = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D); int var5 = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D); int var6 = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D); for (int var7 = var3; var7 <= var4; ++var7) { for (int var8 = var5; var8 <= var6; ++var8) { Chunk chunk = getChunkIfExists(var7, var8); if (chunk != null) { chunk.getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity); } } } return entitiesWithinAABBExcludingEntity; } @Override public int countEntities(Class entityType) { if (loadedEntityList instanceof EntityList) { return ((EntityList) this.loadedEntityList).manager.getEntityCount(entityType); } int count = 0; for (Entity e : (Iterable<Entity>) this.loadedEntityList) { if (entityType.isAssignableFrom(e.getClass())) { ++count; } } return count; } @Override public boolean checkChunksExist(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { if (minY > 255 || maxY < 0) { return false; } minX >>= 4; minZ >>= 4; maxX >>= 4; maxZ >>= 4; ChunkProviderServer chunkProviderServer = (ChunkProviderServer) chunkProvider; for (int x = minX; x <= maxX; ++x) { for (int z = minZ; z <= maxZ; ++z) { if (!chunkProviderServer.chunkExists(x, z)) { return false; } } } return true; } @Override public void unloadEntities(List entitiesToUnload) { this.unloadedEntitySet.addAll(entitiesToUnload); } @Override public void updateEntities() { this.theProfiler.startSection("entities"); this.theProfiler.startSection("global"); int var1; Entity var2; CrashReport var4; CrashReportCategory var5; for (var1 = 0; var1 < this.weatherEffects.size(); ++var1) { var2 = (Entity) this.weatherEffects.get(var1); try { ++var2.ticksExisted; var2.onUpdate(); } catch (Throwable var6) { var4 = CrashReport.makeCrashReport(var6, "Ticking entity"); var5 = var4.makeCategory("Entity being ticked"); var2.func_85029_a(var5); throw new ReportedException(var4); } if (var2.isDead) { this.weatherEffects.remove(var1 } } this.theProfiler.endStartSection("remove"); int var3; int var13; if (this.loadedEntityList instanceof EntityList) { ((EntityList) this.loadedEntityList).manager.batchRemoveEntities(unloadedEntitySet); } else { this.loadedEntityList.removeAll(this.unloadedEntitySet); for (Entity entity : unloadedEntitySet) { var3 = entity.chunkCoordX; var13 = entity.chunkCoordZ; if (entity.addedToChunk) { Chunk chunk = getChunkIfExists(var3, var13); if (chunk != null) { chunk.removeEntity(entity); } } releaseEntitySkin(entity); } } this.unloadedEntitySet.clear(); this.theProfiler.endStartSection("regular"); boolean shouldTickThreadingTick = true; if (this.loadedEntityList instanceof EntityList) { ((EntityList) this.loadedEntityList).manager.doTick(); shouldTickThreadingTick = false; } else { for (var1 = 0; var1 < this.loadedEntityList.size(); ++var1) { var2 = (Entity) this.loadedEntityList.get(var1); if (var2.ridingEntity != null) { if (!var2.ridingEntity.isDead && var2.ridingEntity.riddenByEntity == var2) { continue; } var2.ridingEntity.riddenByEntity = null; var2.ridingEntity = null; } this.theProfiler.startSection("tick"); if (!var2.isDead) { try { this.updateEntity(var2); } catch (Throwable var7) { var4 = CrashReport.makeCrashReport(var7, "Ticking entity"); var5 = var4.makeCategory("Entity being ticked"); var2.func_85029_a(var5); throw new ReportedException(var4); } } this.theProfiler.endSection(); this.theProfiler.startSection("remove"); if (var2.isDead) { var3 = var2.chunkCoordX; var13 = var2.chunkCoordZ; if (var2.addedToChunk) { Chunk chunk = getChunkIfExists(var3, var13); if (chunk != null) { chunk.removeEntity(var2); } } this.loadedEntityList.remove(var1 this.releaseEntitySkin(var2); } this.theProfiler.endSection(); } } this.theProfiler.endStartSection("tileEntities"); if (this.loadedEntityList instanceof EntityList) { if (shouldTickThreadingTick) { ((EntityList) this.loadedEntityList).manager.doTick(); } } else { this.scanningTileEntities = true; Iterator var14 = this.loadedTileEntityList.iterator(); while (var14.hasNext()) { TileEntity var9 = (TileEntity) var14.next(); if (!var9.isInvalid() && var9.func_70309_m() && this.blockExists(var9.xCoord, var9.yCoord, var9.zCoord)) { try { var9.updateEntity(); } catch (Throwable var8) { var4 = CrashReport.makeCrashReport(var8, "Ticking tile entity"); var5 = var4.makeCategory("Tile entity being ticked"); var9.func_85027_a(var5); throw new ReportedException(var4); } } if (var9.isInvalid()) { var14.remove(); Chunk var11 = this.getChunkIfExists(var9.xCoord >> 4, var9.zCoord >> 4); if (var11 != null) { var11.cleanChunkBlockTileEntity(var9.xCoord & 15, var9.yCoord, var9.zCoord & 15); } } } } this.theProfiler.endStartSection("removingTileEntities"); if (!this.tileEntityRemovalSet.isEmpty()) { if (loadedTileEntityList instanceof LoadedTileEntityList) { ((LoadedTileEntityList) loadedTileEntityList).manager.batchRemoveTileEntities(tileEntityRemovalSet); } else { for (TileEntity tile : tileEntityRemovalSet) { tile.onChunkUnload(); } this.loadedTileEntityList.removeAll(tileEntityRemovalSet); } tileEntityRemovalSet.clear(); } this.scanningTileEntities = false; this.theProfiler.endStartSection("pendingTileEntities"); if (!this.addedTileEntityList.isEmpty()) { for (TileEntity te : (Iterable<TileEntity>) this.addedTileEntityList) { if (te.isInvalid()) { Chunk var15 = this.getChunkIfExists(te.xCoord >> 4, te.zCoord >> 4); if (var15 != null) { var15.cleanChunkBlockTileEntity(te.xCoord & 15, te.yCoord, te.zCoord & 15); } } else { if (!this.loadedTileEntityList.contains(te)) { this.loadedTileEntityList.add(te); } } } this.addedTileEntityList.clear(); } this.theProfiler.endSection(); this.theProfiler.endSection(); } @Override @Declare public Chunk getChunkIfExists(int x, int z) { return ((ChunkProviderServer) chunkProvider).getChunkIfExists(x, z); } @Override public void markTileEntityForDespawn(TileEntity tileEntity) { tileEntityRemovalSet.add(tileEntity); } }
package org.ow2.proactive.scripting; import java.io.*; import java.net.URL; import java.util.Map; import java.util.Map.Entry; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import org.apache.log4j.Logger; import org.jruby.RubyException; import org.jruby.exceptions.RaiseException; import org.objectweb.proactive.annotation.PublicAPI; import org.ow2.proactive.utils.BoundedStringWriter; /** * A simple script to evaluate using java 6 scripting API. * * @author The ProActive Team * @since ProActive Scheduling 0.9 * * * @param <E> Template class's type of the result. */ @PublicAPI public abstract class Script<E> implements Serializable { // default output size in chars based on the notorious JL's statistics :) public static final int DEFAULT_OUTPUT_MAX_SIZE = 125; /** Loggers */ public static final Logger logger = Logger.getLogger(Script.class); /** Variable name for script arguments */ public static final String ARGUMENTS_NAME = "args"; /** Name of the script engine */ protected String scriptEngine; /** The script to evaluate */ protected String script; /** Id of this script */ protected String id; /** The parameters of the script */ protected String[] parameters; private static final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); /** ProActive needed constructor */ public Script() { } /** Directly create a script with a string. * @param script String representing the script's source code * @param engineName String representing the execution engine * @param parameters script's execution arguments. * @throws InvalidScriptException if the creation fails. */ public Script(String script, String engineName, String[] parameters) throws InvalidScriptException { for (ScriptEngineFactory factory : scriptEngineManager.getEngineFactories()) { for (String name : factory.getNames()) { if (name.equals(engineName)) { scriptEngine = engineName; break; } } } if (scriptEngine == null) { throw new InvalidScriptException("The engine '" + engineName + "' is not valid"); } this.script = script; this.id = script; this.parameters = parameters; } /** Directly create a script with a string. * @param script String representing the script's source code * @param engineName String representing the execution engine * @throws InvalidScriptException if the creation fails. */ public Script(String script, String engineName) throws InvalidScriptException { this(script, engineName, null); } /** Create a script from a file. * @param file a file containing the script's source code. * @param parameters script's execution arguments. * @throws InvalidScriptException if the creation fails. */ public Script(File file, String[] parameters) throws InvalidScriptException { getEngineName(file.getPath()); try { storeScript(file); } catch (IOException e) { throw new InvalidScriptException("Unable to read script : " + file.getAbsolutePath(), e); } this.id = file.getPath(); this.parameters = parameters; } /** Create a script from a file. * @param file a file containing a script's source code. * @throws InvalidScriptException if Constructor fails. */ public Script(File file) throws InvalidScriptException { this(file, null); } /** Create a script from an URL. * @param url representing a script source code. * @param parameters execution arguments. * @throws InvalidScriptException if the creation fails. */ public Script(URL url, String[] parameters) throws InvalidScriptException { getEngineName(url.getFile()); try { storeScript(url); } catch (IOException e) { throw new InvalidScriptException("Unable to read script : " + url.getPath(), e); } this.id = url.toExternalForm(); this.parameters = parameters; } /** Create a script from an URL. * @param url representing a script source code. * @throws InvalidScriptException if the creation fails. */ public Script(URL url) throws InvalidScriptException { this(url, null); } /** Create a script from another script object * @param script2 script object source * @throws InvalidScriptException if the creation fails. */ public Script(Script<?> script2) throws InvalidScriptException { this(script2.script, script2.scriptEngine, script2.parameters); } /** * Get the script. * * @return the script. */ public String getScript() { return script; } /** * Set the script content, ie the executed code * * @param script the new script content */ public void setScript(String script) { this.script = script; } /** * Get the parameters. * * @return the parameters. */ public String[] getParameters() { return parameters; } /** * Add a binding to the script that will be handle by this handler. * * @param name the name of the variable * @param value the value of the variable */ public void addBinding(String name, Object value) { } /** * Execute the script and return the ScriptResult corresponding. * * @return a ScriptResult object. */ public ScriptResult<E> execute() { return execute(null); } /** * Execute the script and return the ScriptResult corresponding. * This method can add an additional user bindings if needed. * * @param aBindings the additional user bindings to add if needed. Can be null or empty. * @return a ScriptResult object. */ public ScriptResult<E> execute(Map<String, Object> aBindings) { ScriptEngine engine = getEngine(); if (engine == null) { return new ScriptResult<E>(new Exception("No Script Engine Found")); } // SCHEDULING-1532: redirect script output to a buffer (keep the latest DEFAULT_OUTPUT_MAX_SIZE) // the output is still printed to stdout BoundedStringWriter sw = new BoundedStringWriter(DEFAULT_OUTPUT_MAX_SIZE); PrintWriter pw = new PrintWriter(sw); engine.getContext().setWriter(pw); try { Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); //add additional bindings if (aBindings != null) { for (Entry<String, Object> e : aBindings.entrySet()) { bindings.put(e.getKey(), e.getValue()); } } prepareBindings(bindings); engine.eval(getReader()); // Add output to the script result ScriptResult<E> result = this.getResult(bindings); result.setOutput(sw.toString()); return result; } catch (Throwable e) { Throwable cause = e.getCause(); if (cause instanceof RaiseException) { // fix for SCHEDULING-1742 if it's a jruby exception we capture the real ruby stack RaiseException re = (RaiseException) cause; RubyException rbe = re.getException(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); rbe.printBacktrace(ps); ps.flush(); String stack = baos.toString(); // The initial Throwable "e" must NOT be put as the cause of the final exception as "e" can unfortunately // contain a reference to a org.jruby.runtime.CallType object which is NOT SERIALIZABLE Exception finale = new Exception(rbe.message + System.getProperty("line.separator") + stack); logger.error("", finale); return new ScriptResult<E>(new Exception("An exception occurred while executing the script ", finale)); } logger.error("", e); return new ScriptResult<E>(new Exception("An exception occurred while executing the script ", e)); } } /** String identifying the script. * @return a String identifying the script. */ public abstract String getId(); /** The reader used to read the script. */ protected abstract Reader getReader(); /** The Script Engine used to evaluate the script. */ protected abstract ScriptEngine getEngine(); /** Specify the variable awaited from the script execution */ protected abstract void prepareSpecialBindings(Bindings bindings); /** Return the variable awaited from the script execution */ protected abstract ScriptResult<E> getResult(Bindings bindings); /** Set parameters in bindings if any */ protected final void prepareBindings(Bindings bindings) { //add parameters if (this.parameters != null) { bindings.put(Script.ARGUMENTS_NAME, this.parameters); } // add special bindings this.prepareSpecialBindings(bindings); } /** Create string script from url */ protected void storeScript(URL url) throws IOException { BufferedReader buf = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder builder = new StringBuilder(); String tmp = null; while ((tmp = buf.readLine()) != null) { builder.append(tmp + "\n"); } script = builder.toString(); } /** Create string script from file */ protected void storeScript(File file) throws IOException { BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(file))); StringBuilder builder = new StringBuilder(); String tmp = null; while ((tmp = buf.readLine()) != null) { builder.append(tmp + "\n"); } script = builder.toString(); } public String getEngineName() { return scriptEngine; } /** Set the scriptEngine from filepath */ protected void getEngineName(String filepath) throws InvalidScriptException { ScriptEngineManager manager = new ScriptEngineManager(); for (ScriptEngineFactory sef : manager.getEngineFactories()) for (String ext : sef.getExtensions()) if (filepath.endsWith(ext)) { scriptEngine = sef.getNames().get(0); break; } if (scriptEngine == null) { throw new InvalidScriptException("No script engine corresponding for file : " + filepath); } } /** * @see java.lang.Object#equals(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o instanceof Script) { Script<E> new_name = (Script<E>) o; return this.getId().equals(new_name.getId()); } return false; } }
package hudson.tools; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.model.Node; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import org.kohsuke.stapler.DataBoundConstructor; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * {@link NodeProperty} that allows users to specify different locations for {@link ToolInstallation}s. * * @since 1.286 */ public class ToolLocationNodeProperty extends NodeProperty<Node> { private final List<ToolLocation> locations; @DataBoundConstructor public ToolLocationNodeProperty(List<ToolLocation> locations) { this.locations = locations; } public ToolLocationNodeProperty(ToolLocation... locations) { this(Arrays.asList(locations)); } public List<ToolLocation> getLocations() { if (locations == null) return Collections.emptyList(); return Collections.unmodifiableList(locations); } public String getHome(ToolInstallation installation) { for (ToolLocation location : locations) { if (location.getName().equals(installation.getName()) && location.getType() == installation.getDescriptor()) { return location.getHome(); } } return null; } public static String getToolHome(Node node, ToolInstallation installation) { ToolLocationNodeProperty property = node.getNodeProperties().get(ToolLocationNodeProperty.class); if (property != null) { return property.getHome(installation); } return null; } @Extension public static class DescriptorImpl extends NodePropertyDescriptor { public String getDisplayName() { return "Tool Locations"; } public DescriptorExtensionList<ToolInstallation,ToolDescriptor<?>> getToolDescriptors() { return ToolInstallation.all(); } public String getKey(ToolInstallation installation) { return installation.getDescriptor().getClass().getName() + "@" + installation.getName(); } @Override public boolean isApplicable(Class<? extends Node> nodeType) { return nodeType != Hudson.class; } } public static final class ToolLocation { private final String type; private final String name; private final String home; private transient volatile ToolDescriptor descriptor; public ToolLocation(ToolDescriptor type, String name, String home) { this.descriptor = type; this.type = type.getClass().getName(); this.name = name; this.home = home; } @DataBoundConstructor public ToolLocation(String key, String home) { this.type = key.substring(0, key.indexOf('@')); this.name = key.substring(key.indexOf('@') + 1); this.home = home; } public String getName() { return name; } public String getHome() { return home; } public ToolDescriptor getType() { if (descriptor == null) descriptor = (ToolDescriptor) Descriptor.find(type); return descriptor; } public String getKey() { return type.getClass().getName() + "@" + name; } } }
package com.intuit.karate.ui; import com.intuit.karate.ScriptValue; /** * * @author pthomas3 */ public class Var { private final String name; private final ScriptValue value; public Var(String name, ScriptValue value) { this.name = name; this.value = value == null ? ScriptValue.NULL : value; } public String getName() { return name; } public ScriptValue getValue() { return value; } public String getType() { return value.getTypeAsShortString(); } public String getAsString() { return value.getAsString(); } @Override public String toString() { return value.toPrettyString(name); } }
package redradishes.decoder.parser; import java.nio.ByteBuffer; import java.nio.charset.CharsetDecoder; import java.util.function.Function; import java.util.function.LongFunction; public abstract class LongParser { static final LongParser PARSER = new LongParser() { @Override <T> T parse(ByteBuffer buffer, LongFunction<T> resultHandler, PartialHandler<T> partialHandler) { return doParse(buffer, resultHandler, partialHandler, false, 0, SIGN_OR_DIGIT); } }; public static final Parser<Integer> INTEGER_PARSER = PARSER.mapToParser(l -> (int) l); public static final Parser<Long> LONG_PARSER = PARSER.mapToParser(l -> l); private static final int SIGN_OR_DIGIT = 0; private static final int DIGIT = 1; private static final int WAITING_FOR_LF = 2; abstract <T> T parse(ByteBuffer buffer, LongFunction<T> resultHandler, PartialHandler<T> partialHandler); private static <T> T doParse(ByteBuffer buffer, LongFunction<T> resultHandler, PartialHandler<T> partialHandler, boolean negative, long num, int state) { while (buffer.hasRemaining()) { byte b = buffer.get(); switch (state) { case SIGN_OR_DIGIT: state = DIGIT; if (b == '-') { negative = true; break; } case DIGIT: switch (b) { case '0': num *= 10; break; case '1': num = num * 10 + 1; break; case '2': num = num * 10 + 2; break; case '3': num = num * 10 + 3; break; case '4': num = num * 10 + 4; break; case '5': num = num * 10 + 5; break; case '6': num = num * 10 + 6; break; case '7': num = num * 10 + 7; break; case '8': num = num * 10 + 8; break; case '9': num = num * 10 + 9; break; case '\r': state = WAITING_FOR_LF; break; default: throw new IllegalStateException("Unexpected character: " + (char) b); } break; case WAITING_FOR_LF: if (b == '\n') { return resultHandler.apply(negative ? -num : num); } else { throw new IllegalStateException("LF is expected"); } } } return partialHandler.partial(new LongPartial(negative, num, state)); } <T> Parser<T> mapToParser(LongFunction<T> longFunction) { return new ParserAdaptor<>(this, longFunction); } interface PartialHandler<T> { T partial(LongParser partial); } private static class LongPartial extends LongParser { private final boolean negative; private final long num; private final int state; private LongPartial(boolean negative, long num, int state) { this.negative = negative; this.num = num; this.state = state; } @Override <T> T parse(ByteBuffer buffer, LongFunction<T> resultHandler, PartialHandler<T> partialHandler) { return doParse(buffer, resultHandler, partialHandler, negative, num, state); } } private static class ParserAdaptor<T> implements Parser<T> { private final LongParser parser; private final LongFunction<T> longFunction; private ParserAdaptor(LongParser parser, LongFunction<T> longFunction) { this.parser = parser; this.longFunction = longFunction; } @Override public <U> U parse(ByteBuffer buffer, Function<? super T, U> resultHandler, PartialHandler<? super T, U> partialHandler, CharsetDecoder charsetDecoder) { return parser.parse(buffer, value -> resultHandler.apply(longFunction.apply(value)), partial -> partialHandler.partial(new ParserAdaptor<>(partial, longFunction))); } } }
package net.sourceforge.texlipse.viewer; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Map; import java.util.Properties; import net.sourceforge.texlipse.DDEClient; import net.sourceforge.texlipse.PathUtils; import net.sourceforge.texlipse.SelectedResourceManager; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.builder.BuilderRegistry; import net.sourceforge.texlipse.builder.TexlipseBuilder; import net.sourceforge.texlipse.builder.TexlipseNature; import net.sourceforge.texlipse.properties.TexlipseProperties; import net.sourceforge.texlipse.viewer.util.FileLocationListener; import net.sourceforge.texlipse.viewer.util.FileLocationServer; import net.sourceforge.texlipse.viewer.util.ViewerErrorScanner; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Platform; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * A helper class for opening source files. * Defined separately, so that it could be used inside a static method. * * @author Kimmo Karlsson */ class FileLocationOpener implements FileLocationListener { private IProject project; public FileLocationOpener(IProject p) { project = p; } public void showLineOfFile(String file, int lineNumber) { ViewerOutputScanner.openInEditor(project, file, lineNumber); } } /** * Previewer helper class. Includes methods for launching the previewer. * There's no need to create instances of this class. * * @author Anton Klimovsky * @author Kimmo Karlsson * @author Tor Arne Vestb * @author Boris von Loesch */ public class ViewerManager { // the file name variable in the arguments public static final String FILENAME_PATTERN = "%file"; // the line number variable in the arguments public static final String LINE_NUMBER_PATTERN = "%line"; // the source file name variable in the arguments public static final String TEX_FILENAME_PATTERN = "%texfile"; // file name with absolute path public static final String FILENAME_FULLPATH_PATTERN = "%fullfile"; // viewer attributes private ViewerAttributeRegistry registry; // environment variables to add to current environment private Map envSettings; // the current project private IProject project; // progress monitor for current view operation private IProgressMonitor monitor; /** * Run the viewer configured in the given viewer attributes. * First check if there is a viewer already running, * and if there is, return that process. * * @param reg the viewer attributes * @param addEnv additional environment variables, or null * @param monitor monitor for process * @return the viewer process * @throws CoreException if launching the viewer fails */ public static Process preview(ViewerAttributeRegistry reg, Map addEnv, IProgressMonitor monitor) throws CoreException { ViewerManager mgr = new ViewerManager(reg, addEnv, monitor); if (!mgr.initialize()) { return null; } Process process = mgr.getExisting(); if (process != null) { // Can send DDE right away mgr.sendDDEViewCommand(); return process; } // Process must be started first process = mgr.execute(); // Send DDE if on Win32 if (Platform.getOS().equals(Platform.OS_WIN32)) { // Since the process can take a while to start we must wait // to "make sure" the DDE command gets there. // This is probably a HACK: should be fixed/changed. try { Thread.sleep(1000); // 1000 enough? Who knows!? // The timeout should probably be a config setting? } catch (InterruptedException e) { } mgr.sendDDEViewCommand(); } return process; } public static void closeOutputDocument() throws CoreException { ViewerAttributeRegistry registry = new ViewerAttributeRegistry(); // Check to see if we have a running launch configuration which should // override the DDE close command ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); ILaunch[] launches = manager.getLaunches(); for (int i = 0; i < launches.length; i++) { ILaunch l = launches[i]; ILaunchConfiguration configuration = l.getLaunchConfiguration(); if (configuration.exists() && configuration.getType().getIdentifier().equals( TexLaunchConfigurationDelegate.CONFIGURATION_ID)) { Map regMap = configuration.getAttributes(); registry.setValues(regMap); break; } } ViewerManager mgr = new ViewerManager(registry, null, null); if (!mgr.initialize()) { return; } // Can only close documents opened by DDE commands themselves Process process = mgr.getExisting(); if (process != null) { mgr.sendDDECloseCommand(); try { Thread.sleep(500); // A small delay required } catch (InterruptedException e) { e.printStackTrace(); } returnFocusToEclipse(false); } } /** * Returns the application focus to Eclipse after launching an * external previewer. This is done by first activating the * eclipse window, and then setting focus in the editor in a * worker thread. Note the delay needed before setting focus. * * @param useMinimizeTrick if true uses a trick to force focus by * minimizing and restoring the eclipse window */ public static void returnFocusToEclipse(final boolean useMinimizeTrick) { // Return focus/activation to Eclipse/Texlipse Display display = PlatformUI.getWorkbench().getDisplay(); if (null != display) { display.asyncExec(new Runnable() { public void run() { IWorkbenchWindow[] workbenchWindows = PlatformUI.getWorkbench().getWorkbenchWindows(); for (int i = 0; i < workbenchWindows.length; i++) { Shell shell = workbenchWindows[i].getShell(); if (useMinimizeTrick) { shell.setMinimized(true); shell.setMinimized(false); } shell.setActive(); shell.forceActive(); break; } } }); } // Spawn thread to set focus in the editor after the launch has completed // The reason we cannot do this in the current thread is because the progress // window is in the way and will not allow us to set focus on the editor. new Thread(new Runnable() { public void run() { try { Thread.sleep(500); } catch (Exception e) { } Display display = PlatformUI.getWorkbench().getDisplay(); if (null != display) { display.asyncExec(new Runnable() { public void run() { IWorkbenchWindow[] workbenchWindows = PlatformUI.getWorkbench().getWorkbenchWindows(); for (int i = 0; i < workbenchWindows.length; i++) { IWorkbenchPage activePage = workbenchWindows[i].getActivePage(); activePage.activate(activePage.getActiveEditor()); // Although setFocus should not be called by clients it is // required for the focus to work. Activate alone is not enough. activePage.getActiveEditor().setFocus(); } } }); } } }).start(); } /** * Construct a new viewer launcher. * @param reg viewer attributes * @param addEnv environment variables to add to the current environment */ protected ViewerManager(ViewerAttributeRegistry reg, Map addEnv, IProgressMonitor monitor) { this.monitor = monitor; this.registry = reg; this.envSettings = addEnv; } /** * Find out the current project. * @return true, if success */ protected boolean initialize() { project = TexlipsePlugin.getCurrentProject(); if (project == null) { BuilderRegistry.printToConsole(TexlipsePlugin.getResourceString("viewerNoCurrentProject")); return false; } try { // Make sure it's a LaTeX project if (project.getNature(TexlipseNature.NATURE_ID) == null) { return false; } } catch (CoreException e) { } return true; } /** * Rebuilds the project if there has been any changes since the last build * * @deprecated Eclipse has it's own rebuild-if-changed mechanism which works * much better. See Preferences->Run->Launching. Besides, the check to see * if a resource had changed is broken, so this method does always build, and * the build is done in the GUI thread, so output is not flushed in realtime. * */ protected boolean rebuildIfNeeded() { // rebuild, if needed IPreferenceStore prefs = TexlipsePlugin.getDefault().getPreferenceStore(); if (prefs.getBoolean(TexlipseProperties.BUILD_BEFORE_VIEW)) { if (TexlipseBuilder.needsRebuild()) { try { project.build(TexlipseBuilder.FULL_BUILD, monitor); } catch (OperationCanceledException e) { // build failed, so no output file return false; } catch (CoreException e) { // build failed, so no output file return false; } } } return true; // output file is up to date, continue with viewing } /** * Check if viewer already running. * This method returns false also, if the user has enabled multiple viewer instances. * @return the running viewer process, or null if viewer has already terminated */ protected Process getExisting() { Object o = TexlipseProperties.getSessionProperty(project, TexlipseProperties.SESSION_ATTRIBUTE_VIEWER); if (o != null) { if (o instanceof Process) { Process p = (Process) o; int code = -1; try { code = p.exitValue(); } catch (IllegalThreadStateException e) { } // there is a viewer running and forward search is not supported if (code == -1 && !registry.getForward()) { // ... so don't launch another viewer window return p; } } TexlipseProperties.setSessionProperty(project, TexlipseProperties.SESSION_ATTRIBUTE_VIEWER, null); } return null; } /** * Run the viewer configured in the given viewer attributes. * Paths are resolved so that the viewer program is run in source directory. * The viewer program is given a relative pathname and filename as a command line * argument. * * @return the viewer process * @throws CoreException if launching the viewer fails */ protected Process execute() throws CoreException { //load settings, if changed on disk if (TexlipseProperties.isProjectPropertiesFileChanged(project)) { TexlipseProperties.loadProjectProperties(project); } IResource outputRes = getOuputResource(project); if (outputRes == null || !outputRes.exists()) { String msg = TexlipsePlugin.getResourceString("viewerNothingWithExtension"); BuilderRegistry.printToConsole(msg.replaceAll("%s", registry.getFormat())); return null; } // resolve the directory to run the viewer in IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project); File dir = sourceDir.getLocation().toFile(); try { return execute(dir); } catch (IOException e) { throw new CoreException(TexlipsePlugin.stat("Could not start previewer '" + registry.getActiveViewer() + "'. Please make sure you have entered " + "the correct path and filename in the viewer preferences.", e)); } } protected void sendDDEViewCommand() throws CoreException { if (Platform.getOS().equals(Platform.OS_WIN32)) { String command = translatePatterns(registry.getDDEViewCommand()); String server = registry.getDDEViewServer(); String topic = registry.getDDEViewTopic(); int error = DDEClient.execute(server, topic, command); if (error != 0) { String errorMessage = "DDE command " + command + " failed! " + "(server: " + server + ", topic: " + topic + ")"; TexlipsePlugin.log(errorMessage, new Throwable(errorMessage)); } } } protected void sendDDECloseCommand() throws CoreException { if (Platform.getOS().equals(Platform.OS_WIN32)) { String command = translatePatterns(registry.getDDECloseCommand()); String server = registry.getDDECloseServer(); String topic = registry.getDDECloseTopic(); int error = DDEClient.execute(server, topic, command); if (error != 0) { String errorMessage = "DDE command " + command + " failed! " + "(server: " + server + ", topic: " + topic + ")"; TexlipsePlugin.log(errorMessage, new Throwable(errorMessage)); } } } /** * Resolves a relative path from one directory to another. * The path is returned as an OS-specific string with * a terminating separator. * * @param sourcePath a directory to start from * @param outputPath a directory to end up to * @return a relative path from sourcePath to outputPath */ public static String resolveRelativePath(IPath sourcePath, IPath outputPath) { int same = sourcePath.matchingFirstSegments(outputPath); if (same == sourcePath.segmentCount() && same == outputPath.segmentCount()) { return ""; } outputPath = outputPath.removeFirstSegments(same); sourcePath = sourcePath.removeFirstSegments(same); StringBuffer sb = new StringBuffer(); for (int i = 0; i < sourcePath.segmentCount(); i++) { sb.append(".."); sb.append(File.separatorChar); } for (int i = 0; i < outputPath.segmentCount(); i++) { sb.append(outputPath.segment(i)); sb.append(File.separatorChar); } return sb.toString(); } /** * Determines the Resource which should be shown. Respects partial builds. * @return * @throws CoreException */ public static IResource getOuputResource(IProject project) throws CoreException { String outFileName = TexlipseProperties.getProjectProperty(project, TexlipseProperties.OUTPUTFILE_PROPERTY); //Check for partial build Object s = TexlipseProperties.getProjectProperty(project, TexlipseProperties.PARTIAL_BUILD_PROPERTY); if (s != null) { IFile tmpFile = (IFile)TexlipseProperties.getSessionProperty(project, TexlipseProperties.PARTIAL_BUILD_FILE); if (tmpFile != null){ String fmtProp = TexlipseProperties.getProjectProperty(project, TexlipseProperties.OUTPUT_FORMAT); String name = tmpFile.getName(); name = name.substring(0, name.lastIndexOf('.')) + "." + fmtProp; outFileName = name; } } if (outFileName == null || outFileName.length() == 0) { throw new CoreException(TexlipsePlugin.stat("Empty output file name.")); } // find out the directory where the file should be IContainer outputDir = null; // String fmtProp = TexlipseProperties.getProjectProperty(project, // TexlipseProperties.OUTPUT_FORMAT); // if (registry.getFormat().equals(fmtProp)) { outputDir = TexlipseProperties.getProjectOutputDir(project); /* } else { String base = outFileName.substring(0, outFileName.lastIndexOf('.') + 1); outFileName = base + registry.getFormat(); outputDir = TexlipseProperties.getProjectTempDir(project); }*/ if (outputDir == null) { outputDir = project; } return outputDir.findMember(outFileName); } /** * Returns the current line number of the current page, if possible. * * @author Anton Klimovsky * @return the current line number of the current page */ private int getCurrentLineNumber() { int lineNumber = 0; /* Commented this out, because the selection-code did not work * with launch configurations. IWorkbenchPage.getSelection() needs * to run in a UI thread and ILaunchConfigurationDelegate is not one of those. * - Kimmo Karlsson * IWorkbenchPage currentWorkbenchPage = TexlipsePlugin.getCurrentWorkbenchPage(); if (currentWorkbenchPage != null) { ISelection selection = currentWorkbenchPage.getSelection(); if (selection != null) { if (selection instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) selection; // The "srcltx" package's line numbers seem to start from 1 // it is also the case with latex's --source-specials option lineNumber = textSelection.getStartLine() + 1; } } } */ lineNumber = SelectedResourceManager.getDefault().getSelectedLine(); if (lineNumber <= 0) { lineNumber = 1; } return lineNumber; } /** * Run the given viewer in the given directory with the given file. * Also start viewer output listener to enable inverse search. * * @param dir the directory to run the viewer in * @return viewer process * @throws IOException if launching the viewer fails */ private Process execute(File dir) throws IOException, CoreException { // argument list ArrayList list = new ArrayList(); // add command as arg0 String command = registry.getCommand(); if (command.indexOf(' ') > 0) { command = "\"" + command + "\""; } list.add(command); // add arguments String args = translatePatterns(registry.getArguments()); PathUtils.tokenizeEscapedString(args, list); // create environment Properties env = PathUtils.getEnv(); if (envSettings != null) { env.putAll(envSettings); } //String envp[] = PathUtils.getStrings(env); String envp[] = PathUtils.mergeEnvFromPrefs(env, TexlipseProperties.VIEWER_ENV_SETTINGS); // print command BuilderRegistry.printToConsole(TexlipsePlugin.getResourceString("viewerRunning") + " " + command + " " + args); // start viewer process Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec((String[]) list.toArray(new String[0]), envp, dir); // save attribute TexlipseProperties.setSessionProperty(project, TexlipseProperties.SESSION_ATTRIBUTE_VIEWER, process); // start viewer listener startOutputListener(process.getInputStream(), registry.getInverse()); // start error reader new Thread(new ViewerErrorScanner(process)).start(); return process; } /** * Fills the %arg of the input pattern with the real values * @param input The input pattern * @return the filled string * @throws CoreException */ private String translatePatterns(String input) throws CoreException { if (input == null) return null; IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project); if (input.indexOf(FILENAME_PATTERN) >= 0) { // resolve relative path to the output file IResource outputRes = getOuputResource(project); String outFileName = outputRes.getName(); outFileName = resolveRelativePath(sourceDir.getFullPath(), outputRes.getFullPath()); outFileName = outFileName.substring(0, outFileName.length() - 1); input = input.replaceAll(FILENAME_PATTERN, escapeBackslashes(outFileName)); } if (input.indexOf(FILENAME_FULLPATH_PATTERN) >= 0) { input = input.replaceAll(FILENAME_FULLPATH_PATTERN, escapeBackslashes(getOuputResource(project).getLocation().toOSString())); } if (input.indexOf(LINE_NUMBER_PATTERN) >= 0) { input = input.replaceAll(LINE_NUMBER_PATTERN, "" + getCurrentLineNumber()); } if (input.indexOf(TEX_FILENAME_PATTERN) >= 0) { IResource selectedRes = SelectedResourceManager.getDefault().getSelectedResource(); if (selectedRes.getType() != IResource.FOLDER) { selectedRes = SelectedResourceManager.getDefault().getSelectedTexResource(); } String relPath = resolveRelativePath(sourceDir.getFullPath(), selectedRes.getFullPath().removeLastSegments(1)); String texFile = relPath + selectedRes.getName(); input = input.replaceAll(TEX_FILENAME_PATTERN, escapeBackslashes(texFile)); } return input; } /** * Escapes backslashes, so that the string can be given to String.replaceAll() * as argument without the backslashes disappearing. * @param file input string, typically a filename * @return the input string with backslashes doubled */ private String escapeBackslashes(String file) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < file.length(); i++) { char c = file.charAt(i); sb.append(c); if (c == '\\') { sb.append(c); } } return sb.toString(); } /** * Start a listener thread for the viewer program's standard output. * * @param in input stream where the output of a viewer program will be available * @param viewer the name of the viewer */ private void startOutputListener(InputStream in, String inverse) { if (inverse.equals(ViewerAttributeRegistry.INVERSE_SEARCH_RUN)) { FileLocationServer server = FileLocationServer.getInstance(); server.setListener(new FileLocationOpener(project)); if (!server.isRunning()) { new Thread(server).start(); } } else if (inverse.equals(ViewerAttributeRegistry.INVERSE_SEARCH_STD)) { new Thread(new ViewerOutputScanner(project, in)).start(); } } }
package io.undertow.test; import java.io.IOException; import java.io.InputStream; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.undertow.server.HttpCompletionHandler; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.test.utils.AjpIgnore; import io.undertow.test.utils.DefaultServer; import io.undertow.util.TestHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.xnio.ChannelListener; import org.xnio.Options; import org.xnio.channels.StreamSinkChannel; import org.xnio.channels.WriteTimeoutException; /** * Tests read timeout with a client that is slow to read the response * * @author Stuart Douglas */ @RunWith(DefaultServer.class) @AjpIgnore @Ignore("This test fails intermittently") public class WriteTimeoutTestCase { private volatile Exception exception; private static final CountDownLatch errorLatch = new CountDownLatch(1); @Test public void testWriteTimeout() throws IOException, InterruptedException { DefaultServer.setRootHandler(new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange, final HttpCompletionHandler completionHandler) { final StreamSinkChannel response = exchange.getResponseChannelFactory().create(); try { response.setOption(Options.WRITE_TIMEOUT, 10); } catch (IOException e) { throw new RuntimeException(e); } final int capacity = 1 * 1024 * 1024; //1mb final ByteBuffer originalBuffer = ByteBuffer.allocateDirect(capacity); for (int i = 0; i < capacity; ++i) { originalBuffer.put((byte) '*'); } originalBuffer.flip(); response.getWriteSetter().set(new ChannelListener<Channel>() { private ByteBuffer buffer = originalBuffer.duplicate(); int count = 0; @Override public void handleEvent(final Channel channel) { do { try { int res = response.write(buffer); if (res == 0) { return; } } catch (IOException e) { exception = e; errorLatch.countDown(); } if(!buffer.hasRemaining()) { count++; buffer = originalBuffer.duplicate(); } } while (count < 1000); completionHandler.handleComplete(); } }); response.wakeupWrites(); } }); final TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerAddress()); try { HttpResponse result = client.execute(get); InputStream content = result.getEntity().getContent(); byte[] buffer = new byte[512]; int r = 0; while ((r = content.read(buffer)) > 0) { Thread.sleep(200); if (exception != null) { Assert.assertEquals(WriteTimeoutException.class, exception.getClass()); return; } } Assert.fail("Write did not time out"); } catch (IOException e) { if (errorLatch.await(5, TimeUnit.SECONDS)) { Assert.assertEquals(WriteTimeoutException.class, exception.getClass()); } else { Assert.fail("Write did not time out"); } } } finally { client.getConnectionManager().shutdown(); } } }
package com.exedio.cope.pattern; import java.io.IOException; import java.util.Date; import com.exedio.cope.DataAttribute; import com.exedio.cope.StringAttribute; import com.exedio.cope.TestmodelTest; import com.exedio.cope.testmodel.HttpEntityItem; public class HttpEntityTest extends TestmodelTest { // TODO test various combinations of internal, external implicit, and external explicit source private HttpEntityItem item; private final byte[] data = new byte[]{-86,122,-8,23}; private final byte[] data2 = new byte[]{-97,35,-126,86,19,-8}; private final byte[] dataEmpty = new byte[]{}; public void setUp() throws Exception { super.setUp(); deleteOnTearDown(item = new HttpEntityItem()); } private void assertExtension(final String mimeMajor, final String mimeMinor, final String extension) throws IOException { item.setFile(stream(data2), mimeMajor, mimeMinor); assertEquals(mimeMajor, item.getFileMimeMajor()); assertEquals(mimeMinor, item.getFileMimeMinor()); assertTrue(item.getFileURL().endsWith(extension)); } public void testData() throws IOException { // TODO: test item.TYPE.getPatterns // file assertEquals(null, item.file.getFixedMimeMajor()); assertEquals(null, item.file.getFixedMimeMinor()); final DataAttribute fileData = item.file.getData(); assertSame(item.TYPE, fileData.getType()); assertSame("fileData", fileData.getName()); final StringAttribute fileMajor = item.file.getMimeMajor(); assertSame(item.TYPE, fileMajor.getType()); assertEquals("fileMajor", fileMajor.getName()); final StringAttribute fileMinor = item.file.getMimeMinor(); assertSame(item.TYPE, fileMinor.getType()); assertEquals("fileMinor", fileMinor.getName()); assertSame(item.file, HttpEntity.get(fileData)); assertTrue(item.file.isNull(item)); assertEquals(null, item.getFileData()); assertEquals(-1, item.file.getDataLength(item)); assertEquals(-1, item.file.getDataLastModified(item)); assertEquals(null, item.getFileMimeMajor()); assertEquals(null, item.getFileMimeMinor()); assertEquals(null, item.getFileURL()); final Date beforeData = new Date(); item.setFile(stream(data), "fileMajor", "fileMinor"); final Date afterData = new Date(); assertTrue(!item.file.isNull(item)); assertData(data, item.getFileData()); assertEquals(data.length, item.file.getDataLength(item)); assertWithin(1000, beforeData, afterData, new Date(item.file.getDataLastModified(item))); assertEquals("fileMajor", item.getFileMimeMajor()); assertEquals("fileMinor", item.getFileMimeMinor()); assertTrue(item.getFileURL().endsWith(".fileMajor.fileMinor")); final Date beforeData2 = new Date(); item.setFile(stream(data2), "fileMajor2", "fileMinor2"); final Date afterData2 = new Date(); assertTrue(!item.file.isNull(item)); assertData(data2, item.getFileData()); assertEquals(data2.length, item.file.getDataLength(item)); assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item))); assertEquals("fileMajor2", item.getFileMimeMajor()); assertEquals("fileMinor2", item.getFileMimeMinor()); assertTrue(item.getFileURL().endsWith(".fileMajor2.fileMinor2")); assertExtension("image", "jpeg", ".jpg"); assertExtension("image", "pjpeg", ".jpg"); assertExtension("image", "png", ".png"); assertExtension("image", "gif", ".gif"); assertExtension("text", "html", ".html"); assertExtension("text", "plain", ".txt"); assertExtension("text", "css", ".css"); final Date beforeDataEmpty = new Date(); item.setFile(stream(dataEmpty), "emptyMajor", "emptyMinor"); final Date afterDataEmpty = new Date(); assertTrue(!item.file.isNull(item)); assertData(dataEmpty, item.getFileData()); assertEquals(0, item.file.getDataLength(item)); assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item))); assertEquals("emptyMajor", item.getFileMimeMajor()); assertEquals("emptyMinor", item.getFileMimeMinor()); assertTrue(item.getFileURL().endsWith(".emptyMajor.emptyMinor")); item.setFile(null, null, null); assertTrue(item.file.isNull(item)); assertEquals(-1, item.file.getDataLength(item)); assertEquals(-1, item.file.getDataLastModified(item)); assertEquals(null, item.getFileData()); assertEquals(null, item.getFileMimeMajor()); assertEquals(null, item.getFileMimeMinor()); assertEquals(null, item.getFileURL()); // image assertEquals("image", item.image.getFixedMimeMajor()); assertEquals(null, item.image.getFixedMimeMinor()); final DataAttribute imageData = item.image.getData(); assertSame(item.TYPE, imageData.getType()); assertSame("imageData", imageData.getName()); assertEquals(null, item.image.getMimeMajor()); final StringAttribute imageMinor = item.image.getMimeMinor(); assertSame(item.TYPE, imageMinor.getType()); assertEquals("imageMinor", imageMinor.getName()); assertSame(item.image, HttpEntity.get(imageData)); assertTrue(item.image.isNull(item)); assertEquals(null, item.getImageData()); assertEquals(-1, item.image.getDataLength(item)); assertEquals(null, item.getImageMimeMajor()); assertEquals(null, item.getImageMimeMinor()); assertEquals(null, item.getImageURL()); item.setImage(stream(data), "imageMinor"); assertTrue(!item.image.isNull(item)); assertData(data, item.getImageData()); assertEquals(data.length, item.image.getDataLength(item)); assertEquals("image", item.getImageMimeMajor()); assertEquals("imageMinor", item.getImageMimeMinor()); //System.out.println(item.getImageURL()); assertTrue(item.getImageURL().endsWith(".image.imageMinor")); item.setImage(stream(data2), "jpeg"); assertTrue(!item.image.isNull(item)); assertData(data2, item.getImageData()); assertEquals(data2.length, item.image.getDataLength(item)); assertEquals("image", item.getImageMimeMajor()); assertEquals("jpeg", item.getImageMimeMinor()); //System.out.println(item.getImageURL()); assertTrue(item.getImageURL().endsWith(".jpg")); item.setImage(null, null); assertTrue(item.image.isNull(item)); assertEquals(null, item.getImageData()); assertEquals(-1, item.image.getDataLength(item)); assertEquals(null, item.getImageMimeMajor()); assertEquals(null, item.getImageMimeMinor()); assertEquals(null, item.getImageURL()); // photo assertEquals("image", item.photo.getFixedMimeMajor()); assertEquals("jpeg", item.photo.getFixedMimeMinor()); assertSame(item.TYPE, item.photo.getData().getType()); assertSame("photoData", item.photo.getData().getName()); assertEquals(null, item.photo.getMimeMajor()); assertEquals(null, item.photo.getMimeMinor()); assertSame(item.photo, HttpEntity.get(item.photo.getData())); assertTrue(item.photo.isNull(item)); assertEquals(null, item.getPhotoData()); assertEquals(-1, item.photo.getDataLength(item)); assertEquals(null, item.getPhotoMimeMajor()); assertEquals(null, item.getPhotoMimeMinor()); assertEquals(null, item.getPhotoURL()); item.setPhoto(stream(data)); assertTrue(!item.photo.isNull(item)); assertData(data, item.getPhotoData()); assertEquals(data.length, item.photo.getDataLength(item)); assertEquals("image", item.getPhotoMimeMajor()); assertEquals("jpeg", item.getPhotoMimeMinor()); //System.out.println(item.getPhotoURL()); assertTrue(item.getPhotoURL().endsWith(".jpg")); item.setPhoto(stream(data2)); assertTrue(!item.photo.isNull(item)); assertData(data2, item.getPhotoData()); assertEquals(data2.length, item.photo.getDataLength(item)); assertEquals("image", item.getPhotoMimeMajor()); assertEquals("jpeg", item.getPhotoMimeMinor()); //System.out.println(item.getPhotoURL()); assertTrue(item.getPhotoURL().endsWith(".jpg")); item.setPhoto(null); assertTrue(item.photo.isNull(item)); assertEquals(null, item.getPhotoData()); assertEquals(-1, item.photo.getDataLength(item)); assertEquals(null, item.getPhotoMimeMajor()); assertEquals(null, item.getPhotoMimeMinor()); assertEquals(null, item.getPhotoURL()); } }
package imagej.updater.ui; import imagej.updater.core.Conflicts; import imagej.updater.core.Conflicts.Conflict; import imagej.updater.core.Dependency; import imagej.updater.core.FileObject; import imagej.updater.core.FileObject.Action; import imagej.updater.core.FileObject.Status; import imagej.updater.core.FilesCollection; import imagej.updater.core.FilesCollection.Filter; import imagej.updater.core.FilesUploader; import imagej.updater.core.Installer; import imagej.updater.core.UpdateSite; import imagej.updater.util.Downloadable; import imagej.updater.util.Downloader; import imagej.updater.util.Progress; import imagej.updater.util.StderrProgress; import imagej.updater.util.UpdaterUserInterface; import imagej.updater.util.Util; import imagej.util.AppUtils; import java.awt.Frame; import java.io.Console; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.scijava.log.LogService; /** * This is the command-line interface into the ImageJ Updater. * * @author Johannes Schindelin */ public class CommandLine { protected static LogService log = Util.getLogService(); protected FilesCollection files; protected Progress progress; private boolean checksummed = false; /** * Determines whether die() should exit or throw a RuntimeException. */ private boolean standalone; @Deprecated public CommandLine() { this(AppUtils.getBaseDirectory(), 80); } public CommandLine(final File ijDir, final int columnCount) { this(ijDir, columnCount, null); } public CommandLine(final File ijDir, final int columnCount, final Progress progress) { this.progress = progress == null ? new StderrProgress(columnCount) : progress; files = new FilesCollection(log, ijDir); } private void ensureChecksummed() { if (checksummed) return; String warnings; try { warnings = files.downloadIndexAndChecksum(progress); } catch (Exception e) { throw die("Received exception: " + e.getMessage()); } if (!warnings.equals("")) System.err.println(warnings); checksummed = true; } protected class FileFilter implements Filter { protected Set<String> fileNames; public FileFilter(final List<String> files) { if (files != null && files.size() > 0) { fileNames = new HashSet<String>(); for (final String file : files) fileNames.add(FileObject.getFilename(file, true)); } } @Override public boolean matches(final FileObject file) { if (!file.isUpdateablePlatform(files)) return false; if (fileNames != null && !fileNames.contains(file.getFilename(true))) return false; return file.getStatus() != Status.OBSOLETE_UNINSTALLED; } } public void listCurrent(final List<String> list) { ensureChecksummed(); for (final FileObject file : files.filter(new FileFilter(list))) System.out.println(file.filename + "-" + file.getTimestamp()); } public void list(final List<String> list, Filter filter) { ensureChecksummed(); if (filter == null) filter = new FileFilter(list); else filter = files.and(new FileFilter(list), filter); files.sort(); for (final FileObject file : files.filter(filter)) System.out.println(file.filename + "\t(" + file.getStatus() + ")\t" + file.getTimestamp()); } public void list(final List<String> list) { list(list, null); } public void listUptodate(final List<String> list) { list(list, files.is(Status.INSTALLED)); } public void listNotUptodate(final List<String> list) { list(list, files.not(files.oneOf(new Status[] { Status.OBSOLETE, Status.INSTALLED, Status.LOCAL_ONLY }))); } public void listUpdateable(final List<String> list) { list(list, files.is(Status.UPDATEABLE)); } public void listModified(final List<String> list) { list(list, files.is(Status.MODIFIED)); } public void listLocalOnly(final List<String> list) { list(list, files.is(Status.LOCAL_ONLY)); } public void listFromSite(final List<String> sites) { if (sites.size() != 1) throw die("Usage: list-from-site <name>"); list(null, files.isUpdateSite(sites.get(0))); } public void show(final List<String> list) { for (String filename : list) { show(filename); } } public void show(final String filename) { ensureChecksummed(); final FileObject file = files.get(filename); if (file == null) { System.err.println("\nERROR: File not found: " + filename); } else { show(file); } } public void show(final FileObject file) { ensureChecksummed(); System.out.println(); System.out.println("File: " + file.getFilename(true)); if (!file.getFilename(true).equals(file.localFilename)) { System.out.println("(Local filename: " + file.localFilename + ")"); } System.out.println("Update site: " + file.updateSite); if (file.current == null) { System.out.println("Removed from update site"); } else { System.out.println("URL: " + files.getURL(file)); System.out.println("checksum: " + file.current.checksum + ", timestamp: " + file.current.timestamp); } if (file.localChecksum != null && (file.current == null || !file.localChecksum.equals(file.current.checksum))) { System.out.println("Local checksum: " + file.localChecksum + " (" + (file.hasPreviousVersion(file.localChecksum) ? "" : "NOT a ") + "previous version)"); } } class OneFile implements Downloadable { FileObject file; OneFile(final FileObject file) { this.file = file; } @Override public File getDestination() { return files.prefix(file.filename); } @Override public String getURL() { return files.getURL(file); } @Override public long getFilesize() { return file.filesize; } @Override public String toString() { return file.filename; } } public void download(final FileObject file) { ensureChecksummed(); try { new Downloader(progress, files.util).start(new OneFile(file)); if (file.executable && !files.util.platform.startsWith("win")) try { Runtime.getRuntime() .exec( new String[] { "chmod", "0755", files.prefix(file.filename).getPath() }); } catch (final Exception e) { e.printStackTrace(); throw die("Could not mark " + file.filename + " as executable"); } System.err.println("Installed " + file.filename); } catch (final IOException e) { System.err.println("IO error downloading " + file.filename + ": " + e.getMessage()); } } public void delete(final FileObject file) { if (new File(file.filename).delete()) System.err.println("Deleted " + file.filename); else System.err.println("Failed to delete " + file.filename); } protected void addDependencies(final FileObject file, final Set<FileObject> all) { ensureChecksummed(); if (all.contains(file)) return; all.add(file); for (final Dependency dependency : file.getDependencies()) { final FileObject file2 = files.get(dependency.filename); if (file2 != null) addDependencies(file2, all); } } public void update(final List<String> list) { update(list, false); } public void update(final List<String> list, final boolean force) { update(list, force, false); } public void update(final List<String> list, final boolean force, final boolean pristine) { ensureChecksummed(); try { for (final FileObject file : files.filter(new FileFilter(list))) { if (file.getStatus() == Status.LOCAL_ONLY) { if (pristine) file.setAction(files, Action.UNINSTALL); } else if (file.isObsolete()) { if (file.getStatus() == Status.OBSOLETE) { log.info("Removing " + file.filename); file.stageForUninstall(files); } else if (file.getStatus() == Status.OBSOLETE_MODIFIED) { if (force || pristine) { file.stageForUninstall(files); log.info("Removing " + file.filename); } else log.warn("Skipping obsolete, but modified " + file.filename); } } else if (file.getStatus() != Status.INSTALLED && !file.stageForUpdate(files, force)) log.warn("Skipping " + file.filename); } Installer installer = new Installer(files, progress); installer.start(); installer.moveUpdatedIntoPlace(); files.write(); } catch (final Exception e) { if (e.getMessage().indexOf("conflicts") >= 0) { log.error("Could not update due to conflicts:"); for (Conflict conflict : new Conflicts(files).getConflicts(false)) log.error(conflict.getFilename() + ": " + conflict.getConflict()); } else log.error("Error updating", e); } } public void upload(final List<String> list) { if (list == null) throw die("Which files do you mean to upload?"); boolean forceUpdateSite = false; String updateSite = null; while (list.size() > 0 && list.get(0).startsWith("-")) { final String option = list.remove(0); if ("--update-site".equals(option)) { if (list.size() < 1) { throw die("Missing name for --update-site"); } updateSite = list.remove(0); forceUpdateSite = true; } else { throw die("Unknown option: " + option); } } if (list.size() == 0) throw die("Which files do you mean to upload?"); ensureChecksummed(); int count = 0; for (final String name : list) { final FileObject file = files.get(name); if (file == null) throw die("No file '" + name + "' found!"); if (file.getStatus() == Status.INSTALLED) { System.err.println("Skipping up-to-date " + name); continue; } handleLauncherForUpload(file); if (updateSite == null) { updateSite = file.updateSite; if (updateSite == null) updateSite = file.updateSite = chooseUploadSite(name); if (updateSite == null) throw die("Canceled"); } else if (file.updateSite == null) { System.err.println("Uploading new file '" + name + "' to site '" + updateSite + "'"); file.updateSite = updateSite; } else if (!file.updateSite.equals(updateSite)) { if (forceUpdateSite) { file.updateSite = updateSite; } else { throw die("Cannot upload to multiple update sites (" + list.get(0) + " to " + updateSite + " and " + name + " to " + file.updateSite + ")"); } } if (file.getStatus() == Status.NOT_INSTALLED || file.getStatus() == Status.NEW) { System.err.println("Removing file '" + name + "'"); file.setAction(files, Action.REMOVE); } else { file.setAction(files, Action.UPLOAD); } count++; } if (count == 0) { System.err.println("Nothing to upload"); return; } if (updateSite != null && files.getUpdateSite(updateSite) == null) { throw die("Unknown update site: '" + updateSite + "'"); } System.err.println("Uploading to " + getLongUpdateSiteName(updateSite)); upload(updateSite); } public void uploadCompleteSite(final List<String> list) { if (list == null) throw die("Which files do you mean to upload?"); boolean ignoreWarnings = false, forceShadow = false, simulate = false; while (list.size() > 0 && list.get(0).startsWith("-")) { final String option = list.remove(0); if ("--force".equals(option)) { ignoreWarnings = true; } else if ("--force-shadow".equals(option)) { forceShadow = true; } else if ("--simulate".equals(option)) { simulate = true; } else { throw die("Unknown option: " + option); } } if (list.size() != 1) throw die("Which files do you mean to upload?"); String updateSite = list.get(0); ensureChecksummed(); if (files.getUpdateSite(updateSite) == null) { throw die("Unknown update site '" + updateSite + "'"); } int removeCount = 0, uploadCount = 0, warningCount = 0; for (final FileObject file : files) { final String name = file.filename; handleLauncherForUpload(file); switch (file.getStatus()) { case OBSOLETE: case OBSOLETE_MODIFIED: if (forceShadow || (ignoreWarnings && updateSite.equals(file.updateSite))) { file.updateSite = updateSite; file.setAction(files, Action.UPLOAD); if (simulate) System.err.println("Would upload " + file.filename); uploadCount++; } else { System.err.println("Warning: obsolete '" + name + "' still installed!"); warningCount++; } break; case UPDATEABLE: case MODIFIED: if (!forceShadow && !updateSite.equals(file.updateSite)) { System.err.println("Warning: '" + name + "' of update site '" + file.updateSite + "' is not up-to-date!"); warningCount++; continue; } //$FALL-THROUGH$ case LOCAL_ONLY: file.updateSite = updateSite; file.setAction(files, Action.UPLOAD); if (simulate) System.err.println("Would upload new " + (file.getStatus() == Status.LOCAL_ONLY ? "" : "version of ") + file.getLocalFilename(true)); uploadCount++; break; case NEW: case NOT_INSTALLED: // special: keep tools-1.4.2.jar, needed for ImageJ 1.x if ("ImageJ".equals(updateSite) && file.getFilename(true).equals("jars/tools.jar")) break; file.setAction(files, Action.REMOVE); if (simulate) System.err.println("Would mark " + file.filename + " obsolete"); removeCount++; break; case INSTALLED: case OBSOLETE_UNINSTALLED: // leave these alone break; } } // remove all obsolete dependencies of the same upload site for (final FileObject file : files.forUpdateSite(updateSite)) { if (!file.willBeUpToDate()) continue; for (final FileObject dependency : file.getFileDependencies(files, false)) { if (dependency.willNotBeInstalled() && updateSite.equals(dependency.updateSite)) { file.removeDependency(dependency.getFilename(false)); } } } if (!ignoreWarnings && warningCount > 0) { throw die("Use --force to ignore warnings and upload anyway"); } if (removeCount == 0 && uploadCount == 0) { System.err.println("Nothing to upload"); return; } if (simulate) { final Iterable<Conflict> conflicts = new Conflicts(files).getConflicts(true); if (Conflicts.needsFeedback(conflicts)) { System.err.println("Unresolved upload conflicts!\n\n" + Util.join("\n", conflicts)); } else { System.err.println("Would upload " + uploadCount + " (removing " + removeCount + ") to " + getLongUpdateSiteName(updateSite)); } return; } System.err.println("Uploading " + uploadCount + " (removing " + removeCount + ") to " + getLongUpdateSiteName(updateSite)); upload(updateSite); } private void handleLauncherForUpload(final FileObject file) { if (file.getStatus() == Status.LOCAL_ONLY && files.util.isLauncher(file.filename)) { file.executable = true; file.addPlatform(Util.platformForLauncher(file.filename)); for (final String fileName : new String[] { "jars/ij-launcher.jar" }) { final FileObject dependency = files.get(fileName); if (dependency != null) file.addDependency(files, dependency); } } } private void upload(final String updateSite) { FilesUploader uploader = null; try { uploader = new FilesUploader(null, files, updateSite, progress); if (!uploader.login()) throw die("Login failed!"); uploader.upload(progress); files.write(); } catch (final Throwable e) { final String message = e.getMessage(); if (message != null && message.indexOf("conflicts") >= 0) { log.error("Could not upload due to conflicts:"); for (Conflict conflict : new Conflicts(files).getConflicts(true)) log.error(conflict.getFilename() + ": " + conflict.getConflict()); } else { e.printStackTrace(); throw die("Error during upload: " + e); } if (uploader != null) uploader.logout(); } } public String chooseUploadSite(final String file) { final List<String> names = new ArrayList<String>(); final List<String> options = new ArrayList<String>(); for (final String name : files.getUpdateSiteNames()) { final UpdateSite updateSite = files.getUpdateSite(name); if (updateSite.getUploadDirectory() == null || updateSite.getUploadDirectory().equals("")) continue; names.add(name); options.add(getLongUpdateSiteName(name)); } if (names.size() == 0) { System.err.println("No uploadable sites found"); return null; } final String message = "Choose upload site for file '" + file + "'"; final int index = UpdaterUserInterface.get().optionDialog(message, message, options.toArray(new String[options.size()]), 0); return index < 0 ? null : names.get(index); } public String getLongUpdateSiteName(final String name) { final UpdateSite site = files.getUpdateSite(name); return name + " (" + (site.getHost() == null || site.equals("") ? "" : site.getHost() + ":") + site.getUploadDirectory() + ")"; } public void listUpdateSites(Collection<String> args) { ensureChecksummed(); if (args == null || args.size() == 0) args = files.getUpdateSiteNames(); for (final String name : args) { final UpdateSite site = files.getUpdateSite(name); System.out.print(name + ": " + site.getURL()); if (site.getUploadDirectory() == null) System.out.println(); else System.out.println(" (upload host: " + site.getHost() + ", upload directory: " + site.getUploadDirectory() + ")"); } } public void addOrEditUploadSite(final List<String> args, boolean add) { if (args.size() != 2 && args.size() != 4) throw die("Usage: " + (add ? "add" : "edit") + "-update-site <name> <url> [<host> <upload-directory>]"); addOrEditUploadSite(args.get(0), args.get(1), args.size() > 2 ? args.get(2) : null, args.size() > 3 ? args.get(3) : null, add); } public void addOrEditUploadSite(final String name, final String url, final String sshHost, final String uploadDirectory, boolean add) { ensureChecksummed(); UpdateSite site = files.getUpdateSite(name); if (add) { if (site != null) throw die("Site '" + name + "' was already added!"); files.addUpdateSite(name, url, sshHost, uploadDirectory, 0l); } else { if (site == null) throw die("Site '" + name + "' was not yet added!"); site.setURL(url); site.setHost(sshHost); site.setUploadDirectory(uploadDirectory); } try { files.write(); } catch (Exception e) { UpdaterUserInterface.get().handleException(e); throw die("Could not write local file database"); } } public void removeUploadSite(final List<String> names) { if (names == null || names.size() < 1) { throw die("Which update-site do you want to remove, exactly?"); } removeUploadSite(names.toArray(new String[names.size()])); } public void removeUploadSite(final String... names) { ensureChecksummed(); for (final String name : names) { files.removeUpdateSite(name); } try { files.write(); } catch (Exception e) { UpdaterUserInterface.get().handleException(e); throw die("Could not write local file database"); } } @Deprecated public static CommandLine getInstance() { try { return new CommandLine(); } catch (final Exception e) { e.printStackTrace(); System.err.println("Could not parse db.xml.gz: " + e.getMessage()); throw new RuntimeException(e); } } private static List<String> makeList(final String[] list, int start) { final List<String> result = new ArrayList<String>(); while (start < list.length) result.add(list[start++]); return result; } /** * Print an error message and exit the process with an error. * * Note: Java has no "noreturn" annotation, but you can always write: * <code>throw die(<message>)</code> to make the Java compiler understand. * * @param message * the error message * @return a dummy return value to be able to use "throw die(...)" to shut * up the compiler */ private RuntimeException die(final String message) { if (standalone) { System.err.println(message); System.exit(1); } return new RuntimeException(message); } public void usage() { throw die("Usage: imagej.updater.ui.CommandLine <command>\n" + "\n" + "Commands:\n" + "\tlist [<files>]\n" + "\tlist-uptodate [<files>]\n" + "\tlist-not-uptodate [<files>]\n" + "\tlist-updateable [<files>]\n" + "\tlist-modified [<files>]\n" + "\tlist-current [<files>]\n" + "\tlist-local-only [<files>]\n" + "\tlist-from-site <name>\n" + "\tshow [<files>]\n" + "\tupdate [<files>]\n" + "\tupdate-force [<files>]\n" + "\tupdate-force-pristine [<files>]\n" + "\tupload [--update-site <name>] [<files>]\n" + "\tupload-complete-site [--simulate] [--force] [--force-shadow] <name>\n" + "\tlist-update-sites [<nick>...]\n" + "\tadd-update-site <nick> <url> [<host> <upload-directory>]\n" + "\tedit-update-site <nick> <url> [<host> <upload-directory>]"); } public static void main(final String... args) { try { main(AppUtils.getBaseDirectory(), 80, null, true, args); } catch (final RuntimeException e) { System.err.println(e.getMessage()); System.exit(1); } catch (final Exception e) { e.printStackTrace(); System.err.println("Could not parse db.xml.gz: " + e.getMessage()); System.exit(1); } } public static void main(final File ijDir, final int columnCount, final String... args) { main(ijDir, columnCount, null, args); } public static void main(final File ijDir, final int columnCount, final Progress progress, final String... args) { main(ijDir, columnCount, progress, false, args); } private static void main(final File ijDir, final int columnCount, final Progress progress, final boolean standalone, final String[] args) { String http_proxy = System.getenv("http_proxy"); if (http_proxy != null && http_proxy.startsWith("http: final int colon = http_proxy.indexOf(':', 7); final int slash = http_proxy.indexOf('/', 7); int port = 80; if (colon < 0) http_proxy = slash < 0 ? http_proxy.substring(7) : http_proxy.substring(7, slash); else { port = Integer.parseInt(slash < 0 ? http_proxy.substring(colon + 1) : http_proxy.substring(colon + 1, slash)); http_proxy = http_proxy.substring(7, colon); } System.setProperty("http.proxyHost", http_proxy); System.setProperty("http.proxyPort", "" + port); } else Util.useSystemProxies(); Authenticator.setDefault(new ProxyAuthenticator()); setUserInterface(); final CommandLine instance = new CommandLine(ijDir, columnCount, progress); instance.standalone = standalone; if (args.length == 0) { instance.usage(); } final String command = args[0]; if (command.equals("list")) instance.list(makeList(args, 1)); else if (command.equals("list-current")) instance.listCurrent( makeList(args, 1)); else if (command.equals("list-uptodate")) instance.listUptodate( makeList(args, 1)); else if (command.equals("list-not-uptodate")) instance .listNotUptodate(makeList(args, 1)); else if (command.equals("list-updateable")) instance.listUpdateable( makeList(args, 1)); else if (command.equals("list-modified")) instance.listModified( makeList(args, 1)); else if (command.equals("list-local-only")) instance.listLocalOnly( makeList(args, 1)); else if (command.equals("list-from-site")) instance.listFromSite(makeList(args, 1)); else if (command.equals("show")) instance.show(makeList(args, 1)); else if (command.equals("update")) instance.update(makeList(args, 1)); else if (command.equals("update-force")) instance.update( makeList(args, 1), true); else if (command.equals("update-force-pristine")) instance.update( makeList(args, 1), true, true); else if (command.equals("upload")) instance.upload(makeList(args, 1)); else if (command.equals("upload-complete-site")) instance.uploadCompleteSite(makeList(args, 1)); else if (command.equals("list-update-sites")) instance.listUpdateSites(makeList(args, 1)); else if (command.equals("add-update-site")) instance.addOrEditUploadSite(makeList(args, 1), true); else if (command.equals("edit-update-site")) instance.addOrEditUploadSite(makeList(args, 1), false); else if (command.equals("remove-update-site")) instance.removeUploadSite(makeList(args, 1)); else instance.usage(); } protected static class ProxyAuthenticator extends Authenticator { protected Console console = System.console(); @Override protected PasswordAuthentication getPasswordAuthentication() { final String user = console.readLine(" \rProxy User: "); final char[] password = console.readPassword("Proxy Password: "); return new PasswordAuthentication(user, password); } } protected static void setUserInterface() { UpdaterUserInterface.set(new ConsoleUserInterface()); } protected static class ConsoleUserInterface extends UpdaterUserInterface { protected Console console = System.console(); protected int count; @Override public String getPassword(final String message) { if (console == null) { throw new RuntimeException("Password prompt requires interactive operation!"); } System.out.print(message + ": "); return new String(console.readPassword()); } @Override public boolean promptYesNo(final String title, final String message) { System.err.print(title + ": " + message); final String line = console.readLine(); return line.startsWith("y") || line.startsWith("Y"); } public void showPrompt(String prompt) { if (!prompt.endsWith(": ")) prompt += ": "; System.err.print(prompt); } public String getUsername(final String prompt) { showPrompt(prompt); return console.readLine(); } public int askChoice(final String[] options) { for (int i = 0; i < options.length; i++) System.err.println("" + (i + 1) + ": " + options[i]); for (;;) { System.err.print("Choice? "); final String answer = console.readLine(); if (answer.equals("")) return -1; try { return Integer.parseInt(answer) - 1; } catch (final Exception e) { /* ignore */} } } @Override public void error(final String message) { log.error(message); } @Override public void info(final String message, final String title) { log.info(title + ": " + message); } @Override public void log(final String message) { log.info(message); } @Override public void debug(final String message) { log.debug(message); } @Override public OutputStream getOutputStream() { return System.out; } @Override public void showStatus(final String message) { log(message); } @Override public void handleException(final Throwable exception) { exception.printStackTrace(); } @Override public boolean isBatchMode() { return false; } @Override public int optionDialog(final String message, final String title, final Object[] options, final int def) { for (int i = 0; i < options.length; i++) System.err.println("" + (i + 1) + ") " + options[i]); for (;;) { System.out.print("Your choice (default: " + def + ": " + options[def] + ")? "); final String line = console.readLine(); if (line.equals("")) return def; try { final int option = Integer.parseInt(line); if (option > 0 && option <= options.length) return option - 1; } catch (final NumberFormatException e) { // ignore } } } @Override public String getPref(final String key) { return null; } @Override public void setPref(final String key, final String value) { log("Ignoring setting '" + key + "'"); } @Override public void savePreferences() { /* do nothing */} @Override public void openURL(final String url) throws IOException { log("Please open " + url + " in your browser"); } @Override public String getString(final String title) { System.out.print(title + ": "); return console.readLine(); } @Override public void addWindow(final Frame window) { throw new UnsupportedOperationException(); } @Override public void removeWindow(final Frame window) { throw new UnsupportedOperationException(); } } }
package jp.co.nohana.albums; import android.database.Cursor; import android.os.Environment; import android.os.Parcel; import android.os.Parcelable; import android.provider.MediaStore; /** * Wrapper object of the bucket id that represents device album folder as identifiable. * @author KeithYokoma * @since 1.0.0 * @version 1.0.0 */ @SuppressWarnings("unused") // public APIs public final class BucketId implements Parcelable { public static final Creator<BucketId> CREATOR = new Creator<BucketId>() { @Override public BucketId createFromParcel(Parcel source) { return new BucketId(source); } @Override public BucketId[] newArray(int size) { return new BucketId[size]; } }; private final int mHash; /* package */ BucketId(int hash) { mHash = hash; } /* package */ BucketId(Parcel source) { mHash = source.readInt(); } public static BucketId valueOf(String dirName) { String filePath = Environment.getExternalStorageDirectory().toString() + "/" + dirName; return new BucketId(AlbumUtils.getBucketIdHash(filePath)); } /** * Create a bucket id object from a {@link android.database.Cursor}. * This method is not responsible for managing cursor resource. * If the {@link android.database.Cursor} does not have a column of {@link android.provider.MediaStore.Images.Media#BUCKET_ID}, * this will return null. * @param cursor to obtain bucket id. * @return the bucket id object, null if bucket id column does not exist. */ public static BucketId from(Cursor cursor) { int index = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID); if (index == -1) { return null; } int hash = cursor.getInt(index); return new BucketId(hash); } @Override public boolean equals(Object o) { if (o instanceof BucketId) { BucketId e = (BucketId) o; return e.mHash == mHash; } return super.equals(o); } @Override public int hashCode() { return mHash; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mHash); } @Override public String toString() { return String.valueOf(mHash); } public int toInteger() { return mHash; } }
package com.thindeck.dynamo; import com.jcabi.dynamo.Attributes; import com.jcabi.dynamo.Region; import com.jcabi.dynamo.Table; import com.jcabi.dynamo.mock.H2Data; import com.jcabi.dynamo.mock.MkRegion; import com.thindeck.api.Repo; import com.thindeck.api.Task; import com.thindeck.api.mock.MkRepo; import java.io.IOException; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; /** * Test case for {@link DyTasks}. * * @author Paul Polishchuk (ppol@ua.fm) * @version $Id$ * @since 0.5 */ public final class DyTasksTest { /** * The custom command. */ private static final transient String CMD = "command"; /** * DyTasks can retrieve Task by number. * @throws Exception In case of error. */ @Test public void getTask() throws Exception { final Repo repo = new MkRepo(); final long tid = 10L; MatcherAssert.assertThat( new DyTasks( DyTasksTest.region(repo.name(), tid, 2L, 1L), repo ).get(tid).number(), Matchers.equalTo(tid) ); } /** * DyTasks retrieve Task by number fails with * {@link NoSuchElementException} if wrong (non-existing) Task number is * passed. * @throws Exception In case of error. */ @Test(expected = NoSuchElementException.class) public void getInvalidTask() throws Exception { final Repo repo = new MkRepo(); final long tid = 10L; new DyTasks( DyTasksTest.region(repo.name(), tid, 2L, 1L), repo ).get(0L); } /** * DyTask can add a task with attributes in NULL. * @throws Exception In case of error. */ @Test @Ignore public void addTaskNullAttributes() throws Exception { final Repo repo = new MkRepo(); final DyTasks tasks = new DyTasks( DyTasksTest.region(repo.name()), repo ); final Task task = tasks.add(DyTasksTest.CMD, null); MatcherAssert.assertThat( task.command(), Matchers.equalTo(DyTasksTest.CMD) ); } /** * DyTask can add a task without attributes. * @throws Exception In case of error. */ @Test @Ignore public void addTaskWithoutAttributes() throws Exception { final Repo repo = new MkRepo(); final DyTasks tasks = new DyTasks( DyTasksTest.region(repo.name()), repo ); final ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>(); final Task task = tasks.add(DyTasksTest.CMD, map); MatcherAssert.assertThat( task.command(), Matchers.equalTo(DyTasksTest.CMD) ); } /** * DyTask can add a task with attributes. * @throws Exception In case of error. */ @Test @Ignore public void addTaskWithAttributes() throws Exception { final Repo repo = new MkRepo(); final DyTasks tasks = new DyTasks( DyTasksTest.region(repo.name()), repo ); final ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>(); map.put("key", "value"); final Task task = tasks.add(DyTasksTest.CMD, map); MatcherAssert.assertThat( task.command(), Matchers.equalTo(DyTasksTest.CMD) ); } /** * DyTasks can get all task empty. * @throws Exception In case of error. */ @Test public void allWithoutTask() throws Exception { final Repo repo = new MkRepo(); final DyTasks tasks = new DyTasks( DyTasksTest.region(repo.name()), repo ); MatcherAssert.assertThat(tasks.all(), Matchers.emptyIterable()); } /** * DyTasks can get the only one task. * @throws Exception In case of error. */ @Test public void allWithOneTask() throws Exception { final Repo repo = new MkRepo(); final DyTasks tasks = new DyTasks( DyTasksTest.region(repo.name(), 10L), repo ); MatcherAssert.assertThat( tasks.all(), Matchers.<Task>iterableWithSize(1) ); } /** * DyTasks can get the all the tasks. * @throws Exception In case of error. */ @Test public void allWithMoreThatOneTask() throws Exception { final Repo repo = new MkRepo(); final DyTasks tasks = new DyTasks( DyTasksTest.region(repo.name(), 10L, 20L), repo ); MatcherAssert.assertThat( tasks.all(), Matchers.<Task>iterableWithSize(2) ); } /** * Create region with one repo and multiple tasks. * @param repo Repo urn. * @param ids Ids of tasks. * @return Region created. * @throws IOException In case of error. */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") private static Region region(final String repo, final long... ids) throws IOException { final Region region = new MkRegion( new H2Data().with( DyTask.TBL, new String[] {DyTask.ATTR_ID}, new String[] {DyTask.ATTR_REPO_URN} ) ); final Table table = region.table(DyTask.TBL); for (final long tid : ids) { table.put( new Attributes().with(DyTask.ATTR_ID, tid) .with(DyTask.ATTR_REPO_URN, repo) ); } return region; } }
package gpio.example; import gpio.BeagleboneGPio; import gpio.BeagleboneGpioFactory; import gpio.Gpio; import gpio.PwmOutputPin; import java.io.IOException; /** * Test program that fades the P9_14 output ten times. * @author Koert Zeilstra */ public class FadeRgb { private Gpio gpio = new Gpio(new BeagleboneGpioFactory()); private Color[] colors = { new Color(1, 0, 0), new Color(0, 1, 0), new Color(0, 0, 1), new Color(1, 1, 0), new Color(0, 1, 1), new Color(1, 0, 1), new Color(0.5F, 0.5F, 0.5F), new Color(0.5F, 1, 0), new Color(0, 0.5F, 1), new Color(1, 0, 0.5F), new Color(0.5F, 1, 1), new Color(1, 0.5F, 1), new Color(1, 1, 0.5F), new Color(0.5F, 1, 0.5F), new Color(0, 0, 0) }; private Color black = new Color(0, 0, 0); private Color white = new Color(1, 1, 1); private PwmOutputPin red = gpio.pwmOutputPin(BeagleboneGPio.P9_14); private PwmOutputPin green = gpio.pwmOutputPin(BeagleboneGPio.P9_16); private PwmOutputPin blue = gpio.pwmOutputPin(BeagleboneGPio.P9_22); public static void main(String[] args) { FadeRgb fade = null; try { fade = new FadeRgb(); fade.fade(); } catch (Exception e) { e.printStackTrace(); } finally { if (fade != null) { try { fade.close(); } catch (IOException e) { } } } } public FadeRgb() throws IOException { } public void fade() throws IOException { Color currentColor = black; for (Color color : colors) { fade(currentColor, color); currentColor = color; } // for (int i=0; i<10; i++) { // for (int j=15; j<=1000; j++) { // pin.dutyCycle((float) j/10); // Thread.sleep(1); // for (int j=1000; j>=15; j--) { // pin.dutyCycle((float) j/10); // Thread.sleep(1); // pin.dutyCycle(0); // pin.close(); } public void close() throws IOException { red.close(); green.close(); blue.close(); } private void fade(Color from, Color to) throws IOException { for (int i = 0; i <= 1000; i++) { float r = from.red + i * (to.red - from.red) / 1000; float g = from.green + i * (to.green - from.green) / 1000; float b = from.blue + i * (to.blue - from.blue) / 1000; System.out.printf("rgb %1.3f %1.3f %1.3f\r", r, g, b); red.dutyCycle(r); green.dutyCycle(g); blue.dutyCycle(b); try { Thread.sleep(10); } catch (InterruptedException e) { } } } public class Color { public float red; public float green; public float blue; public Color(float red, float green, float blue) { this.red = red; this.green = green; this.blue = blue; } } }
package integrationTests.loops; import org.junit.*; import integrationTests.*; public final class WhileStatementsTest extends CoverageTest { WhileStatements tested; @Test public void whileBlockInSeparateLines() { tested.whileBlockInSeparateLines(); assertLines(7, 12, 4); assertLine(7, 1, 1, 1); assertLine(9, 2, 2, 6); assertLine(10, 1, 1, 5); assertLine(12, 1, 1, 1); findMethodData(7, "whileBlockInSeparateLines"); assertMethodLines(7, 12); assertPaths(2, 1, 1); assertPath(4, 0); assertPath(5, 1); } @Test public void whileBlockInSingleLine() { tested.whileBlockInSingleLine(0); tested.whileBlockInSingleLine(1); tested.whileBlockInSingleLine(2); assertLines(15, 16, 2); assertLine(15, 2, 2, 6); assertLine(16, 1, 1, 3); findMethodData(15, "whileBlockInSingleLine"); assertMethodLines(15, 16); assertPaths(2, 2, 3); assertPath(4, 1); assertPath(5, 2); } @Test public void whileWithContinue() { tested.whileWithContinue(0); tested.whileWithContinue(1); tested.whileWithContinue(2); assertLines(20, 29, 6); assertLine(20, 2, 2, 6); assertLine(21, 2, 2, 3); assertLine(22, 1, 1, 2); assertLine(23, 1, 1, 2); assertLine(26, 1, 1, 1); assertLine(29, 1, 1, 3); findMethodData(20, "whileWithContinue"); assertMethodLines(20, 29); assertPaths(3, 2, 2); // TODO: one path is unfeasible } @Test public void whileWithBreak() { tested.whileWithBreak(0); tested.whileWithBreak(1); tested.whileWithBreak(2); assertLines(34, 42, 5); assertLine(34, 2, 2, 4); assertLine(35, 2, 2, 3); assertLine(36, 1, 1, 2); assertLine(39, 1, 1, 1); assertLine(42, 1, 1, 3); findMethodData(34, "whileWithBreak"); assertMethodLines(34, 42); assertPaths(3, 3, 3); assertPath(5, 1); assertPath(9, 1); assertPath(8, 1); } @Test public void nestedWhile() { tested.nestedWhile(0, 2); tested.nestedWhile(1, 1); assertLines(47, 54, 4); assertLine(47, 2, 2, 3); assertLine(48, 2, 1, 1); assertLine(49, 1, 0, 0); assertLine(52, 1, 1, 1); assertLine(54, 1, 1, 2); findMethodData(47, "nestedWhile"); assertMethodLines(47, 54); assertPaths(3, 2, 2); assertPath(4, 1); assertPath(8, 1); assertPath(9, 0); } @Test public void doWhileInSeparateLines() { tested.doWhileInSeparateLines(); assertLines(58, 63, 4); assertLine(58, 1, 1, 1); assertLine(61, 1, 1, 3); assertLine(62, 1, 1, 3); assertLine(63, 1, 1, 1); findMethodData(58, "doWhileInSeparateLines"); assertMethodLines(58, 63); assertPaths(1, 1, 1); assertPath(2, 1); } @Ignore @Test public void bothKindsOfWhileCombined() { tested.bothKindsOfWhileCombined(0, 2); tested.bothKindsOfWhileCombined(1, 1); assertLines(69, 76, 5); assertLine(69, 1, 1, 3); assertLine(71, 1, 1, 3); assertLine(73, 1, 1, 2); assertLine(75, 1, 1, 2); // why only one segment? assertLine(76, 1, 1, 2); findMethodData(69, "bothKindsOfWhileCombined"); assertMethodLines(69, 76); assertPaths(1, 1, 2); // why only one path? assertPath(2, 2); } }
package edu.kit.informatik.list; /** * Implements a sorted double connected list * * @author JoseNote * * @param <T> A class that implements the interface {@linkplain Comparable} * @version 1.00 */ public class LinkedSortedAppendList<T extends Comparable<T>> implements SortedAppendList<T> { /** * Represents the start of the list, the first element */ private ListCell first; /** * Represents the end of the list, the last element */ private ListCell last; /** * Creates a new empty list */ public LinkedSortedAppendList() { first = null; last = null; } /** * Implementation of {@linkplain SortedAppendList#addSorted(Comparable) SortedAppendList#addSorted} * @param element The new element to add */ public void addSorted(T element) { if (first == null) { //true: the list is empty first = new ListCell(element); last = first; } else { ListCell cursor = first; while (element.compareTo(cursor.value) > 0 && cursor != last) cursor = cursor.next; if (element.compareTo(cursor.value) < 0) { //true: the new element is smaller than the current cursor element ListCell newNode = new ListCell(element, cursor.previous, cursor); cursor.previous = newNode; if (newNode.previous != null)newNode.previous.next = newNode; if (cursor == first) { //true: head must be replaced first = newNode; } } else { //the new element is bigger than or equal to the current cursor element ListCell newNode = new ListCell(element, cursor, cursor.next); cursor.next = newNode; if (newNode.next != null)newNode.next.previous = newNode; if (cursor == last) { //true: the end must be replaced last = newNode; } } } } /** * Implementation of {@linkplain SortedAppendList#iterator() SortedAppendList#iterator} * @return An instance of {@linkplain Iterator} */ public SortedIterator<T> iterator() { return new Iterator(first); } // public String toString() { // StringBuilder builder = new StringBuilder(); // SortedIterator<T> it = iterator(); // while (it.hasNext()) { // T element = it.next(); // builder.append(element); // if (it.hasNext())builder.append("-"); // return builder.toString(); /** * An inner class used to represent the nodes contained in the double connected list * * @author JoseNote * * @param <T> A class that implements the interface {@linkplain Comparable}. */ private final class ListCell { private ListCell previous; private ListCell next; private T value; /** * Creates a new instance * @param value The value for this instance */ private ListCell(T value) { this.value = value; previous = null; next = null; } /** * Creates a new instance associated to two other instances * @param value The value for this instance * @param previous A pointer to another instance * @param next A pointer to another instance */ private ListCell(T value, ListCell previous, ListCell next) { this.value = value; this.previous = previous; this.next = next; } // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append(previous == null ? "null" : previous.value) // .append("<-").append(value).append("->") // .append(next == null ? "null" : next.value); // return builder.toString(); } /** * An inner class used to represent an iterator associated to {@linkplain LinkedSortedAppendList} * @author JoseNote * @version 1.00 */ private final class Iterator implements SortedIterator<T> { /** * A pointer to the current element of the iterator */ private ListCell cursor; /** * Creates a new iterator associated to a list * @param start The start element of a list */ private Iterator(ListCell start) { cursor = start; } public boolean hasNext() { return cursor != null; } public T next() { T currentContent = cursor.value; cursor = cursor.next; return currentContent; } // public String toString() { // StringBuilder builder = new StringBuilder(); // if (cursor == null) return "null"; // else { // builder.append(cursor.previous == null ? "null" : cursor.previous.value) // .append("<-").append(cursor.value).append("->") // .append(cursor.next == null ? "null" : cursor.next.value); // return builder.toString(); } }
package edu.rutgers.css.Rutgers.auxiliary; import java.util.List; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import edu.rutgers.css.Rutgers2.R; /** * Array adapter for menus with items and section headers. * Takes items which implement the RMenuPart interface. The text for the item * is taken from getTitle(). Whether it's a section header is determined with getIsCategory(). * If the object is a category, the category resource will be used for its layout. * If the object is an item, the item resource will be used for its layout. */ public class RMenuAdapter extends ArrayAdapter<RMenuPart> { private final String androidns = "http://schemas.android.com/apk/res/android"; private final static String TAG = "RMenuAdapter"; private int itemResource; private int categoryResource; private int itemBgColor; private int selectColor; private int selectedPos; private int lastPos; private static enum ViewTypes { HEADER, CLICKABLE, UNCLICKABLE; } static class ViewHolder { TextView titleTextView; } /** * * @param context App context * @param itemResource Layout to use for menu items * @param categoryResource Layout to use for section headers * @param objects List of menu objects to use */ public RMenuAdapter(Context context, int itemResource, int categoryResource, List<RMenuPart> objects) { super(context, itemResource, objects); this.itemResource = itemResource; this.categoryResource = categoryResource; /* int itemBgRes = context.getResources().getLayout(itemResource).getAttributeIntValue(null, "background", 0); Log.d(TAG, "get layout = " + context.getResources().getLayout(itemResource).toString()); Log.d(TAG, "get attr = " + itemBgRes); if(itemBgRes != 0) this.itemBgColor = context.getResources().getColor(itemBgRes);*/ this.selectColor = 0; this.selectedPos = -1; this.lastPos = -1; } public void setSelectColor(int id) { this.selectColor = id; } public int getSelectColor() { return this.selectColor; } public void setSelectedPos(int position) { this.selectedPos = position; } public int getSelectedPos() { return this.selectedPos; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater mLayoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); RMenuPart curItem = this.getItem(position); ViewHolder holder = null; // Choose appropriate layout if(convertView == null) { // Section headers if(getItemViewType(position) == ViewTypes.HEADER.ordinal()) { convertView = mLayoutInflater.inflate(this.categoryResource, null); } // Menu items else { convertView = mLayoutInflater.inflate(this.itemResource, null); } // Determine if item should not be clickable if(!curItem.getClickable()) { convertView.setEnabled(false); convertView.setClickable(false); convertView.setOnClickListener(null); } holder = new ViewHolder(); holder.titleTextView = (TextView) convertView.findViewById(R.id.title); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); // Set item text if(holder.titleTextView != null) holder.titleTextView.setText(curItem.getTitle()); else Log.e(TAG, "R.id.title not found"); /* if(getSelectColor() != 0 && getItemViewType(position) == 0) { if(getSelectedPos() == position) { convertView.setBackgroundColor(getSelectColor()); } else { convertView.setBackgroundColor(itemBgColor); } } */ return convertView; } /** * Types of row items: * 1. Category headers * 2. Unclickable items * 3. Clickable items */ @Override public int getViewTypeCount() { return ViewTypes.values().length; } @Override public int getItemViewType(int position) { if(getItem(position).getIsCategory()) return ViewTypes.HEADER.ordinal(); else if(getItem(position).getClickable()) return ViewTypes.CLICKABLE.ordinal(); else return ViewTypes.UNCLICKABLE.ordinal(); } }
package org.jasig.portal.tools.checks; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.portal.spring.PortalApplicationContextFacade; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; /** * Check that a particular named Spring bean is defined. * * @version $Revision$ $Date$ * @since uPortal 2.5 */ public class SpringBeanCheck implements ICheck { protected final Log log = LogFactory.getLog(getClass()); private final String beanName; private final String requiredBeanTypeClassName; private CheckResult nullBeanNameResult = CheckResult.createFailure("This check is fatally misconfigured -- it hasn't been told the name of the Spring bean for which it should be checking.", "Fix the check configuration (probably a List named 'checks' declared in applicationContext.xml)."); public SpringBeanCheck(String beanName, String requiredBeanTypeClassName) { this.beanName = beanName; this.requiredBeanTypeClassName = requiredBeanTypeClassName; } public SpringBeanCheck(String beanName) { this.beanName = beanName; this.requiredBeanTypeClassName = null; } public CheckResult doCheck() { if (this.beanName == null) return this.nullBeanNameResult; // either verify that the bean exists (and is of the desired type if specified) // or translate the resulting RuntimeException into an explanatory // CheckResult. try { if (this.requiredBeanTypeClassName == null) { PortalApplicationContextFacade.getPortalApplicationContext().getBean(this.beanName); return CheckResult.createSuccess("Bean with name [" + this.beanName + "] was present."); } PortalApplicationContextFacade.getPortalApplicationContext().getBean(this.beanName, Class.forName(this.requiredBeanTypeClassName)); return CheckResult.createSuccess("Bean with name [" + this.beanName + "] was present and of class [" + this.requiredBeanTypeClassName + "]"); } catch (NoSuchBeanDefinitionException nsbde) { String remediationAdvice; if (this.requiredBeanTypeClassName == null) { remediationAdvice = "Declare a singleton bean of name [" + this.beanName + "] in a Spring bean definition file mapped in /properties/beanRef.xml."; } else { remediationAdvice = "Declare a singleton bean of name [" + this.beanName + "] and of type [" + this.requiredBeanTypeClassName + "] in a Spring bean definition file mapped in /properties/beanRefFactory.xml."; } return CheckResult.createFailure("There is no bean named [" + this.beanName + "] in uPortal's Spring bean definition file(s) (e.g., applicationContext.xml).", remediationAdvice); } catch (BeanNotOfRequiredTypeException bnfe) { return CheckResult.createFailure("The bean named [" + this.beanName + "] defined in uPotal's Spring bean definitions (likely, applicationContext.xml), is not of type [" + this.requiredBeanTypeClassName + "]", "Fix the declaration of bean [" + this.beanName + "] to be of the required type."); } catch (BeansException be) { log.error("Error instantiating "+ this.beanName, be); return CheckResult.createFailure("There was an error instantiating the bean [" + this.beanName + "] required for configuration of configuration checking.", be.getMessage()); } catch (ClassNotFoundException cnfe) { return CheckResult.createFailure("We can't check for the presence of the bean [" + this.beanName + "] because the desired class [" + this.requiredBeanTypeClassName + "] itself could not be found.", "Either fix the configuration of this check so that it's checking for the right class name, or place the required class on the classpath."); } } public String getDescription() { if (this.beanName == null) return "Fatally misconfigured check doesn't do anything because it hasn't been given a bean name to check."; if (this.requiredBeanTypeClassName == null) return "Checks for the presence of the Spring bean named [" + this.beanName + "]."; return "Checks for the presence of the Spring bean named [" + this.beanName + "] and that it is an instance of class [" + this.requiredBeanTypeClassName + "]"; } }
package edu.ucsb.cs56.w14.drawings.dcoffill; import javax.swing.*; /** SimpleGui1 comes from Head First Java 2nd Edition p. 355. It illustrates a simple GUI with a Button that doesn't do anything yet. @author Head First Java, 2nd Edition p. 355 @author P. Conrad (who only typed it in and added the Javadoc comments) @author David Coffill @version CS56, Winter 2014, UCSB */ public class SimpleGui1 { /** main method to fire up a JFrame on the screen @param args not used */ public static void main (String[] args) { JFrame frame = new JFrame() ; JButton button = new JButton("Click me, please") ; java.awt.Color myColor = new java.awt.Color(50, 200, 240); button.setBackground(myColor); button.setOpaque(true); frame. setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE) ; frame. getContentPane() . add(button) ; frame. setSize(300,300) ; frame. setVisible(true) ; } }
package org.jfree.chart.renderer.xy; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.labels.XYItemLabelGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.data.Range; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.text.TextUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; import org.jfree.util.ShapeUtilities; /** * A renderer that draws a line connecting the start and end Y values for an * {@link XYPlot}. The example shown here is generated by the * {@code YIntervalRendererDemo1.java} program included in the JFreeChart * demo collection: * <br><br> * <img src="../../../../../images/YIntervalRendererSample.png" * alt="YIntervalRendererSample.png"> */ public class YIntervalRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2951586537224143260L; /** * An additional item label generator. If this is non-null, the item * label generated will be displayed near the lower y-value at the * position given by getNegativeItemLabelPosition(). * * @since 1.0.10 */ private XYItemLabelGenerator additionalItemLabelGenerator; /** * The default constructor. */ public YIntervalRenderer() { super(); this.additionalItemLabelGenerator = null; } /** * Returns the generator for the item labels that appear near the lower * y-value. * * @return The generator (possibly {@code null}). * * @see #setAdditionalItemLabelGenerator(XYItemLabelGenerator) * * @since 1.0.10 */ public XYItemLabelGenerator getAdditionalItemLabelGenerator() { return this.additionalItemLabelGenerator; } /** * Sets the generator for the item labels that appear near the lower * y-value and sends a {@link RendererChangeEvent} to all registered * listeners. If this is set to {@code null}, no item labels will be * drawn. * * @param generator the generator ({@code null} permitted). * * @see #getAdditionalItemLabelGenerator() * * @since 1.0.10 */ public void setAdditionalItemLabelGenerator( XYItemLabelGenerator generator) { this.additionalItemLabelGenerator = generator; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset ({@code null} permitted). * * @return The range ({@code null} if the dataset is {@code null} or empty). */ @Override public Range findRangeBounds(XYDataset dataset) { return findRangeBounds(dataset, true); } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * ({@code null} permitted). * @param pass the pass index (ignored here). */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // do nothing if item is not visible if (!getItemVisible(series, item)) { return; } // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset; double x = intervalDataset.getXValue(series, item); double yLow = intervalDataset.getStartYValue(series, item); double yHigh = intervalDataset.getEndYValue(series, item); RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double xx = domainAxis.valueToJava2D(x, dataArea, xAxisLocation); double yyLow = rangeAxis.valueToJava2D(yLow, dataArea, yAxisLocation); double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea, yAxisLocation); Paint p = getItemPaint(series, item); Stroke s = getItemStroke(series, item); Line2D line = null; Shape shape = getItemShape(series, item); Shape top = null; Shape bottom = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(yyLow, xx, yyHigh, xx); top = ShapeUtilities.createTranslatedShape(shape, yyHigh, xx); bottom = ShapeUtilities.createTranslatedShape(shape, yyLow, xx); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(xx, yyLow, xx, yyHigh); top = ShapeUtilities.createTranslatedShape(shape, xx, yyHigh); bottom = ShapeUtilities.createTranslatedShape(shape, xx, yyLow); } else { throw new IllegalStateException(); } g2.setPaint(p); g2.setStroke(s); g2.draw(line); g2.fill(top); g2.fill(bottom); // for item labels, we have a special case because there is the // possibility to draw (a) the regular item label near to just the // upper y-value, or (b) the regular item label near the upper y-value // PLUS an additional item label near the lower y-value. if (isItemLabelVisible(series, item)) { drawItemLabel(g2, orientation, dataset, series, item, xx, yyHigh, false); drawAdditionalItemLabel(g2, orientation, dataset, series, item, xx, yyLow); } // add an entity for the item... Shape hotspot = ShapeUtilities.createLineRegion(line, 4.0f); if (entities != null && hotspot.intersects(dataArea)) { addEntity(entities, hotspot, dataset, series, item, xx, (yyHigh + yyLow) / 2); } } /** * Draws an item label. * * @param g2 the graphics device. * @param orientation the orientation. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param x the x coordinate (in Java2D space). * @param y the y coordinate (in Java2D space). */ private void drawAdditionalItemLabel(Graphics2D g2, PlotOrientation orientation, XYDataset dataset, int series, int item, double x, double y) { if (this.additionalItemLabelGenerator == null) { return; } Font labelFont = getItemLabelFont(series, item); Paint paint = getItemLabelPaint(series, item); g2.setFont(labelFont); g2.setPaint(paint); String label = this.additionalItemLabelGenerator.generateLabel(dataset, series, item); ItemLabelPosition position = getNegativeItemLabelPosition(series, item); Point2D anchorPoint = calculateLabelAnchorPoint( position.getItemLabelAnchor(), x, y, orientation); TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(), position.getRotationAnchor()); } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof YIntervalRenderer)) { return false; } YIntervalRenderer that = (YIntervalRenderer) obj; if (!ObjectUtilities.equal(this.additionalItemLabelGenerator, that.additionalItemLabelGenerator)) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package edu.wustl.xipHost.hostControl; import java.awt.Dimension; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.xml.ws.Endpoint; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import org.nema.dicom.wg23.State; import org.openhealthtools.ihe.atna.auditor.IHEAuditor; import org.xmldb.api.base.XMLDBException; import edu.wustl.xipHost.application.Application; import edu.wustl.xipHost.application.ApplicationManager; import edu.wustl.xipHost.application.ApplicationManagerFactory; import edu.wustl.xipHost.application.ApplicationTerminationEvent; import edu.wustl.xipHost.application.ApplicationTerminationListener; import edu.wustl.xipHost.iterator.IterationTarget; import edu.wustl.xipHost.caGrid.GridManager; import edu.wustl.xipHost.caGrid.GridManagerFactory; import edu.wustl.xipHost.dicom.DicomManager; import edu.wustl.xipHost.dicom.DicomManagerFactory; import edu.wustl.xipHost.gui.ConfigPanel; import edu.wustl.xipHost.gui.ExceptionDialog; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.gui.LoginDialog; import edu.wustl.xipHost.worklist.Worklist; import edu.wustl.xipHost.worklist.WorklistFactory; import edu.wustl.xipHost.xds.XDSManager; import edu.wustl.xipHost.xds.XDSManagerFactory; public class HostConfigurator implements ApplicationTerminationListener { final static Logger logger = Logger.getLogger(HostConfigurator.class); Login login = new Login(); File hostTmpDir; File hostOutDir; File hostConfig; HostMainWindow mainWindow; ConfigPanel configPanel = new ConfigPanel(new JFrame()); //ConfigPanel is used to specify tmp and output dirs GridManager gridMgr; DicomManager dicomMgr; ApplicationManager appMgr; XDSManager xdsMgr; File xipApplicationsConfig; public static final String OS = System.getProperty("os.name"); String userName = "xip"; ApplicationTerminationListener applicationTerminationListener; public HostConfigurator(){ applicationTerminationListener = this; } public boolean runHostStartupSequence(){ logger.info("Launching XIP Host. Platform " + OS); hostConfig = new File("./config/xipConfig.xml"); if(loadHostConfigParameters(hostConfig) == false){ new ExceptionDialog("Unable to load Host configuration parameters.", "Ensure host config file config file is valid.", "Host Startup Dialog"); System.exit(0); } if(loadPixelmedSavedImagesFolder(serverConfig) == false){ new ExceptionDialog("Unable to load Pixelmed/HSQLQB configuration parameters.", "Ensure Pixelmed/HSQLQB config file is valid.", "Host DB Startup Dialog"); System.exit(0); } //if config contains displayConfigDialog true -> displayConfigDialog if(getDisplayStartUp()){ displayConfigDialog(); } hostTmpDir = createSubTmpDir(getParentOfTmpDir()); hostOutDir = createSubOutDir(getParentOfOutDir()); prop.setProperty("Application.SavedImagesFolderName", getPixelmedSavedImagesFolder()); try { prop.store(new FileOutputStream(serverConfig), "Updated Application.SavedImagesFolderName"); } catch (FileNotFoundException e1) { System.exit(0); } catch (IOException e1) { System.exit(0); } dicomMgr = DicomManagerFactory.getInstance(); final Properties workstation1Prop = new Properties(); try { workstation1Prop.load(new FileInputStream("./pixelmed-server-hsqldb/workstation1.properties")); } catch (FileNotFoundException e1) { logger.error(e1, e1); System.exit(0); } catch (IOException e1) { logger.error(e1, e1); System.exit(0); } Thread t = new Thread(){ public void run(){ dicomMgr.runDicomStartupSequence("./pixelmed-server-hsqldb/server", workstation1Prop); // Set up default certificates for security. Must be done after starting dicom, but before login. //TODO Move code to the configuration file, read entries from the configuration file, and move files to an XIP location. System.setProperty("javax.net.ssl.keyStore","/MESA/certificates/XIPkeystore.jks"); System.setProperty("javax.net.ssl.keyStorePassword","caBIG2011"); System.setProperty("javax.net.ssl.trustStore","/MESA/runtime/certs-ca-signed/2011_CA_Cert.jks"); System.setProperty("javax.net.ssl.trustStorePassword","connectathon"); System.setProperty("https.ciphersuites","TLS_RSA_WITH_AES_128_CBC_SHA"); //System.setProperty("javax.net.debug","all"); // Set up audit configuration. Must be done before login. // TODO Get URI and possibly other parameters from the config file IHEAuditor.getAuditor().getConfig().setAuditorEnabled(false); if (auditRepositoryURL != ""){ try { IHEAuditor.getAuditor().getConfig().setAuditRepositoryUri(new URI(auditRepositoryURL)); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("URI to auditor improperly formed"); } IHEAuditor.getAuditor().getConfig().setAuditSourceId(aeTitle); IHEAuditor.getAuditor().getConfig().setAuditorEnabled(true); // TODO figure out what should go here, or get from configuration IHEAuditor.getAuditor().getConfig().setAuditEnterpriseSiteId("IHE ERL"); IHEAuditor.getAuditor().getConfig().setHumanRequestor("ltarbox"); IHEAuditor.getAuditor().getConfig().setSystemUserId(userName); IHEAuditor.getAuditor().getConfig().setSystemUserName("Wash. Univ."); } } }; t.start(); LoginDialog loginDialog = new LoginDialog(); loginDialog.setLogin(login); loginDialog.setModal(true); loginDialog.setVisible(true); userName = login.getUserName(); //run GridManagerImpl startup gridMgr = GridManagerFactory.getInstance(); gridMgr.runGridStartupSequence(); //test for gridMgr == null gridMgr.setImportDirectory(hostTmpDir); //run XDSManager startup xdsMgr = XDSManagerFactory.getInstance(); xdsMgr.runStartupSequence(); //run WorkList startup Worklist worklist = WorklistFactory.getInstance(); String path = "./config/worklist.xml"; File xmlWorklistFile = new File(path); worklist.loadWorklist(xmlWorklistFile); appMgr = ApplicationManagerFactory.getInstance(); appMgr.addApplicationTerminationListener(applicationTerminationListener); xipApplicationsConfig = new File("./config/applications.xml"); try { appMgr.loadApplications(xipApplicationsConfig); //Load test applications, RECIST is currently supported on Windows only boolean loadTestApps = false; if(loadTestApps){ loadTestApplications(); } } catch (JDOMException e) { new ExceptionDialog("Unable to load applications.", "Ensure applications xml config file exists and is valid.", "Host Startup Dialog"); System.exit(0); } catch (IOException e) { new ExceptionDialog("Unable to load applications.", "Ensure applications xml config file exists and is valid.", "Host Startup Dialog"); System.exit(0); } //hostOutDir and hostTmpDir are hold in static variables in ApplicationManager appMgr.setOutputDir(hostOutDir); appMgr.setTmpDir(hostTmpDir); //XindiceManager is used to register XMLDB database used to store and manage //XML Native Models XindiceManager xm = XindiceManagerFactory.getInstance(); try { xm.startup(); } catch (XMLDBException e) { //TODO Auto-generated catch block //Q: what to do if Xindice is not launched //1. Go with no native model support or //2. prompt user and exit e.printStackTrace(); } mainWindow = new HostMainWindow(); mainWindow.setUserName(userName); mainWindow.display(); return true; } SAXBuilder builder = new SAXBuilder(); Document document; Element root; String parentOfTmpDir; String parentOfOutDir; Boolean displayStartup; String aeTitle; String dicomStoragePort; String dicomStorageSecurePort; String dicomCommitPort; String dicomCommitSecurePort; String pdqSendFacilityOID; String pdqSendApplicationOID; String auditRepositoryURL; /** * (non-Javadoc) * @see edu.wustl.xipHost.hostControl.HostManager#loadHostConfigParameters() */ public boolean loadHostConfigParameters (File hostConfigFile) { if(hostConfigFile == null){ return false; }else if(!hostConfigFile.exists()){ return false; }else{ try{ document = builder.build(hostConfigFile); root = document.getRootElement(); //path for the parent of TMP directory if(root.getChild("tmpDir") == null){ parentOfTmpDir = ""; }else if(root.getChild("tmpDir").getValue().trim().isEmpty() || new File(root.getChild("tmpDir").getValue()).exists() == false){ parentOfTmpDir = ""; }else{ parentOfTmpDir = root.getChild("tmpDir").getValue(); } if(root.getChild("outputDir") == null){ parentOfOutDir = ""; }else if(root.getChild("outputDir").getValue().trim().isEmpty() || new File(root.getChild("outputDir").getValue()).exists() == false){ parentOfOutDir = ""; }else{ //path for the parent of output directory. //parentOfOutDir used to store data produced by the xip application parentOfOutDir = root.getChild("outputDir").getValue(); } if(root.getChild("displayStartup") == null){ displayStartup = new Boolean(true); }else{ if(root.getChild("displayStartup").getValue().equalsIgnoreCase("true") || root.getChild("displayStartup").getValue().trim().isEmpty() || parentOfTmpDir.isEmpty() || parentOfOutDir.isEmpty() || parentOfTmpDir.equalsIgnoreCase(parentOfOutDir)){ if(parentOfTmpDir.equalsIgnoreCase(parentOfOutDir)){ parentOfTmpDir = ""; parentOfOutDir = ""; } displayStartup = new Boolean(true); }else if (root.getChild("displayStartup").getValue().equalsIgnoreCase("false")){ displayStartup = new Boolean(false); }else{ displayStartup = new Boolean(true); } } if(root.getChild("AETitle") == null){ aeTitle = ""; }else if(root.getChild("AETitle").getValue().trim().isEmpty()){ aeTitle = ""; }else{ aeTitle = root.getChild("AETitle").getValue(); } if(root.getChild("DicomStoragePort") == null){ dicomStoragePort = ""; }else if(root.getChild("DicomStoragePort").getValue().trim().isEmpty()){ dicomStoragePort = ""; }else{ dicomStoragePort = root.getChild("DicomStoragePort").getValue(); } if(root.getChild("DicomStorageSecurePort") == null){ dicomStorageSecurePort = ""; }else if(root.getChild("DicomStorageSecurePort").getValue().trim().isEmpty()){ dicomStorageSecurePort = ""; }else{ dicomStorageSecurePort = root.getChild("DicomStorageSecurePort").getValue(); } if(root.getChild("DicomCommitPort") == null){ dicomCommitPort = ""; }else if(root.getChild("DicomCommitPort").getValue().trim().isEmpty()){ dicomCommitPort = ""; }else{ dicomCommitPort = root.getChild("DicomCommitPort").getValue(); } if(root.getChild("DicomCommitSecurePort") == null){ dicomCommitSecurePort = ""; }else if(root.getChild("DicomCommitSecurePort").getValue().trim().isEmpty()){ dicomCommitSecurePort = ""; }else{ dicomCommitSecurePort = root.getChild("DicomCommitSecurePort").getValue(); } if(root.getChild("AuditRepositoryURL") == null){ auditRepositoryURL = ""; }else if(root.getChild("AuditRepositoryURL").getValue().trim().isEmpty()){ auditRepositoryURL = ""; }else{ auditRepositoryURL = root.getChild("AuditRepositoryURL").getValue(); } if(root.getChild("PdqSendFacilityOID") == null){ pdqSendFacilityOID = ""; }else if(root.getChild("PdqSendFacilityOID").getValue().trim().isEmpty()){ pdqSendFacilityOID = ""; }else{ pdqSendFacilityOID = root.getChild("PdqSendFacilityOID").getValue(); } if(root.getChild("PdqSendApplicationOID") == null){ pdqSendApplicationOID = ""; }else if(root.getChild("PdqSendApplicationOID").getValue().trim().isEmpty()){ pdqSendApplicationOID = ""; }else{ pdqSendApplicationOID = root.getChild("PdqSendApplicationOID").getValue(); } } catch (JDOMException e) { return false; } catch (IOException e) { return false; } } return true; } File serverConfig = new File("./pixelmed-server-hsqldb/workstation1.properties"); Properties prop = new Properties(); String pixelmedSavedImagesFolder; boolean loadPixelmedSavedImagesFolder(File serverConfig){ if(serverConfig == null){return false;} try { prop.load(new FileInputStream(serverConfig)); pixelmedSavedImagesFolder = prop.getProperty("Application.SavedImagesFolderName"); if(new File(pixelmedSavedImagesFolder).exists() == false){ pixelmedSavedImagesFolder = ""; displayStartup = new Boolean(true); } } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } return true; } public String getParentOfOutDir(){ return parentOfOutDir; } public void setParentOfOutDir(String newDir){ parentOfOutDir = newDir; } public String getParentOfTmpDir(){ return parentOfTmpDir; } public File getHostTmpDir(){ return hostTmpDir; } public void setParentOfTmpDir(String newDir){ parentOfTmpDir = newDir; } public String getPixelmedSavedImagesFolder(){ return pixelmedSavedImagesFolder; } public void setPixelmedSavedImagesFolder(String pixelmedDir){ pixelmedSavedImagesFolder = pixelmedDir; } public Boolean getDisplayStartUp(){ return displayStartup; } public void setDisplayStartUp(Boolean display){ displayStartup = display; } public String getUser(){ return userName; } public String getAETitle(){ return aeTitle; } public String getDicomStoragePort(){ return dicomStoragePort; } public void setDicomStoragePort(String dicomStoragePortIn){ dicomStoragePort = dicomStoragePortIn; } public String getDicomStorageSecurePort(){ return dicomStorageSecurePort; } public void setDicomStorageSecurePort(String dicomStorageSecurePortIn){ dicomStorageSecurePort = dicomStorageSecurePortIn; } public String getDicomCommitPort(){ return dicomCommitPort; } public void setDicomCommitPort(String dicomCommitPortIn){ dicomCommitPort = dicomCommitPortIn; } public String getDicomCommitSecurePort(){ return dicomCommitSecurePort; } public void setDicomCommitSecurePort(String dicomCommitSecurePortIn){ dicomCommitSecurePort = dicomCommitSecurePortIn; } public String getAuditRepositoryURL(){ return auditRepositoryURL; } public void setAuditRepositoryURL(String auditRepositoryURLIn){ auditRepositoryURL = auditRepositoryURLIn; } public String getPDQSendFacilityOID(){ return pdqSendFacilityOID; } public void setPDQSendFacilityOIDL(String pdqSendFacilityOIDIn){ pdqSendFacilityOID = pdqSendFacilityOIDIn; } public String getpdqSendApplicationOID(){ return pdqSendApplicationOID; } public void setpdqSendApplicationOID(String pdqSendApplicationOIDIn){ pdqSendApplicationOID = pdqSendApplicationOIDIn; } /** * method creates subdirectory under parent of tmp directory. * Creating sub directory is meant to prevent situations when tmp dirs * would be created directly on system main dir path e.g. C:\ * @return */ File createSubTmpDir(String parentOfTmpDir){ if(parentOfTmpDir == null || parentOfTmpDir.trim().isEmpty()){return null;} try { File tmpFile = Util.create("TmpXIP", ".tmp", new File(parentOfTmpDir)); tmpFile.deleteOnExit(); return tmpFile; } catch (IOException e) { return null; } } /** * method creates subdirectory under parent of output directory. * Creating sub directory is meant to prevent situations when output dirs * would be created directly on system main dir path e.g. C:\ * @return */ File createSubOutDir(String parentOfOutDir){ if(parentOfOutDir == null || parentOfOutDir.trim().isEmpty()){return null;} if(new File(parentOfOutDir).exists() == false){return null;} File outFile = new File(parentOfOutDir, "OutputXIP"); if(!outFile.exists()){ outFile.mkdir(); } return outFile; } void displayConfigDialog(){ configPanel.setParentOfTmpDir(getParentOfTmpDir()); configPanel.setParentOfOutDir(getParentOfOutDir()); configPanel.setPixelmedSavedImagesDir(getPixelmedSavedImagesFolder()); configPanel.setDisplayStartup(getDisplayStartUp()); configPanel.display(); setParentOfTmpDir(configPanel.getParentOfTmpDir()); setParentOfOutDir(configPanel.getParentOfOutDir()); setPixelmedSavedImagesFolder(configPanel.getPixelmedSavedImagesDir()); setDisplayStartUp(configPanel.getDisplayStartup()); } public void storeHostConfigParameters(File hostConfigFile) { root.getChild("tmpDir").setText(parentOfTmpDir); root.getChild("outputDir").setText(parentOfOutDir); root.getChild("displayStartup").setText(displayStartup.toString()); try { FileOutputStream outStream = new FileOutputStream(hostConfigFile); XMLOutputter outToXMLFile = new XMLOutputter(); outToXMLFile.output(document, outStream); outStream.flush(); outStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } List<URL []> EPRs = new ArrayList<URL []>(); int numOfDeplayedServices = 0; Endpoint ep; static HostConfigurator hostConfigurator; public static void main (String [] args){ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Turn off commons loggin for better performance System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog"); DOMConfigurator.configure("log4j.xml"); hostConfigurator = new HostConfigurator(); boolean startupOK = hostConfigurator.runHostStartupSequence(); if(startupOK == false){ logger.fatal("XIPHost startup error. System exits."); System.exit(0); } /*final long MEGABYTE = 1024L * 1024L; System.out.println("Total heap size: " + (Runtime.getRuntime().maxMemory())/MEGABYTE); System.out.println("Used heap size: " + (Runtime.getRuntime().totalMemory())/MEGABYTE); System.out.println("Free heap size: " + (Runtime.getRuntime().freeMemory())/MEGABYTE);*/ } public static HostConfigurator getHostConfigurator(){ return hostConfigurator; } public HostMainWindow getMainWindow(){ return mainWindow; } List<Application> activeApplications = new ArrayList<Application>(); public void runHostShutdownSequence(){ //TODO //Modify runHostShutdownSequence. Hosted application tabs are not removed, host terminates first, or could terminate first before hosted applications have a chance to terminate first //Host can terminate only if no applications are running (verify applications are not running) List<Application> applications = appMgr.getApplications(); synchronized(activeApplications){ for(Application app : applications){ State state = app.getState(); if(state != null && state.equals(State.EXIT) == false ){ activeApplications.add(app); app.shutDown(); } } while(activeApplications.size() != 0){ try { activeApplications.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } logger.info("Shutting down XIP Host."); //Store Host configuration parameters storeHostConfigParameters(hostConfig); List<Application> notValidApplications = appMgr.getNotValidApplications(); List<Application> appsToStore = new ArrayList<Application>(); appsToStore.addAll(applications); appsToStore.addAll(notValidApplications); //Store Applications appMgr.storeApplications(appsToStore, xipApplicationsConfig); //Perform Grid shutdown that includes store grid locations if(gridMgr.runGridShutDownSequence() == false){ new ExceptionDialog("Error when storing grid locations.", "System will save any modifications made to grid locations.", "Host Shutdown Dialog"); } //Clear content of TmpDir but do not delete TmpDir itself File dir = new File(getParentOfTmpDir()); boolean bln = Util.deleteHostTmpFiles(dir); if(bln == false){ new ExceptionDialog("Not all content of Host TMP directory " + hostTmpDir + " was cleared.", "Only subdirs starting with 'TmpXIP' and ending with '.tmp' and their content is deleted.", "Host Shutdown Dialog"); } XindiceManagerFactory.getInstance().shutdown(); //Clear Xindice directory. Ensures all documents and collections are cleared even when application //does not terminate properly Util.delete(new File("./db")); //Run DICOM shutdown sequence //dicomMgr.runDicomShutDownSequence("jdbc:hsqldb:./pixelmed-server-hsqldb/hsqldb/data/ws1db", "sa", ""); logger.info("XIPHost exits. Thank you for using XIP Host."); /*ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); while (root.getParent() != null) { root = root.getParent(); }*/ // Visit each thread group System.exit(0); } @Override public void applicationTerminated(ApplicationTerminationEvent event) { Application application = (Application)event.getSource(); synchronized(activeApplications){ activeApplications.remove(application); activeApplications.notify(); } } public ApplicationTerminationListener getApplicationTerminationListener(){ return applicationTerminationListener; } void loadTestApplications(){ if(OS.contains("Windows")){ if(appMgr.getApplication("TestApp_WG23FileAccess") == null){ try { String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPApplication_WashU_3.bat").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23FileAccess", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "files", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("TestApp_WG23NativeModel") == null){ try{ String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPAppNativeModel.bat").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23NativeModel", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "native", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("RECIST_Adjudicator") == null){ try { String pathExe = new File("../XIPApp/bin/RECISTFollowUpAdjudicator.bat").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("RECIST_Adjudicator", pathExe, "", "", iconFile.getAbsolutePath(), "rendering", true, "files", 1, IterationTarget.SERIES)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }else{ if(appMgr.getApplication("TestApp_WG23FileAccess") == null){ try { String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPApplication_WashU_3.sh").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23FileAccess", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "files", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("TestApp_WG23NativeModel") == null){ try{ String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPAppNativeModel.sh").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23NativeModel", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "native", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static int adjustForResolution(){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //logger.debug("Sceen size: Width " + screenSize.getWidth() + ", Height " + screenSize.getHeight()); int height = (int)screenSize.getHeight(); int preferredHeight = 600; if (height < 768 && height >= 600 ){ preferredHeight = 350; }else if(height < 1024 && height >= 768 ){ preferredHeight = 470; }else if (height >= 1024 && height < 1200){ preferredHeight = 600 - 100; }else if(height > 1200 && height <= 1440){ preferredHeight = 800; } return preferredHeight; } }
package org.altbeacon.bluetooth; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.app.job.JobScheduler; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.bluetooth.le.AdvertiseCallback; import android.bluetooth.le.AdvertiseData; import android.bluetooth.le.AdvertiseSettings; import android.bluetooth.le.BluetoothLeAdvertiser; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanResult; import android.bluetooth.le.AdvertiseSettings.Builder; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Handler; import android.os.PersistableBundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import java.util.List; import org.altbeacon.beacon.logging.LogManager; /** * * Utility class for checking the health of the bluetooth stack on the device by running two kinds * of tests: scanning and transmitting. The class looks for specific failure codes from these * tests to determine if the bluetooth stack is in a bad state and if so, optionally cycle power to * bluetooth to try and fix the problem. This is known to work well on some Android devices. * * The tests may be called directly, or set up to run automatically approximately every 15 minutes. * To set up in an automated way: * * <code> * BluetoothMedic medic = BluetoothMedic.getInstance(); * medic.enablePowerCycleOnFailures(context); * medic.enablePeriodicTests(context, BluetoothMedic.SCAN_TEST | BluetoothMedic.TRANSMIT_TEST); * </code> * * To set up in a manual way: * * <code> * BluetoothMedic medic = BluetoothMedic.getInstance(); * medic.enablePowerCycleOnFailures(context); * if (!medic.runScanTest(context)) { * // Bluetooth stack is in a bad state * } * if (!medic.runTransmitterTest(context)) { * // Bluetooth stack is in a bad state * } * */ @SuppressWarnings("javadoc") public class BluetoothMedic { /** * Indicates that no test should be run by the BluetoothTestJob */ @SuppressWarnings("WeakerAccess") public static final int NO_TEST = 0; /** * Indicates that the transmitter test should be run by the BluetoothTestJob */ @SuppressWarnings("WeakerAccess") public static final int TRANSMIT_TEST = 2; /** * Indicates that the bluetooth scan test should be run by the BluetoothTestJob */ @SuppressWarnings("WeakerAccess") public static final int SCAN_TEST = 1; private static final String TAG = BluetoothMedic.class.getSimpleName(); @Nullable private BluetoothAdapter mAdapter; @Nullable private LocalBroadcastManager mLocalBroadcastManager; @NonNull private Handler mHandler = new Handler(); private int mTestType = 0; @Nullable private Boolean mTransmitterTestResult = null; @Nullable private Boolean mScanTestResult = null; private boolean mNotificationsEnabled = false; private boolean mNotificationChannelCreated = false; private int mNotificationIcon = 0; private long mLastBluetoothPowerCycleTime = 0L; private static final long MIN_MILLIS_BETWEEN_BLUETOOTH_POWER_CYCLES = 60000L; @Nullable private static BluetoothMedic sInstance; @RequiresApi(21) private BroadcastReceiver mBluetoothEventReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogManager.d(BluetoothMedic.TAG, "Broadcast notification received."); int errorCode; String action = intent.getAction(); if (action != null) { if(action.equalsIgnoreCase("onScanFailed")) { errorCode = intent.getIntExtra("errorCode", -1); if(errorCode == 2) { BluetoothMedic.this.sendNotification(context, "scan failed", "Power cycling bluetooth"); LogManager.d(BluetoothMedic.TAG, "Detected a SCAN_FAILED_APPLICATION_REGISTRATION_FAILED. We need to cycle bluetooth to recover"); if(!BluetoothMedic.this.cycleBluetoothIfNotTooSoon()) { BluetoothMedic.this.sendNotification(context, "scan failed", "" + "Cannot power cycle bluetooth again"); } } } else if(action.equalsIgnoreCase("onStartFailed")) { errorCode = intent.getIntExtra("errorCode", -1); if(errorCode == 4) { BluetoothMedic.this.sendNotification(context, "advertising failed", "Expected failure. Power cycling."); if(!BluetoothMedic.this.cycleBluetoothIfNotTooSoon()) { BluetoothMedic.this.sendNotification(context, "advertising failed", "Cannot power cycle bluetooth again"); } } } else { LogManager.d(BluetoothMedic.TAG, "Unknown event."); } } } }; /** * Get a singleton instance of the BluetoothMedic * @return */ public static BluetoothMedic getInstance() { if(sInstance == null) { sInstance = new BluetoothMedic(); } return sInstance; } private BluetoothMedic() { } @RequiresApi(21) private void initializeWithContext(Context context) { if (this.mAdapter == null || this.mLocalBroadcastManager == null) { BluetoothManager manager = (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE); if(manager == null) { throw new NullPointerException("Cannot get BluetoothManager"); } else { this.mAdapter = manager.getAdapter(); this.mLocalBroadcastManager = LocalBroadcastManager.getInstance(context); } } } /** * If set to true, bluetooth will be power cycled on any tests run that determine bluetooth is * in a bad state. * * @param context */ @SuppressWarnings("unused") @RequiresApi(21) public void enablePowerCycleOnFailures(Context context) { initializeWithContext(context); if (this.mLocalBroadcastManager != null) { this.mLocalBroadcastManager.registerReceiver(this.mBluetoothEventReceiver, new IntentFilter("onScanFailed")); this.mLocalBroadcastManager.registerReceiver(this.mBluetoothEventReceiver, new IntentFilter("onStartFailure")); LogManager.d(TAG, "Medic monitoring for transmission and scan failure notifications with receiver: " + this.mBluetoothEventReceiver); } } /** * Calling this method starts a scheduled job that will run tests of the specified type to * make sure bluetooth is OK and cycle power to bluetooth if needed and configured by * enablePowerCycleOnFailures * * @param context * @param testType e.g. BluetoothMedic.TRANSMIT_TEST | BluetoothMedic.SCAN_TEST */ @SuppressWarnings("unused") @RequiresApi(21) public void enablePeriodicTests(Context context, int testType) { initializeWithContext(context); this.mTestType = testType; LogManager.d(TAG, "Medic scheduling periodic tests of types " + testType); this.scheduleRegularTests(context); } /** * Starts up a brief blueooth scan with the intent of seeing if it results in an error condition * indicating the bluetooth stack may be in a bad state. * * If the failure error code matches a pattern known to be associated with a bad bluetooth stack * state, then the bluetooth stack is turned off and then back on after a short delay in order * to try to recover. * * @return false if the test indicates a failure indicating a bad state of the bluetooth stack */ @SuppressWarnings({"unused","WeakerAccess"}) @RequiresApi(21) public boolean runScanTest(final Context context) { initializeWithContext(context); this.mScanTestResult = null; LogManager.i(TAG, "Starting scan test"); final long testStartTime = System.currentTimeMillis(); if (this.mAdapter != null) { final BluetoothLeScanner scanner = this.mAdapter.getBluetoothLeScanner(); final ScanCallback callback = new ScanCallback() { public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); BluetoothMedic.this.mScanTestResult = true; LogManager.i(BluetoothMedic.TAG, "Scan test succeeded"); try { scanner.stopScan(this); } catch (IllegalStateException e) { /* do nothing */ } // caught if bluetooth is off here } public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); } public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); LogManager.d(BluetoothMedic.TAG, "Sending onScanFailed broadcast with " + BluetoothMedic.this.mLocalBroadcastManager); Intent intent = new Intent("onScanFailed"); intent.putExtra("errorCode", errorCode); if (BluetoothMedic.this.mLocalBroadcastManager != null) { BluetoothMedic.this.mLocalBroadcastManager.sendBroadcast(intent); } LogManager.d(BluetoothMedic.TAG, "broadcast: " + intent + " should be received by " + BluetoothMedic.this.mBluetoothEventReceiver); if(errorCode == 2) { LogManager.w(BluetoothMedic.TAG, "Scan test failed in a way we consider a failure"); BluetoothMedic.this.sendNotification(context, "scan failed", "bluetooth not ok"); BluetoothMedic.this.mScanTestResult = false; } else { LogManager.i(BluetoothMedic.TAG, "Scan test failed in a way we do not consider a failure"); BluetoothMedic.this.mScanTestResult = true; } } }; if(scanner != null) { try { scanner.startScan(callback); while (this.mScanTestResult == null) { LogManager.d(TAG, "Waiting for scan test to complete..."); try { Thread.sleep(1000L); } catch (InterruptedException e) { /* do nothing */ } if (System.currentTimeMillis() - testStartTime > 5000L) { LogManager.d(TAG, "Timeout running scan test"); break; } } scanner.stopScan(callback); } catch (IllegalStateException e) { LogManager.d(TAG, "Bluetooth is off. Cannot run scan test."); } catch (NullPointerException e) { // Needed to stop a crash caused by internal NPE thrown by Android. See issue #636 LogManager.e(TAG, "NullPointerException. Cannot run scan test.", e); } } else { LogManager.d(TAG, "Cannot get scanner"); } } LogManager.d(TAG, "scan test complete"); return this.mScanTestResult == null || this.mScanTestResult; } /** * Starts up a beacon transmitter with the intent of seeing if it results in an error condition * indicating the bluetooth stack may be in a bad state. * * If the failure error code matches a pattern known to be associated with a bad bluetooth stack * state, then the bluetooth stack is turned off and then back on after a short delay in order * to try to recover. * * @return false if the test indicates a failure indicating a bad state of the bluetooth stack */ @SuppressWarnings({"unused","WeakerAccess"}) @RequiresApi(21) public boolean runTransmitterTest(final Context context) { initializeWithContext(context); this.mTransmitterTestResult = null; long testStartTime = System.currentTimeMillis(); if (mAdapter != null) { final BluetoothLeAdvertiser advertiser = getAdvertiserSafely(mAdapter); if(advertiser != null) { AdvertiseSettings settings = (new Builder()).setAdvertiseMode(0).build(); AdvertiseData data = (new android.bluetooth.le.AdvertiseData.Builder()) .addManufacturerData(0, new byte[]{0}).build(); LogManager.i(TAG, "Starting transmitter test"); advertiser.startAdvertising(settings, data, new AdvertiseCallback() { public void onStartSuccess(AdvertiseSettings settingsInEffect) { super.onStartSuccess(settingsInEffect); LogManager.i(BluetoothMedic.TAG, "Transmitter test succeeded"); advertiser.stopAdvertising(this); BluetoothMedic.this.mTransmitterTestResult = true; } public void onStartFailure(int errorCode) { super.onStartFailure(errorCode); Intent intent = new Intent("onStartFailed"); intent.putExtra("errorCode", errorCode); LogManager.d(BluetoothMedic.TAG, "Sending onStartFailure broadcast with " + BluetoothMedic.this.mLocalBroadcastManager); if (BluetoothMedic.this.mLocalBroadcastManager != null) { BluetoothMedic.this.mLocalBroadcastManager.sendBroadcast(intent); } if(errorCode == 4) { BluetoothMedic.this.mTransmitterTestResult = false; LogManager.w(BluetoothMedic.TAG, "Transmitter test failed in a way we consider a test failure"); BluetoothMedic.this.sendNotification(context, "transmitter failed", "bluetooth not ok"); } else { BluetoothMedic.this.mTransmitterTestResult = true; LogManager.i(BluetoothMedic.TAG, "Transmitter test failed, but not in a way we consider a test failure"); } } }); } else { LogManager.d(TAG, "Cannot get advertiser"); } while(this.mTransmitterTestResult == null) { LogManager.d(TAG, "Waiting for transmitter test to complete..."); try { Thread.sleep(1000L); } catch (InterruptedException e) { /* do nothing */ } if(System.currentTimeMillis() - testStartTime > 5000L) { LogManager.d(TAG, "Timeout running transmitter test"); break; } } } LogManager.d(TAG, "transmitter test complete"); return this.mTransmitterTestResult != null && this.mTransmitterTestResult; } /** * * Configure whether to send user-visible notification warnings when bluetooth power is cycled. * * @param enabled if true, a user-visible notification is sent to tell the user when * @param icon the icon drawable to use in notifications (e.g. R.drawable.notification_icon) */ @SuppressWarnings("unused") @RequiresApi(21) public void setNotificationsEnabled(boolean enabled, int icon) { this.mNotificationsEnabled = enabled; this.mNotificationIcon = icon; } @RequiresApi(21) private boolean cycleBluetoothIfNotTooSoon() { long millisSinceLastCycle = System.currentTimeMillis() - this.mLastBluetoothPowerCycleTime; if(millisSinceLastCycle < MIN_MILLIS_BETWEEN_BLUETOOTH_POWER_CYCLES) { LogManager.d(TAG, "Not cycling bluetooth because we just did so " + millisSinceLastCycle + " milliseconds ago."); return false; } else { this.mLastBluetoothPowerCycleTime = System.currentTimeMillis(); LogManager.d(TAG, "Power cycling bluetooth"); this.cycleBluetooth(); return true; } } @RequiresApi(21) private void cycleBluetooth() { LogManager.d(TAG, "Power cycling bluetooth"); LogManager.d(TAG, "Turning Bluetooth off."); if (mAdapter != null) { this.mAdapter.disable(); this.mHandler.postDelayed(new Runnable() { public void run() { LogManager.d(BluetoothMedic.TAG, "Turning Bluetooth back on."); if (BluetoothMedic.this.mAdapter != null) { BluetoothMedic.this.mAdapter.enable(); } } }, 1000L); } else { LogManager.w(TAG, "Cannot cycle bluetooth. Manager is null."); } } @RequiresApi(21) private void sendNotification(Context context, String message, String detail) { initializeWithContext(context); if(this.mNotificationsEnabled) { if (!this.mNotificationChannelCreated) { createNotificationChannel(context, "err"); } NotificationCompat.Builder builder = (new NotificationCompat.Builder(context, "err")) .setContentTitle("BluetoothMedic: " + message) .setSmallIcon(mNotificationIcon) .setVibrate(new long[]{200L, 100L, 200L}).setContentText(detail); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addNextIntent(new Intent("NoOperation")); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); builder.setContentIntent(resultPendingIntent); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) { notificationManager.notify(1, builder.build()); } } } @RequiresApi(21) private void createNotificationChannel(Context context, String channelId) { // On Android 8.0 and above posting a notification without a // channel is an error. So create a notification channel 'err' if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelName = "Errors"; String description = "Scan errors"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(channelId, channelName, importance); channel.setDescription(description); NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); mNotificationChannelCreated = true; } } @RequiresApi(21) private void scheduleRegularTests(Context context) { initializeWithContext(context); ComponentName serviceComponent = new ComponentName(context, BluetoothTestJob.class); android.app.job.JobInfo.Builder builder = new android.app.job.JobInfo.Builder(BluetoothTestJob.getJobId(context), serviceComponent); builder.setRequiresCharging(false); builder.setRequiresDeviceIdle(false); builder.setPeriodic(900000L); // 900 secs is 15 minutes -- the minimum time on Android builder.setPersisted(true); PersistableBundle bundle = new PersistableBundle(); bundle.putInt("test_type", this.mTestType); builder.setExtras(bundle); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); if (jobScheduler != null) { jobScheduler.schedule(builder.build()); } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private BluetoothLeAdvertiser getAdvertiserSafely(BluetoothAdapter adapter) { try { // This can sometimes throw a NullPointerException as reported here: return adapter.getBluetoothLeAdvertiser(); } catch (Exception e) { LogManager.w(TAG, "Cannot get bluetoothLeAdvertiser", e); } return null; } }
package com.kennyc.bottomsheet; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.LightingColorFilter; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.MenuRes; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.annotation.StyleRes; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; 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.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class BottomSheet extends Dialog implements AdapterView.OnItemClickListener, CollapsingView.CollapseListener { private static final int NO_RESOURCE = -1; private static final String TAG = BottomSheet.class.getSimpleName(); private static final int[] ATTRS = new int[]{ R.attr.bottom_sheet_bg_color, R.attr.bottom_sheet_title_color, R.attr.bottom_sheet_list_item_color, R.attr.bottom_sheet_grid_item_color, R.attr.bottom_sheet_item_icon_color }; private Builder mBuilder; private BaseAdapter mAdapter; private GridView mGrid; private TextView mTitle; private BottomSheetListener mListener; /** * Default constructor. It is recommended to use the {@link com.kennyc.bottomsheet.BottomSheet.Builder} for creating a BottomSheet * * @param context App context * @param builder {@link com.kennyc.bottomsheet.BottomSheet.Builder} with supplied options for the dialog * @param style Style resource for the dialog * @param listener The optional {@link BottomSheetListener} for callbacks */ BottomSheet(Context context, Builder builder, @StyleRes int style, BottomSheetListener listener) { super(context, style); mBuilder = builder; mListener = listener; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!canCreateSheet()) { throw new IllegalStateException("Unable to create BottomSheet, missing params"); } Window window = getWindow(); if (window != null) { int width = getContext().getResources().getDimensionPixelSize(R.dimen.bottom_sheet_width); window.setLayout(width <= 0 || mBuilder.isGrid ? ViewGroup.LayoutParams.MATCH_PARENT : width, ViewGroup.LayoutParams.WRAP_CONTENT); window.setGravity(Gravity.BOTTOM); } else { Log.e(TAG, "Window came back as null, unable to set defaults"); } TypedArray ta = getContext().obtainStyledAttributes(ATTRS); initLayout(ta); if (mBuilder.menuItems != null) { initMenu(ta); if (mListener != null) mListener.onSheetShown(); } else { mGrid.setAdapter(mAdapter = new AppAdapter(getContext(), mBuilder)); } ta.recycle(); } @Override public void dismiss() { if (mListener != null) mListener.onSheetDismissed(); super.dismiss(); } private void initLayout(TypedArray ta) { Resources res = getContext().getResources(); setCancelable(mBuilder.cancelable); View view = LayoutInflater.from(getContext()).inflate(R.layout.bottom_sheet_layout, null); ((CollapsingView) view).setCollapseListener(this); if (mBuilder.backgroundColor != Integer.MIN_VALUE) { view.findViewById(R.id.container).setBackgroundColor(mBuilder.backgroundColor); } else { view.findViewById(R.id.container).setBackgroundColor(ta.getColor(0, Color.WHITE)); } mGrid = (GridView) view.findViewById(R.id.grid); mGrid.setOnItemClickListener(this); mTitle = (TextView) view.findViewById(R.id.title); boolean hasTitle = !TextUtils.isEmpty(mBuilder.title); if (hasTitle) { mTitle.setText(mBuilder.title); mTitle.setVisibility(View.VISIBLE); if (mBuilder.titleColor != Integer.MIN_VALUE) { mTitle.setTextColor(mBuilder.titleColor); } else { mTitle.setTextColor(ta.getColor(1, res.getColor(R.color.black_55))); } } else { mTitle.setVisibility(View.GONE); } if (mBuilder.isGrid) { int gridPadding = res.getDimensionPixelSize(R.dimen.bottom_sheet_grid_padding); int topPadding = res.getDimensionPixelSize(R.dimen.bottom_sheet_dialog_padding); mGrid.setNumColumns(res.getInteger(R.integer.bottomsheet_num_columns)); mGrid.setVerticalSpacing(res.getDimensionPixelSize(R.dimen.bottom_sheet_grid_spacing)); mGrid.setPadding(0, topPadding, 0, gridPadding); } else { int padding = res.getDimensionPixelSize(R.dimen.bottom_sheet_list_padding); mGrid.setPadding(0, hasTitle ? 0 : padding, 0, padding); } setContentView(view); } private void initMenu(TypedArray ta) { Resources res = getContext().getResources(); int listColor; int gridColor; if (mBuilder.itemColor != Integer.MIN_VALUE) { listColor = mBuilder.itemColor; gridColor = mBuilder.itemColor; } else { listColor = ta.getColor(2, res.getColor(R.color.black_85)); gridColor = ta.getColor(3, res.getColor(R.color.black_85)); } if (mBuilder.menuItemTintColor == Integer.MIN_VALUE) { mBuilder.menuItemTintColor = ta.getColor(4, Integer.MIN_VALUE); } mGrid.setAdapter(mAdapter = new GridAdapter(getContext(), mBuilder, listColor, gridColor)); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mAdapter instanceof GridAdapter) { if (mListener != null) { MenuItem item = ((GridAdapter) mAdapter).getItem(position); mListener.onSheetItemSelected(item); } } else if (mAdapter instanceof AppAdapter) { AppAdapter.AppInfo info = ((AppAdapter) mAdapter).getItem(position); Intent intent = new Intent(mBuilder.shareIntent); intent.setComponent(new ComponentName(info.packageName, info.name)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(intent); } dismiss(); } /** * Returns if the {@link BottomSheet} can be created based on the {@link com.kennyc.bottomsheet.BottomSheet.Builder} * * @return */ private boolean canCreateSheet() { return mBuilder != null && ((mBuilder.menuItems != null && !mBuilder.menuItems.isEmpty()) || (mBuilder.apps != null && !mBuilder.apps.isEmpty())); } @Override public void onCollapse() { // Post a runnable for dismissing to avoid "Attempting to destroy the window while drawing!" error mGrid.post(new Runnable() { @Override public void run() { dismiss(); } }); } * intent.setType("text/*");<br> * intent.putExtra(Intent.EXTRA_TEXT, "Some text to share");<br> * BottomSheet bottomSheet = BottomSheet.createShareBottomSheet(this, intent, "Share");<br> * if (bottomSheet != null) bottomSheet.show();<br> * * @param context App context * @param intent Intent to get apps for * @param shareTitle The optional title for the share intent * @param isGrid If the share intent BottomSheet should be grid styled * @return A {@link BottomSheet} with the apps that can handle the share intent. NULL maybe returned if no * apps can handle the share intent */ @Nullable public static BottomSheet createShareBottomSheet(Context context, Intent intent, String shareTitle, boolean isGrid) { if (context == null || intent == null) return null; PackageManager manager = context.getPackageManager(); List<ResolveInfo> apps = manager.queryIntentActivities(intent, 0); if (apps != null && !apps.isEmpty()) { List<AppAdapter.AppInfo> appResources = new ArrayList<>(apps.size()); for (ResolveInfo resolveInfo : apps) { String title = resolveInfo.loadLabel(manager).toString(); String packageName = resolveInfo.activityInfo.packageName; String name = resolveInfo.activityInfo.name; Drawable drawable = resolveInfo.loadIcon(manager); appResources.add(new AppAdapter.AppInfo(title, packageName, name, drawable)); } Builder b = new Builder(context) .setApps(appResources, intent) .setTitle(shareTitle); if (isGrid) b.grid(); return b.create(); } return null; } * intent.setType("text/*");<br> * intent.putExtra(Intent.EXTRA_TEXT, "Some text to share");<br> * BottomSheet bottomSheet = BottomSheet.createShareBottomSheet(this, intent, "Share");<br> * if (bottomSheet != null) bottomSheet.show();<br> * * @param context App context * @param intent Intent to get apps for * @param shareTitle The optional title string resource for the share intent * @param isGrid If the share intent BottomSheet should be grid styled * @return A {@link BottomSheet} with the apps that can handle the share intent. NULL maybe returned if no * apps can handle the share intent */ @Nullable public static BottomSheet createShareBottomSheet(Context context, Intent intent, @StringRes int shareTitle, boolean isGrid) { return createShareBottomSheet(context, intent, context.getString(shareTitle), isGrid); } * intent.setType("text/*");<br> * intent.putExtra(Intent.EXTRA_TEXT, "Some text to share");<br> * BottomSheet bottomSheet = BottomSheet.createShareBottomSheet(this, intent, "Share");<br> * if (bottomSheet != null) bottomSheet.show();<br> * * @param context App context * @param intent Intent to get apps for * @param shareTitle The optional title for the share intent * @return A {@link BottomSheet} with the apps that can handle the share intent. NULL maybe returned if no * apps can handle the share intent */ @Nullable public static BottomSheet createShareBottomSheet(Context context, Intent intent, String shareTitle) { return createShareBottomSheet(context, intent, shareTitle, false); } * intent.setType("text/*");<br> * intent.putExtra(Intent.EXTRA_TEXT, "Some text to share");<br> * BottomSheet bottomSheet = BottomSheet.createShareBottomSheet(this, intent, "Share");<br> * if (bottomSheet != null) bottomSheet.show();<br> * * @param context App context * @param intent Intent to get apps for * @param shareTitle The optional title for the share intent * @return A {@link BottomSheet} with the apps that can handle the share intent. NULL maybe returned if no * apps can handle the share intent */ @Nullable public static BottomSheet createShareBottomSheet(Context context, Intent intent, @StringRes int shareTitle) { return createShareBottomSheet(context, intent, context.getString(shareTitle), false); } /** * Builder factory used for creating {@link BottomSheet} */ public static class Builder { @StyleRes int style = NO_RESOURCE; String title = null; boolean cancelable = true; boolean isGrid = false; List<MenuItem> menuItems; @ColorInt int menuItemTintColor = Integer.MIN_VALUE; @ColorInt int titleColor = Integer.MIN_VALUE; @ColorInt int itemColor = Integer.MIN_VALUE; @ColorInt int backgroundColor = Integer.MIN_VALUE; Context context; Resources resources; BottomSheetListener listener; List<AppAdapter.AppInfo> apps; Intent shareIntent; /** * Constructor for creating a {@link BottomSheet}, {@link #setSheet(int)} will need to be called to set the menu resource * * @param context App context */ public Builder(Context context) { this(context, NO_RESOURCE, R.style.BottomSheet); } /** * Constructor for creating a {@link BottomSheet} * * @param context App context * @param sheetItems The menu resource for constructing the sheet */ public Builder(Context context, @MenuRes int sheetItems) { this(context, sheetItems, R.style.BottomSheet); } /** * Constructor for creating a {@link BottomSheet} * * @param context App context * @param sheetItems The menu resource for constructing the sheet * @param style The style for the sheet to use */ public Builder(Context context, @MenuRes int sheetItems, @StyleRes int style) { this.context = context; this.style = style; this.resources = context.getResources(); if (sheetItems != NO_RESOURCE) setSheet(sheetItems); } /** * Sets the title of the {@link BottomSheet} * * @param title String for the title * @return */ public Builder setTitle(String title) { this.title = title; return this; } /** * Sets the title of the {@link BottomSheet} * * @param title String resource for the title * @return */ public Builder setTitle(@StringRes int title) { return setTitle(resources.getString(title)); } /** * Sets the {@link BottomSheet} to use a grid for displaying options. When set, the dialog buttons <b><i>will not</i></b> be shown * * @return */ public Builder grid() { isGrid = true; return this; } /** * Sets whether the {@link BottomSheet} is cancelable with the {@link KeyEvent#KEYCODE_BACK BACK} key. * * @param cancelable * @return */ public Builder setCancelable(boolean cancelable) { this.cancelable = cancelable; return this; } /** * Sets the {@link BottomSheetListener} to receive callbacks * * @param listener * @return */ public Builder setListener(BottomSheetListener listener) { this.listener = listener; return this; } /** * Sets the {@link BottomSheet} to use a dark theme * * @return */ public Builder dark() { style = R.style.BottomSheet_Dark; return this; } /** * Sets the style of the {@link BottomSheet} * * @param style * @return */ public Builder setStyle(@StyleRes int style) { this.style = style; return this; } /** * Sets the menu resource to use for the {@link BottomSheet} * * @param sheetItems * @return */ public Builder setSheet(@MenuRes int sheetItems) { BottomSheetMenu menu = new BottomSheetMenu(context); new MenuInflater(context).inflate(sheetItems, menu); return setMenu(menu); } /** * Sets the menu to use for the {@link BottomSheet} * * @param menu * @return */ public Builder setMenu(@Nullable Menu menu) { if (menu != null) { List<MenuItem> items = new ArrayList<>(menu.size()); for (int i = 0; i < menu.size(); i++) { items.add(menu.getItem(i)); } return setMenuItems(items); } return this; } /** * Sets the {@link List} of menu items to use for the {@link BottomSheet} * * @param menuItems * @return */ public Builder setMenuItems(@Nullable List<MenuItem> menuItems) { this.menuItems = menuItems; return this; } /** * Adds a {@link MenuItem} to the {@link BottomSheet}. For creating a {@link MenuItem}, see {@link BottomSheetMenuItem} * * @param item * @return */ public Builder addMenuItem(MenuItem item) { if (menuItems == null) menuItems = new ArrayList<>(); menuItems.add(item); return this; } /** * Resolves the color resource id and tints the menu item icons with the resolved color * * @param colorRes * @return */ public Builder setMenuItemTintColorRes(@ColorRes int colorRes) { final int menuItemTintColor = resources.getColor(colorRes); return setMenuItemTintColor(menuItemTintColor); } /** * Sets the color to use for tinting the menu item icons * * @param menuItemTintColor * @return */ public Builder setMenuItemTintColor(@ColorInt int menuItemTintColor) { this.menuItemTintColor = menuItemTintColor; return this; } /** * Sets the color to use for the title. Will be ignored if {@link #setTitle(int)} or {@link #setTitle(String)} are not called * * @param titleColor * @return */ public Builder setTitleColor(@ColorInt int titleColor) { this.titleColor = titleColor; return this; } /** * Sets the color resource id to use for the title. Will be ignored if {@link #setTitle(int)} or {@link #setTitle(String)} are not called * * @param colorRes * @return */ public Builder setTitleColorRes(@ColorRes int colorRes) { return setTitleColor(resources.getColor(colorRes)); } /** * Sets the color to use for the list item. Will apply to either list or grid style. * * @param itemColor * @return */ public Builder setItemColor(@ColorInt int itemColor) { this.itemColor = itemColor; return this; } /** * Sets the color resource id to use for the list item. Will apply to either list or grid style. * * @param colorRes * @return */ public Builder setItemColorRes(@ColorRes int colorRes) { return setItemColor(resources.getColor(colorRes)); } /** * Sets the background color * * @param backgroundColor * @return */ public Builder setBackgroundColor(@ColorInt int backgroundColor) { this.backgroundColor = backgroundColor; return this; } /** * Sets the color resource id of the background * * @param backgroundColor * @return */ public Builder setBackgroundColorRes(@ColorRes int backgroundColor) { return setBackgroundColor(resources.getColor(backgroundColor)); } /** * Sets the apps to be used for a share intent. This is not a public facing method.<p> * See {@link BottomSheet#createShareBottomSheet(Context, Intent, String, boolean)} for creating a share intent {@link BottomSheet} * * @param apps List of apps to use in the share intent * @param intent The {@link Intent} used for creating the share intent * @return */ private Builder setApps(List<AppAdapter.AppInfo> apps, Intent intent) { this.apps = apps; shareIntent = intent; return this; } /** * Creates the {@link BottomSheet} but does not show it. * * @return */ public BottomSheet create() { return new BottomSheet(context, this, style, listener); } /** * Creates the {@link BottomSheet} and shows it. */ public void show() { create().show(); } } /** * Adapter used when creating a {@link BottomSheet} through the {@link com.kennyc.bottomsheet.BottomSheet.Builder} interface */ private static class GridAdapter extends BaseAdapter { private final List<MenuItem> mItems; private final LayoutInflater mInflater; private boolean mIsGrid; private int mListTextColor; private int mGridTextColor; private int mTintColor; public GridAdapter(Context context, Builder builder, int listTextColor, int gridTextColor) { mItems = builder.menuItems; mIsGrid = builder.isGrid; mInflater = LayoutInflater.from(context); mListTextColor = listTextColor; mGridTextColor = gridTextColor; mTintColor = builder.menuItemTintColor; } @Override public int getCount() { return mItems.size(); } @Override public MenuItem getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return getItem(position).getItemId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { MenuItem item = getItem(position); ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(mIsGrid ? R.layout.bottom_sheet_grid_item : R.layout.bottom_sheet_list_item, parent, false); holder = new ViewHolder(convertView); holder.title.setTextColor(mIsGrid ? mGridTextColor : mListTextColor); } else { holder = (ViewHolder) convertView.getTag(); } Drawable menuIcon = item.getIcon(); if (mTintColor != Integer.MIN_VALUE && menuIcon != null) { // mutate it, so we do not tint the original menu icon menuIcon = menuIcon.mutate(); menuIcon.setColorFilter(new LightingColorFilter(Color.BLACK, mTintColor)); } holder.icon.setImageDrawable(menuIcon); holder.title.setText(item.getTitle()); return convertView; } } /** * Adapter used when {@link BottomSheet#createShareBottomSheet(Context, Intent, String, boolean)} is invoked */ private static class AppAdapter extends BaseAdapter { List<AppInfo> mApps; private LayoutInflater mInflater; private int mTextColor; private boolean mIsGrid; public AppAdapter(Context context, Builder builder) { mApps = builder.apps; mInflater = LayoutInflater.from(context); mTextColor = context.getResources().getColor(R.color.black_85); mIsGrid = builder.isGrid; } @Override public int getCount() { return mApps.size(); } @Override public AppInfo getItem(int position) { return mApps.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { AppInfo appInfo = getItem(position); ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(mIsGrid ? R.layout.bottom_sheet_grid_item : R.layout.bottom_sheet_list_item, parent, false); holder = new ViewHolder(convertView); holder.title.setTextColor(mTextColor); } else { holder = (ViewHolder) convertView.getTag(); } holder.icon.setImageDrawable(appInfo.drawable); holder.title.setText(appInfo.title); return convertView; } private static class AppInfo { public String title; public String packageName; public String name; public Drawable drawable; public AppInfo(String title, String packageName, String name, Drawable drawable) { this.title = title; this.packageName = packageName; this.name = name; this.drawable = drawable; } } } /** * ViewHolder class for the adapters */ private static class ViewHolder { public TextView title; public ImageView icon; public ViewHolder(View view) { title = (TextView) view.findViewById(R.id.title); icon = (ImageView) view.findViewById(R.id.icon); view.setTag(this); } } }
package com.oasisfeng.condom; import android.app.Application; import android.content.ComponentCallbacks; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.support.annotation.Keep; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.Log; import javax.annotation.CheckReturnValue; import javax.annotation.ParametersAreNonnullByDefault; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.HONEYCOMB_MR1; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2; import static android.os.Build.VERSION_CODES.N; @ParametersAreNonnullByDefault @Keep public class CondomContext extends ContextWrapper { /** * This is the very first (probably only) API you need to wrap the naked {@link Context} under protection of <code>CondomContext</code> * * @param base the original context used before <code>CondomContext</code> is introduced. * @param tag the optional tag to distinguish between multiple instances of <code>CondomContext</code> used parallel. */ public static @CheckReturnValue CondomContext wrap(final Context base, final @Nullable String tag) { if (base instanceof CondomContext) return (CondomContext) base; final Context app_context = base.getApplicationContext(); if (app_context instanceof Application) { // The application context is indeed an Application, this should be preserved semantically. final Application app = (Application) app_context; final CondomApplication condom_app = new CondomApplication(app); final CondomContext condom_context = new CondomContext(base, condom_app, tag); condom_app.attachBaseContext(base == app_context ? condom_context : new CondomContext(app, app, tag)); return condom_context; } else return new CondomContext(base, base == app_context ? null : new CondomContext(app_context, app_context, tag), tag); } enum OutboundType { START_SERVICE, BIND_SERVICE, BROADCAST } interface OutboundJudge { /** * Judge the outbound request by its explicit target package. * * @return whether this outbound request should be allowed. */ boolean judge(OutboundType type, String target_pkg); } /** Set to dry-run mode to inspect the outbound wake-up only, no outbound requests will be actually blocked. */ public CondomContext setDryRun(final boolean dry_run) { if (dry_run == mDryRun) return this; mDryRun = dry_run; if (dry_run) Log.w(TAG, "Start dry-run mode, no outbound requests will be blocked actually, despite stated in log."); else Log.w(TAG, "Stop dry-run mode."); return this; } /** Set a custom judge for the explicit target package of outbound service and broadcast requests. */ public CondomContext setOutboundJudge(final OutboundJudge judge) { mOutboundJudge = judge; return this; } /** * Prevent outbound service request from waking-up force-stopped packages. (default: true, not recommended to change) * * <p>If a package is force-stopped by user, it usually mean that app did not work as expected (most probably due to repeated crashes). * Waking-up those packages usually leads to bad user experience, even the worse, the infamous annoying "APP STOPPED" dialog. */ public CondomContext preventWakingUpStoppedPackages(final boolean prevent_or_not) { mExcludeStoppedPackages = prevent_or_not; return this; } /** * Prevent broadcast to be delivered to manifest receivers in background (cached or not running) apps. (default: true) * * <p>This restriction is supported natively since Android O, and it works similarly by only targeting registered receivers on previous Android versions. */ public CondomContext preventBroadcastToBackgroundPackages(final boolean prevent_or_not) { mExcludeBackgroundPackages = prevent_or_not; return this; } @Override public boolean bindService(final Intent service, final ServiceConnection conn, final int flags) { final int original_flags = adjustIntentFlags(service); if (shouldBlockExplicitRequest(OutboundType.BIND_SERVICE, service)) { if (DEBUG) Log.w(TAG, "Blocked outbound explicit service binding: " + service); if (! mDryRun) return false; } final boolean result = super.bindService(service, conn, flags); service.setFlags(original_flags); return result; } @Override public ComponentName startService(final Intent service) { final int original_flags = adjustIntentFlags(service); if (shouldBlockExplicitRequest(OutboundType.START_SERVICE, service)) { if (DEBUG) Log.w(TAG, "Blocked outbound explicit service starting: " + service); if (! mDryRun) return null; } final ComponentName result = super.startService(service); service.setFlags(original_flags); return result; } @Override public void sendBroadcast(final Intent intent) { final int original_flags = adjustIntentFlags(intent); if (shouldBlockExplicitRequest(OutboundType.BROADCAST, intent)) { if (DEBUG) Log.w(TAG, "Blocked outbound explicit broadcast: " + intent); if (! mDryRun) return; } super.sendBroadcast(intent); intent.setFlags(original_flags); } @Override public Context getApplicationContext() { return mApplicationContext; } // TODO: Protect package queries (for service and receiver) @Override public PackageManager getPackageManager() { if (DEBUG) Log.d(TAG, "getPackageManager() is invoked", new Throwable()); return super.getPackageManager(); } // TODO: Protect outbound provider requests @Override public ContentResolver getContentResolver() { if (DEBUG) Log.d(TAG, "getContentResolver() is invoked", new Throwable()); return super.getContentResolver(); } private int adjustIntentFlags(final Intent intent) { final int original_flags = intent.getFlags(); if (mDryRun) return original_flags; if (mExcludeBackgroundPackages) intent.addFlags(SDK_INT >= N ? FLAG_RECEIVER_EXCLUDE_BACKGROUND : Intent.FLAG_RECEIVER_REGISTERED_ONLY); if (SDK_INT >= HONEYCOMB_MR1 && mExcludeStoppedPackages) intent.setFlags((intent.getFlags() & ~ Intent.FLAG_INCLUDE_STOPPED_PACKAGES) | Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); return original_flags; } private boolean shouldBlockExplicitRequest(final OutboundType type, final Intent intent) { if (mOutboundJudge == null) return false; final ComponentName component = intent.getComponent(); final String target_pkg = component != null ? component.getPackageName() : intent.getPackage(); if (target_pkg == null) return false; if (target_pkg.equals(getPackageName())) return false; // Targeting this package itself actually, not an outbound service. if (! mOutboundJudge.judge(type, target_pkg)) { if (DEBUG) Log.w(TAG, "Blocked outbound " + type + ": " + intent); return true; } else return false; } private CondomContext(final Context base, final @Nullable Context app_context, final @Nullable String tag) { super(base); mApplicationContext = app_context != null ? app_context : this; DEBUG = (base.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; TAG = tag == null ? "Condom" : "Condom." + tag; } private boolean mDryRun; private OutboundJudge mOutboundJudge; private boolean mExcludeStoppedPackages = true; private boolean mExcludeBackgroundPackages = true; private final boolean DEBUG; private final Context mApplicationContext; /** * If set, the broadcast will never go to manifest receivers in background (cached * or not running) apps, regardless of whether that would be done by default. By * default they will receive broadcasts if the broadcast has specified an * explicit component or package name. */ @RequiresApi(N) private static final int FLAG_RECEIVER_EXCLUDE_BACKGROUND = 0x00800000; private final String TAG; private static class CondomApplication extends Application { @Override public void registerComponentCallbacks(final ComponentCallbacks callback) { if (SDK_INT >= ICE_CREAM_SANDWICH) mApplication.registerComponentCallbacks(callback); } @Override public void unregisterComponentCallbacks(final ComponentCallbacks callback) { if (SDK_INT >= ICE_CREAM_SANDWICH) mApplication.unregisterComponentCallbacks(callback); } @Override public void registerActivityLifecycleCallbacks(final ActivityLifecycleCallbacks callback) { if (SDK_INT >= ICE_CREAM_SANDWICH) mApplication.registerActivityLifecycleCallbacks(callback); } @Override public void unregisterActivityLifecycleCallbacks(final ActivityLifecycleCallbacks callback) { if (SDK_INT >= ICE_CREAM_SANDWICH) mApplication.unregisterActivityLifecycleCallbacks(callback); } @Override public void registerOnProvideAssistDataListener(final OnProvideAssistDataListener callback) { if (SDK_INT >= JELLY_BEAN_MR2) mApplication.registerOnProvideAssistDataListener(callback); } @Override public void unregisterOnProvideAssistDataListener(final OnProvideAssistDataListener callback) { if (SDK_INT >= JELLY_BEAN_MR2) mApplication.unregisterOnProvideAssistDataListener(callback); } CondomApplication(final Application app) { mApplication = app; } @Override public void attachBaseContext(final Context base) { super.attachBaseContext(base); } private final Application mApplication; } }
package net.jjc1138.android.scrobbler; import java.net.URLEncoder; import java.text.ChoiceFormat; import java.text.MessageFormat; import android.app.Activity; import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.text.Editable; import android.text.Spannable; import android.text.TextWatcher; import android.text.style.UnderlineSpan; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class ScrobblerConfig extends Activity { private SharedPreferences prefs; private SharedPreferences unsaved; private CheckBox enable; private CheckBox immediate; private EditText username; private EditText password; private TextView sign_up; private TextView view_user_page; private LinearLayout settingsChanged; private TextView scrobble_user_error; private TextView update_link; private TextView queue_status; private TextView scrobble_when; private Button scrobble_now; private TextView scrobble_status; private String scrobbleWaiting; private final Handler handler = new Handler(); private static void show(View v) { v.setVisibility(View.VISIBLE); } private static void hide(View v) { v.setVisibility(View.GONE); } private final IScrobblerServiceNotificationHandler.Stub notifier = new IScrobblerServiceNotificationHandler.Stub() { @Override public void stateChanged(final int queueSize, final boolean scrobbling, final int lastScrobbleResult) throws RemoteException { handler.post(new Runnable() { @Override public void run() { queue_status.setText(MessageFormat.format( new ChoiceFormat(getString(R.string.tracks_ready)) .format(queueSize), queueSize)); // This is perhaps a tad verbose, but at least it's easy // to read: if (queueSize > 0) { show(scrobble_now); } else { hide(scrobble_now); } show(scrobble_when); if (scrobbling) { scrobble_status.setText( getString(R.string.scrobbling_in_progress)); hide(scrobble_user_error); hide(update_link); hide(scrobble_now); show(scrobble_status); } else if (lastScrobbleResult == ScrobblerService.NOT_YET_ATTEMPTED) { hide(scrobble_user_error); hide(update_link); hide(scrobble_status); } else { // TODOLATER BADTIME should also prevent further // handshakes according to the spec., but we don't // yet have a way of resetting from BADTIME when the // time is updated. if (lastScrobbleResult == ScrobblerService.BANNED || lastScrobbleResult == ScrobblerService.BADAUTH) { hide(scrobble_now); hide(scrobble_when); } if (lastScrobbleResult == ScrobblerService.BANNED || lastScrobbleResult == ScrobblerService.BADAUTH || lastScrobbleResult == ScrobblerService.BADTIME) { show(scrobble_user_error); hide(scrobble_status); } else { hide(scrobble_user_error); show(scrobble_status); } if (lastScrobbleResult == ScrobblerService.BANNED) { show(update_link); } else { hide(update_link); } switch (lastScrobbleResult) { case ScrobblerService.OK: scrobble_status.setText(getString( R.string.scrobbling_ok)); break; case ScrobblerService.BANNED: scrobble_user_error.setText(getString( R.string.scrobbling_banned)); break; case ScrobblerService.BADAUTH: scrobble_user_error.setText(getString( R.string.scrobbling_badauth)); break; case ScrobblerService.BADTIME: scrobble_user_error.setText(getString( R.string.scrobbling_badtime)); break; case ScrobblerService.FAILED_NET: scrobble_status.setText(getString( R.string.scrobbling_failed_net)); break; case ScrobblerService.FAILED_OTHER: scrobble_status.setText(getString( R.string.scrobbling_failed_other)); break; default: break; } } } }); } }; private ServiceConnection serviceConnection; private IScrobblerService service; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefs = getSharedPreferences(ScrobblerService.PREFS, 0); unsaved = getSharedPreferences("unsaved", 0); CompoundButton.OnCheckedChangeListener checkWatcher = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { settingsChanged(); } }; TextWatcher textWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { settingsChanged(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} }; setContentView(R.layout.main); enable = (CheckBox) findViewById(R.id.enable); immediate = (CheckBox) findViewById(R.id.immediate); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); sign_up = (TextView) findViewById(R.id.sign_up); view_user_page = (TextView) findViewById(R.id.view_user_page); settingsChanged = (LinearLayout) findViewById(R.id.settings_changed); scrobble_user_error = (TextView) findViewById(R.id.scrobble_user_error); update_link = (TextView) findViewById(R.id.update_link); queue_status = (TextView) findViewById(R.id.queue_status); scrobble_when = (TextView) findViewById(R.id.scrobble_when); scrobble_now = (Button) findViewById(R.id.scrobble_now); scrobble_status = (TextView) findViewById(R.id.scrobble_status); for (TextView tv : new TextView[] { sign_up, view_user_page, update_link }) { Spannable text = (Spannable) tv.getText(); text.setSpan(new UnderlineSpan(), 0, text.length(), 0); } scrobbleWaiting = MessageFormat.format(getString(R.string.scrobble_when), MessageFormat.format( new ChoiceFormat(getString(R.string.scrobble_when_minutes)) .format(ScrobblerService.SCROBBLE_WAITING_TIME_MINUTES), ScrobblerService.SCROBBLE_WAITING_TIME_MINUTES), MessageFormat.format( new ChoiceFormat(getString(R.string.scrobble_when_tracks)) .format(ScrobblerService.SCROBBLE_BATCH_SIZE), ScrobblerService.SCROBBLE_BATCH_SIZE)); enable.setOnCheckedChangeListener(checkWatcher); immediate.setOnCheckedChangeListener(checkWatcher); username.addTextChangedListener(textWatcher); password.addTextChangedListener(textWatcher); ((Button) findViewById(R.id.save)).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { uiToPrefs(prefs); settingsChanged(); } }); ((Button) findViewById(R.id.revert)).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { prefsToUI(prefs); settingsChanged(); } }); scrobble_now.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { service.startScrobble(); } catch (RemoteException e) {} } }); sign_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity((new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.last.fm/join")))); } }); view_user_page.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity((new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.last.fm/user/" + URLEncoder.encode(username.getText().toString()))))); } }); update_link.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity((new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:" + URLEncoder.encode(getPackageName()))))); } }); } protected void settingsChanged() { settingsChanged.setVisibility(isUISaved() ? View.GONE : View.VISIBLE); boolean hasUsername = username.getText().length() != 0; sign_up.setVisibility(hasUsername ? View.GONE : View.VISIBLE); view_user_page.setVisibility(hasUsername ? View.VISIBLE : View.GONE); scrobble_when.setText(immediate.isChecked() ? getString(R.string.scrobble_immediate) : scrobbleWaiting); } private void uiToPrefs(SharedPreferences p) { SharedPreferences.Editor e = p.edit(); e.putBoolean("enable", enable.isChecked()); e.putBoolean("immediate", immediate.isChecked()); e.putString("username", username.getText().toString()); e.putString("password", password.getText().toString()); e.commit(); } private void prefsToUI(SharedPreferences p) { enable.setChecked(p.getBoolean("enable", false)); immediate.setChecked(p.getBoolean("immediate", false)); username.setText(p.getString("username", "")); password.setText(p.getString("password", "")); } private boolean isUISaved() { SharedPreferences p = prefs; return enable.isChecked() == p.getBoolean("enable", false) && immediate.isChecked() == p.getBoolean("immediate", false) && username.getText().toString().equals(p.getString("username", "")) && password.getText().toString().equals(p.getString("password", "")); } @Override protected void onPause() { super.onPause(); if (settingsChanged.getVisibility() == View.VISIBLE) { uiToPrefs(unsaved); } try { if (service != null && notifier != null) { service.unregisterNotificationHandler(notifier); } } catch (RemoteException e) {} unbindService(serviceConnection); } @Override protected void onResume() { super.onResume(); final String examplePref = "enable"; if (unsaved.contains(examplePref)) { prefsToUI(unsaved); SharedPreferences.Editor e = unsaved.edit(); e.clear(); e.commit(); } else if (prefs.contains(examplePref)) { prefsToUI(prefs); } else { // Store defaults: uiToPrefs(prefs); } settingsChanged(); serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName comp, IBinder binder) { service = IScrobblerService.Stub.asInterface(binder); try { service.registerNotificationHandler(notifier); } catch (RemoteException e) {} // There's no need for notifications now that the user is // looking at the UI: ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)) .cancelAll(); } @Override public void onServiceDisconnected(ComponentName comp) {} }; bindService(new Intent(this, ScrobblerService.class), serviceConnection, Context.BIND_AUTO_CREATE); } }
package net.mcft.copy.betterstorage.item; import java.util.List; import net.mcft.copy.betterstorage.Config; import net.mcft.copy.betterstorage.block.tileentity.TileEntityBackpack; import net.mcft.copy.betterstorage.client.model.ModelBackpackArmor; import net.mcft.copy.betterstorage.container.ContainerBetterStorage; import net.mcft.copy.betterstorage.container.SlotArmorBackpack; import net.mcft.copy.betterstorage.inventory.InventoryBackpackEquipped; import net.mcft.copy.betterstorage.inventory.InventoryStacks; import net.mcft.copy.betterstorage.misc.Constants; import net.mcft.copy.betterstorage.misc.CurrentItem; import net.mcft.copy.betterstorage.misc.PropertiesBackpack; import net.mcft.copy.betterstorage.misc.Resources; import net.mcft.copy.betterstorage.misc.handlers.KeyBindingHandler; import net.mcft.copy.betterstorage.misc.handlers.PacketHandler; import net.mcft.copy.betterstorage.utils.DirectionUtils; import net.mcft.copy.betterstorage.utils.EntityUtils; import net.mcft.copy.betterstorage.utils.LanguageUtils; import net.mcft.copy.betterstorage.utils.PlayerUtils; import net.mcft.copy.betterstorage.utils.RandomUtils; import net.mcft.copy.betterstorage.utils.StackUtils; import net.mcft.copy.betterstorage.utils.WorldUtils; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.client.settings.GameSettings; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.EnumArmorMaterial; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.Packet103SetSlot; import net.minecraft.util.DamageSource; import net.minecraft.world.World; import net.minecraftforge.common.EnumHelper; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.common.ISpecialArmor; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemBackpack extends ItemArmor implements ISpecialArmor { public static final EnumArmorMaterial material = EnumHelper.addArmorMaterial( "backpack", 240, new int[]{ 0, 2, 0, 0 }, 15); protected ItemBackpack(int id, EnumArmorMaterial material) { super(id - 256, material, 0, 1); } public ItemBackpack(int id) { this(id, EnumArmorMaterial.CLOTH); } public String getName() { return Constants.containerBackpack; } /** Returns the number of columns this backpack has. */ public int getColumns() { return 9; } /** Returns the number of rows this backpack has. */ public int getRows() { return Config.backpackRows; } protected IInventory getBackpackItemsInternal(EntityLivingBase carrier, EntityPlayer player) { PropertiesBackpack backpackData = getBackpackData(carrier); if (backpackData.contents == null) backpackData.contents = new ItemStack[getColumns() * getRows()]; return new InventoryStacks(getName(), backpackData.contents); } public boolean canTake(PropertiesBackpack backpackData, ItemStack backpack) { return true; } public boolean containsItems(PropertiesBackpack backpackData) { return (backpackData.hasItems || ((backpackData.contents != null) && !StackUtils.isEmpty(backpackData.contents))); } // Item stuff @Override @SideOnly(Side.CLIENT) public int getSpriteNumber() { return 0; } @Override @SideOnly(Side.CLIENT) public void registerIcons(IconRegister iconRegister) { } @Override public String getUnlocalizedName() { return Block.blocksList[itemID].getUnlocalizedName(); } @Override public String getUnlocalizedName(ItemStack stack) { return getUnlocalizedName(); } @Override @SideOnly(Side.CLIENT) public CreativeTabs getCreativeTab() { return Block.blocksList[itemID].getCreativeTabToDisplayOn(); } @Override public boolean isValidArmor(ItemStack stack, int armorType, Entity entity) { return false; } @Override @SideOnly(Side.CLIENT) public ModelBiped getArmorModel(EntityLivingBase entity, ItemStack stack, int slot) { return ModelBackpackArmor.instance; } @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { return ((type == "overlay") ? Resources.backpackOverlayTexture : Resources.backpackTexture).toString(); } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advancedTooltips) { if (getBackpack(player) == stack) { PropertiesBackpack backpackData = getBackpackData(player); boolean containsItems = containsItems(backpackData); String reason = LanguageUtils.translateTooltip("backpack.containsItems"); if (ItemBackpack.isBackpackOpen(player)) { if (containsItems) list.add(reason); LanguageUtils.translateTooltip(list, "backpack.used"); } else if (containsItems) LanguageUtils.translateTooltip(list, "backpack.unequipHint", "%REASON%", reason); if (KeyBindingHandler.serverBackpackKeyEnabled) { String str = GameSettings.getKeyDisplayString(Config.backpackOpenKey); LanguageUtils.translateTooltip(list, "backpack.openHint", "%KEY%", str); } } else LanguageUtils.translateTooltip(list, "backpack.equipHint"); } @Override public void onArmorTickUpdate(World world, EntityPlayer player, ItemStack itemStack) { // Replace the armor slot with a custom one, so the player // can't unequip the backpack when there's items inside. int index = 5 + armorType; Slot slotBefore = player.inventoryContainer.getSlot(index); if (slotBefore instanceof SlotArmorBackpack) return; int slotIndex = player.inventory.getSizeInventory() - getChestSlotOffset(player) - armorType; SlotArmorBackpack slot = new SlotArmorBackpack(player.inventory, slotIndex, 8, 8 + armorType * 18); slot.slotNumber = index; player.inventoryContainer.inventorySlots.set(index, slot); } // For compatibility with Galacticraft. private int getChestSlotOffset(EntityPlayer player) { return isExact(player.inventory, "micdoodle8.mods.galacticraft.core.inventory.GCCoreInventoryPlayer") ? 6 : 1; } private static boolean isExact(Object obj, String str) { try { return obj.getClass().getName().equals(str); } catch (Exception e) { return false; } } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { return stack; } @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { ForgeDirection orientation = DirectionUtils.getOrientation(player).getOpposite(); return placeBackpack(player, player, stack, x, y, z, side, orientation); } // ISpecialArmor implementation @Override public ArmorProperties getProperties(EntityLivingBase entity, ItemStack armor, DamageSource source, double damage, int slot) { return new ArmorProperties(0, 2 / 25.0, armor.getMaxDamage() + 1 - armor.getItemDamage()); } @Override public int getArmorDisplay(EntityPlayer player, ItemStack armor, int slot) { return 2; } @Override public void damageArmor(EntityLivingBase entity, ItemStack stack, DamageSource source, int damage, int slot) { if (!takesDamage(stack, source)) return; stack.damageItem(damage, entity); if (stack.stackSize > 0) return; PropertiesBackpack backpackData = ItemBackpack.getBackpackData(entity); if (backpackData.contents != null) for (ItemStack s : backpackData.contents) WorldUtils.dropStackFromEntity(entity, s, 2.0F); entity.renderBrokenItemStack(stack); } private static final String[] immuneToDamageType = { "inWall", "drown", "starve", "catcus", "fall", "outOfWorld", "generic", "wither", "anvil", "fallingBlock", "thrown" }; protected boolean takesDamage(ItemStack stack, DamageSource source) { // Backpacks don't get damaged from certain // damage types (see above) and magic damage. if (source.isMagicDamage()) return false; for (String immune : immuneToDamageType) if (immune == source.getDamageType()) return false; // Protection enchantments protect the backpack // from taking damage from that damage type. return (!enchantmentProtection(stack, Enchantment.protection, 0.3, 0.35, 0.4, 0.45) && !(source.isProjectile() && enchantmentProtection(stack, Enchantment.projectileProtection, 0.4, 0.5, 0.6, 0.7)) && !(source.isFireDamage() && enchantmentProtection(stack, Enchantment.fireProtection, 0.55, 0.65, 0.75, 0.85)) && !(source.isExplosion() && enchantmentProtection(stack, Enchantment.blastProtection, 0.65, 0.75, 0.85, 0.95))); } private boolean enchantmentProtection(ItemStack stack, Enchantment ench, double... chance) { int level = EnchantmentHelper.getEnchantmentLevel(ench.effectId, stack); level = Math.min(level - 1, chance.length - 1); return ((level >= 0) && RandomUtils.getBoolean(chance[level])); } // Helper functions public static ItemStack getBackpack(EntityLivingBase entity) { ItemStack backpack = entity.getCurrentItemOrArmor(CurrentItem.CHEST); if ((backpack != null) && (backpack.getItem() instanceof ItemBackpack)) return backpack; else return null; } public static void setBackpack(EntityLivingBase entity, ItemStack backpack, ItemStack[] contents) { entity.setCurrentItemOrArmor(3, backpack); PropertiesBackpack backpackData = getBackpackData(entity); backpackData.contents = contents; ItemBackpack.updateHasItems(entity, backpackData); } public static void removeBackpack(EntityLivingBase entity) { setBackpack(entity, null, null); } public static IInventory getBackpackItems(EntityLivingBase carrier, EntityPlayer player) { ItemStack backpack = getBackpack(carrier); if (backpack == null) return null; return ((ItemBackpack)backpack.getItem()).getBackpackItemsInternal(carrier, player); } public static IInventory getBackpackItems(EntityLivingBase carrier) { return getBackpackItems(carrier, null); } public static void initBackpackData(EntityLivingBase entity) { EntityUtils.createProperties(entity, PropertiesBackpack.class); } public static PropertiesBackpack getBackpackData(EntityLivingBase entity) { PropertiesBackpack backpackData = EntityUtils.getOrCreateProperties(entity, PropertiesBackpack.class); if (!backpackData.initialized) { ItemBackpack.initBackpackOpen(entity); updateHasItems(entity, backpackData); backpackData.initialized = true; } return backpackData; } public static void updateHasItems(EntityLivingBase entity, PropertiesBackpack backpackData) { if (entity.worldObj.isRemote || !(entity instanceof EntityPlayer)) return; EntityPlayer player = (EntityPlayer)entity; boolean hasItems = ((backpackData.contents != null) && !StackUtils.isEmpty(backpackData.contents)); if (backpackData.hasItems == hasItems) return; Packet packet = PacketHandler.makePacket(PacketHandler.backpackHasItems, hasItems); PacketDispatcher.sendPacketToPlayer(packet, (Player)player); backpackData.hasItems = hasItems; } public static void initBackpackOpen(EntityLivingBase entity) { entity.getDataWatcher().addObject(Config.backpackOpenDataWatcherId, (byte)0); } public static void setBackpackOpen(EntityLivingBase entity, boolean isOpen) { entity.getDataWatcher().updateObject(Config.backpackOpenDataWatcherId, (byte)(isOpen ? 1 : 0)); } public static boolean isBackpackOpen(EntityLivingBase entity) { return (entity.getDataWatcher().getWatchableObjectByte(Config.backpackOpenDataWatcherId) != 0); } /** Opens the carrier's equipped backpack for the player. */ public static void openBackpack(EntityPlayer player, EntityLivingBase carrier) { ItemStack backpack = ItemBackpack.getBackpack(carrier); if (backpack == null) return; ItemBackpack backpackType = (ItemBackpack)backpack.getItem(); IInventory inventory = ItemBackpack.getBackpackItems(carrier, player); inventory = new InventoryBackpackEquipped(carrier, player, inventory); if (!inventory.isUseableByPlayer(player)) return; int columns = backpackType.getColumns(); int rows = backpackType.getRows(); Container container = new ContainerBetterStorage(player, inventory, columns, rows); String title = StackUtils.get(backpack, "", "display", "Name"); PlayerUtils.openGui(player, inventory.getInvName(), columns, rows, title, container); } /** Places an equipped backpack when the player right clicks * on the ground while sneaking and holding nothing. */ public static boolean onPlaceBackpack(EntityPlayer player, int x, int y, int z, int side) { if (player.getCurrentEquippedItem() != null || !player.isSneaking()) return false; ItemStack backpack = ItemBackpack.getBackpack(player); if (backpack == null) return false; if (!ItemBackpack.isBackpackOpen(player)) { // Try to place the backpack as if it was being held and used by the player. backpack.getItem().onItemUse(backpack, player, player.worldObj, x, y, z, side, 0, 0, 0); if (backpack.stackSize <= 0) backpack = null; } // Send set slot packet to for the chest slot to make // sure the client has the same information as the server. // This is especially important when there's a large delay, the // client might think e placed the backpack, but server didn't. if (!player.worldObj.isRemote) PacketDispatcher.sendPacketToPlayer(new Packet103SetSlot(0, 6, backpack), (Player)player); boolean success = (backpack == null); if (success) player.swingItem(); return success; } public static boolean placeBackpack(EntityLivingBase carrier, EntityPlayer player, ItemStack backpack, int x, int y, int z, int side, ForgeDirection orientation) { if (backpack.stackSize == 0) return false; World world = carrier.worldObj; Block blockBackpack = Block.blocksList[backpack.itemID]; // If a replacable block was clicked, move on. // Otherwise, check if the top side was clicked and adjust the position. if (!WorldUtils.isBlockReplacable(world, x, y, z)) { if (side != 1) return false; y++; } // Return false if there's block is too low or too high. if ((y <= 0) || (y >= world.getHeight() - 1)) return false; // Return false if not placed on top of a solid block. Block blockBelow = Block.blocksList[world.getBlockId(x, y - 1, z)]; if ((blockBelow == null) || !blockBelow.isBlockSolidOnSide(world, x, y - 1, z, ForgeDirection.UP)) return false; // Return false if the player can't edit the block. if ((player != null) && !player.canPlayerEdit(x, y, z, side, backpack)) return false; // Return false if there's an entity blocking the placement. if (!world.canPlaceEntityOnSide(blockBackpack.blockID, x, y, z, false, side, carrier, backpack)) return false; // Actually place the block in the world, // play place sound and decrease stack size if successful. if (!world.setBlock(x, y, z, blockBackpack.blockID, orientation.ordinal(), 3)) return false; if (world.getBlockId(x, y, z) != blockBackpack.blockID) return false; blockBackpack.onBlockPlacedBy(world, x, y, z, carrier, backpack); blockBackpack.onPostBlockPlaced(world, x, y, z, orientation.ordinal()); TileEntityBackpack te = WorldUtils.get(world, x, y, z, TileEntityBackpack.class); te.stack = backpack.copy(); if (ItemBackpack.getBackpack(carrier) == backpack) te.unequip(carrier); String sound = blockBackpack.stepSound.getPlaceSound(); float volume = (blockBackpack.stepSound.getVolume() + 1.0F) / 2.0F; float pitch = blockBackpack.stepSound.getPitch() * 0.8F; world.playSoundEffect(x + 0.5, y + 0.5, z + 0.5F, sound, volume, pitch); backpack.stackSize return true; } }
package nu.validator.checker; import com.cybozu.labs.langdetect.Detector; import com.cybozu.labs.langdetect.DetectorFactory; import com.cybozu.labs.langdetect.LangDetectException; import com.cybozu.labs.langdetect.Language; import com.ibm.icu.util.ULocale; import io.mola.galimatias.GalimatiasParseException; import io.mola.galimatias.Host; import io.mola.galimatias.URL; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import nu.validator.checker.Checker; import nu.validator.checker.LocatorImpl; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; public class LanguageDetectingChecker extends Checker { private static final String languageList = "nu/validator/localentities/files/language-profiles-list.txt"; private static final String profilesDir = "nu/validator/localentities/files/language-profiles/"; private static final Map<String, String[]> LANG_TAGS_BY_TLD = new HashMap<>(); private String systemId; private String tld; private Locator htmlStartTagLocator; private StringBuilder elementContent; private StringBuilder documentContent; private String httpContentLangHeader; private String htmlElementLangAttrValue; private String declaredLangCode; private boolean htmlElementHasLang; private String dirAttrValue; private boolean hasDir; private boolean inBody; private int currentOpenElementsInDifferentLang; private int currentOpenElementsWithSkipName = 0; private int nonWhitespaceCharacterCount; private static final int MAX_CHARS = 30720; private static final int MIN_CHARS = 1024; private static final double MIN_PROBABILITY = .90; private static final String[] RTL_LANGS = { "ar", "azb", "ckb", "dv", "fa", "he", "pnb", "ps", "sd", "ug", "ur" }; private static final String[] SKIP_NAMES = { "a", "figcaption", "form", "li", "nav", "pre", "script", "select", "style", "td", "textarea" }; static { LANG_TAGS_BY_TLD.put("ae", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("af", new String[] { "ps" }); LANG_TAGS_BY_TLD.put("am", new String[] { "hy" }); LANG_TAGS_BY_TLD.put("ar", new String[] { "es" }); LANG_TAGS_BY_TLD.put("at", new String[] { "de" }); LANG_TAGS_BY_TLD.put("az", new String[] { "az" }); LANG_TAGS_BY_TLD.put("ba", new String[] { "bs", "hr", "sr" }); LANG_TAGS_BY_TLD.put("bd", new String[] { "bn" }); LANG_TAGS_BY_TLD.put("be", new String[] { "de", "fr", "nl" }); LANG_TAGS_BY_TLD.put("bg", new String[] { "bg" }); LANG_TAGS_BY_TLD.put("bh", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("bo", new String[] { "es" }); LANG_TAGS_BY_TLD.put("br", new String[] { "pt" }); LANG_TAGS_BY_TLD.put("by", new String[] { "be" }); LANG_TAGS_BY_TLD.put("bz", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ch", new String[] { "de", "fr", "it", "rm" }); LANG_TAGS_BY_TLD.put("cl", new String[] { "es" }); LANG_TAGS_BY_TLD.put("co", new String[] { "es" }); LANG_TAGS_BY_TLD.put("cu", new String[] { "es" }); LANG_TAGS_BY_TLD.put("cr", new String[] { "es" }); LANG_TAGS_BY_TLD.put("cz", new String[] { "cs" }); LANG_TAGS_BY_TLD.put("de", new String[] { "de" }); LANG_TAGS_BY_TLD.put("dk", new String[] { "da" }); LANG_TAGS_BY_TLD.put("do", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ec", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ee", new String[] { "et" }); LANG_TAGS_BY_TLD.put("eg", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("es", new String[] { "es" }); LANG_TAGS_BY_TLD.put("fi", new String[] { "fi" }); LANG_TAGS_BY_TLD.put("fr", new String[] { "fr" }); LANG_TAGS_BY_TLD.put("ge", new String[] { "ka" }); LANG_TAGS_BY_TLD.put("gr", new String[] { "el" }); LANG_TAGS_BY_TLD.put("gt", new String[] { "es" }); LANG_TAGS_BY_TLD.put("hn", new String[] { "es" }); LANG_TAGS_BY_TLD.put("hr", new String[] { "hr" }); LANG_TAGS_BY_TLD.put("hu", new String[] { "hu" }); LANG_TAGS_BY_TLD.put("id", new String[] { "id" }); LANG_TAGS_BY_TLD.put("is", new String[] { "is" }); LANG_TAGS_BY_TLD.put("it", new String[] { "it" }); LANG_TAGS_BY_TLD.put("il", new String[] { "iw" }); LANG_TAGS_BY_TLD.put("in", new String[] { "bn", "gu", "hi", "kn", "ml", "mr", "pa", "ta", "te" }); LANG_TAGS_BY_TLD.put("ja", new String[] { "jp" }); LANG_TAGS_BY_TLD.put("jo", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("ke", new String[] { "sw" }); LANG_TAGS_BY_TLD.put("kg", new String[] { "ky" }); LANG_TAGS_BY_TLD.put("kh", new String[] { "km" }); LANG_TAGS_BY_TLD.put("kr", new String[] { "ko" }); LANG_TAGS_BY_TLD.put("kw", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("kz", new String[] { "kk" }); LANG_TAGS_BY_TLD.put("la", new String[] { "lo" }); LANG_TAGS_BY_TLD.put("li", new String[] { "de" }); LANG_TAGS_BY_TLD.put("lb", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("lk", new String[] { "si", "ta" }); LANG_TAGS_BY_TLD.put("lt", new String[] { "lt" }); LANG_TAGS_BY_TLD.put("lu", new String[] { "de" }); LANG_TAGS_BY_TLD.put("lv", new String[] { "lv" }); LANG_TAGS_BY_TLD.put("md", new String[] { "mo" }); LANG_TAGS_BY_TLD.put("mk", new String[] { "mk" }); LANG_TAGS_BY_TLD.put("mn", new String[] { "mn" }); LANG_TAGS_BY_TLD.put("mx", new String[] { "es" }); LANG_TAGS_BY_TLD.put("my", new String[] { "ms" }); LANG_TAGS_BY_TLD.put("ni", new String[] { "es" }); LANG_TAGS_BY_TLD.put("nl", new String[] { "nl" }); LANG_TAGS_BY_TLD.put("no", new String[] { "nn", "no" }); LANG_TAGS_BY_TLD.put("np", new String[] { "ne" }); LANG_TAGS_BY_TLD.put("pa", new String[] { "es" }); LANG_TAGS_BY_TLD.put("pe", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ph", new String[] { "tl" }); LANG_TAGS_BY_TLD.put("pl", new String[] { "pl" }); LANG_TAGS_BY_TLD.put("pk", new String[] { "ur" }); LANG_TAGS_BY_TLD.put("pr", new String[] { "es" }); LANG_TAGS_BY_TLD.put("pt", new String[] { "pt" }); LANG_TAGS_BY_TLD.put("py", new String[] { "es" }); LANG_TAGS_BY_TLD.put("qa", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("ro", new String[] { "ro" }); LANG_TAGS_BY_TLD.put("rs", new String[] { "sr" }); LANG_TAGS_BY_TLD.put("ru", new String[] { "ru" }); LANG_TAGS_BY_TLD.put("sa", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("se", new String[] { "sv" }); LANG_TAGS_BY_TLD.put("si", new String[] { "sl" }); LANG_TAGS_BY_TLD.put("sk", new String[] { "sk" }); LANG_TAGS_BY_TLD.put("sv", new String[] { "es" }); LANG_TAGS_BY_TLD.put("th", new String[] { "th" }); LANG_TAGS_BY_TLD.put("tj", new String[] { "tg" }); LANG_TAGS_BY_TLD.put("tm", new String[] { "tk" }); LANG_TAGS_BY_TLD.put("ua", new String[] { "uk" }); LANG_TAGS_BY_TLD.put("uy", new String[] { "es" }); LANG_TAGS_BY_TLD.put("uz", new String[] { "uz" }); LANG_TAGS_BY_TLD.put("ve", new String[] { "es" }); LANG_TAGS_BY_TLD.put("vn", new String[] { "vi" }); LANG_TAGS_BY_TLD.put("za", new String[] { "af" }); try { BufferedReader br = new BufferedReader(new InputStreamReader( LanguageDetectingChecker.class.getClassLoader().getResourceAsStream( languageList))); List<String> languageTags = new ArrayList<>(); String languageTagAndName = br.readLine(); while (languageTagAndName != null) { languageTags.add(languageTagAndName.split("\t")[0]); languageTagAndName = br.readLine(); } List<String> profiles = new ArrayList<>(); for (String languageTag : languageTags) { profiles.add((new BufferedReader(new InputStreamReader( LanguageDetectingChecker.class.getClassLoader().getResourceAsStream( profilesDir + languageTag)))).readLine()); } DetectorFactory.clear(); DetectorFactory.loadProfile(profiles); } catch (IOException e) { throw new RuntimeException(e); } catch (LangDetectException e) { } } private boolean shouldAppendToLangdetectContent() { return (inBody && currentOpenElementsWithSkipName < 1 && currentOpenElementsInDifferentLang < 1 && nonWhitespaceCharacterCount < MAX_CHARS); } private void setDocumentLanguage(String languageTag) { if (request != null) { request.setAttribute( "http://validator.nu/properties/document-language", languageTag); } } private String getDetectedLanguageSerboCroatian() throws SAXException { if ("hr".equals(declaredLangCode) || "hr".equals(tld)) { return "hr"; } if ("sr".equals(declaredLangCode) || ".rs".equals(tld)) { return "sr-latn"; } if ("bs".equals(declaredLangCode) || ".ba".equals(tld)) { return "bs"; } return "sh"; } private void checkLangAttributeSerboCroatian() throws SAXException { String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); String langWarning = ""; if (!htmlElementHasLang) { langWarning = "This document appears to be written in either" + " Croatian, Serbian, or Bosnian. Consider adding either" + " \u201Clang=\"hr\"\u201D, \u201Clang=\"sr\"\u201D, or" + " \u201Clang=\"bs\"\u201D to the" + " \u201Chtml\u201D start tag."; } else if (!("hr".equals(declaredLangCode) || "sr".equals(declaredLangCode) || "bs".equals(declaredLangCode))) { langWarning = String.format( "This document appears to be written in either Croatian," + " Serbian, or Bosnian, but the \u201Chtml\u201D" + " start tag has %s. Consider using either" + " \u201Clang=\"hr\"\u201D," + " \u201Clang=\"sr\"\u201D, or" + " \u201Clang=\"bs\"\u201D instead.", getAttValueExpr("lang", lowerCaseLang)); } if (!"".equals(langWarning)) { warn(langWarning, htmlStartTagLocator); } } private void checkLangAttributeNorwegian() throws SAXException { String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); String langWarning = ""; if (!htmlElementHasLang) { langWarning = "This document appears to be written in Norwegian" + " Consider adding either" + " \u201Clang=\"nn\"\u201D or \u201Clang=\"nb\"\u201D" + " (or variant) to the \u201Chtml\u201D start tag."; } else if (!("no".equals(declaredLangCode) || "nn".equals(declaredLangCode) || "nb".equals(declaredLangCode))) { langWarning = String.format( "This document appears to be written in Norwegian, but the" + " \u201Chtml\u201D start tag has %s. Consider" + " using either \u201Clang=\"nn\"\u201D or" + " \u201Clang=\"nb\"\u201D (or variant) instead.", getAttValueExpr("lang", lowerCaseLang)); } if (!"".equals(langWarning)) { warn(langWarning, htmlStartTagLocator); } } private void checkContentLanguageHeaderNorwegian(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode) throws SAXException { if ("".equals(httpContentLangHeader) || httpContentLangHeader.contains(",")) { return; } String lowerCaseContentLang = httpContentLangHeader.toLowerCase(); String contentLangCode = new ULocale( lowerCaseContentLang).getLanguage(); if (!("no".equals(contentLangCode) || "nn".equals(contentLangCode) || "nb".equals(contentLangCode))) { warn("This document appears to be written in" + " Norwegian but the value of the HTTP" + " \u201CContent-Language\u201D header is" + " \u201C" + lowerCaseContentLang + "\u201D. Consider" + " changing it to \u201Cnn\u201D or \u201Cnn\u201D" + " (or variant) instead."); } } private void checkLangAttribute(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode, String preferredLanguageCode) throws SAXException { String langWarning = ""; String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); if (!htmlElementHasLang) { langWarning = String.format( "This document appears to be written in %s." + " Consider adding \u201Clang=\"%s\"\u201D" + " (or variant) to the \u201Chtml\u201D" + " start tag.", detectedLanguageName, preferredLanguageCode); } else { if (request != null) { if ("".equals(lowerCaseLang)) { request.setAttribute( "http://validator.nu/properties/lang-empty", true); } else { request.setAttribute( "http://validator.nu/properties/lang-value", lowerCaseLang); } } if ("tl".equals(detectedLanguageCode) && ("ceb".equals(declaredLangCode) || "ilo".equals(declaredLangCode) || "pag".equals(declaredLangCode) || "war".equals(declaredLangCode))) { return; } if ("id".equals(detectedLanguageCode) && "min".equals(declaredLangCode)) { return; } if ("ms".equals(detectedLanguageCode) && "min".equals(declaredLangCode)) { return; } if ("hr".equals(detectedLanguageCode) && ("sr".equals(declaredLangCode) || "bs".equals(declaredLangCode) || "sh".equals(declaredLangCode))) { return; } if ("sr".equals(detectedLanguageCode) && ("hr".equals(declaredLangCode) || "bs".equals(declaredLangCode) || "sh".equals(declaredLangCode))) { return; } if ("bs".equals(detectedLanguageCode) && ("hr".equals(declaredLangCode) || "sr".equals(declaredLangCode) || "sh".equals(declaredLangCode))) { return; } if ("de".equals(detectedLanguageCode) && ("bar".equals(declaredLangCode) || "gsw".equals(declaredLangCode) || "lb".equals(declaredLangCode))) { return; } if ("zh".equals(detectedLanguageCode) && "yue".equals(lowerCaseLang)) { return; } if ("el".equals(detectedLanguageCode) && "grc".equals(declaredLangCode)) { return; } if ("es".equals(detectedLanguageCode) && ("an".equals(declaredLangCode) || "ast".equals(declaredLangCode))) { return; } if ("it".equals(detectedLanguageCode) && ("co".equals(declaredLangCode) || "pms".equals(declaredLangCode) || "vec".equals(declaredLangCode) || "lmo".equals(declaredLangCode) || "scn".equals(declaredLangCode) || "nap".equals(declaredLangCode))) { return; } if ("rw".equals(detectedLanguageCode) && "rn".equals(declaredLangCode)) { return; } if ("mhr".equals(detectedLanguageCode) && ("chm".equals(declaredLangCode) || "mrj".equals(declaredLangCode))) { return; } if ("mrj".equals(detectedLanguageCode) && ("chm".equals(declaredLangCode) || "mhr".equals(declaredLangCode))) { return; } if ("ru".equals(detectedLanguageCode) && "bg".equals(declaredLangCode)) { return; } String message = "This document appears to be written in %s" + " but the \u201Chtml\u201D start tag has %s. Consider" + " using \u201Clang=\"%s\"\u201D (or variant) instead."; if (zhSubtagMismatch(detectedLanguage, lowerCaseLang) || !declaredLangCode.equals(detectedLanguageCode)) { if (request != null) { request.setAttribute( "http://validator.nu/properties/lang-wrong", true); } langWarning = String.format(message, detectedLanguageName, getAttValueExpr("lang", htmlElementLangAttrValue), preferredLanguageCode); } } if (!"".equals(langWarning)) { warn(langWarning, htmlStartTagLocator); } } private void checkContentLanguageHeader(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode, String preferredLanguageCode) throws SAXException { if ("".equals(httpContentLangHeader) || httpContentLangHeader.contains(",")) { return; } String message = ""; String lowerCaseContentLang = httpContentLangHeader.toLowerCase(); String contentLangCode = new ULocale( lowerCaseContentLang).getLanguage(); if ("tl".equals(detectedLanguageCode) && ("ceb".equals(contentLangCode) || "ilo".equals(contentLangCode) || "pag".equals(contentLangCode) || "war".equals(contentLangCode))) { return; } if ("id".equals(detectedLanguageCode) && "min".equals(contentLangCode)) { return; } if ("ms".equals(detectedLanguageCode) && "min".equals(contentLangCode)) { return; } if ("hr".equals(detectedLanguageCode) && ("sr".equals(contentLangCode) || "bs".equals(contentLangCode) || "sh".equals(contentLangCode))) { return; } if ("sr".equals(detectedLanguageCode) && ("hr".equals(contentLangCode) || "bs".equals(contentLangCode) || "sh".equals(contentLangCode))) { return; } if ("bs".equals(detectedLanguageCode) && ("hr".equals(contentLangCode) || "sr".equals(contentLangCode) || "sh".equals(contentLangCode))) { return; } if ("de".equals(detectedLanguageCode) && ("bar".equals(contentLangCode) || "gsw".equals(contentLangCode) || "lb".equals(contentLangCode))) { return; } if ("zh".equals(detectedLanguageCode) && "yue".equals(lowerCaseContentLang)) { return; } if ("el".equals(detectedLanguageCode) && "grc".equals(contentLangCode)) { return; } if ("es".equals(detectedLanguageCode) && ("an".equals(contentLangCode) || "ast".equals(contentLangCode))) { return; } if ("it".equals(detectedLanguageCode) && ("co".equals(contentLangCode) || "pms".equals(contentLangCode) || "vec".equals(contentLangCode) || "lmo".equals(contentLangCode) || "scn".equals(contentLangCode) || "nap".equals(contentLangCode))) { return; } if ("rw".equals(detectedLanguageCode) && "rn".equals(contentLangCode)) { return; } if ("mhr".equals(detectedLanguageCode) && ("chm".equals(contentLangCode) || "mrj".equals(contentLangCode))) { return; } if ("mrj".equals(detectedLanguageCode) && ("chm".equals(contentLangCode) || "mhr".equals(contentLangCode))) { return; } if ("ru".equals(detectedLanguageCode) && "bg".equals(contentLangCode)) { return; } if (zhSubtagMismatch(detectedLanguage, lowerCaseContentLang) || !contentLangCode.equals(detectedLanguageCode)) { message = "This document appears to be written in %s but the value" + " of the HTTP \u201CContent-Language\u201D header is" + " \u201C%s\u201D. Consider changing it to" + " \u201C%s\u201D (or variant)."; warn(String.format(message, detectedLanguageName, lowerCaseContentLang, preferredLanguageCode, preferredLanguageCode)); } if (htmlElementHasLang) { message = "The value of the HTTP \u201CContent-Language\u201D" + " header is \u201C%s\u201D but it will be ignored because" + " the \u201Chtml\u201D start tag has %s."; String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); if (htmlElementHasLang) { if (zhSubtagMismatch(lowerCaseContentLang, lowerCaseLang) || !contentLangCode.equals(declaredLangCode)) { warn(String.format(message, httpContentLangHeader, getAttValueExpr("lang", htmlElementLangAttrValue)), htmlStartTagLocator); } } } } private void checkDirAttribute(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode, String preferredLanguageCode) throws SAXException { if (Arrays.binarySearch(RTL_LANGS, detectedLanguageCode) < 0) { return; } String dirWarning = ""; if (!hasDir) { dirWarning = String.format( "This document appears to be written in %s." + " Consider adding \u201Cdir=\"rtl\"\u201D" + " to the \u201Chtml\u201D start tag.", detectedLanguageName, preferredLanguageCode); } else if (!"rtl".equals(dirAttrValue)) { String message = "This document appears to be written in %s" + " but the \u201Chtml\u201D start tag has %s." + " Consider using \u201Cdir=\"rtl\"\u201D instead."; dirWarning = String.format(message, detectedLanguageName, getAttValueExpr("dir", dirAttrValue)); } if (!"".equals(dirWarning)) { warn(dirWarning, htmlStartTagLocator); } } private boolean zhSubtagMismatch(String expectedLanguage, String declaredLanguage) { return (("zh-hans".equals(expectedLanguage) && (declaredLanguage.contains("zh-tw") || declaredLanguage.contains("zh-hant"))) || ("zh-hant".equals(expectedLanguage) && (declaredLanguage.contains("zh-cn") || declaredLanguage.contains("zh-hans")))); } private String getAttValueExpr(String attName, String attValue) { if ("".equals(attValue)) { return String.format("an empty \u201c%s\u201d attribute", attName); } else { return String.format("\u201C%s=\"%s\"\u201D", attName, attValue); } } public LanguageDetectingChecker() { super(); } private HttpServletRequest request; public void setHttpContentLanguageHeader(String httpContentLangHeader) { if (httpContentLangHeader != null) { this.httpContentLangHeader = httpContentLangHeader; } } /** * @see nu.validator.checker.Checker#endDocument() */ @Override public void endDocument() throws SAXException { if (!"0".equals(System.getProperty( "nu.validator.checker.enableLangDetection")) && htmlStartTagLocator != null) { detectLanguageAndCheckAgainstDeclaredLanguage(); } } private void warnIfMissingLang() throws SAXException { if (!htmlElementHasLang) { String message = "Consider adding a \u201Clang\u201D" + " attribute to the \u201Chtml\u201D" + " start tag to declare the language" + " of this document."; warn(message, htmlStartTagLocator); } } private void detectLanguageAndCheckAgainstDeclaredLanguage() throws SAXException { if (nonWhitespaceCharacterCount < MIN_CHARS) { warnIfMissingLang(); return; } if ("zxx".equals(declaredLangCode) // "No Linguistic Content" || "eo".equals(declaredLangCode) // Esperanto || "la".equals(declaredLangCode) // Latin ) { return; } if (LANG_TAGS_BY_TLD.containsKey(tld) && Arrays.binarySearch(LANG_TAGS_BY_TLD.get(tld), declaredLangCode) >= 0) { return; } try { String textContent = documentContent.toString() .replaceAll("\\s+", " "); String detectedLanguage = ""; Detector detector = DetectorFactory.create(); detector.append(textContent); detector.getProbabilities(); ArrayList<String> possibileLanguages = new ArrayList<>(); ArrayList<Language> possibilities = detector.getProbabilities(); for (Language possibility : possibilities) { possibileLanguages.add(possibility.lang); if (possibility.prob > MIN_PROBABILITY) { detectedLanguage = possibility.lang; setDocumentLanguage(detectedLanguage); } else if ((possibileLanguages.contains("hr") && (possibileLanguages.contains("sr-latn") || possibileLanguages.contains("bs"))) || (possibileLanguages.contains("sr-latn") && (possibileLanguages.contains("hr") || possibileLanguages.contains("bs"))) || (possibileLanguages.contains("bs") && (possibileLanguages.contains("hr") || possibileLanguages.contains( "sr-latn")))) { if (htmlElementHasLang || systemId != null) { detectedLanguage = getDetectedLanguageSerboCroatian(); setDocumentLanguage(detectedLanguage); } if ("sh".equals(detectedLanguage)) { checkLangAttributeSerboCroatian(); return; } } } if ("".equals(detectedLanguage)) { warnIfMissingLang(); return; } String detectedLanguageName = ""; String preferredLanguageCode = ""; ULocale locale = new ULocale(detectedLanguage); String detectedLanguageCode = locale.getLanguage(); if ("no".equals(detectedLanguage)) { checkLangAttributeNorwegian(); checkContentLanguageHeaderNorwegian(detectedLanguage, detectedLanguageName, detectedLanguageCode); return; } if ("zh-hans".equals(detectedLanguage)) { detectedLanguageName = "Simplified Chinese"; preferredLanguageCode = "zh-hans"; } else if ("zh-hant".equals(detectedLanguage)) { detectedLanguageName = "Traditional Chinese"; preferredLanguageCode = "zh-hant"; } else if ("mhr".equals(detectedLanguage)) { detectedLanguageName = "Meadow Mari"; preferredLanguageCode = "mhr"; } else if ("mrj".equals(detectedLanguage)) { detectedLanguageName = "Hill Mari"; preferredLanguageCode = "mrj"; } else if ("nah".equals(detectedLanguage)) { detectedLanguageName = "Nahuatl"; preferredLanguageCode = "nah"; } else if ("pnb".equals(detectedLanguage)) { detectedLanguageName = "Western Panjabi"; preferredLanguageCode = "pnb"; } else if ("sr-cyrl".equals(detectedLanguage)) { detectedLanguageName = "Serbian"; preferredLanguageCode = "sr"; } else if ("sr-latn".equals(detectedLanguage)) { detectedLanguageName = "Serbian"; preferredLanguageCode = "sr"; } else if ("uz-cyrl".equals(detectedLanguage)) { detectedLanguageName = "Uzbek"; preferredLanguageCode = "uz"; } else if ("uz-latn".equals(detectedLanguage)) { detectedLanguageName = "Uzbek"; preferredLanguageCode = "uz"; } else if ("zxx".equals(detectedLanguage)) { detectedLanguageName = "Lorem ipsum text"; preferredLanguageCode = "zxx"; } else { detectedLanguageName = locale.getDisplayName(); preferredLanguageCode = detectedLanguageCode; } checkLangAttribute(detectedLanguage, detectedLanguageName, detectedLanguageCode, preferredLanguageCode); checkDirAttribute(detectedLanguage, detectedLanguageName, detectedLanguageCode, preferredLanguageCode); checkContentLanguageHeader(detectedLanguage, detectedLanguageName, detectedLanguageCode, preferredLanguageCode); } catch (LangDetectException e) { } } /** * @see nu.validator.checker.Checker#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String name) throws SAXException { if ("http: return; } if (nonWhitespaceCharacterCount < MAX_CHARS) { documentContent.append(elementContent); elementContent.setLength(0); } if ("body".equals(localName)) { inBody = false; currentOpenElementsWithSkipName = 0; } if (currentOpenElementsInDifferentLang > 0) { currentOpenElementsInDifferentLang if (currentOpenElementsInDifferentLang < 0) { currentOpenElementsInDifferentLang = 0; } } else { if (Arrays.binarySearch(SKIP_NAMES, localName) >= 0) { currentOpenElementsWithSkipName if (currentOpenElementsWithSkipName < 0) { currentOpenElementsWithSkipName = 0; } } } } /** * @see nu.validator.checker.Checker#startDocument() */ @Override public void startDocument() throws SAXException { request = getRequest(); httpContentLangHeader = ""; tld = ""; htmlStartTagLocator = null; inBody = false; currentOpenElementsInDifferentLang = 0; currentOpenElementsWithSkipName = 0; nonWhitespaceCharacterCount = 0; elementContent = new StringBuilder(); documentContent = new StringBuilder(); htmlElementHasLang = false; htmlElementLangAttrValue = ""; declaredLangCode = ""; hasDir = false; dirAttrValue = ""; documentContent.setLength(0); currentOpenElementsWithSkipName = 0; try { systemId = getDocumentLocator().getSystemId(); if (systemId != null && systemId.startsWith("http")) { Host hostname = URL.parse(systemId).host(); if (hostname != null) { String host = hostname.toString(); tld = host.substring(host.lastIndexOf(".") + 1); } } } catch (GalimatiasParseException e) { throw new RuntimeException(e); } } /** * @see nu.validator.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if ("http: return; } if ("html".equals(localName)) { htmlStartTagLocator = new LocatorImpl(getDocumentLocator()); for (int i = 0; i < atts.getLength(); i++) { if ("lang".equals(atts.getLocalName(i))) { if (request != null) { request.setAttribute( "http://validator.nu/properties/lang-found", true); } htmlElementHasLang = true; htmlElementLangAttrValue = atts.getValue(i); declaredLangCode = new ULocale( htmlElementLangAttrValue).getLanguage(); } else if ("dir".equals(atts.getLocalName(i))) { hasDir = true; dirAttrValue = atts.getValue(i); } } } else if ("body".equals(localName)) { inBody = true; } else if (inBody) { if (currentOpenElementsInDifferentLang > 0) { currentOpenElementsInDifferentLang++; } else { for (int i = 0; i < atts.getLength(); i++) { if ("lang".equals(atts.getLocalName(i))) { if (!"".equals(htmlElementLangAttrValue) && !htmlElementLangAttrValue.equals( atts.getValue(i))) { currentOpenElementsInDifferentLang++; } } } } } if (Arrays.binarySearch(SKIP_NAMES, localName) >= 0) { currentOpenElementsWithSkipName++; } } /** * @see nu.validator.checker.Checker#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (shouldAppendToLangdetectContent()) { elementContent.append(ch, start, length); } for (int i = start; i < start + length; i++) { char c = ch[i]; switch (c) { case ' ': case '\t': case '\r': case '\n': case ' case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; default: if (shouldAppendToLangdetectContent()) { nonWhitespaceCharacterCount++; } } } } }
package org.app.material; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.content.res.Configuration; import android.graphics.BitmapFactory; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.provider.Browser; import org.app.material.core.ApplicationLoader; public class AndroidUtilities { public static float density = 1; static { density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density; } public static int dp(float value) { if (value == 0) { return 0; } return (int) Math.ceil(density * value); } public static boolean isPortrait() { return ApplicationLoader.applicationContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; } public static boolean isLandscape() { return ApplicationLoader.applicationContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } public static boolean isLollipop() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; } public static boolean isLollipopMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1; } public static boolean isMarshmallow() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } public static Drawable getIcon(int resource, int colorFilter) { Drawable iconDrawable = ApplicationLoader.applicationContext.getResources().getDrawable(resource, null); if (iconDrawable != null) { //iconDrawable.setColorFilter(colorFilter, PorterDuff.Mode.MULTIPLY); iconDrawable.mutate().setColorFilter(colorFilter, PorterDuff.Mode.MULTIPLY); } return iconDrawable; } public static Typeface getTypeface(String path) { Typeface typeFace; typeFace = Typeface.createFromAsset(ApplicationLoader.applicationContext.getAssets(), path); return typeFace; } public static Drawable getRipple(int background, int rippleColor) { ColorStateList colorStateList; RippleDrawable rippleDrawable; colorStateList = ColorStateList.valueOf(rippleColor); rippleDrawable = new RippleDrawable(colorStateList, new ColorDrawable(background), null); return rippleDrawable; } public static void openUrl(Context context, String url) { if (context == null || url == null) { return; } openUrl(context, Uri.parse(url), 0, 0); } public static void openUrl(Context context, String url, int toolbarColor) { if (context == null || url == null) { return; } openUrl(context, Uri.parse(url), toolbarColor, 0); } public static void openUrl(Context context, String url, int toolbarColor, int shareImage) { if (context == null || url == null) { return; } openUrl(context, Uri.parse(url), toolbarColor, shareImage); } public static void openUrl(Context context, Uri uri, int toolbarColor, int shareImage) { if (context == null || uri == null) { return; } try { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra("android.support.customtabs.extra.SESSION", (Parcelable) null); intent.putExtra("android.support.customtabs.extra.TOOLBAR_COLOR", toolbarColor); intent.putExtra("android.support.customtabs.extra.TITLE_VISIBILITY", 1); Intent actionIntent = new Intent(Intent.ACTION_SEND); actionIntent.setType("text/plain"); actionIntent.putExtra(Intent.EXTRA_TEXT, uri.toString()); actionIntent.putExtra(Intent.EXTRA_SUBJECT, ""); PendingIntent pendingIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, actionIntent, PendingIntent.FLAG_ONE_SHOT); Bundle bundle = new Bundle(); bundle.putInt("android.support.customtabs.customaction.ID", 0); bundle.putParcelable("android.support.customtabs.customaction.ICON", BitmapFactory.decodeResource(context.getResources(), shareImage)); bundle.putString("android.support.customtabs.customaction.DESCRIPTION", "ShareFile"); bundle.putParcelable("android.support.customtabs.customaction.PENDING_INTENT", pendingIntent); intent.putExtra("android.support.customtabs.extra.ACTION_BUTTON_BUNDLE", bundle); intent.putExtra("android.support.customtabs.extra.TINT_ACTION_BUTTON", false); intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()); context.startActivity(intent); } catch (Exception ignored) {} } }
package de.eightbitboy.ecorealms.map; public class Map { private int sizeX; private int sizeY; private MapEntity[] entities; public Map(int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; initialize(); } public int getSizeX() { return this.sizeX; } public int getSizeY() { return this.sizeY; } MapEntity[] getEntities() { return this.entities; } private void initialize() { entities = new MapEntity[sizeX * sizeY]; } public void put(MapEntity entity) { if (!hasValidPosition(entity)) { throw new InvalidMapAccessException( "The entity has an invalid position: " + entity.getPosition().toString()); } else { insert(entity); } } private void insert(MapEntity entity) { } private boolean hasValidPosition(MapEntity entity) { MapPoint position = entity.getPosition(); return !(position.x < 0 || position.y < 0 || position.x >= this.sizeX || position.y >= this.sizeY); } public MapEntity get(MapPoint position) { //TODO return new MapEntity() { @Override public MapPoint getPosition() { return null; } @Override public int getSizeX() { return 0; } @Override public int getSizeY() { return 0; } }; } }
package org.ensembl.healthcheck.eg_gui; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashMap; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.text.DefaultEditorKit; /** * <p> * A TextArea that has a popup menu for copy and paste operations. * </p> * * @author michael * */ class JPopupTextArea extends JTextArea { protected void addPopupMenu() { new CopyAndPastePopupBuilder().addPopupMenu(this); } public JPopupTextArea(int rows, int columns) { super(rows, columns); addPopupMenu(); } public JPopupTextArea() { super(); addPopupMenu(); } }
package org.ensembl.healthcheck.testcase.generic; import java.sql.Connection; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ensembl.healthcheck.AssemblyNameInfo; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.util.Utils; /** * Checks the metadata table to make sure it is OK. Only one meta table at a time is done here; * checks for the consistency of the meta table across species are done in MetaCrossSpecies. */ public class Meta extends SingleDatabaseTestCase { // format for genebuild.version private static final String GBV_REGEXP = "[0-9]{4}[a-zA-Z]*"; /** * Creates a new instance of CheckMetaDataTableTestCase */ public Meta() { addToGroup("post_genebuild"); addToGroup("release"); setDescription("Check that the meta table exists, has data, the entries correspond to the " + "database name, and that the values in assembly.type match what's in the meta table"); } /** * Check various aspects of the meta table. * * @param dbre The database to check. * @return True if the test passed. */ public boolean run(final DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); result &= checkTableExists(con); result &= tableHasRows(con); result &= checkKeysPresent(con); result &= checkSpeciesClassification(dbre); result &= checkAssemblyMapping(con); result &= checkTaxonomyID(dbre); result &= checkGenebuildVersion(con); // Use an AssemblyNameInfo object to get te assembly information AssemblyNameInfo assembly = new AssemblyNameInfo(con); String metaTableAssemblyDefault = assembly.getMetaTableAssemblyDefault(); logger.finest("assembly.default from meta table: " + metaTableAssemblyDefault); String dbNameAssemblyVersion = assembly.getDBNameAssemblyVersion(); logger.finest("Assembly version from DB name: " + dbNameAssemblyVersion); String metaTableAssemblyVersion = assembly.getMetaTableAssemblyVersion(); logger.finest("meta table assembly version: " + metaTableAssemblyVersion); String metaTableAssemblyPrefix = assembly.getMetaTableAssemblyPrefix(); logger.finest("meta table assembly prefix: " + metaTableAssemblyPrefix); if (metaTableAssemblyVersion == null || metaTableAssemblyDefault == null || metaTableAssemblyPrefix == null || dbNameAssemblyVersion == null) { ReportManager.problem(this, con, "Cannot get all information from meta table - check for null values"); } else { // check that assembly.default matches the version of the coord_system with the lowest // rank value String lowestRankCS = getRowColumnValue(con, "SELECT version FROM coord_system WHERE version IS NOT NULL ORDER BY rank DESC LIMIT 1"); if (!lowestRankCS.equals(metaTableAssemblyDefault)) { ReportManager.problem(this, con, "assembly.default from meta table is " + metaTableAssemblyDefault + " but lowest ranked coordinate system has version " + lowestRankCS); } // Check that assembly prefix is valid and corresponds to this species // Prefix is OK as long as it starts with the valid one Species dbSpecies = dbre.getSpecies(); String correctPrefix = Species.getAssemblyPrefixForSpecies(dbSpecies); if (!metaTableAssemblyPrefix.startsWith(correctPrefix)) { ReportManager.problem(this, con, "Database species is " + dbSpecies + " but assembly prefix " + metaTableAssemblyPrefix + " should have prefix beginning with " + correctPrefix); result = false; } else { ReportManager.correct(this, con, "Meta table assembly prefix (" + metaTableAssemblyPrefix + ") is correct for " + dbSpecies); } } return result; } // run private boolean checkTableExists(Connection con) { boolean result = true; if (!checkTableExists(con, "meta")) { result = false; ReportManager.problem(this, con, "Meta table not present"); } else { ReportManager.correct(this, con, "Meta table present"); } return result; } private boolean tableHasRows(Connection con) { boolean result = true; int rows = countRowsInTable(con, "meta"); if (rows == 0) { result = false; ReportManager.problem(this, con, "meta table is empty"); } else { ReportManager.correct(this, con, "meta table has data"); } return result; } private boolean checkKeysPresent(Connection con) { boolean result = true; // check that there are species, classification and taxonomy_id entries String[] metaKeys = {"assembly.default", "species.classification", "species.common_name", "species.taxonomy_id"}; for (int i = 0; i < metaKeys.length; i++) { String metaKey = metaKeys[i]; int rows = getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key='" + metaKey + "'"); if (rows == 0) { result = false; ReportManager.problem(this, con, "No entry in meta table for " + metaKey); } else { ReportManager.correct(this, con, metaKey + " entry present"); } } return result; } private boolean checkSpeciesClassification(DatabaseRegistryEntry dbre) { boolean result = true; String dbName = dbre.getName(); Connection con = dbre.getConnection(); // Check that species.classification matches database name String[] metaTableSpeciesGenusArray = getColumnValues(con, "SELECT LCASE(meta_value) FROM meta WHERE meta_key='species.classification' ORDER BY meta_id LIMIT 2"); // if all is well, metaTableSpeciesGenusArray should contain the // species and genus // (in that order) from the meta table if (metaTableSpeciesGenusArray != null && metaTableSpeciesGenusArray.length == 2 && metaTableSpeciesGenusArray[0] != null && metaTableSpeciesGenusArray[1] != null) { String[] dbNameGenusSpeciesArray = dbName.split("_"); String dbNameGenusSpecies = dbNameGenusSpeciesArray[0] + "_" + dbNameGenusSpeciesArray[1]; String metaTableGenusSpecies = metaTableSpeciesGenusArray[1] + "_" + metaTableSpeciesGenusArray[0]; logger.finest("Classification from DB name:" + dbNameGenusSpecies + " Meta table: " + metaTableGenusSpecies); if (!dbNameGenusSpecies.equalsIgnoreCase(metaTableGenusSpecies)) { result = false; //warn(con, "Database name does not correspond to // species/genus data from meta // table"); ReportManager.problem(this, con, "Database name does not correspond to species/genus data from meta table"); } else { ReportManager.correct(this, con, "Database name corresponds to species/genus data from meta table"); } } else { //logger.warning("Cannot get species information from meta // table"); ReportManager.problem(this, con, "Cannot get species information from meta table"); } return result; } private boolean checkAssemblyMapping(Connection con) { boolean result = true; // Check formatting of assembly.mapping entries; should be of format // coord_system1{:default}|coord_system2{:default} with optional third // coordinate system // and all coord systems should be valid from coord_system Pattern assemblyMappingPattern = Pattern .compile("^([a-zA-Z0-9.]+)(:[a-zA-Z0-9.]+)?\\|([a-zA-Z0-9.]+)(:[a-zA-Z0-9.]+)?(\\|([a-zA-Z0-9.]+)(:[a-zA-Z0-9.]+)?)?$"); String[] validCoordSystems = getColumnValues(con, "SELECT name FROM coord_system"); String[] mappings = getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping'"); for (int i = 0; i < mappings.length; i++) { Matcher matcher = assemblyMappingPattern.matcher(mappings[i]); if (!matcher.matches()) { result = false; ReportManager.problem(this, con, "Coordinate system mapping " + mappings[i] + " is not in the correct format"); } else { // if format is OK, check coord systems are valid boolean valid = true; String cs1 = matcher.group(1); String cs2 = matcher.group(3); String cs3 = matcher.group(6); if (!Utils.stringInArray(cs1, validCoordSystems, false)) { valid = false; ReportManager.problem(this, con, "Source co-ordinate system " + cs1 + " is not in the coord_system table"); } if (!Utils.stringInArray(cs2, validCoordSystems, false)) { valid = false; ReportManager.problem(this, con, "Target co-ordinate system " + cs2 + " is not in the coord_system table"); } // third coordinate system is optional if (cs3 != null && !Utils.stringInArray(cs3, validCoordSystems, false)) { valid = false; ReportManager.problem(this, con, "Third co-ordinate system in mapping (" + cs3 + ") is not in the coord_system table"); } if (valid) { ReportManager.correct(this, con, "Coordinate system mapping " + mappings[i] + " is OK"); } } } return result; } private boolean checkTaxonomyID(DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); // Check that the taxonomy ID matches a known one. // The taxonomy ID-species mapping is held in the Species class. Species species = dbre.getSpecies(); String dbTaxonID = getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='species.taxonomy_id'"); logger.finest("Taxonomy ID from database: " + dbTaxonID); if (dbTaxonID.equals(Species.getTaxonomyID(species))) { ReportManager.correct(this, con, "Taxonomy ID " + dbTaxonID + " is correct for " + species.toString()); } else { result = false; ReportManager.problem(this, con, "Taxonomy ID " + dbTaxonID + " in database is not correct - should be " + Species.getTaxonomyID(species) + " for " + species.toString()); } return result; } private boolean checkGenebuildVersion(Connection con) { String gbv = getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.version'"); logger.finest("genebuild.version from database: " + gbv); if (gbv == null || gbv.length() == 0) { ReportManager.problem(this, con, "No genebuild.version entry in meta table"); return false; } else { if (!gbv.matches(GBV_REGEXP)) { ReportManager.problem(this, con, "genebuild.version " + gbv + " is not in correct format - should match " + GBV_REGEXP); return false; } else { int year = Integer.parseInt(gbv.substring(0, 2)); if (year < 0 || year > 99) { ReportManager.problem(this, con, "Year part of genebuild.version (" + year + ") is incorrect"); return false; } int month = Integer.parseInt(gbv.substring(2, 4)); if (month < 1 || month > 12) { ReportManager.problem(this, con, "Month part of genebuild.version (" + month + ") is incorrect"); return false; } } } ReportManager.correct(this, con, "genebuild.version " + gbv + " is present & in a valid format"); return true; } } // Meta
package org.griphyn.cPlanner.common; import org.griphyn.cPlanner.classes.NameValue; import org.griphyn.common.catalog.transformation.TCMode; import org.griphyn.common.util.VDSProperties; import org.griphyn.common.util.Boolean; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.FileOutputStream; import java.util.Collections; import java.util.List; import java.util.MissingResourceException; import java.util.Properties; import java.util.Set; import java.util.HashSet; /** * A Central Properties class that keeps track of all the properties used by * Pegasus. All other classes access the methods in this class to get the value * of the property. It access the VDSProperties class to read the property file. * * @author Karan Vahi * @author Gaurang Mehta * * @version $Revision$ * * @see org.griphyn.common.util.VDSProperties */ public class PegasusProperties { //Replica Catalog Constants public static final String DEFAULT_RC_COLLECTION = "GriphynData"; public static final String DEFAULT_RLI_URL = null; public static final String DEFAULT_RLS_QUERY_MODE = "bulk"; public static final String DEFAULT_RLS_EXIT_MODE = "error"; public static final String DEFAULT_REPLICA_MODE = "rls"; public static final String DEFAULT_RLS_QUERY_ATTRIB = "false"; public static final String DEFAULT_LRC_IGNORE_URL = null; public static final String DEFAULT_RLS_TIMEOUT = "30"; public static final String DEFAULT_EXEC_DIR = ""; public static final String DEFAULT_STORAGE_DIR = ""; public static final String DEFAULT_TC_MODE = TCMode.DEFAULT_TC_CLASS; public static final String DEFAULT_POOL_MODE = "XML"; public static final String DEFAULT_CONDOR_BIN_DIR = ""; public static final String DEFAULT_CONDOR_CONFIG_DIR = ""; public static final String DEFAULT_POSTSCRIPT_MODE = "none"; public static final String POOL_CONFIG_FILE = "sites."; public static final String CONDOR_KICKSTART = "kickstart-condor"; //transfer constants public static final String DEFAULT_TRANSFER_IMPLEMENTATION = "Transfer"; public static final String DEFAULT_SETUP_TRANSFER_IMPLEMENTATION = "GUC"; public static final String DEFAULT_TRANSFER_REFINER = "Default"; public static final String DEFAULT_STAGING_DELIMITER = "-"; public static final String DEFAULT_TRANSFER_PROCESSES = "4"; public static final String DEFAULT_TRANSFER_STREAMS = "1"; //grid start constants public static final String DEFAULT_GRIDSTART_MODE = "Kickstart"; public static final String DEFAULT_INVOKE_LENGTH = "4000"; //site selector constants public static final String DEFAULT_SITE_SELECTOR = "Random"; public static final String DEFAULT_SITE_SELECTOR_TIMEOUT = "300"; public static final String DEFAULT_SITE_SELECTOR_KEEP = "onerror"; ///some simulator constants that are used public static final String DEFAULT_DATA_MULTIPLICATION_FACTOR = "1"; public static final String DEFAULT_COMP_MULTIPLICATION_FACTOR = "1"; public static final String DEFAULT_COMP_ERROR_PERCENTAGE = "0"; public static final String DEFAULT_COMP_VARIANCE_PERCENTAGE = "0"; //collapsing constants public static final String DEFAULT_JOB_AGGREGATOR = "SeqExec"; //some tranformation catalog constants public static final String DEFAULT_TC_MAPPER_MODE = "All"; public static final String DEFAULT_TX_SELECTOR_MODE = "Random"; public static final String TC_DATA_FILE = "tc.data"; //logging constants public static final String DEFAULT_LOGGING_FILE = "stdout"; /** * Default properties that applies priorities to all kinds of transfer * jobs. */ public static final String ALL_TRANSFER_PRIORITY_PROPERTY = "pegasus.transfer.*.priority"; /** * The default DAXCallback that is loaded, if none is specified by the user. */ private static final String DEFAULT_DAX_CALLBACK = "DAX2Graph"; /** * Ensures only one object is created always. Implements the Singleton. */ private static PegasusProperties pegProperties = null; /** * The value of the PEGASUS_HOME environment variable. */ private String mPegasusHome; /** * The object holding all the properties pertaining to the VDS system. */ private VDSProperties mProps; /** * The Logger object. */ // private LogManager mLogger; /** * The String containing the messages to be logged. */ private String mLogMsg; /** * The default path to the transformation catalog. */ private String mDefaultTC; /** * The default path to the pool file. */ private String mDefaultPoolFile; /** * The default path to the kickstart condor script, that allows the user to * submit the concrete DAG directly to the underlying CondorG. */ private String mDefaultCondorKickStart; /** * The default transfer priority that needs to be applied to the transfer * jobs. */ private String mDefaultTransferPriority; /** * The set containing the deprecated properties specified by the user. */ private Set mDeprecatedProperties; /** * The pointer to the properties file that is written out in the submit directory. */ private String mPropsInSubmitDir; /** * Returns an instance to this properties object. * * @return a handle to the Properties class. */ public static PegasusProperties getInstance( ){ return nonSingletonInstance( null ); } /** * Returns an instance to this properties object. * * @param propFileName name of the properties file to picked from * $PEGASUS_HOME/etc/ directory. * * @return a handle to the Properties class. */ public static PegasusProperties getInstance( String propFileName ){ return nonSingletonInstance( propFileName ); } /** * To get a reference to the the object. The properties file that is loaded is * from the path specified in the argument. * This is *not implemented* as singleton. However the invocation of this * does modify the internally held singleton object. * * @param propFileName name of the properties file to picked from * $PEGASUS_HOME/etc/ directory. * * @return a handle to the Properties class. */ protected static PegasusProperties nonSingletonInstance( String propFileName ) { return new PegasusProperties( propFileName ); } /** * To get a reference to the the object. The properties file that is loaded is * from the path specified in the argument. * * This is *not implemented* as singleton. However the invocation of this * does modify the internally held singleton object. * * * @return a handle to the Properties class. */ public static PegasusProperties nonSingletonInstance() { return nonSingletonInstance( VDSProperties.PROPERTY_FILENAME ); } /** * The constructor that constructs the default paths to the various * configuration files, and populates the singleton instance as required. If * the properties file passed is null, then the singleton instance is * invoked, else the non singleton instance is invoked. * * @param propertiesFile name of the properties file to picked * from $PEGASUS_HOME/etc/ directory. */ private PegasusProperties( String propertiesFile ) { // mLogger = LogManager.getInstance(); mDeprecatedProperties = new HashSet(5); initializePropertyFile( propertiesFile ); mPegasusHome = mProps.getPegasusHome(); mDefaultCondorKickStart = getDefaultPathToCondorKickstart(); mDefaultPoolFile = getDefaultPathToSC(); mDefaultTC = getDefaultPathToTC(); mDefaultTransferPriority= getDefaultTransferPriority(); } /** * Returns the default path to the transformation catalog. Currently the * default path defaults to $PEGASUS_HOME/var/tc.data. * * @return the default path to tc.data. */ public String getDefaultPathToTC() { StringBuffer sb = new StringBuffer( 50 ); sb.append( mPegasusHome ); sb.append( File.separator ); sb.append( "var" ); File f = new File( sb.toString(), TC_DATA_FILE ); return f.getAbsolutePath(); } /** * Returns the default path to the site catalog file. * The default path is constructed on the basis of the mode set by * the user. * * @return $PEGASUS_HOME/etc/sites.txt if the pool mode is Text, else * $PEGASUS_HOME/etc/sites.xml * * @see #getPoolMode() */ public String getDefaultPathToSC() { String name = POOL_CONFIG_FILE; name += (getPoolMode().equalsIgnoreCase("Text"))? "txt": "xml"; File f = new File( mProps.getSysConfDir(),name); //System.err.println("Default Path to SC is " + f.getAbsolutePath()); return f.getAbsolutePath(); } /** * Returns the default path to the condor kickstart. Currently the path * defaults to $PEGASUS_HOME/bin/kickstart-condor. * * @return default path to kickstart condor. */ public String getDefaultPathToCondorKickstart() { StringBuffer sb = new StringBuffer( 50 ); sb.append( mPegasusHome ); sb.append( File.separator ); sb.append( "bin" ); sb.append( File.separator ); sb.append( CONDOR_KICKSTART ); return sb.toString(); } /** * Gets the handle to the properties file. The singleton instance is * invoked if the properties file is null (partly due to the way VDSProperties * is implemented ), else the non singleton is invoked. If you want to pick * up the default properties file in a non singleton manner, specify * VDSProperties.PROPERTY_FILENAME as a parameter. * * @param propertiesFile name of the properties file to picked * from $PEGASUS_HOME/etc/ directory. */ private void initializePropertyFile( String propertiesFile ) { try { mProps = ( propertiesFile == null ) ? //invoke the singleton instance VDSProperties.instance() : //invoke the non singleton instance VDSProperties.nonSingletonInstance( propertiesFile ); } catch ( IOException e ) { mLogMsg = "unable to read property file: " + e.getMessage(); System.err.println( mLogMsg ); // mLogger.log( mLogMsg , LogManager.FATAL_MESSAGE_LEVEL); System.exit( 1 ); } catch ( MissingResourceException e ) { mLogMsg = "You forgot to set -Dpegasus.home=$PEGASUS_HOME!"; System.err.println( mLogMsg ); // mLogger.log( mLogMsg , LogManager.FATAL_MESSAGE_LEVEL); System.exit( 1 ); } } /** * It allows you to get any property from the property file without going * through the corresponding accesor function in this class. For coding * and clarity purposes, the function should be used judiciously, and the * accessor function should be used as far as possible. * * @param key the property whose value is desired. * @return String */ public String getProperty( String key ) { return mProps.getProperty( key ); } /** * Returns the VDSProperties that this object encapsulates. Use only when * absolutely necessary. Use accessor methods whereever possible. * * @return VDSProperties */ public VDSProperties getVDSProperties(){ return this.mProps; } /** * Accessor: Overwrite any properties from within the program. * * @param key is the key to look up * @param value is the new property value to place in the system. * @return the old value, or null if it didn't exist before. */ public Object setProperty( String key, String value ) { return mProps.setProperty( key, value ); } /** * Extracts a specific property key subset from the known properties. * The prefix may be removed from the keys in the resulting dictionary, * or it may be kept. In the latter case, exact matches on the prefix * will also be copied into the resulting dictionary. * * @param prefix is the key prefix to filter the properties by. * @param keepPrefix if true, the key prefix is kept in the resulting * dictionary. As side-effect, a key that matches the prefix exactly * will also be copied. If false, the resulting dictionary's keys are * shortened by the prefix. An exact prefix match will not be copied, * as it would result in an empty string key. * * @return a property dictionary matching the filter key. May be * an empty dictionary, if no prefix matches were found. * * @see #getProperty( String ) is used to assemble matches */ public Properties matchingSubset( String prefix, boolean keepPrefix ) { return mProps.matchingSubset( prefix, keepPrefix ); } /** * Returns the properties matching a particular prefix as a list of * sorted name value pairs, where name is the full name of the matching * property (including the prefix) and value is it's value in the properties * file. * * @param prefix the prefix for the property names. * @param system boolean indicating whether to match only System properties * or all including the ones in the property file. * * @return list of <code>NameValue</code> objects corresponding to the matched * properties sorted by keys. * null if no matching property is found. */ public List getMatchingProperties( String prefix, boolean system ) { //sanity check if ( prefix == null ) { return null; } Properties p = (system)? System.getProperties(): matchingSubset(prefix,true); java.util.Enumeration e = p.propertyNames(); List l = ( e.hasMoreElements() ) ? new java.util.ArrayList() : null; while ( e.hasMoreElements() ) { String key = ( String ) e.nextElement(); NameValue nv = new NameValue( key, p.getProperty( key ) ); l.add( nv ); } Collections.sort(l); return ( l.isEmpty() ) ? null : l; } /** * Accessor to $PEGASUS_HOME/etc. The files in this directory have a low * change frequency, are effectively read-only, they reside on a * per-machine basis, and they are valid usually for a single user. * * @return the "etc" directory of the VDS runtime system. */ public File getSysConfDir() { return mProps.getSysConfDir(); } /** * Accessor: Obtains the root directory of the Pegasus runtime * system. * * @return the root directory of the Pegasus runtime system, as initially * set from the system properties. */ public String getPegasusHome() { return mProps.getPegasusHome(); } //PROPERTIES RELATED TO SCHEMAS /** * Returns the location of the schema for the DAX. * * Referred to by the "pegasus.schema.dax" property. * * @return location to the DAX schema. */ public String getDAXSchemaLocation() { return this.getDAXSchemaLocation( null ); } /** * Returns the location of the schema for the DAX. * * Referred to by the "pegasus.schema.dax" property. * * @param defaultLocation the default location to the schema. * * @return location to the DAX schema specified in the properties file, * else the default location if no value specified. */ public String getDAXSchemaLocation( String defaultLocation ) { return mProps.getProperty( "pegasus.schema.dax", defaultLocation ); } /** * Returns the location of the schema for the PDAX. * * Referred to by the "pegasus.schema.pdax" property * * @param defaultLocation the default location to the schema. * * @return location to the PDAX schema specified in the properties file, * else the default location if no value specified. */ public String getPDAXSchemaLocation( String defaultLocation ) { return mProps.getProperty( "pegasus.schema.pdax", defaultLocation ); } //DIRECTORY CREATION PROPERTIES /** * Returns the name of the class that the user wants, to insert the * create directory jobs in the graph in case of creating random * directories. * * Referred to by the "pegasus.dir.create" property. * * @return the create dir classname if specified in the properties file, * else Tentacles. */ public String getCreateDirClass() { return mProps.getProperty( "pegasus.dir.create", "Tentacles" ); } /** * It specifies whether to use the extended timestamp format for generation * of timestamps that are used to create the random directory name, and for * the classads generation. * * Referred to by the "pegasus.dir.timestamp.extended" property. * * @return the value specified in the properties file if valid boolean, else * false. */ public boolean useExtendedTimeStamp() { return Boolean.parse(mProps.getProperty( "pegasus.dir.timestamp.extended"), false ); } /** * Returns a boolean indicating whether to use timestamp for directory * name creation or not. * * Referred to by "pegasus.dir.useTimestamp" property. * * @return the boolean value specified in the properties files, else false. */ public boolean useTimestampForDirectoryStructure(){ return Boolean.parse( mProps.getProperty( "pegasus.dir.useTimestamp" ), false ); } /** * Returns the execution directory suffix or absolute specified * that is appended/replaced to the exec-mount-point specified in the * pool catalog for the various pools. * * Referred to by the "pegasus.dir.exec" property * * @return the value specified in the properties file, * else the default suffix. * * @see #DEFAULT_EXEC_DIR */ public String getExecDirectory() { return mProps.getProperty( "pegasus.dir.exec", DEFAULT_EXEC_DIR ); } /** * Returns the storage directory suffix or absolute specified * that is appended/replaced to the storage-mount-point specified in the * pool catalog for the various pools. * * Referred to by the "pegasus.dir.storage" property. * * @return the value specified in the properties file, * else the default suffix. * * @see #DEFAULT_STORAGE_DIR */ public String getStorageDirectory() { return mProps.getProperty( "pegasus.dir.storage", DEFAULT_STORAGE_DIR ); } /** * Returns a boolean indicating whether to have a deep storage directory * structure or not while staging out data to the output site. * * Referred to by the "pegasus.dir.storage.deep" property. * * @return the boolean value specified in the properties files, else false. */ public boolean useDeepStorageDirectoryStructure(){ return Boolean.parse( mProps.getProperty( "pegasus.dir.storage.deep" ), false ); } //PROPERTIES RELATED TO THE TRANSFORMATION CATALOG /** * Returns the mode to be used for accessing the Transformation Catalog. * * Referred to by the "pegasus.catalog.transformation" property. * * @return the value specified in properties file, * else DEFAULT_TC_MODE. * * @see #DEFAULT_TC_MODE */ public String getTCMode() { return mProps.getProperty( "pegasus.catalog.transformation", DEFAULT_TC_MODE ); } /** * Returns the location of the transformation catalog. * * Referred to by "pegasus.catalog.transformation.file" property. * * @return the value specified in the properties file, * else default path specified by mDefaultTC. * * @see #mDefaultTC */ public String getTCPath() { return mProps.getProperty( "pegasus.catalog.transformation.file", mDefaultTC ); } /** * Returns the mode for loading the transformation mapper that sits in * front of the transformation catalog. * * Referred to by the "pegasus.catalog.transformation.mapper" property. * * @return the value specified in the properties file, * else default tc mapper mode. * * @see #DEFAULT_TC_MAPPER_MODE */ public String getTCMapperMode() { return mProps.getProperty( "pegasus.catalog.transformation.mapper", DEFAULT_TC_MAPPER_MODE ); } //REPLICA CATALOG PROPERTIES /** * Returns the replica mode. It identifies the ReplicaMechanism being used * by Pegasus to determine logical file locations. * * Referred to by the "pegasus.catalog.replica" property. * * @return the replica mode, that is used to load the appropriate * implementing class if property is specified, * else the DEFAULT_REPLICA_MODE * * @see #DEFAULT_REPLICA_MODE */ public String getReplicaMode() { return mProps.getProperty( "pegasus.catalog.replica", DEFAULT_REPLICA_MODE); } /** * Returns the url to the RLI of the RLS. * * Referred to by the "pegasus.rls.url" property. * * @return the value specified in properties file, * else DEFAULT_RLI_URL. * * @see #DEFAULT_RLI_URL */ public String getRLIURL() { return mProps.getProperty( "pegasus.catalog.replica.url", DEFAULT_RLI_URL ); } /** * It returns the timeout value in seconds after which to timeout in case of * no activity from the RLS. * * Referred to by the "pegasus.rc.rls.timeout" property. * * @return the timeout value if specified else, * DEFAULT_RLS_TIMEOUT. * * @see #DEFAULT_RLS_TIMEOUT */ public int getRLSTimeout() { String prop = mProps.getProperty( "pegasus.catalog.replica.rls.timeout", DEFAULT_RLS_TIMEOUT ); int val; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return Integer.parseInt( DEFAULT_RLS_TIMEOUT ); } return val; } //PROPERTIES RELATED TO SITE CATALOG /** * Returns the mode to be used for accessing the pool information. * * Referred to by the "pegasus.catalog.site" property. * * @return the pool mode, that is used to load the appropriate * implementing class if the property is specified, * else default pool mode specified by DEFAULT_POOL_MODE * * @see #DEFAULT_POOL_MODE */ public String getPoolMode() { return mProps.getProperty( "pegasus.catalog.site", DEFAULT_POOL_MODE ); } /** * Returns the path to the pool file. * * Referred to by the "pegasus.catalog.site.file" property. * * @return the path to the pool file specified in the properties file, * else the default path specified by mDefaultPoolFile. * * @see #mDefaultPoolFile */ public String getPoolFile() { return mProps.getProperty( "pegasus.catalog.site.file", mDefaultPoolFile ); } /** * Returns the location of the schema for the DAX. * * Referred to by the "pegasus.schema.sc" property. * * @return the location of pool schema if specified in properties file, * else null. */ public String getPoolSchemaLocation() { return this.getPoolSchemaLocation( null ); } /** * Returns the location of the schema for the site catalog file. * * Referred to by the "pegasus.schema.sc" property * * @param defaultLocation the default location where the schema should be * if no other location is specified. * * @return the location specified by the property, * else defaultLocation. */ public String getPoolSchemaLocation( String defaultLocation ) { return mProps.getProperty("pegasus.schema.sc", defaultLocation ); } //PROVENANCE CATALOG PROPERTIES /** * Returns the provenance store to use to log the refiner actions. * * Referred to by the "pegasus.catalog.provenance.refinement" property. * * @return the value set in the properties, else null if not set. */ public String getRefinementProvenanceStore( ){ return mProps.getProperty( "pegasus.catalog.provenance.refinement" ); } //TRANSFER MECHANISM PROPERTIES /** * Returns the transfer implementation that is to be used for constructing * the transfer jobs. * * Referred to by the "pegasus.transfer.*.impl" property. * * @return the transfer implementation, else the * DEFAULT_TRANSFER_IMPLEMENTATION. * * @see #DEFAULT_TRANSFER_IMPLEMENTATION */ public String getTransferImplementation(){ return getTransferImplementation( "pegasus.transfer.*.impl" ); } /** * Returns the sls transfer implementation that is to be used for constructing * the transfer jobs. * * Referred to by the "pegasus.transfer.sls.*.impl" property. * * @return the transfer implementation, else the * DEFAULT_TRANSFER_IMPLEMENTATION. * * @see #DEFAULT_TRANSFER_IMPLEMENTATION */ public String getSLSTransferImplementation(){ return getTransferImplementation( "pegasus.transfer.sls.*.impl" ); } /** * Returns the transfer implementation. * * @param property property name. * * @return the transfer implementation, * else the one specified by "pegasus.transfer.*.impl", * else the DEFAULT_TRANSFER_IMPLEMENTATION. */ public String getTransferImplementation(String property){ String value = mProps.getProperty(property, getDefaultTransferImplementation()); String dflt = property.equals( "pegasus.transfer.setup.impl" ) ? DEFAULT_SETUP_TRANSFER_IMPLEMENTATION: DEFAULT_TRANSFER_IMPLEMENTATION ; return (value == null)? dflt : value; } /** * Returns the transfer refiner that is to be used for adding in the * transfer jobs in the workflow * * Referred to by the "pegasus.transfer.refiner" property. * * @return the transfer refiner, else the DEFAULT_TRANSFER_REFINER. * * @see #DEFAULT_TRANSFER_REFINER */ public String getTransferRefiner(){ String value = mProps.getProperty("pegasus.transfer.refiner"); //put in default if still we have a non null return (value == null)? DEFAULT_TRANSFER_REFINER: value; } /** * Returns whether to introduce quotes around url's before handing to * g-u-c and condor. * * Referred to by "pegasus.transfer.single.quote" property. * * @return boolean value specified in the properties file, else * true in case of non boolean value being specified or property * not being set. */ public boolean quoteTransferURL() { return Boolean.parse(mProps.getProperty( "pegasus.transfer.single.quote"), true); } /** * It returns the number of processes of g-u-c that the transfer script needs to * spawn to do the transfers. This is applicable only in the case where the * transfer executable has the capability of spawning processes. It should * not be confused with the number of streams that each process opens. * By default it is set to 4. In case a non integer value is specified in * the properties file it returns the default value. * * Referred to by "pegasus.transfer.throttle.processes" property. * * @return the number of processes specified in properties file, else * DEFAULT_TRANSFER_PROCESSES * * @see #DEFAULT_TRANSFER_PROCESSES */ public String getNumOfTransferProcesses() { String prop = mProps.getProperty( "pegasus.transfer.throttle.processes", DEFAULT_TRANSFER_PROCESSES ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return DEFAULT_TRANSFER_PROCESSES; } return Integer.toString( val ); } /** * It returns the number of streams that each transfer process uses to do the * ftp transfer. By default it is set to 1.In case a non integer * value is specified in the properties file it returns the default value. * * Referred to by "pegasus.transfer.throttle.streams" property. * * @return the number of streams specified in the properties file, else * DEFAULT_TRANSFER_STREAMS. * * @see #DEFAULT_TRANSFER_STREAMS */ public String getNumOfTransferStreams() { String prop = mProps.getProperty( "pegasus.transfer.throttle.streams", DEFAULT_TRANSFER_STREAMS ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return DEFAULT_TRANSFER_STREAMS; } return Integer.toString( val ); } /** * It specifies whether the underlying transfer mechanism being used should * use the force option if available to transfer the files. * * Referred to by "pegasus.transfer.force" property. * * @return boolean value specified in the properties file,else * false in case of non boolean value being specified or * property not being set. */ public boolean useForceInTransfer() { return Boolean.parse(mProps.getProperty( "pegasus.transfer.force"), false); } /** * It returns whether the use of symbolic links in case where the source * and destination files happen to be on the same file system. * * Referred to by "pegasus.transfer.links" property. * * @return boolean value specified in the properties file, else * false in case of non boolean value being specified or * property not being set. */ public boolean getUseOfSymbolicLinks() { String value = mProps.getProperty( "pegasus.transfer.links" ); return Boolean.parse(value,false); } /** * Returns the comma separated list of third party sites, specified in the * properties. * * @param property property name. * * @return the comma separated list of sites. */ public String getThirdPartySites(String property){ String value = mProps.getProperty(property); return value; } /** * Returns the comma separated list of third party sites for which * the third party transfers are executed on the remote sites. * * * @param property property name. * * @return the comma separated list of sites. */ public String getThirdPartySitesRemote(String property){ return mProps.getProperty(property); } /** * Returns the delimiter to be used for constructing the staged executable * name, during transfer of executables to remote sites. * * Referred to by the "pegasus.transfer.staging.delimiter" property. * * @return the value specified in the properties file, else * DEFAULT_STAGING_DELIMITER * * @see #DEFAULT_STAGING_DELIMITER */ public String getStagingDelimiter(){ return mProps.getProperty("pegasus.transfer.staging.delimiter", DEFAULT_STAGING_DELIMITER); } /** * Returns the list of sites for which the chmod job creation has to be * disabled for executable staging. * * Referred to by the "pegasus.transfer.disable.chmod" property. * * @return a comma separated list of site names. */ public String getChmodDisabledSites() { return mProps.getProperty( "pegasus.transfer.disable.chmod.sites" ); } /** * It specifies if for a job execution the proxy is to be transferred * from the submit host or not. * * Referred to by "pegasus.transfer.proxy" property. * * @return boolean value specified in the properties file,else * false in case of non boolean value being specified or * property not being set. */ public boolean transferProxy() { return Boolean.parse(mProps.getProperty( "pegasus.transfer.proxy"), false); } /** * Returns the arguments with which the transfer executable needs * to be invoked. * * Referred to by "pegasus.transfer.arguments" property. * * @return the arguments specified in the properties file, * else null if property is not specified. */ public String getTransferArguments() { return mProps.getProperty("pegasus.transfer.arguments"); } /** * Returns the priority to be set for the stage in transfer job. * * Referred to by "pegasus.transfer.stagein.priority" property if set, * else by "pegasus.transfer.*.priority" property. * * @return the priority as String if a valid integer specified in the * properties, else null. */ public String getTransferStageInPriority(){ return getTransferPriority("pegasus.transfer.stagein.priority"); } /** * Returns the priority to be set for the stage out transfer job. * * Referred to by "pegasus.transfer.stageout.priority" property if set, * else by "pegasus.transfer.*.priority" property. * * @return the priority as String if a valid integer specified in the * properties, else null. */ public String getTransferStageOutPriority(){ return getTransferPriority("pegasus.transfer.stageout.priority"); } /** * Returns the priority to be set for the interpool transfer job. * * Referred to by "pegasus.transfer.inter.priority" property if set, * else by "pegasus.transfer.*.priority" property. * * @return the priority as String if a valid integer specified in the * properties, else null. */ public String getTransferInterPriority(){ return getTransferPriority("pegasus.transfer.inter.priority"); } /** * Returns the transfer priority. * * @param property property name. * * @return the priority as String if a valid integer specified in the * properties as value to property, else null. */ private String getTransferPriority(String property){ String value = mProps.getProperty(property, mDefaultTransferPriority); int val = -1; try { val = Integer.parseInt( value ); } catch ( Exception e ) { } //if value in properties file is corrupted //again use the default transfer priority return ( val < 0 ) ? mDefaultTransferPriority : Integer.toString( val ); } //REPLICA SELECTOR FUNCTIONS /** * Returns the mode for loading the transformation selector that selects * amongst the various candidate transformation catalog entry objects. * * Referred to by the "pegasus.selector.transformation" property. * * @return the value specified in the properties file, * else default transformation selector. * * @see #DEFAULT_TC_MAPPER_MODE */ public String getTXSelectorMode() { return mProps.getProperty( "pegasus.selector.transformation", DEFAULT_TX_SELECTOR_MODE ); } /** * Returns the name of the selector to be used for selection amongst the * various replicas of a single lfn. * * Referred to by the "pegasus.selector.replica" property. * * @return the name of the selector if the property is specified, * else null */ public String getReplicaSelector(){ return mProps.getProperty( "pegasus.selector.replica" ); } /** * Returns a comma separated list of sites, that are restricted in terms of * data movement from the site. * * Referred to by the "pegasus.rc.restricted.sites" property. * * @return comma separated list of sites. */ // public String getRestrictedSites(){ // return mProps.getProperty("pegasus.rc.restricted.sites",""); /** * Returns a comma separated list of sites, from which to prefer data * transfers for all sites. * * Referred to by the "pegasus.selector.replica.*.prefer.stagein.sites" property. * * @return comma separated list of sites. */ public String getAllPreferredSites(){ return mProps.getProperty( "pegasus.selector.replica.*.prefer.stagein.sites",""); } /** * Returns a comma separated list of sites, from which to ignore data * transfers for all sites. Replaces the old pegasus.rc.restricted.sites * property. * * Referred to by the "pegasus.selector.ignore.*.prefer.stagein.sites" property. * * @return comma separated list of sites. */ public String getAllIgnoredSites(){ return mProps.getProperty("pegasus.selector.replica.*.ignore.stagein.sites", ""); } //SITE SELECTOR PROPERTIES /** * Returns the class name of the site selector, that needs to be invoked to do * the site selection. * * Referred to by the "pegasus.selector.site" property. * * @return the classname corresponding to the site selector that needs to be * invoked if specified in the properties file, else the default * selector specified by DEFAULT_SITE_SELECTOR. * * @see #DEFAULT_SITE_SELECTOR */ public String getSiteSelectorMode() { return mProps.getProperty( "pegasus.selector.site", DEFAULT_SITE_SELECTOR ); } /** * Returns the path to the external site selector that needs to be called * out to make the decision of site selection. * * Referred to by the "pegasus.selector.site.path" property. * * @return the path to the external site selector if specified in the * properties file, else null. */ public String getSiteSelectorPath() { return mProps.getProperty( "pegasus.selector.site.path" ); } /** * It returns the timeout value in seconds after which to timeout in case of * no activity from the external site selector. * * Referred to by the "pegasus.selector.site.timeout" property. * * @return the timeout value if specified else, * DEFAULT_SITE_SELECTOR_TIMEOUT. * * @see #DEFAULT_SITE_SELECTOR_TIMEOUT */ public int getSiteSelectorTimeout() { String prop = mProps.getProperty( "pegasus.selector.site.timeout", DEFAULT_SITE_SELECTOR_TIMEOUT ); int val; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return Integer.parseInt( DEFAULT_SITE_SELECTOR_TIMEOUT ); } return val; } /** * Returns a value designating whether we need to keep the temporary files * that are passed to the external site selectors. The check for the valid * tristate value should be done at the calling function end. This just * passes on the value user specified in the properties file. * * Referred to by the "pegasus.selector.site.keep.tmp" property. * * @return the value of the property is specified, else * DEFAULT_SITE_SELECTOR_KEEP * * @see #DEFAULT_SITE_SELECTOR_KEEP */ public String getSiteSelectorKeep() { return mProps.getProperty( "pegasus.selector.site.keep.tmp", DEFAULT_SITE_SELECTOR_KEEP ); } //PROPERTIES RELATED TO KICKSTART AND EXITCODE /** * Returns the GRIDSTART that is to be used to launch the jobs on the grid. * * Referred to by the "pegasus.gridstart" property. * * @return the value specified in the property file, * else DEFAULT_GRIDSTART_MODE * * @see #DEFAULT_GRIDSTART_MODE */ public String getGridStart(){ return mProps.getProperty("pegasus.gridstart",DEFAULT_GRIDSTART_MODE); } /** * Return a boolean indicating whether to turn the stat option for kickstart * on or not. By default it is turned on. * * Referred to by the "pegasus.gridstart.kickstart.stat" property. * * @return the boolean value specified in the property file, * else false if not specified or non boolean specified. */ public boolean doStatWithKickstart(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.kickstart.stat"), false ); } /** * Return a boolean indicating whether to generate the LOF files for the jobs * or not. This is used to generate LOF files, but not trigger the stat option * * Referred to by the "pegasus.gridstart.kickstart.generate.loft" property. * * @return the boolean value specified in the property file, * else false if not specified or non boolean specified. */ public boolean generateLOFFiles(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.generate.lof"), false ); } /** * Returns a boolean indicating whether to use invoke in kickstart always * or not. * * Referred to by the "pegasus.gridstart.invoke.always" property. * * @return the boolean value specified in the property file, * else false if not specified or non boolean specified. */ public boolean useInvokeInGridStart(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.invoke.always"), false ); } /** * Returns the trigger value for invoking an application through kickstart * using kickstart. If the arguments value being constructed in the condor * submit file is more than this value, then invoke is used to pass the * arguments to the remote end. Helps in bypassing the Condor 4K limit. * * Referred to by "pegasus.gridstart.invoke.length" property. * * @return the long value specified in the properties files, else * DEFAULT_INVOKE_LENGTH * * @see #DEFAULT_INVOKE_LENGTH */ public long getGridStartInvokeLength(){ long value = new Long(this.DEFAULT_INVOKE_LENGTH).longValue(); String st = mProps.getProperty( "pegasus.gridstart.invoke.length", this.DEFAULT_INVOKE_LENGTH ); try { value = new Long( st ).longValue(); } catch ( Exception e ) { //ignore malformed values from //the property file } return value; } /** * Returns a boolean indicating whehter to pass extra options to kickstart * or not. The extra options have appeared only in VDS version 1.4.2 (like -L * and -T). * * Referred to by "pegasus.gridstart.label" property. * * @return the boolean value specified in the property file, * else false if not specified or non boolean specified. */ public boolean generateKickstartExtraOptions(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.label"), false ); } /** * Returns the mode adding the postscripts for the jobs. At present takes in * only two values all or none default being none. * * Referred to by the "pegasus.exitcode.scope" property. * * @return the mode specified by the property, else * DEFAULT_POSTSCRIPT_MODE * * @see #DEFAULT_POSTSCRIPT_MODE */ public String getPOSTScriptScope() { return mProps.getProperty( "pegasus.exitcode.scope", DEFAULT_POSTSCRIPT_MODE ); } /** * Returns the postscript to use with the jobs in the workflow. They * maybe overriden by values specified in the profiles. * * Referred to by the "pegasus.exitcode.impl" property. * * @return the postscript to use for the workflow, else null if not * specified in the properties. */ public String getPOSTScript(){ return mProps.getProperty( "pegasus.exitcode.impl" ); } /** * Returns the path to the exitcode executable to be used. * * Referred to by the "pegasus.exitcode.path.[value]" property, where [value] * is replaced by the value passed an input to this function. * * @param value the short name of the postscript whose path we want. * * @return the path to the postscript if specified in properties file. */ public String getPOSTScriptPath( String value ){ value = ( value == null ) ? "*" : value; StringBuffer key = new StringBuffer(); key.append( "pegasus.exitcode.path." ).append( value ); return mProps.getProperty( key.toString() ); } /** * Returns the argument string containing the arguments by which exitcode is * invoked. * * Referred to by the "pegasus.exitcode.arguments" property. * * @return String containing the arguments,else empty string. */ public String getPOSTScriptArguments() { return mProps.getProperty( "pegasus.exitcode.arguments", ""); } /** * Returns a boolean indicating whether to turn debug on or not for exitcode. * By default false is returned. * * Referred to by the "pegasus.exitcode.debug" property. * * @return boolean value. */ public boolean setPostSCRIPTDebugON(){ return Boolean.parse( mProps.getProperty( "pegasus.exitcode.debug"), false ); } /** * Returns the argument string containing the arguments by which prescript is * invoked. * * Referred to by the "pegasus.prescript.arguments" property. * * @return String containing the arguments. * null if not specified. */ public String getPrescriptArguments() { return mProps.getProperty( "pegasus.prescript.arguments","" ); } //PROPERTIES RELATED TO REMOTE SCHEDULERS /** * Returns the project names that need to be appended to the RSL String * while creating the submit files. Referred to by * pegasus.remote.projects property. If present, Pegasus ends up * inserting an RSL string (project = value) in the submit file. * * @return a comma separated list of key value pairs if property specified, * else null. */ public String getRemoteSchedulerProjects() { return mProps.getProperty( "pegasus.remote.scheduler.projects" ); } /** * Returns the queue names that need to be appended to the RSL String while * creating the submit files. Referred to by the pegasus.remote.queues * property. If present, Pegasus ends up inserting an RSL string * (project = value) in the submit file. * * @return a comma separated list of key value pairs if property specified, * else null. */ public String getRemoteSchedulerQueues() { return mProps.getProperty( "pegasus.remote.scheduler.queues" ); } /** * Returns the maxwalltimes for the various pools that need to be appended * to the RSL String while creating the submit files. Referred to by the * pegasus.scheduler.remote.queues property. If present, Pegasus ends up * inserting an RSL string (project = value) in the submit file. * * * @return a comma separated list of key value pairs if property specified, * else null. */ public String getRemoteSchedulerMaxWallTimes() { return mProps.getProperty( "pegasus.remote.scheduler.min.maxwalltime" ); } /** * Returns the minimum walltimes that need to be enforced. * * Referred to by "pegasus.scheduler.remote.min.[key]" property. * * @param key the appropriate globus RSL key. Generally are * maxtime|maxwalltime|maxcputime * * @return the integer value as specified, -1 in case of no value being specified. */ public int getMinimumRemoteSchedulerTime( String key ){ StringBuffer property = new StringBuffer(); property.append( "pegasus.remote.scheduler.min." ).append( key ); int val = -1; try { val = Integer.parseInt( mProps.getProperty( property.toString() ) ); } catch ( Exception e ) { } return val; } //PROPERTIES RELATED TO CONDOR /** * Returns a boolean indicating whether we want to Condor Quote the * arguments of the job or not. * * Referred to by the "pegasus.condor.arguments.quote" property. * * @return boolean */ public boolean useCondorQuotingForArguments(){ return Boolean.parse( mProps.getProperty("pegasus.condor.arguments.quote"), true); } /** * Returns the number of release attempts that are written into the condor * submit files. Condor holds jobs on certain kind of failures, which many * a time are transient, and if a job is released it usually progresses. * * Referred to by the "pegasus.condor.release" property. * * @return an int denoting the number of times to release. * null if not specified or invalid entry. */ public String getCondorPeriodicReleaseValue() { String prop = mProps.getProperty( "pegasus.condor.release" ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return null; } return ( val < 0 ) ? null : Integer.toString( val ); } /** * Returns the number of release attempts that are attempted before * Condor removes the job from the queue and marks it as failed. * * Referred to by the "pegasus.condor.remove" property. * * @return an int denoting the number of times to release. * null if not specified or invalid entry. */ public String getCondorPeriodicRemoveValue() { String prop = mProps.getProperty( "pegasus.condor.remove" ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return null; } return ( val < 0 ) ? null : Integer.toString( val ); } /** * Returns the number of times Condor should retry running a job in case * of failure. The retry ends up reinvoking the prescript, that can change * the site selection decision in case of failure. * * Referred to by the "pegasus.dagman.retry" property. * * @return an int denoting the number of times to retry. * null if not specified or invalid entry. */ public String getCondorRetryValue() { String prop = mProps.getProperty( "pegasus.dagman.retry" ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return null; } return Integer.toString( val ); } /** * Tells whether to stream condor output or not. By default it is true , * meaning condor streams the output from the remote hosts back to the submit * hosts, instead of staging it. This helps in saving filedescriptors at the * jobmanager end. * * If it is set to false, output is not streamed back. The line * "stream_output = false" should be added in the submit files for kickstart * jobs. * * Referred to by the "pegasus.condor.output.stream" property. * * @return the boolean value specified by the property, else * true in case of invalid value or property not being specified. * */ public boolean streamCondorOutput() { return Boolean.parse(mProps.getProperty( "pegasus.condor.output.stream"), true ); } /** * Tells whether to stream condor error or not. By default it is true , * meaning condor streams the error from the remote hosts back to the submit * hosts instead of staging it in. This helps in saving filedescriptors at * the jobmanager end. * * Referred to by the "pegasus.condor.error.stream" property. * * If it is set to false, output is not streamed back. The line * "stream_output = false" should be added in the submit files for kickstart * jobs. * * @return the boolean value specified by the property, else * true in case of invalid value or property not being specified. */ public boolean streamCondorError() { return Boolean.parse(mProps.getProperty( "pegasus.condor.error.stream"), true); } //PROPERTIES RELATED TO STORK /** * Returns the credential name to be used for the stork transfer jobs. * * Referred to by the "pegasus.transfer.stork.cred" property. * * @return the credential name if specified by the property, * else null. */ public String getCredName() { return mProps.getProperty( "pegasus.transfer.stork.cred" ); } //SOME LOGGING PROPERTIES /** * Returns the log manager to use. * * Referred to by the "pegasus.log.manager" property. * * @return the value in the properties file, else Default */ public String getLogManager() { return mProps.getProperty( "pegasus.log.manager", "Default" ); } /** * Returns the log formatter to use. * * Referred to by the "pegasus.log.formatter" property. * * @return the value in the properties file, else Simple */ public String getLogFormatter() { return mProps.getProperty( "pegasus.log.formatter", "Simple" ); } /** * Returns the http url for log4j properties for windward project. * * Referred to by the "log4j.configuration" property. * * @return the value in the properties file, else null */ public String getHttpLog4jURL() { //return mProps.getProperty( "pegasus.log.windward.log4j.http.url" ); return mProps.getProperty( "log4j.configuration" ); } /** * Returns the file to which all the logging needs to be directed to. * * Referred to by the "pegasus.log.*" property. * * @return the value of the property that is specified, else * null */ public String getLoggingFile(){ return mProps.getProperty("pegasus.log.*"); } /** * Returns the location of the local log file where you want the messages to * be logged. Not used for the moment. * * Referred to by the "pegasus.log4j.log" property. * * @return the value specified in the property file,else null. */ public String getLog4JLogFile() { return mProps.getProperty( "pegasus.log4j.log" ); } /** * Returns a boolean indicating whether to write out the planner metrics * or not. * * Referred to by the "pegasus.log.metrics" property. * * @return boolean in the properties, else true */ public boolean writeOutMetrics(){ return Boolean.parse( mProps.getProperty( "pegasus.log.metrics" ), true ); } /** * Returns the path to the file that is used to be logging metrics * * Referred to by the "pegasus.log.metrics.file" property. * * @return path to the metrics file if specified, else $PEGASUS_HOME/var/pegasus.log */ public String getMetricsLogFile(){ String file = mProps.getProperty( "pegasus.log.metrics.file" ); if( file == null || file.length() == 0 ){ //construct the default path File dir = new File( this.getPegasusHome(), "var" ); file = new File( dir, "pegasus.log" ).getAbsolutePath(); } return file; } //SOME MISCELLANEOUS PROPERTIES /** * Return returns the environment string specified for the local pool. If * specified the registration jobs are set with these environment variables. * * Referred to by the "pegasus.local.env" property * * @return the environment string for local pool in properties file if * defined, else null. */ public String getLocalPoolEnvVar() { return mProps.getProperty( "pegasus.local.env" ); } /** * Returns a boolean indicating whether to have jobs executing on worker * node tmp or not. * * Referred to by the "pegasus.execute.*.filesystem.local" property. * * @return boolean value in the properties file, else false if not specified * or an invalid value specified. */ public boolean executeOnWorkerNode( ){ return Boolean.parse( mProps.getProperty( "pegasus.execute.*.filesystem.local" ) , false ); } /** * Returns a boolean indicating whether to treat the entries in the cache * files as a replica catalog or not. * * @return boolean */ public boolean treatCacheAsRC(){ return Boolean.parse(mProps.getProperty( "pegasus.catalog.replica.cache.asrc" ), false); } /** * Returns a boolean indicating whether to preserver line breaks. * * Referred to by the "pegasus.parser.dax.preserve.linebreaks" property. * * @return boolean value in the properties file, else false if not specified * or an invalid value specified. */ public boolean preserveParserLineBreaks( ){ return Boolean.parse( mProps.getProperty( "pegasus.parser.dax.preserve.linebreaks" ), false) ; } /** * Returns the path to the wings properties file. * * Referred to by the "pegasus.wings.properties" property. * * @return value in the properties file, else null. */ public String getWingsPropertiesFile( ){ return mProps.getProperty( "pegasus.wings.properties" ) ; } /** * Returns the request id. * * Referred to by the "pegasus.wings.request-id" property. * * @return value in the properties file, else null. */ public String getWingsRequestID( ){ return mProps.getProperty( "pegasus.wings.request.id" ) ; } /** * Returns the timeout value in seconds after which to timeout in case of * opening sockets to grid ftp server. * * Referred to by the "pegasus.auth.gridftp.timeout" property. * * @return the timeout value if specified else, * null. * * @see #DEFAULT_SITE_SELECTOR_TIMEOUT */ public String getGridFTPTimeout(){ return mProps.getProperty("pegasus.auth.gridftp.timeout"); } /** * Returns which submit mode to be used to submit the jobs on to the grid. * * Referred to by the "pegasus.submit" property. * * @return the submit mode specified in the property file, * else the default i.e condor. */ public String getSubmitMode() { return mProps.getProperty( "pegasus.submit", "condor" ); } /** * Returns the mode for parsing the dax while writing out the partitioned * daxes. * * Referred to by the "pegasus.partition.parser.load" property. * * @return the value specified in the properties file, else * the default value i.e single. */ public String getPartitionParsingMode() { return mProps.getProperty( "pegasus.partition.parser.load", "single" ); } /** * Returns the default priority that needs to be applied to all job. * * Referred to by the "pegasus.job.priority" property. * * @return the value specified in the properties file, null if a non * integer value is passed. */ public String getJobPriority(){ String prop = mProps.getProperty( "pegasus.job.priority" ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return null; } return ( val < 0 ) ? null : Integer.toString( val ); } //JOB COLLAPSING PROPERTIES /** * Returns a comma separated list for the node collapsing criteria for the * execution pools. This determines how many jobs one fat node gobbles up. * * Referred to by the "pegasus.cluster.nodes" property. * * @return the value specified in the properties file, else null. */ public String getCollapseFactors() { return mProps.getProperty( "pegasus.clusterer.nodes" ); } /** * Returns what job aggregator is to be used to aggregate multiple * compute jobs into a single condor job. * * Referred to by the "pegasus.cluster.job.aggregator" property. * * @return the value specified in the properties file, else * DEFAULT_JOB_AGGREGATOR * * @see #DEFAULT_JOB_AGGREGATOR */ public String getJobAggregator(){ return mProps.getProperty("pegasus.clusterer.job.aggregator",DEFAULT_JOB_AGGREGATOR); } /** * Returns what job aggregator is to be used to aggregate multiple * compute jobs into a single condor job. * * Referred to by the "pegasus.cluster.job.aggregator.seqexec.log.global" property. * * @return the value specified in the properties file, else true * */ public boolean jobAggregatorLogGlobal(){ return Boolean.parse( mProps.getProperty( "pegasus.clusterer.job.aggregator.seqexec.hasgloballog" ), true ); } /** * Returns a boolean indicating whether seqexec trips on the first job failure. * * Referred to by the "pegasus.cluster.job.aggregator.seqexec.firstjobfail" property. * * @return the value specified in the properties file, else false * */ public boolean abortOnFirstJobFailure(){ return Boolean.parse( mProps.getProperty( "pegasus.clusterer.job.aggregator.seqexec.firstjobfail" ), false ); } //DEFERRED PLANNING PROPERTIES /** * Returns the DAXCallback that is to be used while parsing the DAX. * * Referred to by the "pegasus.parser.dax.callback" property. * * @return the value specified in the properties file, else * DEFAULT_DAX_CALLBACK * * @see #DEFAULT_DAX_CALLBACK */ public String getDAXCallback(){ return mProps.getProperty("pegasus.parser.dax.callback",DEFAULT_DAX_CALLBACK); } /** * Returns the key that is to be used as a label key, for labelled * partitioning. * * Referred to by the "pegasus.partitioner.label.key" property. * * @return the value specified in the properties file. */ public String getPartitionerLabelKey(){ return mProps.getProperty( "pegasus.partitioner.label.key" ); } /** * Returns the bundle value for a particular transformation. * * Referred to by the "pegasus.partitioner.horziontal.bundle.[txname]" property, * where [txname] is replaced by the name passed an input to this function. * * @param name the logical name of the transformation. * * @return the path to the postscript if specified in properties file, * else null. */ public String getHorizontalPartitionerBundleValue( String name ){ StringBuffer key = new StringBuffer(); key.append( "pegasus.partitioner.horizontal.bundle." ).append( name ); return mProps.getProperty( key.toString() ); } /** * Returns the collapse value for a particular transformation. * * Referred to by the "pegasus.partitioner.horziontal.collapse.[txname]" property, * where [txname] is replaced by the name passed an input to this function. * * @param name the logical name of the transformation. * * @return the path to the postscript if specified in properties file, * else null. */ public String getHorizontalPartitionerCollapseValue( String name ){ StringBuffer key = new StringBuffer(); key.append( "pegasus.partitioner.horizontal.collapse." ).append( name ); return mProps.getProperty( key.toString() ); } /** * Returns the key that is to be used as a label key, for labelled * clustering. * * Referred to by the "pegasus.clusterer.label.key" property. * * @return the value specified in the properties file. */ public String getClustererLabelKey(){ return mProps.getProperty( "pegasus.clusterer.label.key"); } /** * Returns the path to the property file that has been writting out in * the submit directory. * * @return path to the property file * * @exception RuntimeException in case of file not being generated. */ public String getPropertiesInSubmitDirectory( ){ if ( mPropsInSubmitDir == null || mPropsInSubmitDir.length() == 0 ){ throw new RuntimeException( "Properties file does not exist in directory " ); } return mPropsInSubmitDir; } /** * Writes out the properties to a temporary file in the directory passed. * * @param directory the directory in which the properties file needs to * be written to. * * @return the absolute path to the properties file written in the directory. * * @throws IOException in case of error while writing out file. */ public String writeOutProperties( String directory ) throws IOException{ File dir = new File(directory); //sanity check on the directory sanityCheck( dir ); //we only want to write out the VDS properties for time being Properties properties = mProps.matchingSubset( "pegasus", true ); //create a temporary file in directory File f = File.createTempFile( "pegasus.", ".properties", dir ); //the header of the file StringBuffer header = new StringBuffer(64); header.append("Pegasus USER PROPERTIES AT RUNTIME \n") .append("#ESCAPES IN VALUES ARE INTRODUCED"); //create an output stream to this file and write out the properties OutputStream os = new FileOutputStream(f); properties.store( os, header.toString() ); os.close(); //also set it to the internal variable mPropsInSubmitDir = f.getAbsolutePath(); return mPropsInSubmitDir; } /** * Checks the destination location for existence, if it can * be created, if it is writable etc. * * @param dir is the new base directory to optionally create. * * @throws IOException in case of error while writing out files. */ protected static void sanityCheck( File dir ) throws IOException{ if ( dir.exists() ) { // location exists if ( dir.isDirectory() ) { // ok, isa directory if ( dir.canWrite() ) { // can write, all is well return; } else { // all is there, but I cannot write to dir throw new IOException( "Cannot write to existing directory " + dir.getPath() ); } } else { // exists but not a directory throw new IOException( "Destination " + dir.getPath() + " already " + "exists, but is not a directory." ); } } else { // does not exist, try to make it if ( ! dir.mkdirs() ) { throw new IOException( "Unable to create directory destination " + dir.getPath() ); } } } /** * Logs a warning about the deprecated property. Logs a warning only if * it has not been displayed before. * * @param deprecatedProperty the deprecated property that needs to be * replaced. * @param newProperty the new property that should be used. */ private void logDeprecatedWarning(String deprecatedProperty, String newProperty){ if(!mDeprecatedProperties.contains(deprecatedProperty)){ //log only if it had already not been logged StringBuffer sb = new StringBuffer(); sb.append( "The property " ).append( deprecatedProperty ). append( " has been deprecated. Use " ).append( newProperty ). append( " instead." ); // mLogger.log(sb.toString(),LogManager.WARNING_MESSAGE_LEVEL ); System.err.println( "[WARNING] " + sb.toString() ); //push the property in to indicate it has already been //warned about mDeprecatedProperties.add(deprecatedProperty); } } /** * Returns a boolean indicating whether to use third party transfers for * all types of transfers or not. * * Referred to by the "pegasus.transfer.*.thirdparty" property. * * @return the boolean value in the properties files, * else false if no value specified, or non boolean specified. */ // private boolean useThirdPartyForAll(){ // return Boolean.parse("pegasus.transfer.*.thirdparty", // false); /** * Returns the default list of third party sites. * * Referred to by the "pegasus.transfer.*.thirdparty.sites" property. * * @return the value specified in the properties file, else * null. */ private String getDefaultThirdPartySites(){ return mProps.getProperty("pegasus.transfer.*.thirdparty.sites"); } /** * Returns the default transfer implementation to be picked up for * constructing transfer jobs. * * Referred to by the "pegasus.transfer.*.impl" property. * * @return the value specified in the properties file, else * null. */ private String getDefaultTransferImplementation(){ return mProps.getProperty("pegasus.transfer.*.impl"); } /** * Returns the default priority for the transfer jobs if specified in * the properties file. * * @return the value specified in the properties file, else null if * non integer value or no value specified. */ private String getDefaultTransferPriority(){ String prop = mProps.getProperty( this.ALL_TRANSFER_PRIORITY_PROPERTY); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return null; } return Integer.toString( val ); } /** * Gets the reference to the internal singleton object. This method is * invoked with the assumption that the singleton method has been invoked once * and has been populated. Also that it has not been disposed by the garbage * collector. Can be potentially a buggy way to invoke. * * @return a handle to the Properties class. */ // public static PegasusProperties singletonInstance() { // return singletonInstance( null ); /** * Gets a reference to the internal singleton object. * * @param propFileName name of the properties file to picked * from $PEGASUS_HOME/etc/ directory. * * @return a handle to the Properties class. */ // public static PegasusProperties singletonInstance( String propFileName ) { // if ( pegProperties == null ) { // //only the default properties file // //can be picked up due to the way // //Singleton implemented in VDSProperties.??? // pegProperties = new PegasusProperties( null ); // return pegProperties; }
package org.griphyn.cPlanner.transfer.refiner; import org.griphyn.cPlanner.classes.ADag; import org.griphyn.cPlanner.classes.SubInfo; import org.griphyn.cPlanner.classes.FileTransfer; import org.griphyn.cPlanner.classes.PlannerOptions; import org.griphyn.cPlanner.common.PegasusProperties; import org.griphyn.cPlanner.common.LogManager; import org.griphyn.cPlanner.engine.ReplicaCatalogBridge; import org.griphyn.cPlanner.transfer.MultipleFTPerXFERJobRefiner; import java.util.ArrayList; import java.util.Iterator; import java.util.Collection; import java.util.TreeMap; import java.util.Map; import java.util.List; /** * The default transfer refiner, that implements the multiple refiner. * For each compute job if required it creates the following * - a single stagein transfer job * - a single stageout transfer job * - a single interpool transfer job * * In addition this implementation prevents file clobbering while staging in data * to a remote site, that is shared amongst jobs. * * @author Karan Vahi * @version $Revision$ */ public class Default extends MultipleFTPerXFERJobRefiner { /** * A short description of the transfer refinement. */ public static final String DESCRIPTION = "Default Multiple Refinement "; /** * The string holding the logging messages */ protected String mLogMsg; /** * A Map containing information about which logical file has been * transferred to which site and the name of the stagein transfer node * that is transferring the file from the location returned from * the replica catalog. * The key for the hashmap is logicalfilename:sitehandle and the value would be * the name of the transfer node. * */ protected Map mFileTable; /** * The overloaded constructor. * * @param dag the workflow to which transfer nodes need to be added. * @param properties the <code>PegasusProperties</code> object containing all * the properties required by Pegasus. * @param options the options passed to the planner. * */ public Default(ADag dag,PegasusProperties properties,PlannerOptions options){ super(dag,properties,options); mLogMsg = null; mFileTable = new TreeMap(); } /** * Adds the stage in transfer nodes which transfer the input files for a job, * from the location returned from the replica catalog to the job's execution * pool. * * @param job <code>SubInfo</code> object corresponding to the node to * which the files are to be transferred to. * @param files Collection of <code>FileTransfer</code> objects containing the * information about source and destURL's. */ public void addStageInXFERNodes(SubInfo job, Collection files){ String jobName = job.getName(); String pool = job.getSiteHandle(); int counter = 0; String newJobName = this.STAGE_IN_PREFIX + jobName + "_" + counter; String key = null; String msg = "Adding stagein transfer nodes for job " + jobName; String par = null; Collection stagedFiles = new ArrayList(1); //to prevent duplicate dependencies java.util.HashSet tempSet = new java.util.HashSet(); int staged = 0; for (Iterator it = files.iterator();it.hasNext();) { FileTransfer ft = (FileTransfer) it.next(); String lfn = ft.getLFN(); //get the key for this lfn and pool //if the key already in the table //then remove the entry from //the Vector and add a dependency //in the graph key = this.constructFileKey(lfn, pool); par = (String) mFileTable.get(key); //System.out.println("lfn " + lfn + " par " + par); if (par != null) { it.remove(); //check if tempSet does not contain the parent //fix for sonal's bug if (tempSet.contains(par)) { mLogMsg = "IGNORING TO ADD rc pull relation from rc tx node: " + par + " -> " + jobName + " for transferring file " + lfn + " to pool " + pool; mLogger.log(mLogMsg,LogManager.DEBUG_MESSAGE_LEVEL); } else { mLogMsg = /*"Adding relation " + par + " -> " + jobName +*/ " For transferring file " + lfn; mLogger.log(mLogMsg, LogManager.DEBUG_MESSAGE_LEVEL); addRelation(par,jobName,pool,false); tempSet.add(par); } } else { if(ft.isTransferringExecutableFile()){ //add to staged files for adding of //set up job. stagedFiles.add(ft); //the staged execution file should be having the setup //job as parent if it does not preserve x bit if(mTXStageInImplementation.doesPreserveXBit()){ mFileTable.put(key,newJobName); } else{ mFileTable.put(key, mTXStageInImplementation.getSetXBitJobName(jobName,staged++)); } } else{ //make a new entry into the table mFileTable.put(key, newJobName); } //add the newJobName to the tempSet so that even //if the job has duplicate input files only one instance //of transfer is scheduled. This came up during collapsing //June 15th, 2004 tempSet.add(newJobName); } } if (!files.isEmpty()) { mLogger.log(msg,LogManager.DEBUG_MESSAGE_LEVEL); msg = "Adding new stagein transfer node named " + newJobName; mLogger.log(msg,LogManager.DEBUG_MESSAGE_LEVEL); //add a direct dependency between compute job //and stagein job only if there is no //executables being staged if(stagedFiles.isEmpty()){ //add the direct relation addRelation(newJobName, jobName, pool, true); addJob(mTXStageInImplementation.createTransferJob(job, files,null, newJobName, SubInfo.STAGE_IN_JOB)); } else{ //the dependency to stage in job is added via the //the setup job that does the chmod addJob(mTXStageInImplementation.createTransferJob(job,files,stagedFiles, newJobName, SubInfo.STAGE_IN_JOB)); } } } /** * Adds the inter pool transfer nodes that are required for transferring * the output files of the parents to the jobs execution site. * * @param job <code>SubInfo</code> object corresponding to the node to * which the files are to be transferred to. * @param files Collection of <code>FileTransfer</code> objects containing the * information about source and destURL's. */ public void addInterSiteTXNodes(SubInfo job, Collection files){ String jobName = job.getName(); int counter = 0; String newJobName = this.INTER_POOL_PREFIX + jobName + "_" + counter; String msg = "Adding inter pool nodes for job " + jobName; String prevParent = null; String lfn = null; String key = null; String par = null; String pool = job.getSiteHandle(); boolean toAdd = true; //to prevent duplicate dependencies java.util.HashSet tempSet = new java.util.HashSet(); //node construction only if there is //a file to transfer if (!files.isEmpty()) { mLogger.log(msg,LogManager.DEBUG_MESSAGE_LEVEL); for(Iterator it = files.iterator();it.hasNext();) { FileTransfer ft = (FileTransfer) it.next(); lfn = ft.getLFN(); //System.out.println("Trying to figure out for lfn " + lfn); //to ensure that duplicate edges //are not added in the graph //between the parent of a node and the //inter tx node that transfers the file //to the node site. //get the key for this lfn and pool //if the key already in the table //then remove the entry from //the Vector and add a dependency //in the graph key = this.constructFileKey(lfn, pool); par = (String) mFileTable.get(key); //System.out.println("\nGot Key :" + key + " Value :" + par ); if (par != null) { //transfer of this file //has already been scheduled //onto the pool it.remove(); //check if tempSet does not contain the parent if (tempSet.contains(par)) { mLogMsg = "IGNORING TO ADD interpool relation 1 from inter tx node: " + par + " -> " + jobName + " for transferring file " + lfn + " to pool " + pool; mLogger.log(mLogMsg,LogManager.DEBUG_MESSAGE_LEVEL); } else { mLogMsg = "Adding interpool relation 1 from inter tx node: " + par + " -> " + jobName + " for transferring file " + lfn + " to pool " + pool; mLogger.log(mLogMsg, LogManager.DEBUG_MESSAGE_LEVEL); addRelation(par, jobName); tempSet.add(par); } } else { //make a new entry into the table mFileTable.put(key, newJobName); //System.out.println("\nPut Key :" + key + " Value :" + newJobName ); //to ensure that duplicate edges //are not added in the graph //between the parent of a node and the //inter tx node that transfers the file //to the node site. if (prevParent == null || !prevParent.equalsIgnoreCase(ft.getJobName())) { mLogMsg = "Adding interpool relation 2" + ft.getJobName() + " -> " + newJobName + " for transferring file " + lfn + " to pool " + pool; mLogger.log(mLogMsg,LogManager.DEBUG_MESSAGE_LEVEL); addRelation(ft.getJobName(), newJobName); } //we only need to add the relation between a //inter tx node and a node once. if (toAdd) { mLogMsg = "Adding interpool relation 3" + newJobName + " -> " + jobName + " for transferring file " + lfn + " to pool " + pool; mLogger.log(mLogMsg,LogManager.DEBUG_MESSAGE_LEVEL); addRelation(newJobName, jobName); tempSet.add(newJobName); toAdd = false; } } prevParent = ft.getJobName(); } //add the new job and construct it's //subinfo only if the vector is not //empty if (!files.isEmpty()) { msg = "Adding new inter pool node named " + newJobName; mLogger.log(msg,LogManager.DEBUG_MESSAGE_LEVEL); //added in make transfer node addJob(mTXInterImplementation.createTransferJob(job, files,null, newJobName, SubInfo.INTER_POOL_JOB)); } } tempSet = null; } /** * Adds the stageout transfer nodes, that stage data to an output site * specified by the user. * * @param job <code>SubInfo</code> object corresponding to the node to * which the files are to be transferred to. * @param files Collection of <code>FileTransfer</code> objects containing the * information about source and destURL's. * @param rcb bridge to the Replica Catalog. Used for creating registration * nodes in the workflow. * */ public void addStageOutXFERNodes(SubInfo job, Collection files, ReplicaCatalogBridge rcb ) { this.addStageOutXFERNodes( job, files, rcb, false); } /** * Adds the stageout transfer nodes, that stage data to an output site * specified by the user. * * @param job <code>SubInfo</code> object corresponding to the node to * which the files are to be transferred to. * @param files Collection of <code>FileTransfer</code> objects containing the * information about source and destURL's. * @param rcb bridge to the Replica Catalog. Used for creating registration * nodes in the workflow. * @param deletedLeaf to specify whether the node is being added for * a deleted node by the reduction engine or not. * default: false */ public void addStageOutXFERNodes(SubInfo job, Collection files, ReplicaCatalogBridge rcb, boolean deletedLeaf){ String jobName = job.getName(); int counter = 0; String newJobName = this.STAGE_OUT_PREFIX + jobName + "_" + counter; String regJob = this.REGISTER_PREFIX + jobName; mLogMsg = "Adding output pool nodes for job " + jobName; //separate the files for transfer //and for registration List txFiles = new ArrayList(); List regFiles = new ArrayList(); for(Iterator it = files.iterator();it.hasNext();){ FileTransfer ft = (FileTransfer) it.next(); if (!ft.getTransientTransferFlag()) { txFiles.add(ft); } if (!ft.getTransientRegFlag()) { regFiles.add(ft); } } boolean makeTNode = !txFiles.isEmpty(); boolean makeRNode = !regFiles.isEmpty(); if (!files.isEmpty()) { mLogger.log(mLogMsg,LogManager.DEBUG_MESSAGE_LEVEL); mLogMsg = "Adding new output pool node named " + newJobName; mLogger.log(mLogMsg,LogManager.DEBUG_MESSAGE_LEVEL); if (makeTNode) { //added in make transfer node //mDag.addNewJob(newJobName); addJob(mTXStageOutImplementation.createTransferJob(job, txFiles,null, newJobName, SubInfo.STAGE_OUT_JOB)); if (!deletedLeaf) { addRelation(jobName, newJobName); } if (makeRNode) { addRelation(newJobName, regJob); } } else if (!makeTNode && makeRNode) { addRelation(jobName, regJob); } if (makeRNode) { //call to make the reg subinfo //added in make registration node addJob(createRegistrationJob( regJob, job, regFiles, rcb )); } } } /** * Creates the registration jobs, which registers the materialized files on * the output site in the Replica Catalog. * * @param regJobName The name of the job which registers the files in the * Replica Mechanism. * @param job The job whose output files are to be registered in the * Replica Mechanism. * @param files Collection of <code>FileTransfer</code> objects containing * the information about source and destURL's. * @param rcb bridge to the Replica Catalog. Used for creating registration * nodes in the workflow. * * * @return the registration job. */ protected SubInfo createRegistrationJob(String regJobName, SubInfo job, Collection files, ReplicaCatalogBridge rcb ) { return rcb.makeRCRegNode( regJobName, job, files); } /** * Signals that the traversal of the workflow is done. This would allow * the transfer mechanisms to clean up any state that they might be keeping * that needs to be explicitly freed. */ public void done(){ } /** * Add a new job to the workflow being refined. * * @param job the job to be added. */ public void addJob(SubInfo job){ mDAG.add(job); } /** * Adds a new relation to the workflow being refiner. * * @param parent the jobname of the parent node of the edge. * @param child the jobname of the child node of the edge. */ public void addRelation(String parent, String child){ mLogger.log("Adding relation " + parent + " -> " + child, LogManager.DEBUG_MESSAGE_LEVEL); mDAG.addNewRelation(parent,child); } /** * Adds a new relation to the workflow. In the case when the parent is a * transfer job that is added, the parentNew should be set only the first * time a relation is added. For subsequent compute jobs that maybe * dependant on this, it needs to be set to false. * * @param parent the jobname of the parent node of the edge. * @param child the jobname of the child node of the edge. * @param site the execution pool where the transfer node is to be run. * @param parentNew the parent node being added, is the new transfer job * and is being called for the first time. */ public void addRelation(String parent, String child, String site, boolean parentNew){ mLogger.log("Adding relation " + parent + " -> " + child, LogManager.DEBUG_MESSAGE_LEVEL); mDAG.addNewRelation(parent,child); } /** * Returns a textual description of the transfer mode. * * @return a short textual description */ public String getDescription(){ return this.DESCRIPTION; } /** * Constructs the key for an entry to the file table. The key returned * is lfn:siteHandle * * @param lfn the logical filename of the file that has to be * transferred. * @param siteHandle the name of the site to which the file is being * transferred. * * @return the key for the entry to be made in the filetable. */ protected String constructFileKey(String lfn, String siteHandle) { StringBuffer sb = new StringBuffer(); sb.append(lfn).append(":").append(siteHandle); return sb.toString(); } }