answer
stringlengths 17
10.2M
|
|---|
import java.util.*;
public class MovementLogic
{
private static final int MOVED_OK = 0;
private static final int MOVE_FINISHED = 1;
private static final int DIRECTION_BLOCKED = 2;
private static final int MOVE_ERROR = 3;
private static final int LOCATION_VISITED = 4;
public static final int NUMBER_OF_FUNCTIONS = 3;
public MovementLogic (Map theMap, boolean debug)
{
_theMap = theMap;
_robotTrack = new Trail(_theMap);
_path = new Stack<String>();
_routeTaken = "";
_robotFacing = CellId.ROBOT_FACING_UP;
_currentMoveDirection = "";
_currentPosition = new Coordinate(_theMap.findStartingPoint());
_fullCommand = "";
_debug = debug;
}
public Vector<MovementFunction> createMovementFunctions ()
{
createPath();
FunctionRoutine routine = new FunctionRoutine(_path, _debug);
_fullCommand = routine.getCommandString();
return routine.createMovementFunctions();
}
public String getMainRoutine (Vector<MovementFunction> functions)
{
FunctionRoutine routine = new FunctionRoutine(_path, _debug);
MovementRoutine mr = new MovementRoutine(_fullCommand, functions, _debug);
return mr.getMainRoutine();
}
/*
* Create path using only L and R.
*/
private int createPath ()
{
if (_debug)
System.out.println("createPath from: "+_currentPosition);
if (_currentPosition != null)
{
/*
* Try L then R.
*
* Robot always starts facing up. Change facing when we
* start to move but remember initial facing so we can
* refer movement directions as L or R.
*/
if (tryToMove(CellId.MOVE_LEFT, leftCoordinate(_currentPosition)) != MOVE_FINISHED)
{
return tryToMove(CellId.MOVE_RIGHT, rightCoordinate(_currentPosition));
}
else
return MOVE_FINISHED;
}
else
{
System.out.println("Robot not found!");
return MOVE_ERROR;
}
}
private int tryToMove (String direction, Coordinate coord)
{
System.out.println("tryMove: "+coord+" with direction: "+direction);
System.out.println("and current position: "+_currentPosition);
/*
* Already visited? Might be sufficient to just check .path
*/
if (_robotTrack.visited(coord) && !_robotTrack.path(coord))
{
System.out.println("Robot already visited this location.");
return LOCATION_VISITED;
}
System.out.println("Location not visited ... yet.");
if (_theMap.isScaffold(coord))
{
System.out.println("Is scaffolding!");
_currentMoveDirection = direction;
System.out.println("Moving "+_currentMoveDirection);
_routeTaken += _currentMoveDirection;
_robotTrack.changeElement(coord, _currentMoveDirection);
_currentPosition = coord;
System.out.println("\n"+_robotTrack);
}
else
{
System.out.println("Not scaffolding!");
System.out.println("Robot was facing "+_robotFacing+" and moving "+direction);
_path.push(_routeTaken);
System.out.println("Pushing: "+_routeTaken);
_routeTaken = "";
if (_theMap.theEnd(_currentPosition))
return MOVE_FINISHED;
changeFacing();
System.out.println("Robot now facing "+_robotFacing);
String nextDirection = getNextDirection();
System.out.println("Next direction to try with new facing: "+nextDirection);
direction = nextDirection;
}
if (CellId.MOVE_LEFT.equals(direction))
coord = leftCoordinate(_currentPosition);
else
coord = rightCoordinate(_currentPosition);
return tryToMove(direction, coord);
}
private String getNextDirection ()
{
System.out.println("Getting next direction to move from: "+_currentPosition);
Coordinate coord = leftCoordinate(_currentPosition);
System.out.println("Left coordinate would be: "+coord);
if (_robotTrack.visited(coord) || !_robotTrack.isScaffold(coord))
{
System.out.println("Visited so try right ...");
coord = rightCoordinate(_currentPosition);
System.out.println("Right coordinate would be: "+coord);
if (_robotTrack.visited(coord))
return null;
else
return CellId.MOVE_RIGHT;
}
else
{
System.out.println("Not visited.");
return CellId.MOVE_LEFT;
}
}
private void changeFacing ()
{
switch (_robotFacing)
{
case CellId.ROBOT_FACING_UP:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_LEFT;
else
_robotFacing = CellId.ROBOT_FACING_RIGHT;
}
break;
case CellId.ROBOT_FACING_DOWN:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_RIGHT;
else
_robotFacing = CellId.ROBOT_FACING_LEFT;
}
break;
case CellId.ROBOT_FACING_LEFT:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_DOWN;
else
_robotFacing = CellId.ROBOT_FACING_UP;
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_UP;
else
_robotFacing = CellId.ROBOT_FACING_DOWN;
}
break;
}
}
/*
* Map/Trail can deal with invalid Coordinates.
*/
private final Coordinate rightCoordinate (Coordinate coord)
{
int x = coord.getX();
int y = coord.getY();
if (_debug)
System.out.println("rightCoordinate facing: "+_robotFacing+" and position: "+coord);
switch (_robotFacing)
{
case CellId.ROBOT_FACING_DOWN:
{
x
}
break;
case CellId.ROBOT_FACING_UP:
{
x++;
}
break;
case CellId.ROBOT_FACING_LEFT:
{
y
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
y++;
}
break;
}
return new Coordinate(x, y);
}
private final Coordinate leftCoordinate (Coordinate coord)
{
int x = coord.getX();
int y = coord.getY();
if (_debug)
System.out.println("leftCoordinate facing: "+_robotFacing+" and position: "+coord);
switch (_robotFacing)
{
case CellId.ROBOT_FACING_DOWN:
{
x++;
}
break;
case CellId.ROBOT_FACING_UP:
{
x
}
break;
case CellId.ROBOT_FACING_LEFT:
{
y++;
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
y
}
break;
}
return new Coordinate(x, y);
}
private Map _theMap;
private Trail _robotTrack;
private Stack<String> _path;
private String _routeTaken;
private String _robotFacing;
private String _currentMoveDirection;
private Coordinate _currentPosition;
private String _fullCommand;
private boolean _debug;
}
|
import java.util.*;
public class MovementLogic
{
public static final int ROUTINE_A = 0;
public static final int ROUTINE_B = 1;
public static final int ROUTINE_C = 2;
public static final int ROUTINE_D = 3;
public static final String MOVE_LEFT = "L";
public static final String MOVE_RIGHT = "R";
public MovementLogic (Map theMap, boolean debug)
{
_theMap = theMap;
_robotTrack = new Trail(_theMap);
_path = new Stack<String>();
_robotFacing = CellId.ROBOT_FACING_UP;
_currentMoveDirection = "";
_currentPosition = new Coordinate(_theMap.findStartingPoint());
_debug = debug;
}
public void createMovementFunctions ()
{
createPath();
String pathElement = _path.pop();
System.out.println("Path:");
while (pathElement != null)
{
System.out.println(pathElement);
try
{
_path.pop();
}
catch (Exception ex)
{
pathElement = null;
}
}
}
public void createMovementRoutine ()
{
}
/*
* Create path using only L and R.
*/
private boolean createPath ()
{
System.out.println("createPath from: "+_currentPosition);
if (_currentPosition != null)
{
/*
* Try L then R.
*
* Robot always starts facing up. Change facing when we
* start to move but remember initial facing so we can
* refer movement directions as L or R.
*/
if (!tryToMove(MOVE_LEFT, leftCoordinate(_currentPosition)))
{
return tryToMove(MOVE_RIGHT, rightCoordinate(_currentPosition));
}
else
return true;
}
else
{
System.out.println("Robot not found!");
return false;
}
}
private boolean tryToMove (String direction, Coordinate coord)
{
System.out.println("tryMove: "+coord+" with direction: "+direction);
if (_robotTrack.visited(coord))
{
System.out.println("Robot already visited this location.");
return false;
}
System.out.println("Location not visited ... yet.");
if (_theMap.isScaffold(coord))
{
System.out.println("Is scaffolding!");
_currentMoveDirection = direction;
_path.push(_currentMoveDirection);
_robotTrack.changeElement(coord, _currentMoveDirection);
_currentPosition = coord;
System.out.println("\n"+_robotTrack);
return createPath();
}
else
{
System.out.println("Not scaffolding!");
System.out.println("Robot was facing "+_robotFacing+" and moving "+direction);
changeFacing();
System.out.println("Robot now facing "+_robotFacing);
String nextDirection = getNextDirection();
System.out.println("Next direction to try with new facing: "+nextDirection);
if (MOVE_LEFT.equals(nextDirection))
coord = leftCoordinate(_currentPosition);
else
coord = rightCoordinate(_currentPosition);
return tryToMove(nextDirection, coord);
}
}
private String getNextDirection ()
{
System.out.println("Getting next direction to move from: "+_currentPosition);
Coordinate coord = leftCoordinate(_currentPosition);
System.out.println("Left coordinate would be: "+coord);
if (_robotTrack.visited(coord) || !_robotTrack.isScaffold(coord))
{
System.out.println("Visited so try right ...");
coord = rightCoordinate(_currentPosition);
System.out.println("Right coordinate would be: "+coord);
if (_robotTrack.visited(coord))
return null;
else
return MOVE_RIGHT;
}
else
{
System.out.println("Not visited.");
return MOVE_LEFT;
}
}
private void changeFacing ()
{
switch (_robotFacing)
{
case CellId.ROBOT_FACING_UP:
{
if (_currentMoveDirection.equals(MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_LEFT;
else
_robotFacing = CellId.ROBOT_FACING_RIGHT;
}
break;
case CellId.ROBOT_FACING_DOWN:
{
if (_currentMoveDirection.equals(MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_RIGHT;
else
_robotFacing = CellId.ROBOT_FACING_LEFT;
}
break;
case CellId.ROBOT_FACING_LEFT:
{
if (_currentMoveDirection.equals(MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_DOWN;
else
_robotFacing = CellId.ROBOT_FACING_UP;
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
if (_currentMoveDirection.equals(MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_UP;
else
_robotFacing = CellId.ROBOT_FACING_DOWN;
}
break;
}
}
private final Coordinate rightCoordinate (Coordinate coord)
{
int x = coord.getX();
int y = coord.getY();
System.out.println("rightCoordinate facing: "+_robotFacing+" and position: "+coord);
switch (_robotFacing)
{
case CellId.ROBOT_FACING_DOWN:
{
x
}
break;
case CellId.ROBOT_FACING_UP:
{
x++;
}
break;
case CellId.ROBOT_FACING_LEFT:
{
y
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
y++;
}
break;
}
return new Coordinate(x, y);
}
private final Coordinate leftCoordinate (Coordinate coord)
{
int x = coord.getX();
int y = coord.getY();
System.out.println("leftCoordinate facing: "+_robotFacing+" and position: "+coord);
switch (_robotFacing)
{
case CellId.ROBOT_FACING_DOWN:
{
x++;
}
break;
case CellId.ROBOT_FACING_UP:
{
x
}
break;
case CellId.ROBOT_FACING_LEFT:
{
y++;
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
y
}
break;
}
return new Coordinate(x, y);
}
private Map _theMap;
private Trail _robotTrack;
private Stack<String> _path;
private String _robotFacing;
private String _currentMoveDirection;
private Coordinate _currentPosition;
private boolean _debug;
}
|
// (Java Object Relational Adapter) * /\| *
// Created: 10-Jun-98 K.A. Knizhnik * / [] \ *
// Class representing database table
package com.samskivert.jdbc.jora;
import java.util.*;
import java.sql.*;
import java.lang.reflect.*;
/** Table class is used to establish mapping between corteges of database
* tables and Java classes. This class is responsible for constructing
* SQL statements for extracting, updating and deleting records of the
* database table.
*/
public class Table {
/** Constructor for table object. Make association between Java class
* and database table.
*
* @param tclassName name of Java class
* @param tableName name of database table mapped on this Java class
* @param key table's primary key. This parameter is used in UPDATE/DELETE
* operations to locate record in the table.
* @param s session, which should be opened before first access to the table
*/
public Table(String className, String tableName, Session s, String key) {
String[] keys = {key};
init(className, tableName, s, keys);
}
/** Constructor for table object. Make association between Java class
* and database table.
*
* @param tclassName name of Java class
* @param tableName name of database table mapped on this Java class
* @param keys table primary keys. This parameter is used in UPDATE/DELETE
* operations to locate record in the table.
* @param s session, which should be opened before first access to the table
*/
public Table(String className, String tableName, Session s, String[] keys)
{
init(className, tableName, s, keys);
}
/** Constructor for table object. Make association between Java class
* and database table. Name of Java class should be the same as name of
* the database table
*
* @param className name of Java class, which should be (without
* package prefix) be the same as the name of database table.
* @param keys table primary keys. This parameter is used in UPDATE/DELETE
* operations to locate record in the table.
* @param s session, which should be opened before first access to the table
*/
public Table(String className, Session s, String[] keys) {
init(className, className.substring(className.lastIndexOf('.')+1),
s, keys);
}
/** Constructor for table object. Make association between Java class
* and database table. Name of Java class should be the same as name of
* the database table
*
* @param className name of Java class, which should be (without
* package prefix) be the same as the name of database table.
* @param key table primary key. This parameter is used in UPDATE/DELETE
* operations to locate record in the table.
* @param s session, which should be opened before first access to the table
*/
public Table(String className, Session s, String key) {
String[] keys = {key};
init(className, className.substring(className.lastIndexOf('.')+1),
s, keys);
}
/** Constructor of table without explicit key specification.
* Specification of key is necessary for update/remove operations.
* If key is not specified, it is inherited from base table (if any).
*/
public Table(String className, Session s) {
init(className, className.substring(className.lastIndexOf('.')+1),
s, null);
}
/** Constructor of table with "key" and "session" parameters inherited
* from base table.
*/
public Table(String className) {
init(className, className.substring(className.lastIndexOf('.')+1),
null, null);
}
/** Select records from database table according to search condition
*
* @param condition valid SQL condition expression started with WHERE
* or empty string if all records should be fetched.
*/
public final Cursor select(String condition) {
String query = "select " + listOfFields + " from " + name +
" " + condition;
return new Cursor(this, session, 1, query);
}
/** Select records from database table according to search condition
* including the specified (comma separated) extra tables into the
* SELECT clause to facilitate a join in determining the key.
*
* @param tables the (comma separated) names of extra tables to
* include in the SELECT clause.
* @param condition valid SQL condition expression started with WHERE.
*/
public final Cursor select(String tables, String condition) {
String query = "select " + qualifiedListOfFields +
" from " + name + "," + tables + " " + condition;
return new Cursor(this, session, 1, query);
}
/** Select records from database table according to search condition
*
* @param condition valid SQL condition expression started with WHERE
* or empty string if all records should be fetched.
* @param session user database session
*/
public final Cursor select(String condition, Session session) {
String query = "select " + listOfFields + " from " + name +
" " + condition;
return new Cursor(this, session, 1, query);
}
/** Select records from specified and derived database tables
*
* @param condition valid SQL condition expression started with WHERE
* or empty string if all records should be fetched.
*/
public final Cursor selectAll(String condition) {
return new Cursor(this, session, nDerived+1, condition);
}
/** Select records from specified and derived database tables
*
* @param condition valid SQL condition expression started with WHERE
* or empty string if all records should be fetched.
* @param session user database session
*/
public final Cursor selectAll(String condition, Session session) {
return new Cursor(this, session, nDerived+1, condition);
}
/** Select records from database table using <I>obj</I> object as
* template for selection. All non-builtin fields of this object,
* which are not null, are compared with correspondent table values.
*
* @param obj object for construction search condition: selected objects
* should match all non-null fields of specified object.
*/
public final Cursor queryByExample(Object obj) {
return new Cursor(this, session, 1, obj);
}
/** Select records from database table using <I>obj</I> object as
* template for selection. All non-builtin fields of this object,
* which are not null, are compared with correspondent table values.
*
* @param obj object for construction search condition: selected objects
* should match all non-null fields of specified object.
* @param session user database session
*/
public final Cursor queryByExample(Object obj, Session session) {
return new Cursor(this, session, 1, obj);
}
/** Select records from specified and derived database tables using
* <I>obj</I> object as template for selection.
* All non-builtin fields of this object,
* which are not null, are compared with correspondent table values.
*
* @param obj object for construction search condition: selected objects
* should match all non-null fields of specified object.
*/
public final Cursor queryAllByExample(Object obj) {
return new Cursor(this, session, nDerived+1, obj);
}
/** Select records from specified and derived database tables using
* <I>obj</I> object as template for selection.
* All non-builtin fields of this object,
* which are not null, are compared with correspondent table values.
*
* @param obj object for construction search condition: selected objects
* should match all non-null fields of specified object.
* @param session user database session
*/
public final Cursor queryAllByExample(Object obj, Session session) {
return new Cursor(this, session, nDerived+1, obj);
}
/** Insert new record in the table. Values of inserted record fields
* are taken from specifed object.
*
* @param obj object specifing values of inserted record fields
*/
public void insert(Object obj)
throws SQLException
{
insert(obj, session);
}
/** Insert new record in the table using specified database session.
* Values of inserted record fields
* are taken from specifed object.
*
* @param obj object specifing values of inserted record fields
* @param session user database session
*/
public synchronized void insert(Object obj, Session session)
throws SQLException
{
if (session == null) {
session = ((SessionThread)Thread.currentThread()).session;
}
// try {
checkConnection(session);
if (insertStmt == null) {
String sql = "insert into " + name + " ("
+ listOfFields + ") values (?";
for (int i = 1; i < nColumns; i++) {
sql += ",?";
}
sql += ")";
insertStmt = session.connection.prepareStatement(sql);
}
bindUpdateVariables(insertStmt, obj);
insertStmt.executeUpdate();
insertStmt.clearParameters();
// } catch(SQLException ex) { session.handleSQLException(ex); }
}
/** Insert several new records in the table. Values of inserted records
* fields are taken from objects of specified array.
*
* @param objects array with objects specifing values of inserted record
* fields
*/
public void insert(Object[] objects)
throws SQLException
{
insert(objects, session);
}
/** Insert several new records in the table. Values of inserted records
* fields are taken from objects of specified array.
*
* @param objects array with objects specifing values of inserted record
* fields
* @param session user database session
*/
public synchronized void insert(Object[] objects, Session session)
throws SQLException
{
if (session == null) {
session = ((SessionThread)Thread.currentThread()).session;
}
// try {
checkConnection(session);
if (insertStmt == null) {
String sql = "insert into " + name + " ("
+ listOfFields + ") values (?";
for (int i = 1; i < nColumns; i++) {
sql += ",?";
}
sql += ")";
insertStmt = session.connection.prepareStatement(sql);
}
for (int i = 0; i < objects.length; i++) {
bindUpdateVariables(insertStmt, objects[i]);
insertStmt.addBatch();
}
insertStmt.executeBatch();
insertStmt.clearParameters();
// } catch(SQLException ex) { session.handleSQLException(ex); }
}
/** Update record in the table using table's primary key to locate
* record in the table and values of fields of specified object <I>obj</I>
* to alter record fields.
*
* @param obj object specifing value of primary key and new values of
* updated record fields
*
* @return number of objects actually updated
*/
public int update(Object obj)
throws SQLException
{
return update(obj, session);
}
/** Update record in the table using table's primary key to locate
* record in the table and values of fields of specified object <I>obj</I>
* to alter record fields.
*
* @param obj object specifing value of primary key and new values of
* updated record fields
* @param session user database session
*
* @return number of objects actually updated
*/
public synchronized int update(Object obj, Session session)
throws SQLException
{
if (primaryKeys == null) {
throw new NoPrimaryKeyError(this);
}
if (session == null) {
session = ((SessionThread)Thread.currentThread()).session;
}
int nUpdated = 0;
// try {
checkConnection(session);
if (updateStmt == null) {
String sql = "update " + name + " set " + listOfAssignments
+ " where " + primaryKeys[0] + " = ?";
for (int i = 1; i < primaryKeys.length; i++) {
sql += " and " + primaryKeys[i] + " = ?";
}
updateStmt = session.connection.prepareStatement(sql);
}
for (int i = 0; i < primaryKeys.length; i++) {
fields[primaryKeyIndices[i]].bindVariable(updateStmt, obj,
nColumns+i+1);
}
bindUpdateVariables(updateStmt, obj);
nUpdated = updateStmt.executeUpdate();
updateStmt.clearParameters();
// } catch(SQLException ex) { session.handleSQLException(ex); }
return nUpdated;
}
/** Update set of records in the table using table's primary key to locate
* record in the table and values of fields of objects from sepecifed
* array <I>objects</I> to alter record fields.
*
* @param objects array of objects specifing primiray keys and and new
* values of updated record fields
*
* @return number of objects actually updated
*/
public int update(Object[] objects)
throws SQLException
{
return update(objects, session);
}
/** Update set of records in the table using table's primary key to locate
* record in the table and values of fields of objects from sepecifed
* array <I>objects</I> to alter record fields.
*
* @param objects array of objects specifing primiray keys and and new
* values of updated record fields
* @param session user database session
*
* @return number of objects actually updated
*/
public synchronized int update(Object[] objects, Session session)
throws SQLException
{
if (primaryKeys == null) {
throw new NoPrimaryKeyError(this);
}
if (session == null) {
session = ((SessionThread)Thread.currentThread()).session;
}
int nUpdated = 0;
// try {
checkConnection(session);
if (updateStmt == null) {
String sql = "update " + name + " set " + listOfAssignments
+ " where " + primaryKeys[0] + " = ?";
for (int i = 1; i < primaryKeys.length; i++) {
sql += " and " + primaryKeys[i] + " = ?";
}
updateStmt = session.connection.prepareStatement(sql);
}
for (int i = 0; i < objects.length; i++) {
for (int j = 0; j < primaryKeys.length; j++) {
fields[primaryKeyIndices[j]].bindVariable(updateStmt,
objects[i],
nColumns+1+j);
}
bindUpdateVariables(updateStmt, objects[i]);
updateStmt.addBatch();
}
int rc[] = updateStmt.executeBatch();
for (int k = 0; k < rc.length; k++) {
nUpdated += rc[k];
}
updateStmt.clearParameters();
// } catch(SQLException ex) { session.handleSQLException(ex); }
return nUpdated;
}
/** Delete record with specified value of primary key from the table.
*
* @param obj object containing value of primary key.
*
* @return number of objects actually deleted
*/
public int delete(Object obj)
throws SQLException
{
return delete(obj, session);
}
/** Delete record with specified value of primary key from the table.
*
* @param obj object containing value of primary key.
* @param session user database session
*/
public synchronized int delete(Object obj, Session session)
throws SQLException
{
if (primaryKeys == null) {
throw new NoPrimaryKeyError(this);
}
if (session == null) {
session = ((SessionThread)Thread.currentThread()).session;
}
int nDeleted = 0;
// try {
checkConnection(session);
if (deleteStmt == null) {
String sql = "delete from " + name +
" where " + primaryKeys[0] + " = ?";
for (int i = 1; i < primaryKeys.length; i++) {
sql += " and " + primaryKeys[i] + " = ?";
}
deleteStmt = session.connection.prepareStatement(sql);
}
for (int i = 0; i < primaryKeys.length; i++) {
fields[primaryKeyIndices[i]].bindVariable(deleteStmt, obj,i+1);
}
nDeleted = deleteStmt.executeUpdate();
deleteStmt.clearParameters();
// } catch(SQLException ex) { session.handleSQLException(ex); }
return nDeleted;
}
/** Delete records with specified primary keys from the table.
*
* @param objects array of objects containing values of primary key.
*
* @return number of objects actually deleted
*/
public int delete(Object[] objects)
throws SQLException
{
return delete(objects, session);
}
/** Delete records with specified primary keys from the table.
*
* @param objects array of objects containing values of primary key.
*
* @return number of objects actually deleted
*/
public synchronized int delete(Object[] objects, Session session)
throws SQLException
{
if (primaryKeys == null) {
throw new NoPrimaryKeyError(this);
}
if (session == null) {
session = ((SessionThread)Thread.currentThread()).session;
}
int nDeleted = 0;
// try {
checkConnection(session);
if (deleteStmt == null) {
String sql = "delete from " + name +
" where " + primaryKeys[0] + " = ?";
for (int i = 1; i < primaryKeys.length; i++) {
sql += " and " + primaryKeys[i] + " = ?";
}
deleteStmt = session.connection.prepareStatement(sql);
}
for (int i = 0; i < objects.length; i++) {
for (int j = 0; j < primaryKeys.length; j++) {
fields[primaryKeyIndices[j]].bindVariable(deleteStmt,
objects[i], j+1);
}
deleteStmt.addBatch();
}
int rc[] = deleteStmt.executeBatch();
for (int k = 0; k < rc.length; k++) {
nDeleted += rc[k];
}
deleteStmt.clearParameters();
// } catch(SQLException ex) { session.handleSQLException(ex); }
return nDeleted;
}
/**
* Configures the table to convert mixed case Java fields
* (e.g. <code>locationId</code>) into underscore separated uppercase
* fields (e.g. <code>LOCATION_ID</code>).
*/
public void setMixedCaseConvert (boolean mixedCaseConvert)
{
this.mixedCaseConvert = mixedCaseConvert;
}
/** Spearator of name components of compound field. For example, if Java
* class constains component "location" of Point class, which
* has two components "x" and "y", then database table should
* have columns "location_x" and "location_y" (if '_' is used
* as separator)
*/
public static String fieldSeparator = "_";
/** Some versions of JDBC driver doesn't support
* <code>getBigDecimal(int columnIndex)</code>. Setting this variable to
* <code>true</code> makes JORA to explicitly request scale from result
* set metadata and use deprecated version of <code>getBigDecimal</code>
* with extra <code>scale</code> parameter.
*/
public static boolean useDepricatedGetBigDecimal = true;
/** Is table abstract - not present in database.
*/
protected boolean isAbstract;
protected Table derived;
protected int nDerived;
protected String name;
protected String listOfFields;
protected String qualifiedListOfFields;
protected String listOfAssignments;
protected Class cls;
protected Session session;
protected boolean mixedCaseConvert = false;
static private Class serializableClass;
private FieldDescriptor[] fields;
private int nFields; // length of "fields" array
private int nColumns; // number of atomic fields in "fields" array
private String primaryKeys[];
private int primaryKeyIndices[];
protected int connectionID;
private PreparedStatement updateStmt;
private PreparedStatement deleteStmt;
private PreparedStatement insertStmt;
private static Table allTables;
private Constructor constructor;
private static Method setBypass;
private static final Object[] bypassFlag = { new Boolean(true) };
private static final Object[] constructorArgs = {};
static {
try {
serializableClass = Class.forName("java.io.Serializable");
Class c = Class.forName("java.lang.reflect.AccessibleObject");
Class[] param = { Boolean.TYPE };
setBypass = c.getMethod("setAccessible", param);
} catch(Exception ex) {}
}
private final void init(String className, String tableName, Session s,
String[] keys)
{
name = tableName;
try {
cls = Class.forName(className);
} catch(ClassNotFoundException ex) {throw new NoClassDefFoundError();}
isAbstract = tableName == null;
session = s;
primaryKeys = keys;
listOfFields = "";
qualifiedListOfFields = "";
listOfAssignments = "";
connectionID = 0;
Vector fieldsVector = new Vector();
nFields = buildFieldsList(fieldsVector, cls, "");
fields = new FieldDescriptor[nFields];
fieldsVector.copyInto(fields);
try {
constructor = cls.getDeclaredConstructor(new Class[0]);
setBypass.invoke(constructor, bypassFlag);
} catch(Exception ex) {}
if (keys != null) {
if (keys.length == 0) {
throw new NoPrimaryKeyError(this);
}
primaryKeyIndices = new int[keys.length];
for (int j = keys.length; --j >= 0;) {
int i = nFields;
while (--i >= 0) {
if (fields[i].name.equals(keys[j])) {
if (!fields[i].isAtomic()) {
throw new NoPrimaryKeyError(this);
}
primaryKeyIndices[j] = i;
break;
}
}
if (i < 0) {
throw new NoSuchFieldError("No such field '" + keys[j]
+ "' in table " + name);
}
}
}
insertIntoTableHierarchy();
}
private final void insertIntoTableHierarchy()
{
Table t, prev = null;
Table after = null;
int nChilds = 0;
for (t = allTables; t != null; prev = t, t = t.derived) {
if (t.cls.isAssignableFrom(cls)) {
if (primaryKeys == null && t.primaryKeys != null) {
primaryKeys = t.primaryKeys;
primaryKeyIndices = t.primaryKeyIndices;
}
if (session == null) {
session = t.session;
}
t.nDerived += 1;
after = t;
} else if (cls.isAssignableFrom(t.cls)) {
after = prev;
do {
if (cls.isAssignableFrom(t.cls)) {
if (primaryKeys != null && t.primaryKeys == null) {
t.primaryKeys = primaryKeys;
t.primaryKeyIndices = primaryKeyIndices;
}
if (t.session == null) {
t.session = session;
}
nChilds += 1;
}
} while ((t = t.derived) != null);
break;
}
}
if (after == null) {
derived = allTables;
allTables = this;
} else {
derived = after.derived;
after.derived = this;
}
nDerived = nChilds;
}
private final void checkConnection(Session s) throws SQLException {
if (connectionID != s.connectionID) {
if (insertStmt != null) {
insertStmt.close();
insertStmt = null;
}
if (updateStmt != null) {
updateStmt.close();
updateStmt = null;
}
if (deleteStmt != null) {
deleteStmt.close();
deleteStmt = null;
}
connectionID = s.connectionID;
}
}
private final String convertName (String name)
{
if (mixedCaseConvert) {
boolean seenLower = false;
StringBuffer nname = new StringBuffer();
int nlen = name.length();
for (int i = 0; i < nlen; i++) {
char c = name.charAt(i);
// if we see an upper case character and we've seen a lower
// case character since the last time we did so, slip in an _
if (Character.isUpperCase(c)) {
nname.append("_");
seenLower = false;
nname.append(c);
} else {
seenLower = true;
nname.append(Character.toUpperCase(c));
}
}
return nname.toString();
} else {
return name;
}
}
private final int buildFieldsList(Vector buf, Class cls, String prefix)
{
Field[] f = cls.getDeclaredFields();
Class superclass = cls;
while ((superclass = superclass.getSuperclass()) != null) {
Field[] inheritedFields = superclass.getDeclaredFields();
Field[] allFields = new Field[inheritedFields.length + f.length];
System.arraycopy(inheritedFields, 0, allFields, 0,
inheritedFields.length);
System.arraycopy(f,0, allFields, inheritedFields.length, f.length);
f = allFields;
}
try {
for (int i = f.length; --i>= 0;) {
setBypass.invoke(f[i], bypassFlag);
}
} catch(Exception ex) {
System.err.println("Failed to set bypass attribute");
}
int n = 0;
for (int i = 0; i < f.length; i++) {
if ((f[i].getModifiers()&(Modifier.TRANSIENT|Modifier.STATIC))==0)
{
String name = f[i].getName();
Class fieldClass = f[i].getType();
String fullName = prefix + convertName(name);
FieldDescriptor fd = new FieldDescriptor(f[i], fullName);
int type;
buf.addElement(fd);
n += 1;
String c = fieldClass.getName();
if (c.equals("byte")) type = FieldDescriptor.t_byte;
else if (c.equals("short")) type = FieldDescriptor.t_short;
else if (c.equals("int")) type = FieldDescriptor.t_int;
else if (c.equals("long")) type = FieldDescriptor.t_long;
else if (c.equals("float")) type = FieldDescriptor.t_float;
else if (c.equals("double")) type = FieldDescriptor.t_double;
else if (c.equals("boolean")) type = FieldDescriptor.t_boolean;
else if (c.equals("java.lang.Byte"))
type = FieldDescriptor.tByte;
else if (c.equals("java.lang.Short"))
type = FieldDescriptor.tShort;
else if (c.equals("java.lang.Integer"))
type = FieldDescriptor.tInteger;
else if (c.equals("java.lang.Long"))
type = FieldDescriptor.tLong;
else if (c.equals("java.lang.Float"))
type = FieldDescriptor.tFloat;
else if (c.equals("java.lang.Double"))
type = FieldDescriptor.tDouble;
else if (c.equals("java.lang.Boolean"))
type = FieldDescriptor.tBoolean;
else if (c.equals("java.math.BigDecimal"))
type = FieldDescriptor.tDecimal;
else if (c.equals("java.lang.String"))
type = FieldDescriptor.tString;
else if (fieldClass.equals(BYTE_PROTO.getClass()))
type = FieldDescriptor.tBytes;
else if (c.equals("java.sql.Date"))
type = FieldDescriptor.tDate;
else if (c.equals("java.sql.Time"))
type = FieldDescriptor.tTime;
else if (c.equals("java.sql.Timestamp"))
type = FieldDescriptor.tTimestamp;
else if (c.equals("java.lang.InputStream"))
type = FieldDescriptor.tStream;
else if (c.equals("java.sql.BlobLocator"))
type = FieldDescriptor.tBlob;
else if (c.equals("java.sql.ClobLocator"))
type = FieldDescriptor.tClob;
else if (serializableClass.isAssignableFrom(fieldClass))
type = FieldDescriptor.tClosure;
else {
int nComponents = buildFieldsList(buf, fieldClass,
fd.name+fieldSeparator);
fd.inType = fd.outType =
FieldDescriptor.tCompound + nComponents;
try {
fd.constructor =
fieldClass.getDeclaredConstructor(new Class[0]);
setBypass.invoke(fd.constructor, bypassFlag);
} catch(Exception ex) {}
n += nComponents;
continue;
}
if (listOfFields.length() != 0) {
listOfFields += ",";
qualifiedListOfFields += ",";
listOfAssignments += ",";
}
listOfFields += fullName;
qualifiedListOfFields += this.name + "." + fullName;
listOfAssignments += fullName + "=?";
fd.inType = fd.outType = type;
nColumns += 1;
}
}
return n;
}
protected final Object load(ResultSet result) throws SQLException {
Object obj;
try {
obj = constructor.newInstance(constructorArgs);
}
catch(IllegalAccessException ex) { throw new IllegalAccessError(); }
catch(InstantiationException ex) { throw new InstantiationError(); }
catch(Exception ex) {
throw new InstantiationError("Exception was thrown by constructor");
}
load(obj, 0, nFields, 0, result);
return obj;
}
private final int load(Object obj, int i, int end, int column,
ResultSet result)
throws SQLException
{
try {
while (i < end) {
FieldDescriptor fd = fields[i++];
if (!fd.loadVariable(result, obj, ++column)) {
Object component =
fd.constructor.newInstance(constructorArgs);
fd.field.set(obj, component);
int nComponents = fd.inType - FieldDescriptor.tCompound;
column = load(component, i, i + nComponents,
column-1, result);
i += nComponents;
}
}
}
catch(IllegalAccessException ex) { throw new IllegalAccessError(); }
catch(InstantiationException ex) { throw new InstantiationError(); }
catch(InvocationTargetException ex) {
throw new InstantiationError("Exception was thrown by constructor");
}
return column;
}
protected final void bindUpdateVariables(PreparedStatement pstmt,
Object obj)
throws SQLException
{
bindUpdateVariables(pstmt, obj, 0, nFields, 0);
}
protected final void bindQueryVariables(PreparedStatement pstmt,
Object obj)
throws SQLException
{
bindQueryVariables(pstmt, obj, 0, nFields, 0);
}
protected final void updateVariables(ResultSet result, Object obj)
throws SQLException
{
updateVariables(result, obj, 0, nFields, 0);
result.updateRow();
}
protected final String buildQueryList(Object qbe)
{
StringBuffer buf = new StringBuffer();
buildQueryList(buf, qbe, 0, nFields);
if (buf.length() > 0) {
buf.insert(0, " where ");
}
return "select " + listOfFields + " from " + name + buf;
}
private final int bindUpdateVariables(PreparedStatement pstmt, Object obj,
int i, int end, int column)
throws SQLException
{
try {
while (i < end) {
FieldDescriptor fd = fields[i++];
Object comp = null;
if (!fd.isBuiltin() && (comp = fd.field.get(obj)) == null) {
if (fd.isCompound()) {
int nComponents = fd.outType-FieldDescriptor.tCompound;
while (--nComponents >= 0) {
fd = fields[i++];
if (!fd.isCompound()) {
pstmt.setNull(++column,
FieldDescriptor.sqlTypeMapping[fd.outType]);
}
}
} else {
pstmt.setNull(++column,
FieldDescriptor.sqlTypeMapping[fd.outType]);
}
} else {
if (!fd.bindVariable(pstmt, obj, ++column)) {
int nComponents = fd.outType-FieldDescriptor.tCompound;
column = bindUpdateVariables(pstmt, comp,
i,i+nComponents,column-1);
i += nComponents;
}
}
}
} catch(IllegalAccessException ex) { throw new IllegalAccessError(); }
return column;
}
private final int bindQueryVariables(PreparedStatement pstmt, Object obj,
int i, int end, int column)
throws SQLException
{
try {
while (i < end) {
Object comp;
FieldDescriptor fd = fields[i++];
if (!fd.field.getDeclaringClass().isInstance(obj)) {
return column;
}
int nComponents =
fd.isCompound() ? fd.outType-FieldDescriptor.tCompound : 0;
if (!fd.isBuiltin()
&& fd.outType != FieldDescriptor.tClosure
&& (comp = fd.field.get(obj)) != null)
{
if (!fd.bindVariable(pstmt, obj, ++column)) {
column = bindQueryVariables(pstmt, comp,
i,i+nComponents,column-1);
}
}
i += nComponents;
}
} catch(IllegalAccessException ex) { throw new IllegalAccessError(); }
return column;
}
private final void buildQueryList(StringBuffer buf, Object qbe,
int i, int end)
{
try {
while (i < end) {
Object comp;
FieldDescriptor fd = fields[i++];
int nComponents =
fd.isCompound() ? fd.outType-FieldDescriptor.tCompound : 0;
if (!fd.isBuiltin()
&& fd.outType != FieldDescriptor.tClosure
&& (comp = fd.field.get(qbe)) != null)
{
if (nComponents != 0) {
buildQueryList(buf, comp, i, i+nComponents);
} else {
if (buf.length() != 0) {
buf.append(",");
}
buf.append(fd.name);
buf.append("=?");
}
}
i += nComponents;
}
} catch(IllegalAccessException ex) { throw new IllegalAccessError(); }
}
protected final int updateVariables(ResultSet result, Object obj,
int i, int end, int column)
throws SQLException
{
try {
while (i < end) {
FieldDescriptor fd = fields[i++];
Object comp = null;
if (!fd.isBuiltin() && (comp = fd.field.get(obj)) == null) {
if (fd.isCompound()) {
int nComponents = fd.outType-FieldDescriptor.tCompound;
while (--nComponents >= 0) {
fd = fields[i++];
if (!fd.isCompound()) {
result.updateNull(++column);
}
}
} else {
result.updateNull(++column);
}
} else {
if (!fd.updateVariable(result, obj, ++column)) {
int nComponents = fd.outType-FieldDescriptor.tCompound;
column = updateVariables(result, comp,
i, i+nComponents, column-1);
i += nComponents;
}
}
}
} catch(IllegalAccessException ex) { throw new IllegalAccessError(); }
return column;
}
// used to identify byte[] fields
private static final byte[] BYTE_PROTO = new byte[0];
}
|
package com.relayrides.pushy.apns;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class TopicUtilTest {
private static final String SINGLE_TOPIC_CERTIFICATE_FILE = "/single-topic-client.pem";
private static final String MULTI_TOPIC_CERTIFICATE_FILE = "/multi-topic-client.pem";
@Test
public void testExtractApnsTopicsFromSingleTopicCertificate() throws Exception {
final Certificate singleTopicCertificate = TopicUtilTest.loadCertificateFromResource(SINGLE_TOPIC_CERTIFICATE_FILE);
final Set<String> expectedTopics = new HashSet<String>(Arrays.asList("com.relayrides.pushy"));
assertEquals(expectedTopics, TopicUtil.extractApnsTopicsFromCertificate(singleTopicCertificate));
}
@Test
public void testExtractApnsTopicsFromMultiTopicCertificate() throws Exception {
final Certificate multiTopicCertificate = TopicUtilTest.loadCertificateFromResource(MULTI_TOPIC_CERTIFICATE_FILE);
final Set<String> expectedTopics = new HashSet<String>(
Arrays.asList("com.relayrides.pushy", "com.relayrides.pushy.voip", "com.relayrides.pushy.complication"));
assertEquals(expectedTopics, TopicUtil.extractApnsTopicsFromCertificate(multiTopicCertificate));
}
private static Certificate loadCertificateFromResource(final String resourceName) throws CertificateException, IOException {
try (final InputStream certificateInputStream = TopicUtilTest.class.getResourceAsStream(resourceName)) {
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
return certificateFactory.generateCertificate(certificateInputStream);
}
}
}
|
// Seth Hoenig 2013
// I herby declare this piece of crap to be in the public domain.
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URI;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
import java.lang.reflect.Method;
public final class JarInspector {
public static void main(String[] args) throws IOException, InterruptedException, MalformedURLException {
if (args.length != 1) {
System.err.println("Usage: java JarInspector [jar file]");
return;
}
System.out.println("Going to inspect jar file: " + args[0]);
File jf = getJarFile(args[0]);
System.out.println("jf path: " + jf.getCanonicalPath());
String rawlist = execute(new String[]{"jar", "-tf", jf.getCanonicalPath()});
List<String> classes = listOfClassFiles(rawlist);
for (String s : classes) {
String className = path2pkg(s);
System.out.println("className: " + className);
Class<?> c = extractClassFromJar(jf, className);
if (c != null) {
System.out.println(" EXTRACTED: " + c);
processClass(c);
}
else
System.out.println(" FAILED");
}
}
private static File getJarFile(String jarname) {
File f = new File(jarname);
if (!f.exists())
throw new IllegalArgumentException(jarname + " does not exist");
return f;
}
private static Class<?> extractClassFromJar(File jar, String klass) throws MalformedURLException {
URL jurl = jar.toURI().toURL();
URL[] jurls = new URL[]{jurl};
ClassLoader loader = new URLClassLoader(jurls);
try {
Class<?> c = loader.loadClass(klass);
return c;
} catch(Throwable t) { // screw you too, Java
return null;
}
}
private static void processClass(Class<?> klass) {
Method[] methods = klass.getDeclaredMethods();
for(Method m : methods)
System.out.println(" " + m);
}
private static String execute(String[] cmd) throws IOException, InterruptedException {
StringBuffer out = new StringBuffer();
Process proc = Runtime.getRuntime().exec(cmd);
proc.waitFor();
InputStream is = proc.getInputStream();
int c;
while ((c = is.read()) != -1)
out.append((char)c);
is.close();
return out.toString();
}
private static List<String> listOfClassFiles(String rawOutput) {
List<String> result = new ArrayList<>();
String[] toks = rawOutput.split("\\s+");
for (String line : toks)
if (line.endsWith(".class"))
result.add(line);
return result;
}
private static String path2pkg(String path) {
return path.replaceAll("/", ".").replaceAll(".class", "");
}
}
|
package net.somethingdreadful.MAL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.squareup.picasso.Picasso;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.MALApi.ListType;
import net.somethingdreadful.MAL.api.response.Anime;
import net.somethingdreadful.MAL.api.response.GenericRecord;
import net.somethingdreadful.MAL.api.response.Manga;
import net.somethingdreadful.MAL.tasks.NetworkTask;
import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
import net.somethingdreadful.MAL.tasks.WriteDetailTask;
import java.util.ArrayList;
import java.util.Collection;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
public class IGF extends Fragment implements OnScrollListener, OnItemLongClickListener, OnItemClickListener, NetworkTaskCallbackListener, RecordStatusUpdatedListener {
Context context;
ListType listType = ListType.ANIME; // just to have it proper initialized
TaskJob taskjob;
GridView Gridview;
PrefManager pref;
ViewFlipper viewflipper;
SwipeRefreshLayout swipeRefresh;
Activity activity;
ArrayList<GenericRecord> gl = new ArrayList<GenericRecord>();
ListViewAdapter<GenericRecord> ga;
IGFCallbackListener callback;
NetworkTask networkTask;
RecordStatusUpdatedReceiver recordStatusReceiver;
int page = 1;
int list = -1;
int resource;
boolean useSecondaryAmounts;
boolean loading = true;
boolean clearAfterLoading = false;
boolean hasmorepages = false;
/* setSwipeRefreshEnabled() may be called before swipeRefresh exists (before onCreateView() is
* called), so save it and apply it in onCreateView() */
boolean swipeRefreshEnabled = true;
String query;
/*
* set the watched/read count & status on the covers.
*/
public static void setStatus(String myStatus, TextView textview, TextView progressCount, ImageView actionButton) {
actionButton.setVisibility(View.GONE);
progressCount.setVisibility(View.GONE);
if (myStatus == null) {
textview.setText("");
} else if (myStatus.equals("watching")) {
textview.setText(R.string.cover_Watching);
progressCount.setVisibility(View.VISIBLE);
actionButton.setVisibility(View.VISIBLE);
} else if (myStatus.equals("reading")) {
textview.setText(R.string.cover_Reading);
progressCount.setVisibility(View.VISIBLE);
actionButton.setVisibility(View.VISIBLE);
} else if (myStatus.equals("completed")) {
textview.setText(R.string.cover_Completed);
} else if (myStatus.equals("on-hold")) {
textview.setText(R.string.cover_OnHold);
progressCount.setVisibility(View.VISIBLE);
} else if (myStatus.equals("dropped")) {
textview.setText(R.string.cover_Dropped);
} else if (myStatus.equals("plan to watch")) {
textview.setText(R.string.cover_PlanningToWatch);
} else if (myStatus.equals("plan to read")) {
textview.setText(R.string.cover_PlanningToRead);
} else {
textview.setText("");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
setRetainInstance(true);
View view = inflater.inflate(R.layout.record_igf_layout, container, false);
viewflipper = (ViewFlipper) view.findViewById(R.id.viewFlipper);
Gridview = (GridView) view.findViewById(R.id.gridview);
Gridview.setOnItemClickListener(this);
Gridview.setOnItemLongClickListener(this);
Gridview.setOnScrollListener(this);
context = getActivity();
activity = getActivity();
pref = new PrefManager(context);
useSecondaryAmounts = pref.getUseSecondaryAmountsEnabled();
if (pref.getTraditionalListEnabled()) {
Gridview.setColumnWidth((int) Math.pow(9999, 9999)); //remain in the listview mode
resource = R.layout.record_igf_listview;
} else {
resource = R.layout.record_igf_gridview;
}
swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
if (isOnHomeActivity()) {
swipeRefresh.setOnRefreshListener((Home) getActivity());
swipeRefresh.setColorScheme(
R.color.holo_blue_bright,
R.color.holo_green_light,
R.color.holo_orange_light,
R.color.holo_red_light
);
}
swipeRefresh.setEnabled(swipeRefreshEnabled);
if ( gl.size() > 0 ) // there are already records, fragment has been rotated
refresh();
NfcHelper.disableBeam(activity);
if (callback != null)
callback.onIGFReady(this);
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
if (IGFCallbackListener.class.isInstance(activity))
callback = (IGFCallbackListener)activity;
recordStatusReceiver = new RecordStatusUpdatedReceiver(this);
IntentFilter filter = new IntentFilter(recordStatusReceiver.RECV_IDENT);
LocalBroadcastManager.getInstance(activity).registerReceiver(recordStatusReceiver, filter);
}
@Override
public void onDetach() {
if (recordStatusReceiver != null)
LocalBroadcastManager.getInstance(activity).unregisterReceiver(recordStatusReceiver);
super.onDetach();
}
private boolean isOnHomeActivity() {
return getActivity() != null && getActivity().getClass() == Home.class;
}
/*
* add +1 episode/volume/chapters to the anime/manga.
*/
public void setProgressPlusOne(Anime anime, Manga manga) {
if (listType.equals(ListType.ANIME)) {
anime.setWatchedEpisodes(anime.getWatchedEpisodes() + 1);
if (anime.getWatchedEpisodes() == anime.getEpisodes())
anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED);
new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime);
} else {
manga.setProgress(useSecondaryAmounts, manga.getProgress(useSecondaryAmounts) + 1);
if (manga.getProgress(useSecondaryAmounts) == manga.getTotal(useSecondaryAmounts))
manga.setReadStatus(GenericRecord.STATUS_COMPLETED);
new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga);
}
refresh();
}
/*
* mark the anime/manga as completed.
*/
public void setMarkAsComplete(Anime anime, Manga manga) {
if (listType.equals(ListType.ANIME)) {
anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED);
if (anime.getEpisodes() > 0)
anime.setWatchedEpisodes(anime.getEpisodes());
anime.setDirty(true);
gl.remove(anime);
new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime);
} else {
manga.setReadStatus(GenericRecord.STATUS_COMPLETED);
manga.setDirty(true);
gl.remove(manga);
new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga);
}
refresh();
}
/*
* handle the loading indicator
*/
private void toggleLoadingIndicator(boolean show) {
if (viewflipper != null) {
viewflipper.setDisplayedChild(show ? 1 : 0);
}
}
public void toggleSwipeRefreshAnimation(boolean show) {
if (swipeRefresh != null) {
swipeRefresh.setRefreshing(show);
}
}
public void setSwipeRefreshEnabled(boolean enabled) {
swipeRefreshEnabled = enabled;
if (swipeRefresh != null) {
swipeRefresh.setEnabled(enabled);
}
}
/*
* get the anime/manga lists.
* (if clear is true the whole list will be cleared and loaded)
*/
public void getRecords(boolean clear, TaskJob task, int list) {
if (task != null) {
taskjob = task;
}
if (list != this.list) {
this.list = list;
}
/* only show loading indicator if
* - is not own list and on page 1
* - force sync and list is empty (only show swipe refresh animation if not empty)
* - clear is set
*/
boolean isEmpty = gl.isEmpty();
toggleLoadingIndicator((page == 1 && !isList()) || (taskjob.equals(TaskJob.FORCESYNC) && isEmpty) || clear);
/* show swipe refresh animation if
* - loading more pages
* - forced update
* - clear is unset
*/
toggleSwipeRefreshAnimation((page > 1 && !isList() || taskjob.equals(TaskJob.FORCESYNC)) && !taskjob.equals(TaskJob.SEARCH) && !clear);
loading = true;
try{
if (clear){
resetPage();
gl.clear();
if (ga == null) {
setAdapter();
}
ga.clear();
}
Bundle data = new Bundle();
data.putInt("page", page);
if (networkTask != null)
networkTask.cancelTask();
networkTask = new NetworkTask(taskjob, listType, context, data, this);
networkTask.execute(isList() ? MALManager.listSortFromInt(list, listType) : query);
}catch (Exception e){
Log.e("MALX", "error getting records: " + e.getMessage());
}
}
public void searchRecords(String search) {
if (search != null && !search.equals(query) && !search.equals("")) { // no need for searching the same again or empty string
query = search;
page = 1;
setSwipeRefreshEnabled(false);
getRecords(true, TaskJob.SEARCH, 0);
}
}
/*
* reset the page number of anime/manga lists.
*/
public void resetPage(){
page = 1;
if (Gridview != null) {
Gridview.requestFocusFromTouch();
Gridview.post(new Runnable() {
@Override
public void run() {
Gridview.setSelection(0);
}
});
}
}
/*
* set the adapter anime/manga
*/
public void setAdapter() {
ga = new ListViewAdapter<GenericRecord>(context, resource);
ga.setNotifyOnChange(true);
}
/*
* refresh the covers.
*/
public void refresh() {
try {
if (ga == null)
setAdapter();
ga.clear();
ga.supportAddAll(gl);
if (Gridview.getAdapter() == null)
Gridview.setAdapter(ga);
} catch (Exception e) {
if (MALApi.isNetworkAvailable(context)) {
e.printStackTrace();
if (taskjob.equals(TaskJob.SEARCH)) {
Crouton.makeText(activity, R.string.crouton_error_Search, Style.ALERT).show();
} else {
if (listType.equals(ListType.ANIME)) {
Crouton.makeText(activity, R.string.crouton_error_Anime_Sync, Style.ALERT).show();
} else {
Crouton.makeText(activity, R.string.crouton_error_Manga_Sync, Style.ALERT).show();
}
}
Log.e("MALX", "error on refresh: " + e.getMessage());
} else {
Crouton.makeText(activity, R.string.crouton_error_noConnectivity, Style.ALERT).show();
}
}
loading = false;
}
/*
* check if the taskjob is my personal anime/manga list
*/
public boolean isList() {
return taskjob != null && (taskjob.equals(TaskJob.GETLIST) || taskjob.equals(TaskJob.FORCESYNC));
}
private boolean jobReturnsPagedResults(TaskJob job) {
return !isList() && !job.equals(TaskJob.SEARCH);
}
/*
* set the list with the new page/list.
*/
@SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions
@Override
public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) {
if ( !cancelled || (cancelled && job.equals(TaskJob.FORCESYNC))) { // forced sync tasks are completed even after cancellation
ArrayList resultList;
try {
if (type == ListType.ANIME) {
resultList = (ArrayList<Anime>) result;
} else {
resultList = (ArrayList<Manga>) result;
}
} catch (ClassCastException e) {
Log.e("MALX", "error reading result because of invalid result class: " + result.getClass().toString());
resultList = null;
}
if (resultList != null) {
if (resultList.size() == 0 && taskjob.equals(TaskJob.SEARCH)) {
if (this.page == 1)
doRecordsLoadedCallback(type, job, false, true, cancelled);
} else {
if (job.equals(TaskJob.FORCESYNC))
doRecordsLoadedCallback(type, job, false, false, cancelled);
if (!cancelled) { // only add results if not cancelled (on FORCESYNC)
if (clearAfterLoading || job.equals(TaskJob.FORCESYNC)) { // a forced sync always reloads all data, so clear the list
gl.clear();
clearAfterLoading = false;
}
if (jobReturnsPagedResults(job))
hasmorepages = resultList.size() > 0;
gl.addAll(resultList);
refresh();
}
}
} else {
doRecordsLoadedCallback(type, job, true, false, cancelled); // no resultList ? something went wrong
}
}
networkTask = null;
toggleSwipeRefreshAnimation(false);
toggleLoadingIndicator(false);
}
@Override
public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) {
doRecordsLoadedCallback(type, job, true, true, false);
}
private void doRecordsLoadedCallback(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) {
if (callback != null)
callback.onRecordsLoadingFinished(type, job, error, resultEmpty, cancelled);
}
/*
* handle the gridview click by navigating to the detailview.
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent startDetails = new Intent(getView().getContext(), DetailView.class);
startDetails.putExtra("net.somethingdreadful.MAL.recordID", ga.getItem(position).getId());
startDetails.putExtra("net.somethingdreadful.MAL.recordType", listType);
startActivity(startDetails);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
/*
* load more pages if we are almost on the bottom.
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// don't do anything if there is nothing in the list
if (firstVisibleItem == 0 && visibleItemCount == 0 && totalItemCount == 0)
return;
if (totalItemCount - firstVisibleItem <= (visibleItemCount * 2) && !loading && hasmorepages){
loading = true;
if (jobReturnsPagedResults(taskjob)){
page++;
getRecords(false, null, list);
}
}
}
/*
* corpy the anime title to the clipboard on long click.
*/
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Crouton.makeText(activity, R.string.crouton_info_Copied, Style.CONFIRM).show();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
c.setText(gl.get(position).getTitle());
} else {
android.content.ClipboardManager c1 = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData c2;
c2 = android.content.ClipData.newPlainText("Atarashii", gl.get(position).getTitle());
c1.setPrimaryClip(c2);
}
return false;
}
static class ViewHolder {
TextView label;
TextView progressCount;
TextView flavourText;
ImageView cover;
ImageView bar;
ImageView actionButton;
}
/*
* the custom adapter for the covers anime/manga.
*/
public class ListViewAdapter<T> extends ArrayAdapter<T> {
public ListViewAdapter(Context context, int resource) {
super(context, resource);
}
@SuppressWarnings("deprecation")
public View getView(int position, View view, ViewGroup parent) {
final GenericRecord record = gl.get(position);
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(resource, parent, false);
viewHolder = new ViewHolder();
viewHolder.label = (TextView) view.findViewById(R.id.animeName);
viewHolder.progressCount = (TextView) view.findViewById(R.id.watchedCount);
viewHolder.cover = (ImageView) view.findViewById(R.id.coverImage);
viewHolder.bar = (ImageView) view.findViewById(R.id.textOverlayPanel);
viewHolder.actionButton = (ImageView) view.findViewById(R.id.popUpButton);
viewHolder.flavourText = (TextView) view.findViewById(R.id.stringWatched);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
try {
if (taskjob.equals(TaskJob.GETMOSTPOPULAR) || taskjob.equals(TaskJob.GETTOPRATED)) {
viewHolder.progressCount.setVisibility(View.VISIBLE);
viewHolder.progressCount.setText(Integer.toString(position + 1));
viewHolder.actionButton.setVisibility(View.GONE);
viewHolder.flavourText.setText(R.string.label_Number);
} else if (listType.equals(ListType.ANIME)) {
viewHolder.progressCount.setText(Integer.toString(((Anime) record).getWatchedEpisodes()));
setStatus(((Anime) record).getWatchedStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton);
} else {
if (useSecondaryAmounts)
viewHolder.progressCount.setText(Integer.toString(((Manga) record).getVolumesRead()));
else
viewHolder.progressCount.setText(Integer.toString(((Manga) record).getChaptersRead()));
setStatus(((Manga) record).getReadStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton);
}
viewHolder.label.setText(record.getTitle());
Picasso.with(context)
.load(record.getImageUrl())
.error(R.drawable.cover_error)
.placeholder(R.drawable.cover_loading)
.into(viewHolder.cover);
if (viewHolder.actionButton.getVisibility() == View.VISIBLE) {
viewHolder.actionButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(context, v);
popup.getMenuInflater().inflate(R.menu.record_popup, popup.getMenu());
if (!listType.equals(ListType.ANIME))
popup.getMenu().findItem(R.id.plusOne).setTitle(R.string.action_PlusOneRead);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.plusOne:
if (listType.equals(ListType.ANIME))
setProgressPlusOne((Anime) record, null);
else
setProgressPlusOne(null, (Manga) record);
break;
case R.id.markCompleted:
if (listType.equals(ListType.ANIME))
setMarkAsComplete((Anime) record, null);
else
setMarkAsComplete(null, (Manga) record);
break;
}
return true;
}
});
popup.show();
}
});
}
viewHolder.bar.setAlpha(175);
} catch (Exception e) {
Log.e("MALX", "error on the ListViewAdapter: " + e.getMessage());
}
return view;
}
public void supportAddAll(Collection<? extends T> collection) {
for (T record : collection) {
this.add(record);
}
}
}
// user updated record on DetailsView, so update the list if necessary
@Override
public void onRecordStatusUpdated(ListType type) {
// broadcast received
if (type != null && type.equals(listType) && isList()) {
clearAfterLoading = true;
getRecords(false, TaskJob.GETLIST, list);
}
}
}
|
package com.dmnlk.sample;
import com.dmnlk.doma.dao.TAccountDao;
import io.dropwizard.Application;
import io.dropwizard.jdbi.DBIFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.skife.jdbi.v2.DBI;
/**
* @author dmnlk
*/
public class SampleApplication extends Application<SampleConfiguration> {
public static void main(String[] args) throws Exception {
new SampleApplication().run(args);
}
@Override
public String getName() {
return "hello";
}
@Override
public void initialize(Bootstrap<SampleConfiguration> bootstrap) {
// nothing to do yet
}
@Override
public void run(SampleConfiguration configuration,
Environment environment) {
final DBIFactory dbiFactory = new DBIFactory();
final DBI dbi = dbiFactory.build(environment, configuration.getDataSourceFactory(), "postgresql");
TAccountDao tAccountDao = dbi.onDemand(TAccountDao.class);
final SampleResource resource = new SampleResource(
configuration.getTemplate(),
configuration.getDefaultName(),
tAccountDao
);
final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
environment.healthChecks().register("template", healthCheck);
environment.jersey().register(resource);
}
}
|
package fi.jumi.test;
public class Timeouts {
public static final int END_TO_END_TEST = 5000;
public static final int ASSERTION = 1000;
}
|
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class BracketCheckerTest {
@Test
public void testPairedSquareBrackets() {
final BracketChecker bracketChecker = new BracketChecker("[]");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testEmptyString() {
final BracketChecker bracketChecker = new BracketChecker("");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testUnpairedBrackets() {
final BracketChecker bracketChecker = new BracketChecker("[[");
assertFalse(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testIncorrectlyOrderedBrackets() {
final BracketChecker bracketChecker = new BracketChecker("}{");
assertFalse(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testPairedBracketsWithWhitespace() {
final BracketChecker bracketChecker = new BracketChecker("{ }");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testSimpleNestedBrackets() {
final BracketChecker bracketChecker = new BracketChecker("{[]}");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testSeveralPairedBrackets() {
final BracketChecker bracketChecker = new BracketChecker("{}[]");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testPairedAndNestedBrackets() {
final BracketChecker bracketChecker = new BracketChecker("([{}({}[])])");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testUnopenedClosingBracket() {
final BracketChecker bracketChecker = new BracketChecker("{[)][]}");
assertFalse(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testUnpairedAndNestedBracket() {
final BracketChecker bracketChecker = new BracketChecker("([{])");
assertFalse(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testPairedAndIncorrectlyNestedBrackets() {
final BracketChecker bracketChecker = new BracketChecker("[({]})");
assertFalse(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testValidMathExpression() {
final BracketChecker bracketChecker = new BracketChecker("(((185 + 223.85) * 15) - 543)/2");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
@Ignore("Remove to run test")
@Test
public void testValidComplexLaTeXExpression() {
final BracketChecker bracketChecker = new BracketChecker(
"\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)");
assertTrue(bracketChecker.areBracketsMatchedAndNestedCorrectly());
}
}
|
package nl.mpi.kinnate.ui;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeContainer;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.ui.ArbilTable;
import nl.mpi.arbil.ui.ArbilTableModel;
import nl.mpi.arbil.ui.ArbilWindowManager;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.arbil.userstorage.ArbilSessionStorage;
import nl.mpi.kinnate.KinTermSavePanel;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.kindata.VisiblePanelSetting;
import nl.mpi.kinnate.kindata.VisiblePanelSetting.PanelType;
import nl.mpi.kinnate.svg.GraphPanel;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.entityindexer.EntityCollection;
import nl.mpi.kinnate.entityindexer.EntityService;
import nl.mpi.kinnate.entityindexer.EntityServiceException;
import nl.mpi.kinnate.entityindexer.QueryParser;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import nl.mpi.kinnate.kintypestrings.KinTypeStringConverter;
import nl.mpi.kinnate.kintypestrings.ParserHighlight;
import nl.mpi.kinnate.ui.DocumentNewMenu.DocumentType;
public class KinDiagramPanel extends JPanel implements SavePanel, KinTermSavePanel, ArbilDataNodeContainer {
private EntityCollection entityCollection;
private KinTypeStringInput kinTypeStringInput;
private GraphPanel graphPanel;
private GraphSorter graphSorter;
private EgoSelectionPanel egoSelectionPanel;
private HidePane kinTermHidePane;
private HidePane kinTypeHidePane;
private KinTermTabPane kinTermPanel;
private EntityService entityIndex;
private JProgressBar progressBar;
public ArbilTable imdiTable;
static private File defaultDiagramTemplate;
private HashMap<ArbilDataNode, UniqueIdentifier> registeredArbilDataNode;
private HashSet<ArbilNode> arbilDataNodesFirstLoadDone;
private String defaultString = "# The kin type strings entered here will determine how the entities show on the graph below\n";
public static String defaultGraphString = "# The kin type strings entered here will determine how the entities show on the graph below\n"
+ "# Enter one string per line.\n"
//+ "# By default all relations of the selected entity will be shown.\n"
+ "# for example:\n"
// + "EmWMMM\n"
// + "E:1:FFE\n"
// + "EmWMMM:1:\n"
// + "E:1:FFE\n"
+ "Em:Charles II of Spain:W:Marie Louise d'Orlans\n"
+ "Em:Charles II of Spain:F:Philip IV of Spain:F:Philip III of Spain:F:Philip II of Spain:F:Charles V, Holy Roman Emperor:F:Philip I of Castile\n"
+ "Em:Charles II of Spain:M:Mariana of Austria:M:Maria Anna of Spain:M:Margaret of Austria:M:Maria Anna of Bavaria\n"
+ "M:Mariana of Austria:F:Ferdinand III, Holy Roman Emperor:\n"
+ "F:Philip IV of Spain:M:Margaret of Austria\n"
+ "F:Ferdinand III, Holy Roman Emperor:\n"
+ "M:Maria Anna of Spain:\n"
+ "F:Philip III of Spain\n"
+ "M:Margaret of Austria\n"
+ "\n";
// + "FS:1:BSSWMDHFF:1:\n"
// + "M:2:SSDHMFM:2:\n"
// + "F:3:SSDHMF:3:\n"
// + "E=[Bob]MFM\n"
// + "E=[Bob]MZ\n"
// + "E=[Bob]F\n"
// + "E=[Bob]M\n"
// + "E=[Bob]S";
// private String kinTypeStrings[] = new String[]{};
public KinDiagramPanel(File existingFile) {
initKinDiagramPanel(existingFile, null);
}
public KinDiagramPanel(DocumentType documentType) {
initKinDiagramPanel(null, documentType);
}
private void initKinDiagramPanel(File existingFile, DocumentType documentType) {
entityCollection = new EntityCollection();
progressBar = new JProgressBar();
EntityData[] svgStoredEntities = null;
graphPanel = new GraphPanel(this);
kinTypeStringInput = new KinTypeStringInput(defaultString);
if (existingFile != null && existingFile.exists()) {
svgStoredEntities = graphPanel.readSvg(existingFile);
String kinTermContents = null;
for (String currentKinTypeString : graphPanel.getKinTypeStrigs()) {
if (currentKinTypeString.trim().length() > 0) {
if (kinTermContents == null) {
kinTermContents = "";
} else {
kinTermContents = kinTermContents + "\n";
}
kinTermContents = kinTermContents + currentKinTypeString.trim();
}
}
kinTypeStringInput.setText(kinTermContents);
} else {
if (documentType == null) {
// this is the default document that users see when they run the application for the first time
documentType = DocumentType.Simple;
}
boolean showKinTerms = false;
boolean showArchiveLinker = false;
boolean showDiagramTree = false;
boolean showEntitySearch = false;
boolean showIndexerSettings = false;
boolean showKinTypeStrings = false;
boolean showMetaData = false;
switch (documentType) {
case ArchiveLinker:
showMetaData = true;
showDiagramTree = true;
showArchiveLinker = true;
break;
case CustomQuery:
showMetaData = true;
showKinTypeStrings = true;
showDiagramTree = true;
showIndexerSettings = true;
break;
case EntitySearch:
showMetaData = true;
showEntitySearch = true;
showDiagramTree = true;
break;
case KinTerms:
showKinTerms = true;
break;
case KinTypeString:
// showDiagramTree = true;
showKinTypeStrings = true;
break;
case Simple:
showMetaData = true;
showDiagramTree = true;
break;
case Query:
showMetaData = true;
showDiagramTree = true;
showKinTypeStrings = true;
default:
break;
}
graphPanel.generateDefaultSvg();
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTerms, 150, showKinTerms);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.ArchiveLinker, 150, showArchiveLinker);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.DiagramTree, 150, showDiagramTree);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.EntitySearch, 150, showEntitySearch);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.IndexerSettings, 150, showIndexerSettings);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTypeStrings, 150, showKinTypeStrings);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.MetaData, 150, showMetaData);
}
this.setLayout(new BorderLayout());
ArbilTableModel imdiTableModel = new ArbilTableModel();
progressBar.setVisible(false);
graphPanel.add(progressBar, BorderLayout.PAGE_START);
imdiTable = new ArbilTable(imdiTableModel, "Selected Nodes");
TableCellDragHandler tableCellDragHandler = new TableCellDragHandler();
imdiTable.setTransferHandler(tableCellDragHandler);
imdiTable.setDragEnabled(true);
registeredArbilDataNode = new HashMap<ArbilDataNode, UniqueIdentifier>();
arbilDataNodesFirstLoadDone = new HashSet<ArbilNode>();
egoSelectionPanel = new EgoSelectionPanel(imdiTable, graphPanel);
kinTermPanel = new KinTermTabPane(this, graphPanel.getkinTermGroups());
// kinTypeStringInput.setText(defaultString);
JPanel kinGraphPanel = new JPanel(new BorderLayout());
kinTypeHidePane = new HidePane(HidePane.HidePanePosition.top, 0);
IndexerParametersPanel indexerParametersPanel = new IndexerParametersPanel(this, graphPanel, tableCellDragHandler);
// JPanel advancedPanel = new JPanel(new BorderLayout());
JScrollPane tableScrollPane = new JScrollPane(imdiTable);
// advancedPanel.add(tableScrollPane, BorderLayout.CENTER);
//HidePane indexParamHidePane = new HidePane(HidePane.HidePanePosition.right, 0);
//advancedPanel.add(indexParamHidePane, BorderLayout.LINE_END);
HidePane tableHidePane = new HidePane(HidePane.HidePanePosition.bottom, 0);
KinDragTransferHandler dragTransferHandler = new KinDragTransferHandler(this);
graphPanel.setTransferHandler(dragTransferHandler);
egoSelectionPanel.setTransferHandler(dragTransferHandler);
EntitySearchPanel entitySearchPanel = new EntitySearchPanel(entityCollection, graphPanel, imdiTable);
entitySearchPanel.setTransferHandler(dragTransferHandler);
HidePane egoSelectionHidePane = new HidePane(HidePane.HidePanePosition.left, 0);
kinTermHidePane = new HidePane(HidePane.HidePanePosition.right, 0);
graphPanel.setArbilTableModel(imdiTableModel, tableHidePane);
for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) {
switch (panelSetting.getPanelType()) {
case ArchiveLinker:
panelSetting.setTargetPanel(kinTermHidePane, new ArchiveEntityLinkerPanel(imdiTable, dragTransferHandler), "Archive Linker");
break;
case DiagramTree:
panelSetting.setTargetPanel(egoSelectionHidePane, egoSelectionPanel, "Diagram Tree");
break;
case EntitySearch:
panelSetting.setTargetPanel(kinTermHidePane, entitySearchPanel, "Search Entities");
break;
case IndexerSettings:
panelSetting.setTargetPanel(kinTypeHidePane, indexerParametersPanel, "Indexer Parameters");
break;
case KinTerms:
panelSetting.setTargetPanel(kinTermHidePane, kinTermPanel, "Kin Terms");
break;
case KinTypeStrings:
panelSetting.setTargetPanel(kinTypeHidePane, new JScrollPane(kinTypeStringInput), "Kin Type Strings");
break;
case MetaData:
panelSetting.setTargetPanel(tableHidePane, tableScrollPane, "Metadata");
break;
}
}
tableHidePane.toggleHiddenState(); // put the metadata table plane into the closed state
kinGraphPanel.add(kinTypeHidePane, BorderLayout.PAGE_START);
kinGraphPanel.add(egoSelectionHidePane, BorderLayout.LINE_START);
kinGraphPanel.add(graphPanel, BorderLayout.CENTER);
kinGraphPanel.add(kinTermHidePane, BorderLayout.LINE_END);
kinGraphPanel.add(tableHidePane, BorderLayout.PAGE_END);
this.add(kinGraphPanel);
entityIndex = new QueryParser(svgStoredEntities);
graphSorter = new GraphSorter();
kinTypeStringInput.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
synchronized (e) {
redrawIfKinTermsChanged();
}
}
});
}
static public File getDefaultDiagramFile() {
if (defaultDiagramTemplate == null) {
defaultDiagramTemplate = new File(ArbilSessionStorage.getSingleInstance().getStorageDirectory(), "DefaultKinDiagram.svg");
}
return defaultDiagramTemplate;
}
public void redrawIfKinTermsChanged() {
if (kinTypeStringInput.hasChanges()) {
graphPanel.setKinTypeStrigs(kinTypeStringInput.getCurrentStrings());
drawGraph();
}
}
boolean graphThreadRunning = false;
boolean graphUpdateRequired = false;
public synchronized void drawGraph() {
graphUpdateRequired = true;
if (!graphThreadRunning) {
graphThreadRunning = true;
new Thread() {
@Override
public void run() {
// todo: there are probably other synchronisation issues to resolve here.
while (graphUpdateRequired) {
graphUpdateRequired = false;
try {
String[] kinTypeStrings = graphPanel.getKinTypeStrigs();
ParserHighlight[] parserHighlight = new ParserHighlight[kinTypeStrings.length];
progressBar.setValue(0);
progressBar.setVisible(true);
boolean isQuery = false;
if (!graphPanel.dataStoreSvg.egoEntities.isEmpty() || !graphPanel.dataStoreSvg.requiredEntities.isEmpty()) {
isQuery = true;
} else {
for (String currentLine : kinTypeStrings) {
if (currentLine.contains("=")) {
isQuery = true;
break;
}
}
}
if (isQuery) {
EntityData[] graphNodes = entityIndex.processKinTypeStrings(null, graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, kinTypeStrings, parserHighlight, graphPanel.getIndexParameters(), progressBar);
graphSorter.setEntitys(graphNodes);
// register interest Arbil updates and update the graph when data is edited in the table
// registerCurrentNodes(graphSorter.getDataNodes());
graphPanel.drawNodes(graphSorter);
egoSelectionPanel.setTreeNodes(graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, graphSorter.getDataNodes(), graphPanel.getIndexParameters());
} else {
KinTypeStringConverter graphData = new KinTypeStringConverter();
graphData.readKinTypes(kinTypeStrings, graphPanel.getkinTermGroups(), graphPanel.dataStoreSvg, parserHighlight);
graphPanel.drawNodes(graphData);
egoSelectionPanel.setTransientNodes(graphData.getDataNodes());
// KinDiagramPanel.this.doLayout();
}
kinTypeStringInput.highlightKinTerms(parserHighlight, kinTypeStrings);
// kinTypeStrings = graphPanel.getKinTypeStrigs();
} catch (EntityServiceException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to load all entities required", "Draw Graph");
}
progressBar.setVisible(false);
}
graphThreadRunning = false;
}
}.start();
}
}
// @Deprecated
// public void setDisplayNodes(String typeString, String[] egoIdentifierArray) {
// // todo: should this be replaced by the required nodes?
// if (kinTypeStringInput.getText().equals(defaultString)) {
// kinTypeStringInput.setText("");
// String kinTermContents = kinTypeStringInput.getText();
// for (String currentId : egoIdentifierArray) {
// kinTermContents = kinTermContents + typeString + "=[" + currentId + "]\n";
// kinTypeStringInput.setText(kinTermContents);
// graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n"));
//// kinTypeStrings = graphPanel.getKinTypeStrigs();
// drawGraph();
public void setEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities = new HashSet<UniqueIdentifier>(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void addEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities.addAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void removeEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities.removeAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void addRequiredNodes(UniqueIdentifier[] egoIdentifierArray) {
graphPanel.dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void removeRequiredNodes(UniqueIdentifier[] egoIdentifierArray) {
graphPanel.dataStoreSvg.requiredEntities.removeAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public boolean hasSaveFileName() {
return (graphPanel.hasSaveFileName() && getDefaultDiagramFile() != graphPanel.getFileName());
}
public File getFileName() {
return graphPanel.getFileName();
}
public boolean requiresSave() {
return graphPanel.requiresSave();
}
public void setRequiresSave() {
graphPanel.setRequiresSave();
}
public void saveToFile() {
graphPanel.saveToFile();
}
public void saveToFile(File saveFile) {
graphPanel.saveToFile(saveFile);
}
public void updateGraph() {
this.drawGraph();
}
public void exportKinTerms() {
kinTermPanel.getSelectedKinTermPanel().exportKinTerms();
}
public void hideShow() {
kinTermHidePane.toggleHiddenState();
}
public void importKinTerms() {
kinTermPanel.getSelectedKinTermPanel().importKinTerms();
}
public void addKinTermGroup() {
graphPanel.addKinTermGroup();
kinTermPanel.updateKinTerms(graphPanel.getkinTermGroups());
}
public VisiblePanelSetting[] getVisiblePanels() {
return graphPanel.dataStoreSvg.getVisiblePanels();
}
public void setPanelState(PanelType panelType, int panelWidth, boolean panelVisible) {
// todo: show / hide the requested panel
graphPanel.dataStoreSvg.setPanelState(panelType, panelWidth, panelVisible);
}
public void setSelectedKinTypeSting(String kinTypeStrings) {
kinTermPanel.setAddableKinTypeSting(kinTypeStrings);
}
public boolean isHidden() {
return kinTermHidePane.isHidden();
}
public EntityData[] getGraphEntities() {
return graphSorter.getDataNodes();
}
public void registerArbilNode(UniqueIdentifier uniqueIdentifier, ArbilDataNode arbilDataNode) {
// todo: i think this is resolved but double check the issue where arbil nodes update frequency is too high and breaks basex
// todo: load the nodes in the KinDataNode when putting them in the table and pass on the reload requests here when they occur
// todo: replace the data node registering process.
// for (EntityData entityData : currentEntities) {
// ArbilDataNode arbilDataNode = null;
if (!registeredArbilDataNode.containsKey(arbilDataNode)) {
arbilDataNode.registerContainer(this);
registeredArbilDataNode.put(arbilDataNode, uniqueIdentifier);
}
// try {
// String metadataPath = entityData.getEntityPath();
// if (metadataPath != null) {
// // todo: this should not load the arbil node only register an interest
//// and this needs to be tested
// arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNodeWithoutLoading(new URI(metadataPath));
// registeredArbilDataNode.put(entityData.getUniqueIdentifier(), arbilDataNode);
// arbilDataNode.registerContainer(this);
// // todo: keep track of registered nodes and remove the unrequired ones here
// } else {
// GuiHelper.linorgBugCatcher.logError(new Exception("Error getting path for: " + entityData.getUniqueIdentifier().getAttributeIdentifier() + " : " + entityData.getLabel()[0]));
// } catch (URISyntaxException exception) {
// GuiHelper.linorgBugCatcher.logError(exception);
// } else {
// arbilDataNode = registeredArbilDataNode.get(entityData.getUniqueIdentifier());
// if (arbilDataNode != null) {
// entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false);
}
public void entityRelationsChanged(UniqueIdentifier[] selectedIdentifiers) {
// this method does not need to update the database because the link changing process has already done that
// remove the stored graph locations of the selected ids
graphPanel.clearEntityLocations(selectedIdentifiers);
graphPanel.getIndexParameters().valuesChanged = true;
drawGraph();
}
public void dataNodeIconCleared(ArbilNode arbilNode) {
if (arbilDataNodesFirstLoadDone.contains(arbilNode)) {
// todo: this needs to be updated to be multi threaded so users can link or save multiple nodes at once
boolean dataBaseRequiresUpdate = false;
boolean redrawRequired = false;
if (arbilNode instanceof ArbilDataNode) {
ArbilDataNode arbilDataNode = (ArbilDataNode) arbilNode;
UniqueIdentifier uniqueIdentifier = registeredArbilDataNode.get(arbilDataNode);
// find the entity data for this arbil data node
for (EntityData entityData : graphSorter.getDataNodes()) {
if (entityData.getUniqueIdentifier().equals(uniqueIdentifier)) {
// check if the metadata has been changed
// todo: something here fails to act on multiple nodes that have changed (it is the db update that was missed)
if (entityData.metadataRequiresSave && !arbilDataNode.getNeedsSaveToDisk(false)) {
dataBaseRequiresUpdate = true;
redrawRequired = true;
}
// clear or set the needs save flag
entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false);
if (entityData.metadataRequiresSave) {
redrawRequired = true;
}
}
}
if (dataBaseRequiresUpdate) {
entityCollection.updateDatabase(arbilDataNode.getURI());
graphPanel.getIndexParameters().valuesChanged = true;
}
}
if (redrawRequired) {
drawGraph();
}
}
if (!arbilNode.isLoading()) {
// this is to make sure that the initial loading process does not cause db updates nor graph redraws
arbilDataNodesFirstLoadDone.add(arbilNode);
}
}
public void dataNodeChildAdded(ArbilNode destination, ArbilNode newChildNode) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void dataNodeRemoved(ArbilNode adn) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
/*
* $Log: BatchFileTransformerPipe.java,v $
* Revision 1.10 2007-09-04 07:57:15 europe\L190409
* fix bug in rename after transform
*
* Revision 1.9 2007/07/26 16:07:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* updated javadoc
*
* Revision 1.8 2007/07/24 16:10:11 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* new style BatchFileTransformerPipe
*
*/
package nl.nn.adapterframework.batch;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import nl.nn.adapterframework.core.PipeLineSession;
import nl.nn.adapterframework.core.PipeRunException;
import nl.nn.adapterframework.core.PipeRunResult;
import org.apache.commons.lang.StringUtils;
/**
* Pipe for transforming a (batch)file with records. Records in the file must be separated
* with new line characters.
* You can use the <child> tag to register RecordHandlers, RecordHandlerManagers, ResultHandlers
* and RecordHandlingFlow elements. This is deprecated, however. Since 4.7 one should use <manager>,
* <recordHandler>, <resultHandler> and <flow>
*
* <p><b>Configuration:</b>
* <table border="1">
* <tr><th>attributes</th><th>description</th><th>default</th></tr>
* <tr><td>classname</td><td>nl.nn.adapterframework.batch.BatchFileTransformerPipe</td><td> </td></tr>
* <tr><td>{@link #move2dirAfterTransform(String) directory}</td><td>Directory in which the transformed file(s) is stored</td><td> </td></tr>
* <tr><td>{@link #move2dirAfterError(String) directory}</td><td>Directory to which the inputfile is moved in case an error occurs</td><td> </td></tr>
* </table>
* </p>
* <table border="1">
* <tr><th>nested elements</th><th>description</th></tr>
* <tr><td>{@link nl.nn.adapterframework.batch.IRecordHandlerManager manager}</td><td>Manager determines which handlers are to be used for the current line</td></tr>
* <tr><td>{@link nl.nn.adapterframework.batch.RecordHandlingFlow manager/flow}</td><td>Element that contains the handlers for a specific record type, to be assigned to the manager</td></tr>
* <tr><td>{@link nl.nn.adapterframework.batch.IRecordHandler recordHandler}</td><td>Handler for transforming records of a specific type</td></tr>
* <tr><td>{@link nl.nn.adapterframework.batch.IResultHandler resultHandler}</td><td>Handler for processing transformed records</td></tr>
* </table>
* </p>
*
* @author John Dekker
* @version Id
*/
public class BatchFileTransformerPipe extends StreamTransformerPipe {
public static final String version = "$RCSfile: BatchFileTransformerPipe.java,v $ $Revision: 1.10 $ $Date: 2007-09-04 07:57:15 $";
private String move2dirAfterTransform;
private String move2dirAfterError;
protected String getStreamId(Object input, PipeLineSession session) throws PipeRunException {
return ((File)input).getName();
}
protected Reader getReader(String streamId, Object input, PipeLineSession session) throws PipeRunException {
try {
return new FileReader(((File)input));
} catch (FileNotFoundException e) {
throw new PipeRunException(this,"cannot find file ["+streamId+"]",e);
}
}
/**
* Open a reader for the file named according the input messsage and
* transform it.
* Move the input file to a done directory when transformation is finished
* and return the names of the generated files.
*
* @see nl.nn.adapterframework.core.IPipe#doPipe(java.lang.Object, nl.nn.adapterframework.core.PipeLineSession)
*/
public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException {
String filename = input.toString();
File file = new File(filename);
try {
PipeRunResult result = super.doPipe(file,session);
if (! StringUtils.isEmpty(getMove2dirAfterTransform())) {
File move2 = new File(getMove2dirAfterTransform(), file.getName());
file.renameTo(move2);
}
return result;
} catch (PipeRunException e) {
if (! StringUtils.isEmpty(getMove2dirAfterError())) {
File move2 = new File(getMove2dirAfterError(), file.getName());
file.renameTo(move2);
}
throw e;
}
}
/**
* @param readyDir directory where input file is moved to in case of a succesful transformation
*/
public void setMove2dirAfterTransform(String readyDir) {
move2dirAfterTransform = readyDir;
}
public String getMove2dirAfterTransform() {
return move2dirAfterTransform;
}
/**
* @param errorDir directory where input file is moved to in case of an error
*/
public void setMove2dirAfterError(String errorDir) {
move2dirAfterError = errorDir;
}
public String getMove2dirAfterError() {
return move2dirAfterError;
}
}
|
package VASSAL.configure;
import VASSAL.build.Buildable;
import VASSAL.build.Builder;
import VASSAL.build.Configurable;
import VASSAL.build.GameModule;
import VASSAL.build.IllegalBuildException;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.KeyNamer;
import VASSAL.build.module.Plugin;
import VASSAL.build.module.PrototypeDefinition;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.documentation.HelpWindow;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.build.module.properties.GlobalProperties;
import VASSAL.build.module.properties.GlobalProperty;
import VASSAL.build.module.properties.GlobalTranslatableMessage;
import VASSAL.build.module.properties.ZoneProperty;
import VASSAL.build.widget.CardSlot;
import VASSAL.build.widget.PieceSlot;
import VASSAL.counters.Decorator;
import VASSAL.counters.EditablePiece;
import VASSAL.counters.GamePiece;
import VASSAL.counters.MassPieceLoader;
import VASSAL.i18n.Resources;
import VASSAL.i18n.TranslateAction;
import VASSAL.launch.EditorWindow;
import VASSAL.preferences.Prefs;
import VASSAL.search.SearchTarget;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.ProblemDialog;
import VASSAL.tools.ReflectionUtils;
import VASSAL.tools.menu.MenuManager;
import VASSAL.tools.swing.SwingUtils;
import java.awt.Component;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
/**
* The beating heart of the Editor, this class handles the Configuration Tree
* that appears in the Configuration window when editing a VASSAL module. Each
* node in the tree structure is a {@link VASSAL.build.Configurable} object,
* whose child nodes are obtained via {@link VASSAL.build.Configurable#getConfigureComponents}.
*
* When we're running as the Extension Editor, this is subclassed by {@link ExtensionTree}, which
* overrides some methods to handle extension-specific differences.
*/
public class ConfigureTree extends JTree implements PropertyChangeListener, MouseListener, MouseMotionListener, TreeSelectionListener, TreeExpansionListener {
private static final long serialVersionUID = 1L;
protected Map<Configurable, DefaultMutableTreeNode> nodes = new HashMap<>();
protected DefaultMutableTreeNode copyData;
protected DefaultMutableTreeNode cutData;
protected HelpWindow helpWindow;
protected EditorWindow editorWindow;
protected Configurable selected;
protected int selectedRow;
protected String searchCmd;
protected String moveCmd;
protected String deleteCmd;
protected String pasteCmd;
protected String copyCmd;
protected String cutCmd;
protected String helpCmd;
protected String propertiesCmd;
protected String translateCmd;
protected KeyStroke cutKey;
protected KeyStroke copyKey;
protected KeyStroke pasteKey;
protected KeyStroke deleteKey;
protected KeyStroke moveKey;
protected KeyStroke searchKey;
protected KeyStroke helpKey;
protected KeyStroke propertiesKey;
protected KeyStroke translateKey;
protected Action cutAction;
protected Action copyAction;
protected Action pasteAction;
protected Action deleteAction;
protected Action moveAction;
protected Action searchAction;
protected Action propertiesAction;
protected Action translateAction;
protected Action helpAction;
protected JDialog searchDialog;
protected JTextField searchField;
protected JCheckBox searchAdvanced;
private final SearchParameters searchParameters;
protected static Chatter chatter;
public static final Font POPUP_MENU_FONT = new Font(Font.DIALOG, Font.PLAIN, 11);
protected static final List<AdditionalComponent> additionalComponents = new ArrayList<>();
/**
* Creates new ConfigureTree
*/
public ConfigureTree(Configurable root, HelpWindow helpWindow) {
this(root, helpWindow, null);
}
public ConfigureTree(Configurable root, HelpWindow helpWindow, EditorWindow editorWindow) {
toggleClickCount = 3;
this.helpWindow = helpWindow;
this.editorWindow = editorWindow;
setShowsRootHandles(true);
setModel(new DefaultTreeModel(buildTreeNode(root)));
setCellRenderer(buildRenderer());
addMouseListener(this);
addMouseMotionListener(this);
addTreeSelectionListener(this);
addTreeExpansionListener(this);
searchCmd = Resources.getString("Editor.search"); //$NON-NLS-1$
moveCmd = Resources.getString("Editor.move"); //$NON-NLS-1$
deleteCmd = Resources.getString("Editor.delete"); //$NON-NLS-1$
pasteCmd = Resources.getString("Editor.paste"); //$NON-NLS-1$
copyCmd = Resources.getString("Editor.copy"); //$NON-NLS-1$
cutCmd = Resources.getString("Editor.cut"); //$NON-NLS-1$
propertiesCmd = Resources.getString("Editor.properties"); //$NON-NLS-1$
translateCmd = Resources.getString("Editor.ModuleEditor.translate"); //$NON-NLS-1$
helpCmd = Resources.getString("Editor.ModuleEditor.component_help"); //$NON-NLS-1$
final int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
cutKey = KeyStroke.getKeyStroke(KeyEvent.VK_X, mask);
copyKey = KeyStroke.getKeyStroke(KeyEvent.VK_C, mask);
pasteKey = KeyStroke.getKeyStroke(KeyEvent.VK_V, mask);
deleteKey = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
moveKey = KeyStroke.getKeyStroke(KeyEvent.VK_M, mask);
searchKey = KeyStroke.getKeyStroke(KeyEvent.VK_F, mask);
propertiesKey = KeyStroke.getKeyStroke(KeyEvent.VK_P, mask);
translateKey = KeyStroke.getKeyStroke(KeyEvent.VK_T, mask);
helpKey = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
copyAction = new KeyAction(copyCmd, copyKey);
pasteAction = new KeyAction(pasteCmd, pasteKey);
cutAction = new KeyAction(cutCmd, cutKey);
deleteAction = new KeyAction(deleteCmd, deleteKey);
moveAction = new KeyAction(moveCmd, moveKey);
searchAction = new KeyAction(searchCmd, searchKey);
propertiesAction = new KeyAction(propertiesCmd, propertiesKey);
translateAction = new KeyAction(translateCmd, translateKey);
helpAction = new KeyAction(helpCmd, helpKey);
/*
* Cut, Copy and Paste will not work unless I add them to the JTree input and action maps. Why??? All the others
* work fine.
*/
getInputMap().put(cutKey, cutCmd);
getInputMap().put(copyKey, copyCmd);
getInputMap().put(pasteKey, pasteCmd);
getInputMap().put(deleteKey, deleteCmd);
getActionMap().put(cutCmd, cutAction);
getActionMap().put(copyCmd, copyAction);
getActionMap().put(pasteCmd, pasteAction);
getActionMap().put(deleteCmd, deleteAction);
this.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
searchParameters = new SearchParameters();
final TreePath path = new TreePath(((DefaultMutableTreeNode) (getModel().getRoot())).getPath());
setSelectionPath(path);
scrollPathToVisible(path);
chatter = GameModule.getGameModule().getChatter();
createKeyBindings();
}
protected static String noHTML(String text) {
return text.replaceAll("<", "<") //NON-NLS // This prevents any unwanted tag from functioning
.replaceAll(">", ">"); //NON-NLS // This makes sure > doesn't break any of our legit <div> tags
}
protected static void chat(String text) {
if (chatter != null) {
chatter.show("- " + text);
}
}
protected JDialog getSearchDialog() {
return searchDialog;
}
protected void setSearchDialog(JDialog searchDialog) {
this.searchDialog = searchDialog;
}
protected JTextField getSearchField() {
return searchField;
}
protected void setSearchField(JTextField searchField) {
this.searchField = searchField;
}
protected void setSearchAdvanced(JCheckBox searchAdvanced) {
this.searchAdvanced = searchAdvanced;
}
protected JCheckBox getSearchAdvanced() {
return searchAdvanced;
}
public JFrame getFrame() {
return editorWindow;
}
/**
* Create a key binding for ENTER key to do meaningful things.
*/
private void createKeyBindings() {
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
getActionMap().put("Enter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
// Do something meaningful when Enter key pressed
final TreePath path = getSelectionPath();
if (path == null) { //BR// Apparently this can happen.
return;
}
final DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (isExpanded(path) || (node.getChildCount() == 0)) {
final Configurable target = (Configurable) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
if ((target != null) && (target.getConfigurer() != null)) {
final Action a = buildEditAction(target);
if (a != null) {
a.actionPerformed(new ActionEvent(ae.getSource(), ActionEvent.ACTION_PERFORMED, "Edit"));
}
}
}
else {
setExpandedState(path, true);
}
}
});
}
@Override
public void treeExpanded(TreeExpansionEvent event) {
}
/**
* A cell has been collapsed. Reset the edit flag on all the children owned by this node
* @param event Expansion event
*/
@Override
public void treeCollapsed(TreeExpansionEvent event) {
final ConfigureTreeNode node = (ConfigureTreeNode) event.getPath().getLastPathComponent();
node.resetChildEditFlags();
}
class KeyAction extends AbstractAction {
private static final long serialVersionUID = 1L;
protected String actionName;
public KeyAction(String name, KeyStroke key) {
super(name);
actionName = name;
putValue(Action.ACCELERATOR_KEY, key);
}
@Override
public void actionPerformed(ActionEvent e) {
doKeyAction(actionName);
}
}
protected Renderer buildRenderer() {
return new Renderer();
}
/**
* Tell our enclosing EditorWindow that we are now clean
* or dirty.
*
* @param changed true = state is not dirty
*/
protected void notifyStateChanged(boolean changed) {
if (editorWindow != null) {
editorWindow.treeStateChanged(changed);
}
}
protected Configurable getTarget(int x, int y) {
final TreePath path = getPathForLocation(x, y);
Configurable target = null;
if (path != null) {
target = (Configurable) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
}
return target;
}
protected DefaultMutableTreeNode buildTreeNode(Configurable c) {
c.addPropertyChangeListener(this);
final DefaultMutableTreeNode node = new ConfigureTreeNode(c);
final Configurable[] children = c.getConfigureComponents();
for (final Configurable child : children) {
if (! (child instanceof Plugin)) { // Hide Plug-ins
node.add(buildTreeNode(child));
}
}
nodes.put(c, node);
return node;
}
protected void addAction(JPopupMenu menu, Action a) {
if (a != null) {
menu.add(a).setFont(POPUP_MENU_FONT);
}
}
private void addActionGroup(JPopupMenu menu, List<Action> l) {
boolean empty = true;
for (final Action a : l) {
if (a != null) {
menu.add(a).setFont(POPUP_MENU_FONT);
empty = false;
}
}
if (!empty) {
menu.addSeparator();
}
l.clear();
}
protected JPopupMenu buildPopupMenu(final Configurable target) {
final JPopupMenu popup = new JPopupMenu();
final ArrayList<Action> l = new ArrayList<>();
l.add(buildEditAction(target));
l.add(buildEditPiecesAction(target));
addActionGroup(popup, l);
l.add(buildTranslateAction(target));
addActionGroup(popup, l);
l.add(buildHelpAction(target));
addActionGroup(popup, l);
l.add(buildSearchAction(target));
addActionGroup(popup, l);
l.add(buildDeleteAction(target));
l.add(buildCutAction(target));
l.add(buildCopyAction(target));
l.add(buildPasteAction(target));
l.add(buildMoveAction(target));
addActionGroup(popup, l);
for (final Action a : buildAddActionsFor(target)) {
addAction(popup, a);
}
if (hasChild(target, PieceSlot.class) || hasChild(target, CardSlot.class)) {
addAction(popup, buildMassPieceLoaderAction(target));
}
addAction(popup, buildImportAction(target));
return popup;
}
/**
* Enumerates our configure tree in preparation for searching it
* @param root - root of our module's tree.
* @return a list of search nodes
*/
private List<DefaultMutableTreeNode> getSearchNodes(DefaultMutableTreeNode root) {
final List<DefaultMutableTreeNode> searchNodes = new ArrayList<>();
final Enumeration<?> e = root.preorderEnumeration();
while (e.hasMoreElements()) {
searchNodes.add((DefaultMutableTreeNode)e.nextElement());
}
return searchNodes;
}
/**
* @return Search action - runs search dialog box, then searches
*/
protected Action buildSearchAction(final Configurable target) {
final Action a = new SearchAction(this, searchParameters);
a.setEnabled(true);
return a;
}
protected Action buildMoveAction(final Configurable target) {
Action a = null;
if (getTreeNode(target).getParent() != null) {
a = new AbstractAction(moveCmd) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), true);
d.setTitle(target.getConfigureName() == null ? moveCmd : moveCmd + " " + target.getConfigureName());
d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS));
final Box box = Box.createHorizontalBox();
box.add(new JLabel(Resources.getString("Editor.ConfigureTree.move_to_position")));
box.add(Box.createHorizontalStrut(10));
final JComboBox<String> select = new JComboBox<>();
final TreeNode parentNode = getTreeNode(target).getParent();
for (int i = 0; i < parentNode.getChildCount(); ++i) {
final Configurable c = (Configurable) ((DefaultMutableTreeNode) parentNode.getChildAt(i)).getUserObject();
final String name = (c.getConfigureName() != null ? c.getConfigureName() : "") + " [" + getConfigureName(c.getClass()) + "]";
select.addItem((i + 1) + ": " + name);
}
final DefaultMutableTreeNode targetNode = getTreeNode(target);
final int currentIndex = targetNode.getParent().getIndex(targetNode);
select.setSelectedIndex(currentIndex);
box.add(select);
final JButton ok = new JButton(Resources.getString(Resources.OK));
ok.addActionListener(e1 -> {
final int index = select.getSelectedIndex();
if (currentIndex != index) {
final Configurable parent = getParent(targetNode);
if (remove(parent, target)) {
insert(parent, target, index);
}
}
d.dispose();
});
d.add(box);
d.add(ok);
SwingUtils.repack(d);
d.setLocationRelativeTo(d.getParent());
d.setVisible(true);
}
};
}
return a;
}
protected Action buildCutAction(final Configurable target) {
Action a = null;
if (getTreeNode(target).getParent() != null) {
a = new AbstractAction(cutCmd) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
cutData = getTreeNode(target);
copyData = null;
updateEditMenu();
}
};
}
return a;
}
protected Action buildCopyAction(final Configurable target) {
Action a = null;
if (getTreeNode(target).getParent() != null) {
a = new AbstractAction(copyCmd) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
copyData = getTreeNode(target);
cutData = null;
updateEditMenu();
}
};
}
return a;
}
protected Action buildPasteAction(final Configurable target) {
final Action a = new AbstractAction(pasteCmd) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
if (cutData != null) {
final DefaultMutableTreeNode targetNode = getTreeNode(target);
if (targetNode.isNodeAncestor(cutData)) {
chat(Resources.getString("Editor.cant_cut_ancestor_to_child"));
return;
}
final Configurable cutObj = (Configurable) cutData.getUserObject();
final Configurable convertedCutObj = convertChild(target, cutObj);
if (remove(getParent(cutData), cutObj)) {
insert(target, convertedCutObj, targetNode.getChildCount());
}
copyData = getTreeNode(convertedCutObj);
}
else if (copyData != null) {
final Configurable copyBase = (Configurable) copyData.getUserObject();
Configurable clone = null;
try {
clone = convertChild(target, copyBase.getClass().getConstructor().newInstance());
}
catch (Throwable t) {
ReflectionUtils.handleNewInstanceFailure(t, copyBase.getClass());
}
if (clone != null) {
clone.build(copyBase.getBuildElement(Builder.createNewDocument()));
insert(target, clone, getTreeNode(target).getChildCount());
updateGpIds(clone);
}
}
cutData = null;
updateEditMenu();
}
};
a.setEnabled(isValidPasteTarget(target));
return a;
}
protected boolean isValidPasteTarget(Configurable target) {
return (cutData != null &&
isValidParent(target, (Configurable) cutData.getUserObject())) ||
(copyData != null &&
isValidParent(target, (Configurable) copyData.getUserObject()));
}
/**
* Some components need to be converted to a new type before insertion.
*
* Currently this is used to allow cut and paste of CardSlots and PieceSlots
* between Decks and GamePiece Palette components.
*
* @param parent Parent Configurable
* @param child Child Configurable
* @return new Child
*/
protected Configurable convertChild(Configurable parent, Configurable child) {
if (child.getClass() == PieceSlot.class && isAllowedChildClass(parent, CardSlot.class)) {
return new CardSlot((PieceSlot) child);
}
else if (child.getClass() == CardSlot.class && isAllowedChildClass(parent, PieceSlot.class)) {
return new PieceSlot((CardSlot) child);
}
else {
return child;
}
}
protected boolean isAllowedChildClass(Configurable parent, Class<?> childClass) {
final Class<?>[] allowableClasses = parent.getAllowableConfigureComponents();
for (final Class<?> allowableClass : allowableClasses) {
if (allowableClass == childClass) {
return true;
}
}
return false;
}
/**
* Allocate new PieceSlot Id's to any PieceSlot sub-components
*
* @param c Configurable to update
*/
public void updateGpIds(Configurable c) {
if (c instanceof PieceSlot) {
((PieceSlot) c).updateGpId(GameModule.getGameModule());
}
else {
for (final Configurable comp : c.getConfigureComponents()) updateGpIds(comp);
}
}
protected Action buildImportAction(final Configurable target) {
return new AbstractAction(Resources.getString("Editor.ConfigureTree.add_imported_class")) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent evt) {
final Configurable child = importConfigurable();
if (child != null) {
try {
child.build(null);
if (child.getConfigurer() != null) {
final PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), false, child, helpWindow) {
private static final long serialVersionUID = 1L;
@Override
public void save() {
super.save();
insert(target, child, getTreeNode(target).getChildCount());
}
@Override
public void cancel() {
dispose();
}
};
w.setVisible(true);
}
else {
insert(target, child, getTreeNode(target).getChildCount());
}
}
// FIXME: review error message
catch (Exception ex) {
JOptionPane.showMessageDialog(getTopLevelAncestor(), "Error adding " + getConfigureName(child) + " to " + getConfigureName(target) + "\n" //NON-NLS
+ ex.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE); //NON-NLS
}
}
}
};
}
protected Action buildMassPieceLoaderAction(final Configurable target) {
Action a = null;
final ConfigureTree tree = this;
if (getTreeNode(target).getParent() != null) {
Resources.getString("Editor.ConfigureTree.add_cards");
final String desc = hasChild(target, CardSlot.class) ? Resources.getString("Editor.ConfigureTree.add_cards") : Resources.getString("Editor.ConfigureTree.add_pieces");
a = new AbstractAction(desc) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
new MassPieceLoader(tree, target).load();
}
};
}
return a;
}
protected boolean hasChild(Configurable parent, Class<?> childClass) {
for (final Class<?> c : parent.getAllowableConfigureComponents()) {
if (c.equals(childClass)) {
return true;
}
}
return false;
}
protected List<Action> buildAddActionsFor(final Configurable target) {
final ArrayList<Action> l = new ArrayList<>();
for (final Class<? extends Buildable> newConfig :
target.getAllowableConfigureComponents()) {
l.add(buildAddAction(target, newConfig));
}
for (final AdditionalComponent add : additionalComponents) {
if (target.getClass().equals(add.getParent())) {
final Class<? extends Buildable> newConfig = add.getChild();
l.add(buildAddAction(target, newConfig));
}
}
return l;
}
/**
* @deprecated Use {@link #buildAddActionsFor(Configurable)} instead.
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
protected Enumeration<Action> buildAddActions(final Configurable target) {
ProblemDialog.showDeprecated("2020-08-06");
return Collections.enumeration(buildAddActionsFor(target));
}
protected Action buildAddAction(final Configurable target, final Class<? extends Buildable> newConfig) {
return new AbstractAction(Resources.getString("Editor.ConfigureTree.add_component", getConfigureName(newConfig))) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent evt) {
Configurable ch = null;
try {
ch = (Configurable) newConfig.getConstructor().newInstance();
}
catch (Throwable t) {
ReflectionUtils.handleNewInstanceFailure(t, newConfig);
}
if (ch != null) {
final Configurable child = ch;
child.build(null);
if (child instanceof PieceSlot) {
((PieceSlot) child).updateGpId(GameModule.getGameModule());
}
if (child.getConfigurer() != null) {
if (insert(target, child, getTreeNode(target).getChildCount())) {
// expand the new node
final TreePath path = new TreePath(getTreeNode(child).getPath());
expandPath(path);
final PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), false, child, helpWindow) {
private static final long serialVersionUID = 1L;
@Override
public void cancel() {
ConfigureTree.this.remove(target, child);
dispose();
}
};
w.setVisible(true);
}
}
else {
insert(target, child, getTreeNode(target).getChildCount());
}
}
}
};
}
protected Action buildHelpAction(final Configurable target) {
final Action showHelp;
final HelpFile helpFile = target.getHelpFile();
if (helpFile == null) {
showHelp = new ShowHelpAction(null, null);
showHelp.setEnabled(false);
}
else {
showHelp = new ShowHelpAction(helpFile.getContents(), null);
}
return showHelp;
}
protected Action buildCloneAction(final Configurable target) {
final DefaultMutableTreeNode targetNode = getTreeNode(target);
if (targetNode.getParent() != null) {
return new AbstractAction(Resources.getString("Editor.ConfigureTree.clone")) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent evt) {
Configurable clone = null;
try {
clone = target.getClass().getConstructor().newInstance();
}
catch (Throwable t) {
ReflectionUtils.handleNewInstanceFailure(t, target.getClass());
}
if (clone != null) {
clone.build(target.getBuildElement(Builder.createNewDocument()));
insert(getParent(targetNode), clone,
targetNode.getParent().getIndex(targetNode) + 1);
}
}
};
}
else {
return null;
}
}
protected Configurable getParent(final DefaultMutableTreeNode targetNode) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) targetNode.getParent();
return parentNode == null ? null : (Configurable) parentNode.getUserObject();
}
protected Action buildDeleteAction(final Configurable target) {
final DefaultMutableTreeNode targetNode = getTreeNode(target);
final Configurable parent = getParent(targetNode);
if (targetNode.getParent() != null) {
return new AbstractAction(deleteCmd) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent evt) {
final int row = selectedRow;
remove(parent, target);
if (row < getRowCount()) {
setSelectionRow(row);
}
else {
setSelectionRow(row - 1);
}
}
};
}
else {
return null;
}
}
protected Action buildEditPiecesAction(final Configurable target) {
if (canContainGamePiece(target)) {
return new EditContainedPiecesAction(target);
}
else {
return null;
}
}
protected Action buildEditAction(final Configurable target) {
return new EditPropertiesAction(target, helpWindow, (Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this);
}
protected Action buildTranslateAction(final Configurable target) {
final Action a = new TranslateAction(target, helpWindow, this);
a.setEnabled(target.getI18nData().isTranslatable());
return a;
}
public boolean canContainGamePiece(final Configurable target) {
boolean canContainPiece = false;
for (final Class<?> c : target.getAllowableConfigureComponents()) {
if (PieceSlot.class.isAssignableFrom(c)) {
canContainPiece = true;
break;
}
}
return canContainPiece;
}
protected boolean remove(Configurable parent, Configurable child) {
try {
child.removeFrom(parent);
parent.remove(child);
((DefaultTreeModel) getModel()).removeNodeFromParent(getTreeNode(child));
notifyStateChanged(true);
return true;
}
// FIXME: review error message
catch (IllegalBuildException err) {
JOptionPane.showMessageDialog(getTopLevelAncestor(), "Cannot delete " + getConfigureName(child) + " from " + getConfigureName(parent) + "\n" //NON-NLS
+ err.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE); //NON-NLS
return false;
}
}
protected boolean insert(Configurable parent, Configurable child, int index) {
Configurable theChild = child;
// Convert subclasses of GlobalProperty to an actual GlobalProperty before inserting into the GlobalProperties container
if (parent.getClass() == GlobalProperties.class && child.getClass() == ZoneProperty.class) {
theChild = new GlobalProperty((GlobalProperty) child);
}
if (parent.getClass() == Zone.class && child.getClass() == GlobalProperty.class) {
theChild = new ZoneProperty((GlobalProperty) child);
}
final DefaultMutableTreeNode childNode = buildTreeNode(theChild);
final DefaultMutableTreeNode parentNode = getTreeNode(parent);
final Configurable[] oldContents = parent.getConfigureComponents();
final ArrayList<Configurable> moveToBack = new ArrayList<>();
for (int i = index; i < oldContents.length; ++i) {
try {
oldContents[i].removeFrom(parent);
parent.remove(oldContents[i]);
}
// FIXME: review error message
catch (IllegalBuildException err) {
JOptionPane.showMessageDialog(getTopLevelAncestor(), "Can't insert " + getConfigureName(theChild) + " before " + getConfigureName(oldContents[i]), //NON-NLS
"Illegal configuration", JOptionPane.ERROR_MESSAGE); //NON-NLS
for (int j = index; j < i; ++j) {
parent.add(oldContents[j]);
oldContents[j].addTo(parent);
}
return false;
}
moveToBack.add(oldContents[i]);
}
boolean succeeded = true;
try {
theChild.addTo(parent);
parent.add(theChild);
parentNode.insert(childNode, index);
final int[] childI = new int[1];
childI[0] = index;
((DefaultTreeModel) getModel()).nodesWereInserted(parentNode, childI);
}
// FIXME: review error message
catch (IllegalBuildException err) {
JOptionPane.showMessageDialog(getTopLevelAncestor(), "Can't add " + getConfigureName(child) + "\n" + err.getMessage(), "Illegal configuration", //NON-NLS
JOptionPane.ERROR_MESSAGE);
succeeded = false;
}
for (final Configurable c : moveToBack) {
parent.add(c);
c.addTo(parent);
}
notifyStateChanged(true);
return succeeded;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
final DefaultMutableTreeNode newValue = getTreeNode((Configurable) evt.getSource());
((DefaultTreeModel) getModel()).nodeChanged(newValue);
}
/**
* Custom Tree Cell Renderer
* Change the font to italic if the Configurable held by the node for this cell has been edited.
*/
static class Renderer extends javax.swing.tree.DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
private Font plainFont;
private Font italicFont;
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
final JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (plainFont == null) {
plainFont = label.getFont();
}
if (value instanceof ConfigureTreeNode) {
final ConfigureTreeNode c = (ConfigureTreeNode) value;
if (c.isEdited()) {
if (italicFont == null) {
final Font f = label.getFont();
italicFont = new Font(f.getFontName(), Font.ITALIC, f.getSize());
}
label.setFont(italicFont);
}
else {
label.setFont(plainFont);
}
}
return label;
}
}
/**
* Returns the name of the class for display purposes. Reflection is
* used to call <code>getConfigureTypeName()</code>, which should be
* a static method if it exists in the given class. (This is necessary
* because static methods are not permitted in interfaces.)
*
* @param c the class whose configure name will be returned
* @return the configure name of the class
*/
public static String getConfigureName(Class<?> c) {
try {
return (String) c.getMethod("getConfigureTypeName").invoke(null);
}
catch (NoSuchMethodException e) {
// Ignore. This is normal, since some classes won't have this method.
}
catch (IllegalAccessException | ExceptionInInitializerError
| NullPointerException | InvocationTargetException | IllegalArgumentException e) {
ErrorDialog.bug(e);
}
return c.getName().substring(c.getName().lastIndexOf(".") + 1);
}
public static String getConfigureName(Configurable c) {
if (c.getConfigureName() != null && c.getConfigureName().length() > 0) {
return c.getConfigureName();
}
else {
return getConfigureName(c.getClass());
}
}
protected Configurable importConfigurable() {
final String className = JOptionPane.showInputDialog(
getTopLevelAncestor(),
Resources.getString("Editor.ConfigureTree.java_name"));
if (className == null) return null;
Object o = null;
try {
o = GameModule.getGameModule().getDataArchive()
.loadClass(className).getConstructor().newInstance();
}
catch (Throwable t) {
ReflectionUtils.handleImportClassFailure(t, className);
}
if (o == null) return null;
if (o instanceof Configurable) return (Configurable) o;
ErrorDialog.show("Error.not_a_configurable", className); //$NON-NLS-1$//
return null;
}
protected void maybePopup(MouseEvent e) {
final Configurable target = getTarget(e.getX(), e.getY());
if (target == null) {
return;
}
setSelectionRow(getClosestRowForLocation(e.getX(), e.getY()));
final JPopupMenu popup = buildPopupMenu(target);
popup.show(this, e.getX(), e.getY());
popup.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuCanceled(PopupMenuEvent evt) {
repaint();
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent evt) {
repaint();
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent evt) {
}
});
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
maybePopup(e);
}
}
// FIXME: should clicked handling be in mouseClicked()?
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
maybePopup(e);
}
else if (e.getClickCount() == 2 && SwingUtils.isMainMouseButtonDown(e)) {
final Configurable target = getTarget(e.getX(), e.getY());
if (target == null) {
return;
}
if (target.getConfigurer() != null) {
final Action a = buildEditAction(target);
if (a != null) {
a.actionPerformed(new ActionEvent(e.getSource(), ActionEvent.ACTION_PERFORMED, "Edit"));
}
}
}
}
/*
* protected void performDrop(Configurable target) { DefaultMutableTreeNode dragNode = getTreeNode(dragging);
* DefaultMutableTreeNode targetNode = getTreeNode(target); Configurable parent = null; int index = 0; if
* (isValidParent(target, dragging)) { parent = target; index = targetNode.getChildCount(); if (dragNode.getParent() ==
* targetNode) { index--; } } else if (targetNode.getParent() != null && isValidParent(getParent(targetNode),
* dragging)) { parent = (Configurable) ((DefaultMutableTreeNode) targetNode.getParent()).getUserObject(); index =
* targetNode.getParent().getIndex(targetNode); } if (parent != null) { remove(getParent(dragNode), dragging);
* insert(parent, dragging, index); } dragging = null; }
*/
public DefaultMutableTreeNode getTreeNode(Configurable target) {
return nodes.get(target);
}
@Override
public void mouseDragged(MouseEvent evt) {
}
protected boolean isValidParent(Configurable parent, Configurable child) {
if (parent != null && child != null) {
final Class<?>[] c = parent.getAllowableConfigureComponents();
for (final Class<?> aClass : c) {
if (aClass.isAssignableFrom(child.getClass()) ||
((aClass == CardSlot.class) && (child.getClass() == PieceSlot.class)) || // Allow PieceSlots to be pasted to Decks
((aClass == ZoneProperty.class) && (child.getClass() == GlobalProperty.class)) // Allow Global Properties to be saved as Zone Properties
) {
return true;
}
}
}
return false;
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
/*
* Refresh the display of a node
*/
public void nodeUpdated(Configurable target) {
final DefaultMutableTreeNode node = getTreeNode(target);
final Configurable parent = getParent(node);
if (remove(parent, target)) {
insert(parent, target, 0);
}
((DefaultTreeModel) getModel()).nodeChanged(node);
}
/**
* Configurers that add or remove their own children directly should implement the Mutable interface so that
* ConfigureTree can refresh the changed node.
*/
public interface Mutable {
}
/**
* Build an AddAction and execute it to request a new component from the user
*
* @param parent
* Target Parent
* @param child
* Type to add
*/
public void externalInsert(Configurable parent, Configurable child) {
insert(parent, child, getTreeNode(parent).getChildCount());
}
public Action getHelpAction() {
return helpAction;
}
public void populateEditMenu(EditorWindow ew) {
final MenuManager mm = MenuManager.getInstance();
mm.addAction("Editor.delete", deleteAction);
mm.addAction("Editor.cut", cutAction);
mm.addAction("Editor.copy", copyAction);
mm.addAction("Editor.paste", pasteAction);
mm.addAction("Editor.move", moveAction);
mm.addAction("Editor.search", searchAction);
mm.addAction("Editor.properties", propertiesAction);
mm.addAction("Editor.ModuleEditor.translate", translateAction);
updateEditMenu();
}
/**
* Handle main Edit menu selections/accelerators
*
* @param action
* Edit command name
*/
protected void doKeyAction(String action) {
final DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) this.getLastSelectedPathComponent();
if (targetNode != null) {
final Configurable target = (Configurable) targetNode.getUserObject();
Action a = null;
if (cutCmd.equals(action)) {
a = buildCutAction(target);
}
else if (copyCmd.equals(action)) {
a = buildCopyAction(target);
}
else if (pasteCmd.equals(action) || action.equals(String.valueOf(pasteKey.getKeyChar()))) {
a = buildPasteAction(target);
}
else if (deleteCmd.equals(action)) {
a = buildDeleteAction(target);
}
else if (moveCmd.equals(action)) {
a = buildMoveAction(target);
}
else if (searchCmd.equals(action)) {
a = buildSearchAction(target);
}
else if (propertiesCmd.equals(action)) {
a = buildEditAction(target);
}
else if (translateCmd.equals(action)) {
a = buildTranslateAction(target);
}
else if (helpCmd.equals(action)) {
a = buildHelpAction(target);
}
if (a != null) {
a.actionPerformed(null);
}
}
}
/**
* Tree selection changed, record info about the currently selected component
*/
@Override
public void valueChanged(TreeSelectionEvent e) {
selected = null;
final TreePath path = e.getPath();
if (path != null) {
final DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
selected = (Configurable) selectedNode.getUserObject();
selectedRow = getRowForPath(path);
updateEditMenu();
((DefaultTreeModel) getModel()).nodeChanged(selectedNode);
}
}
protected void updateEditMenu() {
deleteAction.setEnabled(selected != null);
cutAction.setEnabled(selected != null);
copyAction.setEnabled(selected != null);
pasteAction.setEnabled(selected != null && isValidPasteTarget(selected));
moveAction.setEnabled(selected != null);
searchAction.setEnabled(true);
// Check the cached Configurer in the TreeNode, not the Configurable as Configurable.getConfigurer()
// is very expensive and resets the Configurer causing label truncation issues in the JTree
propertiesAction.setEnabled(selected != null && selected.getConfigurer() != null);
translateAction.setEnabled(selected != null);
}
/**
* Find the parent Configurable of a specified Configurable
*
* @param target target Configurable
* @return parent
*/
protected Configurable getParent(Configurable target) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) getTreeNode(target).getParent();
return (Configurable) parentNode.getUserObject();
}
public String getSearchCmd() {
return searchCmd;
}
/**
* Record additional available components to add to the popup menu.
*
* @param parent Parent Class
* @param child Child Class
*/
public static void addAdditionalComponent(Class<? extends Buildable> parent, Class<? extends Buildable> child) {
additionalComponents.add(new AdditionalComponent(parent, child));
}
protected static class AdditionalComponent {
Class<? extends Buildable> parent;
Class<? extends Buildable> child;
public AdditionalComponent(Class<? extends Buildable> p, Class<? extends Buildable> c) {
parent = p;
child = c;
}
public Class<? extends Buildable> getParent() {
return parent;
}
public Class<? extends Buildable> getChild() {
return child;
}
}
/**
* Container for search parameters
*/
private static class SearchParameters {
public static final String SEARCH_STRING = "searchString"; //$NON-NLS-1$//
public static final String MATCH_CASE = "matchCase"; //$NON-NLS-1$//
public static final String MATCH_NAMES = "matchNames"; //$NON-NLS-1$//
public static final String MATCH_TYPES = "matchTypes"; //$NON-NLS-1$//
public static final String MATCH_ADVANCED = "matchAdvanced"; //$NON-NLS-1$//
public static final String MATCH_TRAITS = "matchTraits"; //$NON-NLS-1$//
public static final String MATCH_EXPRESSIONS = "matchExpressions"; //$NON-NLS-1$//
public static final String MATCH_PROPERTIES = "matchProperties"; //$NON-NLS-1$//
public static final String MATCH_KEYS = "matchKeys"; //$NON-NLS-1$//
public static final String MATCH_MENUS = "matchMenus"; //$NON-NLS-1$//
public static final String MATCH_MESSAGES = "matchMessages"; //$NON-NLS-1$//
/** Current search string */
private String searchString;
/** True if case-sensitive */
private boolean matchCase;
/** True if match configurable names */
private boolean matchNames;
/** True if match class names */
private boolean matchTypes;
/** True if using advanced search (enables subsequent items) */
private boolean matchAdvanced;
/** True if match traits (names, descriptions, menu commands) */
private boolean matchTraits;
/** True if match expressions */
private boolean matchExpressions;
/** True if match Properties */
private boolean matchProperties;
/** True if match key commands */
private boolean matchKeys;
/** True if match context menu text */
private boolean matchMenus;
/** True if match Message Formats */
private boolean matchMessages;
/** Attach to our module preferences, if relevant */
private static Prefs prefs;
/**
* Constructs a new search parameters object, using the preferences.
*/
public SearchParameters() {
// Attach to our module preferences if constructed this way. This also marks that we will write them when modified
prefs = GameModule.getGameModule().getPrefs();
prefs.addOption(null, new StringConfigurer(SearchParameters.SEARCH_STRING, null, ""));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_CASE, null, false));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_NAMES, null, true));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_TYPES, null, true));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_ADVANCED, null, false));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_TRAITS, null, true));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_EXPRESSIONS, null, true));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_PROPERTIES, null, true));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_KEYS, null, true));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_MENUS, null, true));
prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_MESSAGES, null, true));
searchString = (String) prefs.getValue(SearchParameters.SEARCH_STRING);
matchCase = (Boolean)prefs.getValue(SearchParameters.MATCH_CASE);
matchNames = (Boolean)prefs.getValue(SearchParameters.MATCH_NAMES);
matchTypes = (Boolean)prefs.getValue(SearchParameters.MATCH_TYPES);
matchAdvanced = (Boolean)prefs.getValue(SearchParameters.MATCH_ADVANCED);
matchTraits = (Boolean)prefs.getValue(SearchParameters.MATCH_TRAITS);
matchExpressions = (Boolean)prefs.getValue(SearchParameters.MATCH_EXPRESSIONS);
matchProperties = (Boolean)prefs.getValue(SearchParameters.MATCH_PROPERTIES);
matchKeys = (Boolean)prefs.getValue(SearchParameters.MATCH_KEYS);
matchMenus = (Boolean)prefs.getValue(SearchParameters.MATCH_MENUS);
matchMessages = (Boolean)prefs.getValue(SearchParameters.MATCH_MESSAGES);
}
/**
* Constructs a new search parameters object
*/
public SearchParameters(String searchString, boolean matchCase, boolean matchNames, boolean matchTypes, boolean matchAdvanced, boolean matchTraits, boolean matchExpressions, boolean matchProperties, boolean matchKeys, boolean matchMenus, boolean matchMessages) {
this.searchString = searchString;
this.matchCase = matchCase;
this.matchNames = matchNames;
this.matchTypes = matchTypes;
this.matchAdvanced = matchAdvanced;
this.matchTraits = matchTraits;
this.matchExpressions = matchExpressions;
this.matchProperties = matchProperties;
this.matchKeys = matchKeys;
this.matchMenus = matchMenus;
this.matchMessages = matchMessages;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
writePrefs();
}
public boolean isMatchCase() {
return matchCase;
}
public void setMatchCase(boolean matchCase) {
this.matchCase = matchCase;
writePrefs();
}
public boolean isMatchNames() {
return matchNames;
}
public void setMatchNames(boolean matchNames) {
this.matchNames = matchNames;
writePrefs();
}
public boolean isMatchTypes() {
return matchTypes;
}
public void setMatchTypes(boolean matchTypes) {
this.matchTypes = matchTypes;
writePrefs();
}
public boolean isMatchAdvanced() {
return matchAdvanced;
}
public void setMatchAdvanced(boolean matchAdvanced) {
this.matchAdvanced = matchAdvanced;
writePrefs();
}
public boolean isMatchTraits() {
return matchTraits;
}
public void setMatchTraits(boolean matchTraits) {
this.matchTraits = matchTraits;
writePrefs();
}
public boolean isMatchExpressions() {
return matchExpressions;
}
public void setMatchExpressions(boolean matchExpressions) {
this.matchExpressions = matchExpressions;
writePrefs();
}
public boolean isMatchProperties() {
return matchProperties;
}
public void setMatchProperties(boolean matchProperties) {
this.matchProperties = matchProperties;
writePrefs();
}
public boolean isMatchKeys() {
return matchKeys;
}
public void setMatchKeys(boolean matchKeys) {
this.matchKeys = matchKeys;
writePrefs();
}
public boolean isMatchMenus() {
return matchMenus;
}
public void setMatchMenus(boolean matchMenus) {
this.matchMenus = matchMenus;
writePrefs();
}
public boolean isMatchMessages() {
return matchMessages;
}
public void setMatchMessages(boolean matchMessages) {
this.matchMessages = matchMessages;
writePrefs();
}
public void setFrom(final SearchParameters searchParameters) {
searchString = searchParameters.getSearchString();
matchCase = searchParameters.isMatchCase();
matchNames = searchParameters.isMatchNames();
matchTypes = searchParameters.isMatchTypes();
matchAdvanced = searchParameters.isMatchAdvanced();
matchTraits = searchParameters.isMatchTraits();
matchExpressions = searchParameters.isMatchExpressions();
matchProperties = searchParameters.isMatchProperties();
matchKeys = searchParameters.isMatchKeys();
matchMenus = searchParameters.isMatchMenus();
matchMessages = searchParameters.isMatchMessages();
writePrefs();
}
public void writePrefs() {
if (prefs != null) {
prefs.setValue(SEARCH_STRING, searchString);
prefs.setValue(MATCH_CASE, matchCase);
prefs.setValue(MATCH_NAMES, matchNames);
prefs.setValue(MATCH_TYPES, matchTypes);
prefs.setValue(MATCH_ADVANCED, matchAdvanced);
prefs.setValue(MATCH_TRAITS, matchTraits);
prefs.setValue(MATCH_EXPRESSIONS, matchExpressions);
prefs.setValue(MATCH_PROPERTIES, matchProperties);
prefs.setValue(MATCH_KEYS, matchKeys);
prefs.setValue(MATCH_MENUS, matchMenus);
prefs.setValue(MATCH_MESSAGES, matchMessages);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final SearchParameters that = (SearchParameters) o;
return isMatchCase() == that.isMatchCase() &&
isMatchNames() == that.isMatchNames() &&
isMatchTypes() == that.isMatchTypes() &&
isMatchTraits() == that.isMatchTraits() &&
isMatchAdvanced() == that.isMatchAdvanced() &&
isMatchExpressions() == that.isMatchExpressions() &&
isMatchProperties() == that.isMatchProperties() &&
isMatchKeys() == that.isMatchKeys() &&
isMatchMenus() == that.isMatchMenus() &&
isMatchMessages() == that.isMatchMessages() &&
getSearchString().equals(that.getSearchString());
}
@Override
public int hashCode() {
return Objects.hash(getSearchString(), isMatchCase(), isMatchNames(), isMatchTypes(), isMatchAdvanced(),
isMatchTraits(), isMatchExpressions(), isMatchProperties(), isMatchKeys(),
isMatchMenus(), isMatchMessages());
}
}
private static class SearchAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private final ConfigureTree configureTree;
private final SearchParameters searchParameters;
/**
* Constructs a new {@link SearchAction}
*
* @param configureTree back reference to the {@link ConfigureTree}
* @param searchParameters reference to the search parameter object
*/
public SearchAction(ConfigureTree configureTree, SearchParameters searchParameters) {
super(configureTree.getSearchCmd());
this.configureTree = configureTree;
this.searchParameters = searchParameters;
}
@Override
public void actionPerformed(ActionEvent e) {
JDialog d = configureTree.getSearchDialog();
final JTextField search;
if (d != null) {
search = configureTree.getSearchField();
search.selectAll();
}
else {
d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, configureTree), false);
configureTree.setSearchDialog(d);
d.setTitle(configureTree.getSearchCmd());
search = new HintTextField(32, Resources.getString("Editor.search_string"));
search.setText(searchParameters.getSearchString());
configureTree.setSearchField(search);
search.selectAll();
final JCheckBox sensitive = new JCheckBox(Resources.getString("Editor.search_case"), searchParameters.isMatchCase());
final JCheckBox advanced = new JCheckBox(Resources.getString("Editor.search_advanced"), searchParameters.isMatchAdvanced());
final JCheckBox names = new JCheckBox(Resources.getString("Editor.search_names"), searchParameters.isMatchNames());
final JCheckBox types = new JCheckBox(Resources.getString("Editor.search_types"), searchParameters.isMatchTypes());
final JCheckBox traits = new JCheckBox(Resources.getString("Editor.search_traits"), searchParameters.isMatchTraits());
final JCheckBox expressions = new JCheckBox(Resources.getString("Editor.search_expressions"), searchParameters.isMatchExpressions());
final JCheckBox properties = new JCheckBox(Resources.getString("Editor.search_properties"), searchParameters.isMatchProperties());
final JCheckBox keys = new JCheckBox(Resources.getString("Editor.search_keys"), searchParameters.isMatchKeys());
final JCheckBox menus = new JCheckBox(Resources.getString("Editor.search_menus"), searchParameters.isMatchMenus());
final JCheckBox messages = new JCheckBox(Resources.getString("Editor.search_messages"), searchParameters.isMatchMessages());
final Consumer<Boolean> visSetter = visible -> {
names.setVisible(visible);
types.setVisible(visible);
traits.setVisible(visible);
expressions.setVisible(visible);
properties.setVisible(visible);
keys.setVisible(visible);
menus.setVisible(visible);
messages.setVisible(visible);
};
advanced.addChangeListener(l -> {
visSetter.accept(advanced.isSelected());
SwingUtils.repack(configureTree.getSearchDialog());
});
visSetter.accept(advanced.isSelected());
configureTree.setSearchAdvanced(advanced);
final JButton find = new JButton(Resources.getString("Editor.search_next"));
find.addActionListener(e12 -> {
final SearchParameters parametersSetInDialog =
new SearchParameters(search.getText(), sensitive.isSelected(), names.isSelected(), types.isSelected(), true, traits.isSelected(), expressions.isSelected(), properties.isSelected(), keys.isSelected(), menus.isSelected(), messages.isSelected());
final boolean anyChanges = !searchParameters.equals(parametersSetInDialog);
if (anyChanges) {
searchParameters.setFrom(parametersSetInDialog);
}
// If literally no search parameters are selectable, turn at least one on (and print warning)
if (!searchParameters.isMatchNames() && !searchParameters.isMatchTypes() && searchParameters.isMatchAdvanced() && (!searchParameters.isMatchTraits() && !searchParameters.isMatchExpressions() && !searchParameters.isMatchProperties() && !searchParameters.isMatchKeys() && !searchParameters.isMatchMenus() && !searchParameters.isMatchMessages())) {
searchParameters.setMatchNames(true);
names.setSelected(true);
ConfigureTree.chat(Resources.getString("Editor.search_all_off"));
}
if (!searchParameters.getSearchString().isEmpty()) {
if (anyChanges) {
// Unless we're just continuing to the next match in an existing search, compute & display hit count
final int matches = getNumMatches(searchParameters.getSearchString());
chat(matches + " " + Resources.getString("Editor.search_count") + noHTML(searchParameters.getSearchString()));
}
// Find first match
final DefaultMutableTreeNode node = findNode(searchParameters.getSearchString());
// Assuming *something* matched, scroll to it and show any "trait hits"
if (node != null) {
final TreePath path = new TreePath(node.getPath());
configureTree.setSelectionPath(path);
configureTree.scrollPathToVisible(path);
if (searchParameters.isMatchAdvanced()) {
showHitList(node, searchParameters.getSearchString());
}
}
else {
chat(Resources.getString("Editor.search_none_found") + noHTML(searchParameters.getSearchString()));
}
}
});
final JButton cancel = new JButton(Resources.getString(Resources.CANCEL));
cancel.addActionListener(e1 -> configureTree.getSearchDialog().setVisible(false));
final JButton help = new JButton(Resources.getString(Resources.HELP));
help.addActionListener(e2 -> showSearchHelp());
d.setLayout(new MigLayout("", "[fill]")); // NON-NLS
final JPanel panel = new JPanel(new MigLayout("hidemode 3,wrap 1" + "," + ConfigurerLayout.STANDARD_GAPY, "[fill]")); // NON-NLS
panel.setBorder(BorderFactory.createEtchedBorder());
// top row
panel.add(search);
// options row
panel.add(sensitive);
panel.add(advanced);
// Advanced 1
panel.add(names);
panel.add(types);
// Advanced 2
panel.add(traits);
panel.add(expressions);
panel.add(properties);
// Advanced 3
panel.add(keys);
panel.add(menus);
panel.add(messages);
// buttons row
final JPanel bPanel = new JPanel(new MigLayout("ins 0", "push[]rel[]rel[]push")); // NON-NLS
bPanel.add(find, "tag ok,sg 1"); //$NON-NLS-1$//
bPanel.add(cancel, "tag cancel,sg 1"); //$NON-NLS-1$//
bPanel.add(help, "tag help,sg 1"); // NON-NLS
panel.add(bPanel, "grow"); // NON-NLS
d.add(panel, "grow"); // NON-NLS
d.getRootPane().setDefaultButton(find); // Enter key activates search
// Esc Key cancels
final KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
d.getRootPane().registerKeyboardAction(ee -> configureTree.getSearchDialog().setVisible(false), k, JComponent.WHEN_IN_FOCUSED_WINDOW);
}
search.requestFocus(); // Start w/ focus in search string field
if (!d.isVisible()) {
d.setLocationRelativeTo(d.getParent());
SwingUtils.repack(d);
d.setVisible(true);
}
}
private void showSearchHelp() {
// FIXME - Add Help ref
}
/**
* Search through the tree, starting at the currently selected location (and wrapping around if needed)
* Compare nodes until we find our search string (or have searched everything we can search)
* @return the node we found, or null if none
*/
private DefaultMutableTreeNode findNode(String searchString) {
final List<DefaultMutableTreeNode> searchNodes =
configureTree.getSearchNodes((DefaultMutableTreeNode)configureTree.getModel().getRoot());
final DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)configureTree.getLastSelectedPathComponent();
int bookmark = -1;
if (currentNode != null) {
bookmark =
IntStream
.range(0, searchNodes.size())
.filter(i -> searchNodes.get(i) == currentNode)
.findFirst()
.orElse(-1);
}
final Predicate<DefaultMutableTreeNode> nodeMatchesSearchString = node -> checkNode(node, searchString);
final DefaultMutableTreeNode foundNode =
searchNodes
.stream()
.skip(bookmark + 1)
.filter(nodeMatchesSearchString)
.findFirst()
.orElse(null);
if (foundNode != null) {
return foundNode;
}
return
searchNodes
.stream()
.limit(bookmark + 1)
.filter(nodeMatchesSearchString)
.findFirst()
.orElse(null);
}
/**
* @return how many total nodes match the search string
*/
private int getNumMatches(String searchString) {
final List<DefaultMutableTreeNode> searchNodes = configureTree.getSearchNodes((DefaultMutableTreeNode)configureTree.getModel().getRoot());
return (int) searchNodes.stream().filter(node -> checkNode(node, searchString)).count();
}
/**
* @param st - Search target (usually Decorator or AbstractConfigurable)
* @param searchString - our search string
* @return true if the node matches our searchString based on search configuration ("match" checkboxes)
*/
private boolean checkSearchTarget(SearchTarget st, String searchString) {
if (searchParameters.isMatchExpressions()) {
final List<String> exps = st.getExpressionList();
if (exps != null) {
for (final String s : exps) {
if (!StringUtils.isEmpty(s) && checkString(s, searchString)) {
return true;
}
}
}
}
if (searchParameters.isMatchProperties()) {
final List<String> props = st.getPropertyList();
if (props != null) {
for (final String s : props) {
if (!StringUtils.isEmpty(s) && checkString(s, searchString)) {
return true;
}
}
}
}
if (searchParameters.isMatchKeys()) {
final List<NamedKeyStroke> keys = st.getNamedKeyStrokeList();
if (keys != null) {
for (final NamedKeyStroke k : keys) {
if (k != null) {
final String s = k.isNamed() ? k.getName() : KeyNamer.getKeyString(k.getStroke());
if (!StringUtils.isEmpty(s) && checkString(s, searchString)) {
return true;
}
}
}
}
}
if (searchParameters.isMatchMenus()) {
final List<String> menus = st.getMenuTextList();
if (menus != null) {
for (final String s : menus) {
if (!StringUtils.isEmpty(s) && checkString(s, searchString)) {
return true;
}
}
}
}
if (searchParameters.isMatchMessages()) {
final List<String> msgs = st.getFormattedStringList();
if (msgs != null) {
for (final String s : msgs) {
if (!StringUtils.isEmpty(s) && checkString(s, searchString)) {
return true;
}
}
}
}
return false;
}
/**
* @param node - any node of our module tree
* @param searchString - our search string
* @return true if the node matches our searchString based on search configuration ("match" checkboxes)
*/
private boolean checkNode(DefaultMutableTreeNode node, String searchString) {
final Configurable c = (Configurable) node.getUserObject();
if (searchParameters.isMatchNames() || !searchParameters.isMatchAdvanced()) {
final String objectName = c.getConfigureName();
if (objectName != null && checkString(objectName, searchString)) {
return true;
}
}
if (searchParameters.isMatchTypes() || !searchParameters.isMatchAdvanced()) {
final String className = getConfigureName(c.getClass());
if ((className != null) && checkString(className, searchString)) {
return true;
}
}
if (!searchParameters.isMatchAdvanced()) {
return false;
}
// From here down we are only searching inside of SearchTarget objects (Piece/Prototypes, or searchable AbstractConfigurables)
GamePiece p;
boolean protoskip;
if (c instanceof GamePiece) {
p = (GamePiece) c;
protoskip = false;
}
else if (c instanceof PieceSlot) {
p = ((PieceSlot)c).getPiece();
protoskip = false;
}
else if (c instanceof PrototypeDefinition) {
p = ((PrototypeDefinition)c).getPiece();
protoskip = true;
}
else if (c instanceof SearchTarget) {
return checkSearchTarget((SearchTarget) c, searchString);
}
else {
return false;
}
// We're going to search Decorator from inner-to-outer (BasicPiece-on-out), so that user sees the traits hit in
// the same order they're listed in the PieceDefiner window. So we first traverse them in the "normal" direction
// outer to inner and make a list in the order we want to traverse it (for architectural reasons, just traversing
// with getOuter() would take us inside of prototypes inside a piece, which we don't want).
final List<GamePiece> pieces = new ArrayList<>();
pieces.add(p);
while (p instanceof Decorator) {
p = ((Decorator) p).getInner();
pieces.add(p);
}
Collections.reverse(pieces);
for (final GamePiece piece : pieces) {
if (!protoskip) { // Skip the fake "Basic Piece" on a Prototype definition
if (searchParameters.isMatchTraits()) {
if (piece instanceof EditablePiece) {
final String desc = ((EditablePiece) piece).getDescription();
if ((desc != null) && checkString(desc, searchString)) {
return true;
}
}
}
if (piece instanceof SearchTarget) {
if (checkSearchTarget((SearchTarget)piece, searchString)) {
return true;
}
}
}
protoskip = false;
}
return false;
}
/**
* Tracks how we are progressing through searching a target GamePiece or Configurable and its traits/attributes, and whether we need to display headers
*/
private static class TargetProgress {
public boolean targetShown = false;
public boolean traitShown = false;
/**
* When we're starting a new trait within the piece, clear the traitShown flag.
*/
void startNewTrait() {
traitShown = false;
}
/**
* Checks and displays the piece header if needed
* @param matchString our match string
*/
void checkShowPiece(String matchString) {
if (!targetShown) {
targetShown = true;
chat(matchString);
}
}
/**
* Checks and displays the piece header & trait/component headers, if needed
* @param matchString our match string
* @param desc trait description
*/
void checkShowTrait(String matchString, String idString, String desc) {
checkShowPiece(matchString);
if (!traitShown) {
traitShown = true;
chat(" {" + idString + "} " + ((desc != null) ? desc : "")); //NON-NLS
}
}
}
private void hitCheck(String s, String searchString, String matchString, String item, String desc, String show, TargetProgress progress) {
if (!StringUtils.isEmpty(s) && checkString(s, searchString)) {
progress.checkShowTrait(matchString, item, desc);
chat(" {" + show + "} " + noHTML(s)); //NON-NLS
}
}
private void stringListHits(Boolean flag, List<String> strings, String searchString, String matchString, String item, String desc, String show, TargetProgress progress) {
if (!flag || (strings == null)) {
return;
}
for (final String s : strings) {
hitCheck(s, searchString, matchString, item, desc, show, progress);
}
}
private void keyListHits(Boolean flag, List<NamedKeyStroke> keys, String searchString, String matchString, String item, String desc, String show, TargetProgress progress) {
if (!flag || (keys == null)) {
return;
}
for (final NamedKeyStroke k : keys) {
if (k != null) {
final String s = k.isNamed() ? k.getName() : KeyNamer.getKeyString(k.getStroke());
hitCheck(s, searchString, matchString, item, desc, show, progress);
}
}
}
private void showConfigurableHitList(DefaultMutableTreeNode node, String searchString) {
final Configurable c = (Configurable) node.getUserObject();
if (!(c instanceof SearchTarget)) {
return;
}
final String name = (c.getConfigureName() != null ? c.getConfigureName() : "") +
" [" + getConfigureName(c.getClass()) + "]";
final String matchString = "<b><u>Matches for " + noHTML(name) + ": </u></b>";
final SearchTarget st = (SearchTarget) c;
final String item = getConfigureName(c.getClass());
final TargetProgress progress = new TargetProgress();
stringListHits(searchParameters.isMatchNames(), Arrays.asList(c.getConfigureName()), searchString, matchString, item, "", "Name", progress);
stringListHits(searchParameters.isMatchTypes(), Arrays.asList(item), searchString, matchString, item, "", "Type", progress);
stringListHits(searchParameters.isMatchExpressions(), st.getExpressionList(), searchString, matchString, item, "", "Expression", progress);
stringListHits(searchParameters.isMatchProperties(), st.getPropertyList(), searchString, matchString, item, "", "Property", progress);
stringListHits(searchParameters.isMatchMenus(), st.getMenuTextList(), searchString, matchString, item, "", "UI Text", progress);
stringListHits(searchParameters.isMatchMessages(), st.getFormattedStringList(), searchString, matchString, item, "", "Message/Field", progress);
keyListHits(searchParameters.isMatchKeys(), st.getNamedKeyStrokeList(), searchString, matchString, item, "", "KeyCommand", progress);
}
/**
* If this node contains a Game Piece of some kind, displays a list of Trait information from the piece that
* matches our search parameters.
* @param node - any node of our module tree
* @param searchString - our search string
*/
private void showHitList(DefaultMutableTreeNode node, String searchString) {
final Configurable c = (Configurable) node.getUserObject();
GamePiece p;
boolean protoskip;
if (c instanceof GamePiece) {
p = (GamePiece)c;
protoskip = false; // This is a "real" GamePiece so we will look at the BasicPiece too
}
else if (c instanceof PieceSlot) {
p = ((PieceSlot)c).getPiece();
protoskip = false; // This is a "real" GamePiece so we will look at the BasicPiece too
}
else if (c instanceof PrototypeDefinition) {
p = ((PrototypeDefinition)c).getPiece();
protoskip = true; // This is a prototype definition, so we will ignore the BasicPiece entry
}
else {
showConfigurableHitList(node, searchString); // If no GamePiece, try regular Configurable search.
return;
}
final String name = (c.getConfigureName() != null ? c.getConfigureName() : "") +
" [" + getConfigureName(c.getClass()) + "]";
final TargetProgress progress = new TargetProgress();
final String matchString = "<b><u>Matches for " + name + ": </u></b>";
stringListHits(searchParameters.isMatchNames(), Arrays.asList(c.getConfigureName()), searchString, matchString, protoskip ? "Prototype Definition" : "Game Piece", "", "Name", progress);
stringListHits(searchParameters.isMatchTypes(), Arrays.asList(getConfigureName(c.getClass())), searchString, matchString, protoskip ? "Prototype Definition" : "Game Piece", "", "Type", progress);
// We're going to search Decorator from inner-to-outer (BasicPiece-on-out), so that user sees the traits hit in
// the same order they're listed in the PieceDefiner window. So we first traverse them in the "normal" direction
// outer to inner and make a list in the order we want to traverse it (for architectural reasons, just traversing
// with getOuter() would take us inside of prototypes inside a piece, which we don't want).
final List<GamePiece> pieces = new ArrayList<>();
pieces.add(p);
while (p instanceof Decorator) {
p = ((Decorator) p).getInner();
pieces.add(p);
}
Collections.reverse(pieces);
for (final GamePiece piece : pieces) {
if (!protoskip && (piece instanceof EditablePiece) && (piece instanceof Decorator)) { // Skip the fake "Basic Piece" on a Prototype definition
final String desc = ((EditablePiece) piece).getDescription();
final Decorator d = (Decorator)piece;
progress.startNewTrait(); // A new trait, so reset our "trait progress".
if (searchParameters.isMatchTraits()) {
if ((desc != null) && checkString(desc, searchString)) {
progress.checkShowTrait(matchString, "Trait", desc);
}
}
stringListHits(searchParameters.isMatchExpressions(), d.getExpressionList(), searchString, matchString, "Trait", desc, "Expression", progress);
stringListHits(searchParameters.isMatchProperties(), d.getPropertyList(), searchString, matchString, "Trait", desc, "Property", progress);
stringListHits(searchParameters.isMatchMenus(), d.getMenuTextList(), searchString, matchString, "Trait", desc, "UI Text", progress);
stringListHits(searchParameters.isMatchMessages(), d.getFormattedStringList(), searchString, matchString, "Trait", desc, "Message/Field", progress);
keyListHits(searchParameters.isMatchKeys(), d.getNamedKeyStrokeList(), searchString, matchString, "Trait", desc, "KeyCommand", progress);
}
protoskip = false;
}
}
/**
* Checks a single string against our search parameters
* @param target - string to check
* @param searchString - our search string
* @return true if this is a match based on our "matchCase" checkbox
*/
private boolean checkString(String target, String searchString) {
if (searchParameters.isMatchCase()) {
return target.contains(searchString);
}
else {
return target.toLowerCase().contains(searchString.toLowerCase());
}
}
}
/**
* Called when the Configurable held by a node has been edited.
* Set the edit status and re-build the Jtree label
* @param target Edited Configurable
*/
public void nodeEdited(Configurable target) {
final ConfigureTreeNode node = (ConfigureTreeNode) getTreeNode(target);
node.setEdited(true);
((DefaultTreeModel) getModel()).nodeChanged(node);
}
/**
* Custom TreeNode
* - Determine description for the node
* - Track this node has been edited
*/
private static class ConfigureTreeNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 1L;
private boolean edited;
public ConfigureTreeNode(Object userObject) {
super(userObject);
edited = false;
}
@Override
public String toString() {
String description = "";
final Configurable c = (Configurable) getUserObject();
if (c != null) {
description = (c.getConfigureName() != null ? c.getConfigureName() : "");
if (c instanceof GlobalProperty) {
final String desc = ((GlobalProperty)c).getDescription();
if (!desc.isEmpty()) {
description += " - " + desc;
}
}
if (c instanceof GlobalTranslatableMessage) {
final String desc = ((GlobalTranslatableMessage)c).getDescription();
if (!desc.isEmpty()) {
description += " - " + desc;
}
}
description += " [" + getConfigureName(c.getClass()) + "]";
}
return description;
}
public boolean isEdited() {
return edited;
}
public void setEdited(boolean edited) {
this.edited = edited;
}
/**
* Reset the edit flags on this node and all Children of this node
*/
private void resetEditFlags() {
setEdited(false);
resetChildEditFlags();
}
/**
* Reset the edit flags on all Children of this node
*/
public void resetChildEditFlags() {
if (getChildCount() > 0) {
for (final TreeNode node : children) {
((ConfigureTreeNode) node).resetEditFlags();
}
}
}
}
}
|
import java.io.*;
import java.util.Scanner;
import java.nio.file.*;
public class JuegoColores {
public static Scanner sc = new Scanner(System.in);
public static void printearpers (int[][] x, int f, int c) {
int i,j;
File progresivo = new File("progresivo.txt");
int opcion = leerposicion(777,progresivo);
for(i=0;i<=f-1;i++) {
System.out.println(" ");
for(j=0;j<=c-1;j++) {
if(opcion==1) {
if(x[i][j] ==1){
System.out.print("\033[38;5;196;48;5;196m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==2){
System.out.print("\033[38;5;34;48;5;34m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==3){
System.out.print("\033[38;5;21;48;5;21m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==4){
System.out.print("\033[38;5;226;48;5;226m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==5){
System.out.print("\033[38;5;165;48;5;165m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==6){
System.out.print("\033[38;5;45;48;5;45m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==7){
System.out.print("\033[38;5;94;48;5;94m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==8){
System.out.print("\033[37;47m"+x[i][j]+"\033[0m");
}
}
if(opcion==2) {
if(x[i][j] ==1){
System.out.print("\033[38;5;196m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==2){
System.out.print("\033[38;5;34m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==3){
System.out.print("\033[38;5;21m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==4){
System.out.print("\033[38;5;226m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==5){
System.out.print("\033[38;5;165m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==6){
System.out.print("\033[38;5;45m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==7){
System.out.print("\033[38;5;94m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==8){
System.out.print("\033[37m"+x[i][j]+"\033[0m");
}
}
if(opcion==3) {
System.out.print(""+x[i][j]);
}
System.out.print(" ");
}
System.out.println(" ");
}
System.out.print(" ");
System.out.println(" ");
}
public static void editor (String nombre) {
File Nivel = new File("niveles/"+nombre);
File carpeta = new File("niveles");
try {
if(carpeta.exists()==false){
carpeta.mkdirs();
}else{
}
if(Nivel.isFile()==true){
System.out.println("Ya existe un nivel con el mismo nombre");
System.out.println("Elije un nuevo nombre para el programa");
editor(sc.next());
}else{
Nivel.createNewFile();
}
} catch (IOException er) {
}
try {
FileOutputStream escribir = new FileOutputStream(Nivel);
if (Nivel.isFile()) {
} else {
Nivel.createNewFile();
}
System.out.println("Escribe el numero de filas");
int f = sc.nextInt();
escribir.write(f);
System.out.println("Escribe el numero de columnas");
int c = sc.nextInt();
escribir.write(c);
System.out.println("Escribe el numero de colores");
int a = sc.nextInt();
escribir.write(a);
int [][] x = new int[f][c];
while (leerposicion((f*c)+3,Nivel) == -1 ) {
for(int i=0;i<=f-1;i++) {
for(int j=0;j<=c-1;j++) {
System.out.println("Escribe un numero para la posicion ["+i+"]["+j+"]");
int y = sc.nextInt();
x[i][j] = y;
printearpers(x,f,c);
escribir.write(y);
}
}
}
escribir.close();
menus(6);
seleccionarEditor();
}catch (IOException e) {
}
}
public static void jugarP (String s) {
File save = new File("niveles/"+s);
int cont = 1;
int f = leerposicion(cont,save);
cont++;
int c = leerposicion(cont,save);
cont++;
int a = leerposicion(cont,save);
cont++;
juego(f,c,a,3,-1,save);
}
public static int[][] crearnivel (File save) {
System.out.println("Escribe el numero de columnas");
int cont = 1;
int f = leerposicion(cont,save);
cont++;
int c = leerposicion(cont,save);
cont++;
cont++;
int [][] x= new int [f][c];
for(int i=0;i<=f-1;i++) {
for(int j=0;j<=c-1;j++) {
int y = leerposicion(cont,save);
x[i][j]=y;
cont++;
}
}
return x;
}
public static void iniciarstats(){
try{
File progresivo = new File("progresivo.txt");
FileOutputStream escribir= new FileOutputStream(progresivo);
int contador=0;
while(contador<1000){
escribir.write(0);
contador++;
}
escribir.close();
}catch(IOException e){}
}
public static void reiniciarstats(){
File progresivo = new File("progresivo.txt");
try{
progresivo.delete();
progresivo = new File("progresivo.txt");
if (progresivo.isFile()){
}else{
progresivo.createNewFile();
}
iniciarstats();
}catch(IOException e){}
}
public static int size(File archivo) {
try {
FileInputStream leer = new FileInputStream(archivo);
int cont = 0;
while(leer.read() != -1){
cont++;
}
leer.close();
return cont;
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return 0;
}
public static int leerposicion(int posicion, File archivo) {
int a = 0;
try {
FileInputStream leer = new FileInputStream(archivo);
int cont=0;
while(posicion>cont){
a = leer.read();
cont++;
}
leer.close();
return a;
} catch (IOException e) {
}
return 0;
}
public static File duplicar(File primera, String nombre){
try{
File nuevo= new File(nombre);
FileInputStream leer= new FileInputStream(primera);
FileOutputStream escribir= new FileOutputStream(nuevo);
for(int cont=1;cont<=size(primera);cont++){
escribir.write(leerposicion(cont,primera));
}
leer.close();
escribir.close();
return nuevo;
}catch(IOException e){
}
return primera;
}
public static File escribirposicion(int numero, int posicion, File archivo,String nombre) {
try {
File auxiliar = new File("auxiliar.txt");
if(archivo.isFile()){
}else{
archivo.createNewFile();
}
FileOutputStream escribir = new FileOutputStream(auxiliar);
FileInputStream leer = new FileInputStream(archivo);
int tama = 1;
if (size(archivo) > posicion) {
tama = size(archivo);
} else {
tama = posicion;
}
for (int cont = 1; cont <= tama; cont++) {
if (cont != posicion) {
if(leerposicion(cont,archivo)!=-1)
escribir.write(leerposicion(cont,archivo));
else{
escribir.write(0);
}
} else {
escribir.write(numero);
}
}
leer.close();
archivo.delete();
escribir.close();
archivo=duplicar(auxiliar,nombre);
auxiliar.delete();
return archivo;
} catch (IOException e) {
}
return archivo;
}
public static void menus (int smenu ) {
File progresivo = new File("progresivo.txt");
switch(smenu) {
case 1:
System.out.println(" MODO DE JUEGO");
System.out.println("1. Modo Continuo ");
System.out.println("2. Modo Progresivo ");
System.out.println("3. Iniciar todas las estadisticas de juego ");
System.out.println("4. Opciones");
System.out.println("5. Editor de niveles");
System.out.println("0. Salir ");
break;
case 2:System.out.println("¿NUEVO TABLERO?");
System.out.println("1. Nuevo tablero con estas caracterÃsticas ");
System.out.println("2. Cambiar tamaño ");
System.out.println("3. Cambiar número de colores");
System.out.println("0. Volver al menu de MODO DE JUEGO ");
break;
case 3:clear();
System.out.println("TAMAÑO DEL TABLERO");
System.out.println("1. PEQUEÑO(9x9) ");
System.out.println("2. MEDIANO(11x11) ");
System.out.println("3. GRANDE(15x15)");
System.out.println("0. Volver al menu de MODO DE JUEGO ");
break;
case 4:System.out.println("MODO PROGRESIVO");
System.out.println("0.Volver al menu de MODO DE JUEGO ");
if(leerposicion(1,progresivo)==0){
System.out.println("1.Nivel 1- Aún no hay estadisticas");
}
else {
System.out.println("1.Nivel 1-Resuelto en "+leerposicion(1,progresivo)+" intentos");
}
if(leerposicion(2,progresivo)==0){
System.out.println("2.Nivel 2- Aún no hay estadisticas");
}
else {
System.out.println("2.Nivel 2-Resuelto en "+leerposicion(2,progresivo)+" intentos");
}
if(leerposicion(3,progresivo)==0){
System.out.println("3.Nivel 3- Aún no hay estadisticas");
}
else {
System.out.println("3.Nivel 3-Resuelto en "+leerposicion(3,progresivo)+" intentos");
}
if(leerposicion(4,progresivo)==0){
System.out.println("4.Nivel 4- Aún no hay estadisticas");
}
else {
System.out.println("4.Nivel 4-Resuelto en "+leerposicion(4,progresivo)+" intentos");
}
break;
case 5:clear();
System.out.println("1. Cuadrados de color");
System.out.println("2. Números de color ");
System.out.println("3. Números");
System.out.println("0.Volver al menu de MODO DE JUEGO ");
break;
case 6:System.out.println("EDITOR DE NIVELES");
System.out.println("1. Crear tablero ");
System.out.println("2. Jugar tablero ");
System.out.println("0. Volver al menu de MODO DE JUEGO ");
default: break;
}
}
public static void seleccionarEditor () {
int caso = -1;
try {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
while(caso<0 || caso >3) {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
seleccionarEditor();
}
switch(caso) {
case 0: clear();menus(1);menuPrimero();break;
case 1: clear();System.out.println("Escribe el nombre del nivel");String crear = sc.next();editor(crear);break;
case 2: clear();seleccionarPersonalizado ();break;
case 3: clear();System.out.println("Escribe el nombre del nivel a jugar");String jugar = sc.next();jugarP(jugar);break;
default: break;
}
}
public static void seleccionarPersonalizado () {
int j = 1;
int k = 1;
String s ="";
try {
Path dir = Paths.get("niveles/");
DirectoryStream<Path> stream = Files.newDirectoryStream(dir);
System.out.println("0.Volver al menu MODO DE JUEGO");
for (Path file: stream) {
System.out.println(j+"."+file.getFileName());
j++;
}
} catch (IOException e) {
}
int caso = -1;
try {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
while(caso<0 || caso >j) {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
}
Path dir = Paths.get("niveles/");
DirectoryStream<Path> stream = Files.newDirectoryStream(dir);
for (Path file: stream) {
if (k==caso) {
s=""+file.getFileName();
}
k++;
}
}
catch(Exception e) {
sc.next();
seleccionarPersonalizado();
}
switch(caso) {
case 0: clear();menus(1);menuPrimero();break;
default: clear();jugarP(s);break;
}
}
public static void seleccionarOpcion () {
int caso = -1;
File progresivo = new File("progresivo.txt");
try {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
while(caso<0 || caso >3) {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
seleccionarOpcion();
}
switch(caso) {
case 0: clear();menus(1);menuPrimero();break;
case 1: clear();escribirposicion(1,777,progresivo,"progresivo.txt");menus(1);menuPrimero();break;
case 2: clear();escribirposicion(2,777,progresivo,"progresivo.txt");menus(1);menuPrimero();break;
case 3: clear();escribirposicion(3,777,progresivo,"progresivo.txt");menus(1);menuPrimero();break;
default: break;
}
}
public static void seleccionarProgresivo () {
int caso = -1;
try {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
while(caso<0 || caso >4) {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
seleccionarProgresivo();
}
switch(caso) {
case 0: clear();menus(1);menuPrimero();break;
case 1: clear();juego(9,9,2,2,1,null);break;
case 2: clear();juego(9,9,3,2,2,null);break;
case 3: clear();juego(9,9,3,2,3,null);break;
case 4: clear();juego(9,9,3,2,4,null);break;
default: break;
}
}
public static int[][] nivelesP (int nivel) {
int[][] x = null;
if(nivel==1) {
x = new int[9][9];
int k,z;
for(k=0;k<=8;k++) {
for(z=0;z<=8;z++) {
x[k][z] = 1;
}
}
x[0][0] = 2;
}
if(nivel==2) {
x = new int[9][9];
int k,z;
for(k=0;k<=8;k++) {
for(z=0;z<=8;z++) {
x[k][z] = 1;
}
}
x[0][0] = 3;
x[1][0] = 2;
x[0][1] = 2;
}
if(nivel==3) {
x = new int[9][9];
int k,z;
for(k=0;k<=8;k++) {
for(z=0;z<=8;z++) {
x[k][z] = 1;
if(((k==4 || k==8) && z>3) || ((z==4 || z==8) && k>3)) {
x[k][z] = 2;
}
if(((k==5 || k==7) && (z>4 && z<8) || ((z==5 || z==7) && (k>4 && k<8)))) {
x[k][z] = 3;
}
}
}
k = 0;
z = 5;
while(z>=0) {
x[k][z] = 2;
k++;
z
}
k = 0;
z = 6;
while(z>=0) {
x[k][z] = 3;
k++;
z
}
}
if(nivel==4) {
x = new int[9][9];
int k,z;
for(k=0;k<=8;k++) {
for(z=0;z<=8;z++) {
x[k][z] = 1;
}
}
k = 2;
z = 0;
while(k<=8) {
x[k][z] = 3;
k++;
}
k = 0;
while(k<=7) {
z = 1;
if(k==0 || k%2==1) {
while(z<=8) {
x[k][z] = 2;
z++;
}
}
k++;
}
}
return x;
}
public static void seleccionarSize (int a) {
int caso = -1;
int cont = 0;
try {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
while(caso<0 || caso >3) {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
seleccionarSize(a);
}
switch(caso) {
case 0: clear();menus(1);menuPrimero();break;
case 1: clear();info(1,9,9,a,cont,1,0);menus(2);finJuego(9,9,a);break;
case 2: clear();info(1,11,11,a,cont,1,0);menus(2);finJuego(11,11,a);break;
case 3: clear();info(1,15,15,a,cont,1,0);menus(2);finJuego(15,15,a);break;
default: break;
}
}
public static void seleccionarColor (int f, int c) {
int color = -1;
try {
System.out.println("Por favor, elija un número de colores entre 2 y 6");
color = sc.nextInt();
while(color<2 || color >6) {
System.out.println("Por favor, elija un número de colores entre 2 y 6");
color = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
seleccionarColor(f,c);
}
int cont = 0;
clear();
info(1,f,c,color,cont,1,0);
menus(2);
finJuego(f,c,color);
}
public static void finJuego (int f,int c, int a) {
int caso = -1;
try {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
while(caso<0 || caso >3) {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
finJuego(f,c,a);
}
switch(caso) {
case 0: clear();menus(1);menuPrimero();break;
case 1: clear();juego(f,c,a,caso,0,null);break;
case 2: clear();menus(3);seleccionarSize(a);break;
case 3: clear();;seleccionarColor(f,c);break;
default: break;
}
}
public static void info (int caso,int f,int c,int a,int cont, int menu ,int nivel) {
File progresivo = new File("progresivo.txt");
String size = null;
if (f<=9)
size = "PEQUEÑO";
if (f>9 && f<=11)
size = "MEDIANO";
if (f>11)
size = "GRANDE";
switch(caso){
case 1: if(menu==1) {
System.out.println("MODO CONTINUO");
info(2,f,c,a,cont,1,0);
break;
}
if(menu==2) {
System.out.print(" MODO PROGRESIVO");
break;
}
if(menu==3) {
System.out.print(" MODO PERSONALIZADO");
break;
}
System.out.print(" MODO CONTINUO");
break;
case 2: if(menu==1) {
System.out.println("Tamaño de tablero: "+size+" ("+f+"x"+c+")");
info(3,f,c,a,cont,1,0);
break;
}
if(menu==2) {
System.out.print(" NIVEL "+nivel);
break;
}
System.out.print(" Tamaño de tablero: "+size+" ("+f+"x"+c+")");
break;
case 3: if(menu==1) {
System.out.println("Número de colores: "+a);
info(4,f,c,a,cont,1,0);
break;
}
System.out.print(" Número de colores: "+a);
break;
case 4: if(menu==1) {
System.out.println("Pasos empleados: "+cont);
info(5,f,c,a,cont,1,0);
break;
}
System.out.print(" Pasos empleados: "+cont);
break;
case 5:
if(menu==1) {
if(leerposicion(((((f+c)*4)+a)+20),progresivo)==0) {
System.out.println("No hay estadisticas aún");
System.out.println(" ");
}
else {
System.out.println("Menor número de pasos empleados :"+leerposicion(((((f+c)*4)+a)+20),progresivo));
System.out.println(" ");
}
break;
}
if(menu==2) {
if(leerposicion((nivel),progresivo)==0) {
System.out.print("No hay estadisticas aún");
}
else {
System.out.print("Menor número de pasos empleados :"+leerposicion((nivel),progresivo));
}
break;
}
if(menu==3) {
if(leerposicion((800+2*f+3*c+2*a+cont-7),progresivo)==0) {
System.out.print(" No hay estadisticas aún");
}
else {
System.out.print(" Menor número de pasos empleados :"+leerposicion((800+2*f+3*c+2*a+cont-7),progresivo));
}
break;
}
if(leerposicion(((((f+c)*4)+a)+20),progresivo)==0) {
System.out.print(" No hay estadisticas aún");
}
else {
System.out.print(" Menor número de pasos empleados :"+leerposicion(((((f+c)*4)+a)+20),progresivo));
}
break;
default: break;
}
}
public static int color (int a) {
int color = -1;
try {
System.out.println("Por favor, elija un color entre 1 y "+a);
color = sc.nextInt();
while(color<1 || color>a) {
System.out.println("Por favor, elija un color entre 1 y "+a);
color = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
return color(a);
}
return color;
}
public static void juego (int f,int c, int a, int caso, int nivel,File level) {
int cont = 0;
File progresivo = new File("progresivo.txt");
if(caso==3) {
int[][] x = crearnivel(level);
printear(x,f,c,a,cont,nivel);
while(finalcheck(x,f,c)==false) {
int z = x[0][0];
int y = color(a);
while(z==y) {
System.out.println("Escoja un color distinto de "+z+" puesto que ya esta seleccionado");
y = color(a);
}
x[0][0] = y;
checkv3(x,0,0,z,f-1,c-1);
cont++;
clear();
printear(x,f,c,a,cont,nivel);
}
if(leerposicion((800+2*f+3*c+2*a+cont-7),progresivo)>cont || leerposicion((800+2*f+3*c+2*a+cont-7),progresivo)==0 ) {
System.out.println("FELICIDADES, HAS BATIDO EL RECORD DE ESTE TABLERO");
System.out.println("GUARDANDO RECORD............");
escribirposicion(cont,nivel,progresivo,"progresivo.txt");
}
clear();
System.out.println(" ");
menus(6);
seleccionarEditor();
}
if(caso==2) {
int[][] x = nivelesP(nivel);
printear(x,f,c,a,cont,nivel);
while(finalcheck(x,f,c)==false) {
int z = x[0][0];
int y = color(a);
while(z==y) {
System.out.println("Escoja un color distinto de "+z+" puesto que ya esta seleccionado");
y = color(a);
}
x[0][0] = y;
checkv3(x,0,0,z,f-1,c-1);
cont++;
clear();
printear(x,f,c,a,cont,nivel);
}
if(leerposicion(nivel,progresivo)>cont || leerposicion(nivel,progresivo)==0 ) {
System.out.println("FELICIDADES, HAS BATIDO EL RECORD DE ESTE TABLERO");
System.out.println("GUARDANDO RECORD............");
escribirposicion(cont,nivel,progresivo,"progresivo.txt");
}
clear();
System.out.println(" ");
menus(4);
seleccionarProgresivo();
}
if(caso==1) {
int[][] x = crear(f,c,a);
printear(x,f,c,a,cont,0);
while(finalcheck(x,f,c)==false) {
int z = x[0][0];
int y = color(a);
while(z==y) {
System.out.println("Escoja un color distinto de "+z+" puesto que ya esta seleccionado");
y = color(a);
}
x[0][0] = y;
checkv3(x,0,0,z,f-1,c-1);
cont++;
clear();
printear(x,f,c,a,cont,0);
}
if(leerposicion(((((f+c)*4)+a)+20),progresivo)>cont || leerposicion(((((f+c)*4)+a)+20),progresivo)==0) {
System.out.println("FELICIDADES, HAS BATIDO EL RECORD DE ESTE TABLERO");
System.out.println("GUARDANDO RECORD............");
escribirposicion(cont,((((f+c)*4)+a)+20),progresivo,"progresivo.txt");
}
clear();
info(1,f,c,a,cont,1,0);
menus(2);
finJuego(f,c,a);
}
}
public static void clear () {
for (int z=0;z<=50;z++) {
System.out.println(" ");
}
}
public static void menuPrimero () {
int caso = -1;
try {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
while(caso<0 || caso >5) {
System.out.println("Por favor, elija una de las opciones que se muestra en pantalla");
caso = sc.nextInt();
}
}
catch(Exception e) {
sc.next();
menuPrimero();
}
switch(caso) {
case 0: clear();System.out.println(" FIN DEL JUEGO");break;
case 1: clear();juego(9,9,2,caso,0,null);break;
case 2: clear();menus(4);seleccionarProgresivo();break;
case 3: clear();reiniciarstats();
System.out.println("ESTADISTICAS REINICIADAS");
menus(1);menuPrimero();break;
case 4: clear();menus(5);seleccionarOpcion();break;
case 5: clear();menus(6);seleccionarEditor();break;
default: break;
}
}
public static int[][] crear (int f, int c, int a) {
int[][] x = new int[f][c];
int k,z;
for(k=0;k<=f-1;k++) {
for(z=0;z<=c-1;z++) {
x[k][z] = (int) Math.ceil((Math.random() * a));
}
}
return x;
}
public static void chuleta (int caso) {
int a=0;
switch(caso){
case 1: System.out.print(" Pulse 1 para escoger --> "+"\033[38;5;196;48;5;196m"+a+"\033[0m");
break;
case 2: System.out.print(" Pulse 2 para escoger --> "+"\033[38;5;34;48;5;34m"+a+"\033[0m");
break;
case 3: System.out.print(" Pulse 3 para escoger --> "+"\033[38;5;21;48;5;21m"+a+"\033[0m");
break;
case 4: System.out.print(" Pulse 4 para escoger --> "+"\033[38;5;226;48;5;226m"+a+"\033[0m");
break;
case 5: System.out.print(" Pulse 5 para escoger --> "+"\033[38;5;165;48;5;165m"+a+"\033[0m");
break;
case 6: System.out.print(" Pulse 6 para escoger --> "+"\033[38;5;45;48;5;45m"+a+"\033[0m");
break;
case 7: System.out.print(" Pulse 7 para escoger --> "+"\033[38;5;94;48;5;94m"+a+"\033[0m");
break;
case 8: System.out.print(" Pulse 8 para escoger --> "+"\033[37;47m"+a+"\033[0m");
break;
default: break;
}
}
public static void printear (int[][] x, int f, int c,int a,int cont ,int nivel) {
File progresivo = new File("progresivo.txt");
int i,j,caso=1,casoi=1;
int opcion = leerposicion(777,progresivo);
for(i=0;i<=f-1;i++) {
System.out.println(" ");
for(j=0;j<=c-1;j++) {
if(opcion==1) {
if(x[i][j] ==1){
System.out.print("\033[38;5;196;48;5;196m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==2){
System.out.print("\033[38;5;34;48;5;34m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==3){
System.out.print("\033[38;5;21;48;5;21m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==4){
System.out.print("\033[38;5;226;48;5;226m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==5){
System.out.print("\033[38;5;165;48;5;165m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==6){
System.out.print("\033[38;5;45;48;5;45m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==7){
System.out.print("\033[38;5;94;48;5;94m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==8){
System.out.print("\033[37;47m"+x[i][j]+"\033[0m");
}
}
if(opcion==2) {
if(x[i][j] ==1){
System.out.print("\033[38;5;196m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==2){
System.out.print("\033[38;5;34m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==3){
System.out.print("\033[38;5;21m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==4){
System.out.print("\033[38;5;226m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==5){
System.out.print("\033[38;5;165m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==6){
System.out.print("\033[38;5;45m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==7){
System.out.print("\033[38;5;94m"+x[i][j]+"\033[0m");
}
if(x[i][j] ==8){
System.out.print("\033[37m"+x[i][j]+"\033[0m");
}
}
if(opcion==3) {
System.out.print(""+x[i][j]);
}
if(j==c-1){
if(caso<=a){
chuleta(caso);
caso++;
}
}
if(j==c-1){
if(casoi<=5 && casoi+1==caso){
if(nivel<0) {
info(casoi,f,c,a,cont,3,nivel);
casoi++;
}
else if(nivel>0) {
info(casoi,f,c,a,cont,2,nivel);
casoi++;
}
else{
info(casoi,f,c,a,cont,0,0);
casoi++;
}
}
else if(caso>a && casoi <=5){
for(int r=0;r<=28;r++){
System.out.print(" ");
}
if(nivel<0) {
info(casoi,f,c,a,cont,3,nivel);
casoi++;
}
else if(nivel>0) {
info(casoi,f,c,a,cont,2,nivel);
casoi++;
}
else{
info(casoi,f,c,a,cont,0,0);
casoi++;
}
}
}
System.out.print(" ");
}
System.out.println(" ");
}
while(caso<=a) {
System.out.println(" ");
for(int z=0;z<=(c*3)-3;z++) {
System.out.print(" ");
}
chuleta(caso);
System.out.println(" ");
caso++;
}
}
public static boolean finalcheck (int[][] x, int f, int c) {
int i,j;
boolean igual = true;
int z = x[0][0];
for(i=0;i<=f-1;i++) {
if (igual==false) {
break;
}
for(j=0;j<=c-1;j++) {
igual = z==x[i][j];
if (igual==false) {
break;
}
z = x[i][j];
}
}
return igual;
}
public static void checkv3(int[][]x,int i,int j,int y,int f,int c) {
if((i>=0 && i<=f)&&(j>=0 && j<=c)) {
if(i!=0){
if(x[i-1][j]==y) {
x[i-1][j]=x[0][0];
checkv3(x,i-1,j,y,f,c);
}
}
if(i!=f){
if(x[i+1][j]==y) {
x[i+1][j]=x[0][0];
checkv3(x,i+1,j,y,f,c);
}
}
if(j!=0){
if(x[i][j-1]==y) {
x[i][j-1]=x[0][0];
checkv3(x,i,j-1,y,f,c);
}
}
if(j!=c){
if(x[i][j+1]==y) {
x[i][j+1]=x[0][0];
checkv3(x,i,j+1,y,f,c);
}
}
}
}
public static void main (String[] args) {
File progresivo = new File("progresivo.txt");
if(leerposicion(1,progresivo)==-1) {
reiniciarstats();
}
escribirposicion(1,777,progresivo,"progresivo.txt");
menus(1);
menuPrimero();
}
}
|
/*
* $Log: IfsaFacade.java,v $
* Revision 1.8 2008-10-06 14:30:36 europe\L190409
* use JMS transacted sessions for FF
*
* Revision 1.7 2008/09/02 11:43:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* close reply sender in finally clause
*
* Revision 1.6 2008/07/14 17:17:49 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added space after logprefix
*
* Revision 1.5 2008/05/22 07:23:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added serviceId to logPrefix of requester
* added some support for bif and btc
*
* Revision 1.4 2008/03/27 12:00:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* set default timeout to 20s
*
* Revision 1.3 2008/01/17 16:20:01 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* never use jmsTransacted sessions
*
* Revision 1.2 2007/10/16 08:39:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* moved IfsaException and IfsaMessageProtocolEnum back to main package
*
* Revision 1.1 2007/10/16 08:15:43 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* introduced switch class for jms and ejb
*
* Revision 1.46 2007/09/05 15:48:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* moved XA determination capabilities to IfsaConnection
*
* Revision 1.45 2007/08/10 11:11:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* removed attribute 'transacted'
* automatic determination of transaction state and capabilities
*
* Revision 1.44 2007/02/12 13:47:55 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Logger from LogUtil
*
* Revision 1.43 2007/02/05 14:56:29 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* make isJmsTransacted() protected
*
* Revision 1.42 2006/11/06 08:15:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* modifications for dynamic serviceId
*
* Revision 1.41 2006/10/13 08:08:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* modify comments
*
* Revision 1.40 2006/08/21 15:08:03 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* corrected javadoc
*
* Revision 1.39 2006/07/17 08:54:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* documented custom property ifsa.provider.useSelectors
*
* Revision 1.38 2006/02/09 07:59:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* restored compatibility with IFSA releases without provider selection mechanism
*
* Revision 1.37 2006/01/23 08:55:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* use providerSelector (when available in ifsajms)
*
* Revision 1.36 2005/12/28 08:47:34 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved logging
*
* Revision 1.35 2005/12/20 16:59:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* implemented support for connection-pooling
*
* Revision 1.34 2005/11/02 09:08:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* ifsa-mode connection not for single dynamic reply queue
*
* Revision 1.33 2005/10/26 08:23:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved logging
*
* Revision 1.32 2005/10/24 15:10:13 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made sessionsArePooled configurable via appConstant 'jms.sessionsArePooled'
*
* Revision 1.31 2005/10/18 07:04:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* better handling of dynamic reply queues
*
* Revision 1.30 2005/09/26 11:44:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Jms-commit only if not XA-transacted
*
* Revision 1.29 2005/09/13 15:48:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* changed acknowledge mode back to AutoAcknowledge
*
* Revision 1.28 2005/08/31 16:32:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* corrected code for static reply queues
*
* Revision 1.27 2005/07/28 07:31:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* change default acknowledge mode to CLIENT
*
* Revision 1.26 2005/07/19 12:33:56 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* implements IXAEnabled
* polishing of serviceIds, to work around problems with ':' and '/'
*
* Revision 1.25 2005/06/20 09:12:47 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* set sessionsArePooled false by default
*
* Revision 1.24 2005/06/13 15:07:58 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* avoid excessive logging in debug mode
*
* Revision 1.23 2005/06/13 11:59:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* corrected version-string
*
* Revision 1.22 2005/06/13 11:57:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added support for pooled sessions and for XA-support
*
* Revision 1.21 2005/05/03 15:58:49 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* rework of shared connection code
*
* Revision 1.20 2005/04/26 15:17:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* rework, using IfsaApplicationConnection resulting in shared usage of connection objects
*
* Revision 1.19 2005/01/13 08:15:08 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made queue type IfsaQueue
*
* Revision 1.18 2004/08/23 13:12:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* updated JavaDoc
*
* Revision 1.17 2004/08/09 08:46:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* small changes
*
* Revision 1.16 2004/08/03 13:07:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved closing
*
* Revision 1.15 2004/07/22 13:19:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* let requestor receive IFSATimeOutMessages
*
* Revision 1.14 2004/07/22 11:01:04 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added configurable timeOut
*
* Revision 1.13 2004/07/20 16:37:47 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* toch maar niet IFSA-mode timeout
*
* Revision 1.12 2004/07/20 13:28:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* implemented IFSA timeout mode
*
* Revision 1.11 2004/07/19 13:20:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* increased logging + close connection on 'close'
*
* Revision 1.10 2004/07/15 07:35:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* cosmetic changes
*
* Revision 1.9 2004/07/08 12:55:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* logging refinements
*
* Revision 1.8 2004/07/08 08:56:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* show physical destination after configure
*
* Revision 1.7 2004/07/06 14:50:06 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* included PhysicalDestination
*
* Revision 1.6 2004/07/05 14:29:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* restructuring to align with IFSA naming scheme
*
*/
package nl.nn.adapterframework.extensions.ifsa.jms;
import java.util.Map;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.HasPhysicalDestination;
import nl.nn.adapterframework.core.INamedObject;
import nl.nn.adapterframework.core.IbisException;
import nl.nn.adapterframework.extensions.ifsa.IfsaException;
import nl.nn.adapterframework.extensions.ifsa.IfsaMessageProtocolEnum;
import nl.nn.adapterframework.util.AppConstants;
import nl.nn.adapterframework.util.JtaUtil;
import nl.nn.adapterframework.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import com.ing.ifsa.IFSAConstants;
import com.ing.ifsa.IFSAMessage;
import com.ing.ifsa.IFSAQueue;
import com.ing.ifsa.IFSAQueueSender;
import com.ing.ifsa.IFSAServerQueueSender;
import com.ing.ifsa.IFSATextMessage;
/**
* Base class for IFSA 2.0/2.2 functions.
* <br/>
* <p>Descenderclasses must set either Requester or Provider behaviour in their constructor.</p>
* <p><b>Configuration:</b>
* <table border="1">
* <tr><th>attributes</th><th>description</th><th>default</th></tr>
* <tr><td>classname</td><td>nl.nn.adapterframework.extensions.ifsa.IfsaFacade</td><td> </td></tr>
* <tr><td>{@link #setName(String) name}</td><td>name of the object</td><td> </td></tr>
* <tr><td>{@link #setApplicationId(String) applicationId}</td><td>the ApplicationID, in the form of "IFSA://<i>AppId</i>"</td><td> </td></tr>
* <tr><td>{@link #setServiceId(String) serviceId}</td><td>only for Requesters: the ServiceID, in the form of "IFSA://<i>ServiceID</i>"</td><td> </td></tr>
* <tr><td>{@link #setMessageProtocol(String) messageProtocol}</td><td>protocol of IFSA-Service to be called. Possible values
* <ul>
* <li>"FF": Fire & Forget protocol</li>
* <li>"RR": Request-Reply protocol</li>
* </ul></td><td> </td></tr>
* <tr><td>{@link #setTransacted(boolean) transacted}</td><td>must be set <code>true</true> for FF senders/listeners in transacted mode</td><td>false</td></tr>
* <tr><td>{@link #setTimeOut(long) timeOut}</td><td>receiver timeout, in milliseconds. To use the timeout defined as IFSA expiry, set this value to -1</td><td>20000 (20s)</td></tr>
* </table>
*
* N.B.
* Starting from IFSA-jms version 2.2.10.055(beta) a feature was created to have separate service-queues for Request/Reply
* and for Fire & Forget services. This allows applications to provide both types of services, each in its own transaction
* mode. This options is not compatible with earlier versions of IFSA-jms. If an earlier version of IFSA-jms is deployed on
* the server, this behaviour must be disabled by the following setting in DeploymentSpecifics.properties:
*
* <code> ifsa.provider.useSelectors=false</code>
*
* @author Johan Verrips / Gerrit van Brakel
* @since 4.2
*/
public class IfsaFacade implements INamedObject, HasPhysicalDestination {
public static final String version = "$RCSfile: IfsaFacade.java,v $ $Revision: 1.8 $ $Date: 2008-10-06 14:30:36 $";
protected Logger log = LogUtil.getLogger(this);
private static int BASIC_ACK_MODE = Session.AUTO_ACKNOWLEDGE;
private final static String USE_SELECTOR_FOR_PROVIDER_KEY="ifsa.provider.useSelectors";
private static Boolean useSelectorsStore=null;
private String name;
private String applicationId;
private String serviceId;
private String polishedServiceId=null;;
private IfsaMessageProtocolEnum messageProtocol;
private long timeOut = 20000; // when set less than zero the IFSA-expiry will be used
private IFSAQueue queue;
private IfsaConnection connection=null;
private boolean requestor=false;
private boolean provider=false;
private String providerSelector=null;
public IfsaFacade(boolean asProvider) {
super();
if (asProvider) {
provider=true;
}
else
requestor=true;
}
protected String getLogPrefix() {
String objectType;
String serviceInfo="";
try {
if (isRequestor()) {
objectType = "IfsaRequester";
serviceInfo = "of Application ["+getApplicationId()+"] "+(polishedServiceId!=null?"to Service ["+polishedServiceId+"] ":"");
} else {
objectType = "IfsaProvider";
serviceInfo = "for Application ["+getApplicationId()+"] ";
}
} catch (IfsaException e) {
log.debug("Exception determining objectType in getLogPrefix",e);
objectType="Object";
serviceInfo = "of Application ["+getApplicationId()+"]";
}
return objectType + "["+ getName()+ "] " + serviceInfo;
}
/**
* Checks if messageProtocol and serviceId (only for Requestors) are specified
*/
public void configure() throws ConfigurationException {
// perform some basic checks
if (StringUtils.isEmpty(getApplicationId()))
throw new ConfigurationException(getLogPrefix()+"applicationId is not specified");
if (getMessageProtocolEnum() == null)
throw new ConfigurationException(getLogPrefix()+
"invalid messageProtocol specified ["
+ getMessageProtocolEnum()
+ "], should be one of the following "
+ IfsaMessageProtocolEnum.getNames());
// TODO: check if serviceId is specified, either as attribute or as parameter
// try {
// log.debug(getLogPrefix()+"opening connection for service, to obtain info about XA awareness");
// getConnection(); // obtain and cache connection, then start it.
// closeService();
// } catch (IfsaException e) {
// cleanUpAfterException();
// throw new ConfigurationException(e);
}
protected void cleanUpAfterException() {
try {
closeService();
} catch (IfsaException e) {
log.warn("exception closing ifsaConnection after previous exception, current:",e);
}
}
/**
* Prepares object for communication on the IFSA bus.
* Obtains a connection and a serviceQueue.
*/
public void openService() throws IfsaException {
try {
log.debug(getLogPrefix()+"opening connection for service");
getConnection(); // obtain and cache connection, then start it.
getServiceQueue(); // obtain and cache service queue
} catch (IfsaException e) {
cleanUpAfterException();
throw e;
}
}
/**
* Stops communication on the IFSA bus.
* Releases references to serviceQueue and connection.
*/
public void closeService() throws IfsaException {
try {
if (connection != null) {
try {
connection.close();
} catch (IbisException e) {
if (e instanceof IfsaException) {
throw (IfsaException)e;
}
throw new IfsaException(e);
}
log.debug(getLogPrefix()+"closed connection for service");
}
} finally {
// make sure all objects are reset, to be able to restart after IFSA parameters have changed (e.g. at iterative installation time)
queue = null;
connection = null;
}
}
/**
* Looks up the <code>serviceId</code> in the <code>IFSAContext</code>.<br/>
* <p>The method is knowledgable of Provider versus Requester processing.
* When the request concerns a Provider <code>lookupProviderInput</code> is used,
* when it concerns a Requester <code>lookupService(serviceId)</code> is used.
* This method distinguishes a server-input queue and a client-input queue
*/
protected IFSAQueue getServiceQueue() throws IfsaException {
if (queue == null) {
if (isRequestor()) {
if (getServiceId() != null) {
queue = getConnection().lookupService(getServiceId());
if (log.isDebugEnabled()) {
log.info(getLogPrefix()+ "got Queue to send messages on "+getPhysicalDestinationName());
}
}
} else {
queue = getConnection().lookupProviderInput();
if (log.isDebugEnabled()) {
log.info(getLogPrefix()+ "got Queue to receive messages from "+getPhysicalDestinationName());
}
}
}
return queue;
}
protected IfsaConnection getConnection() throws IfsaException {
if (connection == null) {
synchronized (this) {
if (connection == null) {
log.debug(getLogPrefix()+"instantiating IfsaConnectionFactory");
IfsaConnectionFactory ifsaConnectionFactory = new IfsaConnectionFactory();
try {
log.debug(getLogPrefix()+"creating IfsaConnection");
connection = (IfsaConnection)ifsaConnectionFactory.getConnection(getApplicationId());
} catch (IbisException e) {
if (e instanceof IfsaException) {
throw (IfsaException)e;
}
throw new IfsaException(e);
}
}
}
}
return connection;
}
/**
* Create a session on the connection to the service
*/
protected QueueSession createSession() throws IfsaException {
try {
int mode = BASIC_ACK_MODE;
if (isRequestor() && connection.canUseIfsaModeSessions()) {
mode += IFSAConstants.QueueSession.IFSA_MODE; // let requestor receive IFSATimeOutMessages
}
return (QueueSession) connection.createSession(isJmsTransacted(), mode);
} catch (IbisException e) {
if (e instanceof IfsaException) {
throw (IfsaException)e;
}
throw new IfsaException(e);
}
}
protected void closeSession(Session session) {
try {
getConnection().releaseSession(session);
} catch (IfsaException e) {
log.warn("Exception releasing session", e);
}
}
protected QueueSender createSender(QueueSession session, Queue queue)
throws IfsaException {
try {
QueueSender queueSender = session.createSender(queue);
if (log.isDebugEnabled()) {
log.debug(getLogPrefix()+ "got queueSender ["
+ ToStringBuilder.reflectionToString((IFSAQueueSender) queueSender)+ "]");
}
return queueSender;
} catch (Exception e) {
throw new IfsaException(e);
}
}
protected synchronized String getProviderSelector() {
if (providerSelector==null && useSelectorsForProviders()) {
try {
providerSelector=""; // set default, also to avoid re-evaluation time and time again for lower ifsa-versions.
if (messageProtocol.equals(IfsaMessageProtocolEnum.REQUEST_REPLY)) {
providerSelector=IFSAConstants.QueueReceiver.SELECTOR_RR;
}
if (messageProtocol.equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET)) {
providerSelector=IFSAConstants.QueueReceiver.SELECTOR_FF;
}
} catch (Throwable t) {
log.debug(getLogPrefix()+"exception determining selector, probably lower ifsa version, ignoring");
}
}
return providerSelector;
}
/**
* Gets the queueReceiver, by utilizing the <code>getInputQueue()</code> method.<br/>
* For serverside getQueueReceiver() the creating of the QueueReceiver is done
* without the <code>selector</code> information, as this is not allowed
* by IFSA.<br/>
* For a clientconnection, the receiver is done with the <code>getClientReplyQueue</code>
* @see javax.jms.QueueReceiver
*/
protected QueueReceiver getServiceReceiver(
QueueSession session)
throws IfsaException {
try {
QueueReceiver queueReceiver;
if (isProvider()) {
String selector = getProviderSelector();
if (StringUtils.isEmpty(selector)) {
queueReceiver = session.createReceiver(getServiceQueue());
} else {
//log.debug(getLogPrefix()+"using selector ["+selector+"]");
try {
queueReceiver = session.createReceiver(getServiceQueue(), selector);
} catch (JMSException e) {
log.warn("caught exception, probably due to use of selector ["+selector+"], falling back to non-selected mode",e);
queueReceiver = session.createReceiver(getServiceQueue());
}
}
} else {
throw new IfsaException("cannot obtain ServiceReceiver: Requestor cannot act as Provider");
}
if (log.isDebugEnabled() && !isSessionsArePooled()) {
log.debug(getLogPrefix()+ "got receiver for queue ["
+ queueReceiver.getQueue().getQueueName()
+ "] "+ ToStringBuilder.reflectionToString(queueReceiver));
}
return queueReceiver;
} catch (JMSException e) {
throw new IfsaException(e);
}
}
public long getExpiry() throws IfsaException {
return getExpiry((IFSAQueue) getServiceQueue());
}
public long getExpiry(IFSAQueue queue) throws IfsaException {
long expiry = getTimeOut();
if (expiry>=0) {
return expiry;
}
try {
return queue.getExpiry();
} catch (JMSException e) {
throw new IfsaException("error retrieving timeOut value", e);
}
}
public String getMessageProtocol() {
return messageProtocol.getName();
}
public IfsaMessageProtocolEnum getMessageProtocolEnum() {
return messageProtocol;
}
/**
* Gets the queueReceiver, by utilizing the <code>getInputQueue()</code> method.<br/>
* For serverside getQueueReceiver() the creating of the QueueReceiver is done
* without the <code>selector</code> information, as this is not allowed
* by IFSA.<br/>
* For a clientconnection, the receiver is done with the <code>getClientReplyQueue</code>
*/
public QueueReceiver getReplyReceiver(QueueSession session, Message sentMessage)
throws IfsaException {
if (isProvider()) {
throw new IfsaException("cannot get ReplyReceiver: Provider cannot act as Requestor");
}
return getConnection().getReplyReceiver(session, sentMessage);
}
public void closeReplyReceiver(QueueReceiver receiver) throws IfsaException {
log.debug(getLogPrefix()+"closing replyreceiver");
getConnection().closeReplyReceiver(receiver);
}
/**
* Indicates whether the object at hand represents a Client (returns <code>True</code>) or
* a Server (returns <code>False</code>).
*/
public boolean isRequestor() throws IfsaException {
if (requestor && provider) {
throw new IfsaException("cannot be both Requestor and Provider");
}
if (!requestor && !provider) {
throw new IfsaException("not configured as Requestor or Provider");
}
return requestor;
}
/**
* Indicates whether the object at hand represents a Client (returns <code>False</code>) or
* a Server (returns <code>True</code>).
*
* @see #isRequestor()
*/
public boolean isProvider() throws IfsaException {
return ! isRequestor();
}
/**
* Sends a message,and if transacted, the queueSession is committed.
* <p>This method is intended for <b>clients</b>, as <b>server</b>s
* will use the <code>sendReply</code>.
* @return the correlationID of the sent message
*/
public TextMessage sendMessage(QueueSession session, QueueSender sender, String message, Map udzMap, String bifName, byte btcData[])
throws IfsaException {
try {
if (!isRequestor()) {
throw new IfsaException(getLogPrefix()+ "Provider cannot use sendMessage, should use sendReply");
}
IFSATextMessage msg = (IFSATextMessage)session.createTextMessage();
msg.setText(message);
if (udzMap != null && msg instanceof IFSAMessage) {
// Handle UDZs
log.debug(getLogPrefix()+"add UDZ map to IFSAMessage");
// process the udzMap
Map udzObject = (Map)((IFSAMessage) msg).getOutgoingUDZObject();
udzObject.putAll(udzMap);
}
String replyToQueueName="-";
//Client side
if (messageProtocol.equals(IfsaMessageProtocolEnum.REQUEST_REPLY)) {
// set reply-to address
Queue replyTo=getConnection().getClientReplyQueue(session);
msg.setJMSReplyTo(replyTo);
replyToQueueName=replyTo.getQueueName();
}
if (messageProtocol.equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET)) {
// not applicable
}
if (StringUtils.isNotEmpty(bifName)) {
msg.setBifName(bifName);
}
if (btcData!=null && btcData.length>0) {
msg.setBtcData(btcData);
}
log.info(getLogPrefix()
+ " messageProtocol ["
+ messageProtocol
+ "] replyToQueueName ["
+ replyToQueueName
+ "] sending message ["
+ message
+ "]");
// send the message
sender.send(msg);
// perform commit
if (isJmsTransacted() && !(connection.isXaEnabledForSure() && JtaUtil.inTransaction())) {
session.commit();
log.debug(getLogPrefix()+ "committing (send) transaction");
}
return msg;
} catch (Exception e) {
throw new IfsaException(e);
}
}
/**
* Intended for server-side reponse sending and implies that the received
* message *always* contains a reply-to address.
*/
public void sendReply(QueueSession session, Message received_message, String response) throws IfsaException {
QueueSender tqs=null;
try {
TextMessage answer = session.createTextMessage();
answer.setText(response);
Queue replyQueue = (Queue)received_message.getJMSReplyTo();
tqs = session.createSender(replyQueue );
if (log.isDebugEnabled()) log.debug(getLogPrefix()+ "sending reply to ["+ received_message.getJMSReplyTo()+ "]");
((IFSAServerQueueSender) tqs).sendReply(received_message, answer);
} catch (Throwable t) {
throw new IfsaException(t);
} finally {
if (tqs!=null) {
try {
tqs.close();
} catch (JMSException e) {
log.warn(getLogPrefix()+ "exception closing reply queue sender",e);
}
}
}
}
public void setMessageProtocol(String newMessageProtocol) {
if (null==IfsaMessageProtocolEnum.getEnum(newMessageProtocol)) {
throw new IllegalArgumentException(getLogPrefix()+
"illegal messageProtocol ["
+ newMessageProtocol
+ "] specified, it should be one of the values "
+ IfsaMessageProtocolEnum.getNames());
}
messageProtocol = IfsaMessageProtocolEnum.getEnum(newMessageProtocol);
log.debug(getLogPrefix()+"message protocol set to "+messageProtocol.getName());
}
public boolean isSessionsArePooled() {
try {
return getConnection().sessionsArePooled();
} catch (IfsaException e) {
log.error(getLogPrefix()+"could not get session",e);
return false;
}
}
/**
* controls whether sessions are created in JMS transacted mode. JMS transacted sessions
* are required by IFSA for FF, although they result in log messages about active transactions
* that should be present.
*/
protected boolean isJmsTransacted() {
return getMessageProtocolEnum().equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET);
}
public String toString() {
String result = super.toString();
ToStringBuilder ts = new ToStringBuilder(this);
ts.append("applicationId", applicationId);
ts.append("serviceId", serviceId);
if (messageProtocol != null) {
ts.append("messageProtocol", messageProtocol.getName());
// ts.append("transacted", isTransacted());
ts.append("jmsTransacted", isJmsTransacted());
}
else
ts.append("messageProtocol", "null!");
result += ts.toString();
return result;
}
public String getPhysicalDestinationName() {
String result = null;
try {
if (isRequestor()) {
result = getServiceId();
} else {
result = getApplicationId();
}
log.debug("obtaining connection and servicequeue for "+result);
if (getConnection()!=null && getServiceQueue() != null) {
result += " ["+ getServiceQueue().getQueueName()+"]";
}
} catch (Throwable t) {
log.warn(getLogPrefix()+"got exception in getPhysicalDestinationName", t);
}
return result;
}
/**
* set the IFSA service Id, for requesters only
* @param newServiceId the name of the service, e.g. IFSA://SERVICE/CLAIMINFORMATIONMANAGEMENT/NLDFLT/FINDCLAIM:01
*/
public void setServiceId(String newServiceId) {
serviceId = newServiceId;
}
public String getServiceId() {
if (polishedServiceId==null && serviceId!=null) {
try {
IfsaConnection conn = getConnection();
polishedServiceId = conn.polishServiceId(serviceId);
} catch (IfsaException e) {
log.warn("could not obtain connection, no polishing of serviceId",e);
polishedServiceId = serviceId;
}
}
return polishedServiceId;
}
public void setApplicationId(String newApplicationId) {
applicationId = newApplicationId;
}
public String getApplicationId() {
return applicationId;
}
protected synchronized boolean useSelectorsForProviders() {
if (useSelectorsStore==null) {
boolean pooled=AppConstants.getInstance().getBoolean(USE_SELECTOR_FOR_PROVIDER_KEY, true);
useSelectorsStore = new Boolean(pooled);
}
return useSelectorsStore.booleanValue();
}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
}
|
package org.exist.repo;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.SystemProperties;
import org.exist.start.Classpath;
import org.exist.start.EXistClassLoader;
import org.exist.storage.BrokerPool;
import org.exist.storage.BrokerPoolService;
import org.exist.storage.BrokerPoolServiceException;
import org.expath.pkg.repo.*;
import org.expath.pkg.repo.Package;
import org.expath.pkg.repo.deps.ProcessorDependency;
/**
* Helper class to construct classpath for expath modules containing
* jar files. Part of start.jar
*/
public class ClasspathHelper implements BrokerPoolService {
private final static Logger LOG = LogManager.getLogger(ClasspathHelper.class);
@Override
public void prepare(final BrokerPool brokerPool) {
final ClassLoader loader = brokerPool.getClassLoader();
if (!(loader instanceof EXistClassLoader)) {
return;
}
final Classpath cp = new Classpath();
scanPackages(brokerPool, cp);
((EXistClassLoader)loader).addURLs(cp);
}
public static void updateClasspath(BrokerPool pool, org.expath.pkg.repo.Package pkg) throws PackageException {
final ClassLoader loader = pool.getClassLoader();
if (!(loader instanceof EXistClassLoader))
{return;}
if (!isCompatible(pkg)) {
LOG.warn("Package " + pkg.getName() + " is not compatible with this version of eXist. " +
"To avoid conflicts, Java libraries shipping with this package are not loaded.");
return;
}
final FileSystemStorage.FileSystemResolver resolver = (FileSystemStorage.FileSystemResolver) pkg.getResolver();
final Path packageDir = resolver.resolveResourceAsFile(".");
final Classpath cp = new Classpath();
try {
scanPackageDir(cp, packageDir);
((EXistClassLoader)loader).addURLs(cp);
} catch (final IOException e) {
LOG.warn("An error occurred while updating classpath for package " + pkg.getName(), e);
}
}
private static void scanPackages(BrokerPool pool, Classpath classpath) {
try {
final Optional<ExistRepository> repo = pool.getExpathRepo();
if (repo.isPresent()) {
for (final Packages pkgs : repo.get().getParentRepo().listPackages()) {
final Package pkg = pkgs.latest();
if (!isCompatible(pkg)) {
LOG.warn("Package " + pkg.getName() + " is not compatible with this version of eXist. " +
"To avoid conflicts, Java libraries shipping with this package are not loaded.");
} else {
try {
final FileSystemStorage.FileSystemResolver resolver = (FileSystemStorage.FileSystemResolver) pkg.getResolver();
final Path packageDir = resolver.resolveResourceAsFile(".");
scanPackageDir(classpath, packageDir);
} catch (final IOException e) {
LOG.warn("An error occurred while updating classpath for package " + pkg.getName(), e);
}
}
}
}
} catch (final Exception e) {
LOG.warn("An error occurred while updating classpath for packages", e);
}
}
private static boolean isCompatible(final Package pkg) throws PackageException {
// determine the eXist-db version this package is compatible with
final Collection<ProcessorDependency> processorDeps = pkg.getProcessorDeps();
final String procVersion = SystemProperties.getInstance().getSystemProperty("product-version", "1.0");
PackageLoader.Version requiresExistVersion = null;
for (final ProcessorDependency dependency: processorDeps) {
if (Deployment.PROCESSOR_NAME.equals(dependency.getProcessor())) {
if (dependency.getSemver() != null) {
requiresExistVersion = new PackageLoader.Version(dependency.getSemver(), true);
} else if (dependency.getSemverMax() != null || dependency.getSemverMin() != null) {
requiresExistVersion = new PackageLoader.Version(dependency.getSemverMin(), dependency.getSemverMax());
} else if (dependency.getVersions() != null) {
requiresExistVersion = new PackageLoader.Version(dependency.getVersions(), false);
}
break;
}
}
if (requiresExistVersion == null) {
return true;
} else {
return requiresExistVersion.getDependencyVersion().isCompatible(procVersion);
}
}
private static void scanPackageDir(Classpath classpath, Path module) throws IOException {
final Path dotExist = module.resolve(".exist");
if (Files.exists(dotExist)) {
if (!Files.isDirectory(dotExist)) {
throw new IOException("The .exist config dir is not a dir: " + dotExist);
}
final Path cp = dotExist.resolve("classpath.txt");
if (Files.exists(cp)) {
try (final BufferedReader reader = Files.newBufferedReader(cp)) {
String line;
while ((line = reader.readLine()) != null) {
classpath.addComponent(line);
}
}
}
}
}
}
|
package ch.hevs.aislab.magpie.agent;
import android.util.Log;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
import ch.hevs.aislab.magpie.environment.IEnvironment;
import ch.hevs.aislab.magpie.event.MagpieEvent;
public class MagpieAgent implements IAgentBody {
private final String TAG = getClass().getName();
private String name;
private int id;
private ArrayList<String> interests;
private IAgentMind mind;
private ConcurrentLinkedQueue<MagpieEvent> events;
private IEnvironment env;
public MagpieAgent(String name, String ... interests) {
this.name = name;
this.interests = new ArrayList<String>(interests.length);
for (String interest: interests) {
this.interests.add(interest);
}
this.events = new ConcurrentLinkedQueue<MagpieEvent>();
// Assign the mind too
//this.mind = new PrologAgentMind();
}
public MagpieAgent(String name, ArrayList<String> interests) {
this.name = name;
this.interests = interests;
}
public void senseEvent(MagpieEvent event) {
Log.i(TAG, "Event type '" + event.getType() + "' perceived by agent " + this.name);
/*
Toast.makeText(
MagpieService.getContext(),
"Event type '" + event.getType() + "' perceived by agent " + this.name,
Toast.LENGTH_LONG)
.show();
*/
this.events.add(event);
Log.i(TAG, "Events in the agent queue after sensing: " + events.size());
}
public void setMind(IAgentMind mind){
this.mind = mind;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public ArrayList<String> getInterests() {
return interests;
}
public void setInterests(String...interests) {
this.interests.clear();
for (String interest : interests) {
this.interests.add(interest);
}
}
@Override
public void activate() {
Log.i(TAG, "Agent " + name + " active");
this.doPerception();
this.doBehaviour();
}
@Override
public void doPerception() {
for(int i=0; i<this.events.size(); i++) {
this.mind.updatePerception(this.events.peek());
}
Log.i(TAG, "Events in the agent queue after perception:" + events.size());
}
@Override
public void doBehaviour() {
//do something with the environment
for (int i=0; i<this.events.size(); i++) {
MagpieEvent alert = this.mind.produceAction(
this.events.poll().getTimeStamp()
);
if (alert != null) {
this.env.registerAlert(alert);
}
}
}
@Override
public void setEnvironment(IEnvironment env) {
this.env = env;
}
}
|
package org.minimalj.backend;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.minimalj.application.Application;
import org.minimalj.transaction.StreamConsumer;
import org.minimalj.transaction.StreamProducer;
import org.minimalj.transaction.Transaction;
import org.minimalj.util.LoggingRuntimeException;
import org.minimalj.util.UnclosingOutputStream;
public class SocketBackendServer {
private static final Logger logger = Logger.getLogger(SocketBackendServer.class.getName());
private final int port;
private final ThreadPoolExecutor executor;
public SocketBackendServer(int port) {
this.port = port;
this.executor = new ThreadPoolExecutor(10, 30, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
public void run() {
Thread.currentThread().setName("MjServer");
try (ServerSocket serverSocket = new ServerSocket(port)) {
accecptInvocations(serverSocket);
} catch (IOException iox) {
throw new LoggingRuntimeException(iox, logger, "Could not create server socket");
}
}
private void accecptInvocations(ServerSocket serverSocket) {
while (true) {
Socket socket;
try {
socket = serverSocket.accept();
SocketBackendRunnable runnable = new SocketBackendRunnable(socket);
executor.execute(runnable);
} catch (IOException e) {
logger.log(Level.SEVERE, "Server socket couldn't accept connection", e);
}
}
}
private static class SocketBackendRunnable implements Runnable {
private final Socket socket;
public SocketBackendRunnable(Socket socket) {
this.socket = socket;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void run() {
try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
Object input = ois.readObject();
Object result = null;
if (input instanceof Transaction) {
Transaction transaction = (Transaction) input;
result = Backend.getInstance().execute(transaction);
} else if (input instanceof StreamConsumer) {
StreamConsumer streamConsumer = (StreamConsumer) input;
result = Backend.getInstance().execute(streamConsumer, ois);
}
try (ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())) {
if (input instanceof StreamProducer) {
StreamProducer streamProducer = (StreamProducer) input;
result = Backend.getInstance().execute(streamProducer, new UnclosingOutputStream(oos));
}
oos.writeObject(result);
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Could not create ObjectInputStream from socket", e);
e.printStackTrace();
} catch (Exception e) {
logger.log(Level.SEVERE, "SocketRunnable failed", e);
e.printStackTrace();
}
}
}
public static void main(final String[] args) throws Exception {
Application.initApplication(args);
new SocketBackendServer(8020).run();
}
}
|
package org.exist.xquery.util;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import org.exist.util.CodePointString;
import org.exist.xmldb.XmldbURI;
/**
* Utilities for URI related functions
*
* @author <a href="mailto:pierrick.brihaye@free.fr">Pierrick Brihaye</a>
*/
public class URIUtils {
private final static class CharArray {
char[] buf;
int count;
public CharArray(final int initalSize) {
buf = new char[initalSize];
}
void append(final char c) {
final int newcount = count + 1;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = c;
count = newcount;
}
public void append(final char c, final char c1) {
final int newcount = count + 2;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = c;
buf[count+1] = c1;
count = newcount;
}
public void append(final char c, final char c1, final char c2) {
final int newcount = count + 3;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = c;
buf[count+1] = c1;
buf[count+2] = c2;
count = newcount;
}
public void append(final char[] cc) {
if (cc.length > 2) {
append(cc[0], cc[1], cc[2]);
} else if (cc.length > 1) {
append(cc[0], cc[1]);
} else if (cc.length == 1) {
append(cc[0]);
} else {
throw new UnsupportedOperationException("Only supported upto array size 3");
}
}
}
private static final char[][] ASCII_TABLE_URI_PATH_COMPONENT_ENCODED = new char[][] {
new char[] { '%', '0', '0' }, //NUL
new char[] { '%', '0', '1' }, //SOH
new char[] { '%', '0', '2' }, //STX
new char[] { '%', '0', '3' }, //ETX
new char[] { '%', '0', '4' }, //EOT
new char[] { '%', '0', '5' }, //ENQ
new char[] { '%', '0', '6' }, //ACK
new char[] { '%', '0', '7' }, //BEL
new char[] { '%', '0', '8' },
new char[] { '%', '0', '9' },
new char[] { '%', '0', 'A' },
new char[] { '%', '0', 'B' },
new char[] { '%', '0', 'C' },
new char[] { '%', '0', 'D' },
new char[] { '%', '0', 'E' },
new char[] { '%', '0', 'F' },
new char[] { '%', '1', '0' }, //DLE
new char[] { '%', '1', '1' }, //DC1
new char[] { '%', '1', '2' }, //DC2
new char[] { '%', '1', '3' }, //DC3
new char[] { '%', '1', '4' }, //DC4
new char[] { '%', '1', '5' }, //NAK
new char[] { '%', '1', '6' }, //SYN
new char[] { '%', '1', '7' }, //ETB
new char[] { '%', '1', '8' }, //CAN
new char[] { '%', '1', '9' },
new char[] { '%', '1', 'A' }, //SUB
new char[] { '%', '1', 'B' }, //ESC
new char[] { '%', '1', 'C' },
new char[] { '%', '1', 'D' },
new char[] { '%', '1', 'E' },
new char[] { '%', '1', 'F' },
new char[] { '%', '2', '0' }, //space
new char[] { '%', '2', '1' },
new char[] { '%', '2', '2' },
new char[] { '%', '2', '3' }, //
new char[] { '%', '2', '4' },
new char[] { '%', '2', '5' },
new char[] { '%', '2', '6' },
new char[] { '%', '2', '7' },
new char[] { '%', '2', '8' },
new char[] { '%', '2', '9' },
public static String encodeForURI(final String pathComponent) {
final CodePointString codePoints = new CodePointString(pathComponent);
final CharArray buf = new CharArray(pathComponent.length());
for (int i = 0; i < codePoints.length(); i++) {
final int c = codePoints.codePointAt(i);
if (c <= 0x7F) {
buf.append(ASCII_TABLE_URI_PATH_COMPONENT_ENCODED[c]);
} else if (c <= 0x7FF) {
buf.append('%');
final int c1 = 0xC0 | c >> 6;
buf.append(HEX_TABLE[c1 >> 4], HEX_TABLE[c1 & 0xF]);
buf.append('%');
final int c2 = 0x80 | (c & 0x3F);
buf.append(HEX_TABLE[c2 >> 4], HEX_TABLE[c2 & 0xF]);
// unicode code point to utf8
// u8 = 0xC000 | ((c >> 6) << 8);
// u8 |= 0x80 | (c & 0x3F);
} else if (c <= 0xFFFF) {
buf.append('%');
final int c1 = 0xE0 | c >> 12;
buf.append(HEX_TABLE[c1 >> 4], HEX_TABLE[c1 & 0xF]);
buf.append('%');
final int c2 = 0x80 | ((c >> 6) & 0x3F);
buf.append(HEX_TABLE[c2 >> 4], HEX_TABLE[c2 & 0xF]);
buf.append('%');
final int c3 = 0x80 | (c & 0x3F);
buf.append(HEX_TABLE[c3 >> 4], HEX_TABLE[c3 & 0xF]);
} else {
buf.append('%');
final int c1 = 0xF0 | c >> 18;
buf.append(HEX_TABLE[c1 >> 4], HEX_TABLE[c1 & 0xF]);
buf.append('%');
final int c2 = 0x80 | ((c >> 12) & 0x3F);
buf.append(HEX_TABLE[c2 >> 4], HEX_TABLE[c2 & 0xF]);
buf.append('%');
final int c3 = 0x80 | ((c >> 6) & 0x3F);
buf.append(HEX_TABLE[c3 >> 4], HEX_TABLE[c3 & 0xF]);
buf.append('%');
final int c4 = 0x80 | (c & 0x3F);
buf.append(HEX_TABLE[c4 >> 4], HEX_TABLE[c4 & 0xF]);
}
}
return new String(buf.buf, 0, buf.count);
}
public static String iriToURI(String uriPart) {
String result = urlEncodeUtf8(uriPart);
result = result.replaceAll("%23", "
result = result.replaceAll("%2D", "-");
result = result.replaceAll("%5F", "_");
result = result.replaceAll("%2E", ".");
result = result.replaceAll("%21", "!");
result = result.replaceAll("%7E", "~");
result = result.replaceAll("%2A", "*");
result = result.replaceAll("%27", "'");
result = result.replaceAll("%28", "(");
result = result.replaceAll("%29", ")");
result = result.replaceAll("%3B", ";");
result = result.replaceAll("%2F", "/");
result = result.replaceAll("%3F", "?");
result = result.replaceAll("%3A", ":");
result = result.replaceAll("%40", "@");
result = result.replaceAll("%26", "&");
result = result.replaceAll("%3D", "=");
result = result.replaceAll("%2B", "+");
result = result.replaceAll("%24", "\\$");
result = result.replaceAll("%2C", ",");
result = result.replaceAll("%5B", "[");
result = result.replaceAll("%5D", "]");
result = result.replaceAll("%25", "%");
return result;
}
public static String escapeHtmlURI(String uri){
String result = urlEncodeUtf8(uri);
//TODO : to be continued
result = result.replaceAll("\\+", " ");
result = result.replaceAll("%20", " ");
result = result.replaceAll("%23", "
result = result.replaceAll("%2D", "-");
result = result.replaceAll("%5F", "_");
result = result.replaceAll("%2E", ".");
result = result.replaceAll("%21", "!");
result = result.replaceAll("%7E", "~");
result = result.replaceAll("%2A", "*");
result = result.replaceAll("%27", "'");
result = result.replaceAll("%28", "(");
result = result.replaceAll("%29", ")");
result = result.replaceAll("%3B", ";");
result = result.replaceAll("%2F", "/");
result = result.replaceAll("%3F", "?");
result = result.replaceAll("%3A", ":");
result = result.replaceAll("%40", "@");
result = result.replaceAll("%26", "&");
result = result.replaceAll("%3D", "=");
result = result.replaceAll("%2B", "+");
result = result.replaceAll("%24", "\\$");
result = result.replaceAll("%2C", ",");
result = result.replaceAll("%5B", "[");
result = result.replaceAll("%5D", "]");
result = result.replaceAll("%25", "%");
return result;
}
/**
* This method is a wrapper for {@link java.net.URLEncoder#encode(java.lang.String,java.lang.String)}
* It calls this method, suppying the url parameter as
* the first parameter, and "UTF-8" (the W3C recommended
* encoding) as the second. UnsupportedEncodingExceptions
* are wrapped in a runtime exception.
*
* IMPORTANT: the java.net.URLEncoder class encodes a space (" ")
* as a "+". The proper method of encoding spaces in the path of
* a URI is with "%20", so this method will replace all instances of "+"
* in the encoded string with "%20" before returning. This means that
* XmldbURIs constructed from java.net.URLEncoder#encoded strings
* will not be String equivalents of XmldbURIs created with the result of
* calls to this function.
*
* @param uri The uri to encode
* @return The UTF-8 encoded value of the supplied uri
*/
public static String urlEncodeUtf8(String uri) {
try {
final String almostEncoded = URLEncoder.encode(uri, "UTF-8");
return almostEncoded.replaceAll("\\+","%20");
} catch(final UnsupportedEncodingException e) {
//wrap with a runtime Exception
throw new RuntimeException(e);
}
}
/**
* This method decodes the provided uri for human readability. The
* method simply wraps URLDecoder.decode(uri,"UTF-8). It is places here
* to provide a friendly way to decode URIs encoded by urlEncodeUtf8()
*
* @param uri The uri to decode
* @return The decoded value of the supplied uri
*/
public static String urlDecodeUtf8(String uri) {
try {
return URLDecoder.decode(uri, "UTF-8");
} catch(final UnsupportedEncodingException e) {
//wrap with a runtime Exception
throw new RuntimeException(e);
}
}
/**
* This method decodes the provided uri for human readability. The
* method simply wraps URLDecoder.decode(uri,"UTF-8). It is places here
* to provide a friendly way to decode URIs encoded by urlEncodeUtf8()
*
* @param uri The uri to decode
* @return The decoded value of the supplied uri
*/
public static String urlDecodeUtf8(XmldbURI uri) {
try {
return URLDecoder.decode(uri.toString(), "UTF-8");
} catch(final UnsupportedEncodingException e) {
//wrap with a runtime Exception
throw new RuntimeException(e);
}
}
/**
* This method splits the supplied url on the character
* '/' then URL encodes the segments between, returning
* a URL encoded version of the passed url, leaving any
* occurrence of '/' as it is.
*
* @param url The path to encode
* @return A UTF-8 URL encoded string
*/
public static String urlEncodePartsUtf8(String url) {
final String[] split = url.split("/",-1);
final StringBuilder ret = new StringBuilder(url.length());
for(int i=0;i<split.length;i++) {
ret.append(urlEncodeUtf8(split[i]));
if(i<split.length-1) {
ret.append("/");
}
}
return ret.toString();
}
/**
* This method ensure that a collection path (e.g. /db/[])
* is properly URL encoded. Uses W3C recommended UTF-8
* encoding.
*
* @param path The path to check
* @return A UTF-8 URL encoded string
*/
public static String ensureUrlEncodedUtf8(String path) {
try {
final XmldbURI uri = XmldbURI.xmldbUriFor(path);
return uri.getRawCollectionPath();
} catch (final URISyntaxException e) {
return URIUtils.urlEncodePartsUtf8(path);
}
}
/**
* This method creates an <code>XmldbURI</code> by encoding the provided
* string, then calling XmldbURI.xmldbUriFor(String) with the result of that
* encoding
*
* @param path The path to encode and create an XmldbURI from
* @return A UTF-8 URI encoded string
* @throws URISyntaxException A URISyntaxException is thrown if the path
* cannot be parsed by XmldbURI, after being encoded by
* <code>urlEncodePartsUtf8</code>
*/
public static XmldbURI encodeXmldbUriFor(String path) throws URISyntaxException {
return XmldbURI.xmldbUriFor(URIUtils.urlEncodePartsUtf8(path));
}
}
|
package devopsdistilled.operp.client.main;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.Toolkit;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import devopsdistilled.operp.client.abstracts.TaskPane;
public class MainWindow implements MainModelObserver {
private static MainWindow mainWindow = new MainWindow();
@Inject
private MainWindowController controller;
@Inject
private MainModel model;
@Inject
private NavigationPane navigationPane;
private JFrame frame;
private JSplitPane splitPane;
private MainWindow() {
}
public static MainWindow getInstance() {
return mainWindow;
}
@PostConstruct
private void registerObserver() {
model.registerObserver(this);
model.castObservers();
}
public void init() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
initComponents();
frame.getContentPane().add(splitPane);
splitPane.setLeftComponent(navigationPane.getPane());
splitPane.setRightComponent(model.getSelectedTaskPane()
.getPane());
frame.setVisible(true);
}
});
}
private void initComponents() {
frame = new JFrame(model.getTitle());
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds(new Rectangle(screenSize));
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
splitPane = new JSplitPane();
splitPane.setDividerLocation(200);
}
@Override
public void updateTaskPane(TaskPane taskPane) {
splitPane.setRightComponent(taskPane.getPane());
}
@Override
public void updateTitle(String title) {
frame.setTitle(title);
}
public MainModel getModel() {
return model;
}
@Override
public void updateAll() {
}
public MainWindowController getController() {
return controller;
}
}
|
package org.exist.xquery.util;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import org.exist.xmldb.XmldbURI;
/**
* Utilities for URI related functions
*
* @author <a href="mailto:pierrick.brihaye@free.fr">Pierrick Brihaye</a>
*/
public class URIUtils {
private final static class CharArray {
char[] buf;
int count;
public CharArray(final int initalSize) {
buf = new char[initalSize];
}
void append(final char c) {
final int newcount = count + 1;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = c;
count = newcount;
}
public void append(final char c, final char c1) {
final int newcount = count + 2;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = c;
buf[count+1] = c1;
count = newcount;
}
public void append(final char c, final char c1, final char c2) {
final int newcount = count + 3;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = c;
buf[count+1] = c1;
buf[count+2] = c2;
count = newcount;
}
}
public static String encodeForURI(final String pathComponent) {
final String src;
try {
src = URLEncoder.encode(pathComponent, "UTF-8");
} catch(final UnsupportedEncodingException e) {
//wrap with a runtime Exception
throw new RuntimeException(e);
}
final CharArray result = new CharArray(src.length());
for (int i = 0; i < src.length(); i++) {
final char c = src.charAt(i);
if (c == '%') {
if (i + 2 < src.length()) {
final char c1 = src.charAt(i + 1);
final char c2 = src.charAt(i + 2);
if (c1 =='2') {
if (c2 == 'D') {
result.append('-');
i += 2;
} else if (c2 == 'E') {
result.append('.');
i += 2;
} else {
result.append(c, c1);
i++;
}
} else if (c1 == '5') {
if (c2 == 'F') {
result.append('_');
i += 2;
} else {
result.append(c, c1);
i++;
}
} else if (c1 == '7') {
if (c2 == 'E') {
result.append('~');
i += 2;
} else {
result.append(c, c1);
i++;
}
} else {
result.append(c); //TODO(AR) should this be % encoded
}
} else {
result.append(c);
}
} else if (c == '*') {
result.append('%', '2', 'A');
} else if (c == '+') {
result.append('%', '2', '0');
} else {
result.append(c);
}
}
return new String(result.buf, 0, result.count);
}
public static String iriToURI(String uriPart) {
String result = urlEncodeUtf8(uriPart);
result = result.replaceAll("%23", "
result = result.replaceAll("%2D", "-");
result = result.replaceAll("%5F", "_");
result = result.replaceAll("%2E", ".");
result = result.replaceAll("%21", "!");
result = result.replaceAll("%7E", "~");
result = result.replaceAll("%2A", "*");
result = result.replaceAll("%27", "'");
result = result.replaceAll("%28", "(");
result = result.replaceAll("%29", ")");
result = result.replaceAll("%3B", ";");
result = result.replaceAll("%2F", "/");
result = result.replaceAll("%3F", "?");
result = result.replaceAll("%3A", ":");
result = result.replaceAll("%40", "@");
result = result.replaceAll("%26", "&");
result = result.replaceAll("%3D", "=");
result = result.replaceAll("%2B", "+");
result = result.replaceAll("%24", "\\$");
result = result.replaceAll("%2C", ",");
result = result.replaceAll("%5B", "[");
result = result.replaceAll("%5D", "]");
result = result.replaceAll("%25", "%");
return result;
}
public static String escapeHtmlURI(String uri){
String result = urlEncodeUtf8(uri);
//TODO : to be continued
result = result.replaceAll("\\+", " ");
result = result.replaceAll("%20", " ");
result = result.replaceAll("%23", "
result = result.replaceAll("%2D", "-");
result = result.replaceAll("%5F", "_");
result = result.replaceAll("%2E", ".");
result = result.replaceAll("%21", "!");
result = result.replaceAll("%7E", "~");
result = result.replaceAll("%2A", "*");
result = result.replaceAll("%27", "'");
result = result.replaceAll("%28", "(");
result = result.replaceAll("%29", ")");
result = result.replaceAll("%3B", ";");
result = result.replaceAll("%2F", "/");
result = result.replaceAll("%3F", "?");
result = result.replaceAll("%3A", ":");
result = result.replaceAll("%40", "@");
result = result.replaceAll("%26", "&");
result = result.replaceAll("%3D", "=");
result = result.replaceAll("%2B", "+");
result = result.replaceAll("%24", "\\$");
result = result.replaceAll("%2C", ",");
result = result.replaceAll("%5B", "[");
result = result.replaceAll("%5D", "]");
result = result.replaceAll("%25", "%");
return result;
}
/**
* This method is a wrapper for {@link java.net.URLEncoder#encode(java.lang.String,java.lang.String)}
* It calls this method, suppying the url parameter as
* the first parameter, and "UTF-8" (the W3C recommended
* encoding) as the second. UnsupportedEncodingExceptions
* are wrapped in a runtime exception.
*
* IMPORTANT: the java.net.URLEncoder class encodes a space (" ")
* as a "+". The proper method of encoding spaces in the path of
* a URI is with "%20", so this method will replace all instances of "+"
* in the encoded string with "%20" before returning. This means that
* XmldbURIs constructed from java.net.URLEncoder#encoded strings
* will not be String equivalents of XmldbURIs created with the result of
* calls to this function.
*
* @param uri The uri to encode
* @return The UTF-8 encoded value of the supplied uri
*/
public static String urlEncodeUtf8(String uri) {
try {
final String almostEncoded = URLEncoder.encode(uri, "UTF-8");
return almostEncoded.replaceAll("\\+","%20");
} catch(final UnsupportedEncodingException e) {
//wrap with a runtime Exception
throw new RuntimeException(e);
}
}
/**
* This method decodes the provided uri for human readability. The
* method simply wraps URLDecoder.decode(uri,"UTF-8). It is places here
* to provide a friendly way to decode URIs encoded by urlEncodeUtf8()
*
* @param uri The uri to decode
* @return The decoded value of the supplied uri
*/
public static String urlDecodeUtf8(String uri) {
try {
return URLDecoder.decode(uri, "UTF-8");
} catch(final UnsupportedEncodingException e) {
//wrap with a runtime Exception
throw new RuntimeException(e);
}
}
/**
* This method decodes the provided uri for human readability. The
* method simply wraps URLDecoder.decode(uri,"UTF-8). It is places here
* to provide a friendly way to decode URIs encoded by urlEncodeUtf8()
*
* @param uri The uri to decode
* @return The decoded value of the supplied uri
*/
public static String urlDecodeUtf8(XmldbURI uri) {
try {
return URLDecoder.decode(uri.toString(), "UTF-8");
} catch(final UnsupportedEncodingException e) {
//wrap with a runtime Exception
throw new RuntimeException(e);
}
}
/**
* This method splits the supplied url on the character
* '/' then URL encodes the segments between, returning
* a URL encoded version of the passed url, leaving any
* occurrence of '/' as it is.
*
* @param url The path to encode
* @return A UTF-8 URL encoded string
*/
public static String urlEncodePartsUtf8(String url) {
final String[] split = url.split("/",-1);
final StringBuilder ret = new StringBuilder(url.length());
for(int i=0;i<split.length;i++) {
ret.append(urlEncodeUtf8(split[i]));
if(i<split.length-1) {
ret.append("/");
}
}
return ret.toString();
}
/**
* This method ensure that a collection path (e.g. /db/[])
* is properly URL encoded. Uses W3C recommended UTF-8
* encoding.
*
* @param path The path to check
* @return A UTF-8 URL encoded string
*/
public static String ensureUrlEncodedUtf8(String path) {
try {
final XmldbURI uri = XmldbURI.xmldbUriFor(path);
return uri.getRawCollectionPath();
} catch (final URISyntaxException e) {
return URIUtils.urlEncodePartsUtf8(path);
}
}
/**
* This method creates an <code>XmldbURI</code> by encoding the provided
* string, then calling XmldbURI.xmldbUriFor(String) with the result of that
* encoding
*
* @param path The path to encode and create an XmldbURI from
* @return A UTF-8 URI encoded string
* @throws URISyntaxException A URISyntaxException is thrown if the path
* cannot be parsed by XmldbURI, after being encoded by
* <code>urlEncodePartsUtf8</code>
*/
public static XmldbURI encodeXmldbUriFor(String path) throws URISyntaxException {
return XmldbURI.xmldbUriFor(URIUtils.urlEncodePartsUtf8(path));
}
}
|
package com.opensoc.dataservices;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Properties;
import javax.servlet.DispatcherType;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.jasper.servlet.JspServlet;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.SimpleInstanceManager;
import org.eclipse.jetty.annotations.ServletContainerInitializersStarter;
import org.eclipse.jetty.apache.jsp.JettyJasperInitializer;
import org.eclipse.jetty.plus.annotation.ContainerInitializer;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;
import com.opensoc.alerts.server.AlertsProcessingServer;
import com.opensoc.dataservices.modules.guice.AlertsServerModule;
import com.opensoc.dataservices.modules.guice.DefaultServletModule;
import com.opensoc.dataservices.modules.guice.DefaultShiroWebModule;
public class Main {
static int port = 9091;
private static final String WEBROOT_INDEX = "/webroot/";
private static final Logger logger = LoggerFactory.getLogger( Main.class );
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addOption( "homeDir", true, "Home directory for the service" );
CommandLineParser parser = new GnuParser();
CommandLine cmd = parser.parse( options, args);
Properties configProps = new Properties();
String homeDir = cmd.getOptionValue("homeDir");
if( homeDir.endsWith( "/" ))
{
homeDir = homeDir.substring(0, homeDir.length()-1);
}
DOMConfigurator.configure( homeDir + "/log4j.xml" );
logger.warn( "DataServices Server starting..." );
File configFile = new File( homeDir + "/config.properties" );
FileReader configFileReader = new FileReader( configFile );
try
{
configProps.load(configFileReader);
Option[] cmdOptions = cmd.getOptions();
for( Option opt : cmdOptions )
{
String argName = opt.getOpt();
String argValue = opt.getValue();
configProps.put(argName, argValue);
}
}
finally
{
if( configFileReader != null )
{
configFileReader.close();
}
}
WebAppContext context = new WebAppContext();
Injector injector = Guice.createInjector( new DefaultServletModule(configProps),
new AlertsServerModule(configProps),
new DefaultShiroWebModule(configProps, context.getServletContext()),
new AbstractModule() {
@Override
protected void configure() {
binder().requireExplicitBindings();
bind(GuiceFilter.class);
bind( GuiceResteasyBootstrapServletContextListener.class );
bind( EnvironmentLoaderListener.class );
}
}
);
injector.getAllBindings();
injector.createChildInjector().getAllBindings();
Server server = new Server(port);
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
http_config.setRequestHeaderSize(8192);
http_config.setResponseHeaderSize(8192);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);
// httpConfig.addCustomizer(new ForwardedRequestCustomizer())
// SSL Context Factory
SslContextFactory sslContextFactory = new SslContextFactory();
String sslKeystorePath = configProps.getProperty( "sslKeystorePath", "/keystore" );
logger.debug( "sslKeystorePath: " + sslKeystorePath );
sslContextFactory.setKeyStorePath( homeDir + sslKeystorePath );
String sslKeystorePassword = configProps.getProperty( "sslKeystorePassword" );
sslContextFactory.setKeyStorePassword(sslKeystorePassword);
String sslKeyManagerPassword = configProps.getProperty( "sslKeyManagerPassword" );
if( sslKeyManagerPassword != null && !sslKeyManagerPassword.isEmpty() )
{
sslContextFactory.setKeyManagerPassword(sslKeyManagerPassword);
}
String sslTruststorePath = configProps.getProperty( "sslTruststorePath" );
if( sslTruststorePath != null && !sslTruststorePath.isEmpty() )
{
sslContextFactory.setTrustStorePath( homeDir + sslTruststorePath );
}
String sslTruststorePassword = configProps.getProperty( "sslTruststorePassword" );
if( sslTruststorePassword != null && !sslTruststorePassword.isEmpty())
{
sslContextFactory.setTrustStorePassword( sslTruststorePassword );
}
sslContextFactory.setExcludeCipherSuites(
"SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_DSS_WITH_DES_CBC_SHA",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
// SSL HTTP Configuration
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,"http/1.1"),
new HttpConnectionFactory(https_config));
sslConnector.setPort(8443);
server.addConnector(sslConnector);
FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
/** For JSP support. Used only for testing and debugging for now. This came come out
* once the real consumers for this service are in place
*/
URL indexUri = Main.class.getResource(WEBROOT_INDEX);
if (indexUri == null)
{
throw new FileNotFoundException("Unable to find resource " + WEBROOT_INDEX);
}
// Points to wherever /webroot/ (the resource) is
URI baseUri = indexUri.toURI();
// Establish Scratch directory for the servlet context (used by JSP compilation)
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File scratchDir = new File(tempDir.toString(),"embedded-jetty-jsp");
if (!scratchDir.exists())
{
if (!scratchDir.mkdirs())
{
throw new IOException("Unable to create scratch directory: " + scratchDir);
}
}
// Set JSP to use Standard JavaC always
System.setProperty("org.apache.jasper.compiler.disablejsr199","false");
context.setAttribute("javax.servlet.context.tempdir",scratchDir);
context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
//Ensure the jsp engine is initialized correctly
JettyJasperInitializer sci = new JettyJasperInitializer();
ServletContainerInitializersStarter sciStarter = new ServletContainerInitializersStarter(context);
ContainerInitializer initializer = new ContainerInitializer(sci, null);
List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>();
initializers.add(initializer);
context.setAttribute("org.eclipse.jetty.containerInitializers", initializers);
context.addBean(sciStarter, true);
// Set Classloader of Context to be sane (needed for JSTL)
// JSP requires a non-System classloader, this simply wraps the
// embedded System classloader in a way that makes it suitable
// for JSP to use
// new URL( "file:///home/prhodes/.m2/repository/javax/servlet/jsp/javax.servlet.jsp-api/2.3.1/javax.servlet.jsp-api-2.3.1.jar" )
ClassLoader jspClassLoader = new URLClassLoader(new URL[] {}, Thread.currentThread().getContextClassLoader());
context.setClassLoader(jspClassLoader);
// Add JSP Servlet (must be named "jsp")
ServletHolder holderJsp = new ServletHolder("jsp",JspServlet.class);
holderJsp.setInitOrder(0);
holderJsp.setInitParameter("logVerbosityLevel","DEBUG");
holderJsp.setInitParameter("fork","false");
holderJsp.setInitParameter("xpoweredBy","false");
holderJsp.setInitParameter("compilerTargetVM","1.7");
holderJsp.setInitParameter("compilerSourceVM","1.7");
holderJsp.setInitParameter("keepgenerated","true");
context.addServlet(holderJsp,"*.jsp");
//context.addServlet(holderJsp,"*.jspf");
//context.addServlet(holderJsp,"*.jspx");
// Add Default Servlet (must be named "default")
ServletHolder holderDefault = new ServletHolder("default",DefaultServlet.class);
holderDefault.setInitParameter("resourceBase",baseUri.toASCIIString());
holderDefault.setInitParameter("dirAllowed","true");
context.addServlet(holderDefault,"/");
/** end "for JSP support */
context.setResourceBase(baseUri.toASCIIString());
context.setInitParameter("resteasy.guice.modules", "com.opensoc.dataservices.modules.guice.RestEasyModule");
context.setInitParameter("resteasy.servlet.mapping.prefix", "/rest");
context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
|
package org.apps8os.trafficsense.second;
import org.apps8os.trafficsense.TrafficsenseContainer;
import org.apps8os.trafficsense.core.Route;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class SchematicView extends Activity{
EditText myEditText;
Button myButton;
TextView myTextView;
String key=null;
String request;
TrafficsenseContainer mContainer;
Route route = new Route();
// SparseArray<Group> groups = new SparseArray<Group>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.schematic_main);
mContainer = TrafficsenseContainer.getInstance();
route = mContainer.getRoute();
ExpandableListView listView = (ExpandableListView) findViewById(R.id.listview);
ExpandableListAdapter adapter = new ExpandableListAdapter(this, route);
listView.setAdapter(adapter);
myTextView = (TextView) findViewById(R.id.textView1);
//myTextView.setText("From: ");
myTextView.setText("From: " + route.getStart() + ", to " + route.getDestination());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
package com.armandgray.seeme.views;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.armandgray.seeme.NoteEditorActivity;
import com.armandgray.seeme.R;
import com.armandgray.seeme.db.DatabaseHelper;
import com.armandgray.seeme.db.NotesProvider;
import com.armandgray.seeme.models.User;
import com.armandgray.seeme.services.HttpService;
import com.armandgray.seeme.utils.NotesLvAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.app.Activity.RESULT_OK;
import static com.armandgray.seeme.MainActivity.ACTIVE_USER;
import static com.armandgray.seeme.MainActivity.API_URI;
import static com.armandgray.seeme.network.HttpHelper.sendGetRequest;
import static com.armandgray.seeme.network.HttpHelper.sendPostRequest;
/**
* A simple {@link Fragment} subclass.
*/
public class NotesFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String POST_NOTES_URI = API_URI + "/notes/post?";
private static final String GET_NOTES_URI = API_URI + "/notes/get?";
private static final String TAG = "NOTES_FRAGMENT";
private static final int EDITOR_REQUEST_CODE = 1001;
private static final String USER_NOT_FOUND = "User Not Found!";
private static final String NOTES_UPLOADED = "Notes Uploaded";
private static final String PREPARE_UPDATE_ERROR = "Prepare Update Error!";
private static final String UPDATE_QUERY_ERROR = "Update Query Error!";
private static final String INTERNAL_UPDATE_ERROR = "Internal Update Error!";
private String[] responseArray = {USER_NOT_FOUND, PREPARE_UPDATE_ERROR, NOTES_UPLOADED,
UPDATE_QUERY_ERROR, INTERNAL_UPDATE_ERROR};
private CursorAdapter adapter;
private User activeUser;
private BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "http Broadcast Received");
handleHttpResponse(intent.getStringExtra(HttpService.HTTP_SERVICE_STRING_PAYLOAD),
intent.getStringArrayExtra(HttpService.HTTP_SERVICE_NOTES_PAYLOAD));
}
};
public NotesFragment() {}
public static NotesFragment newInstance(User activeUser) {
Bundle args = new Bundle();
args.putParcelable(ACTIVE_USER, activeUser);
NotesFragment fragment = new NotesFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
activeUser = getArguments().getParcelable(ACTIVE_USER);
adapter = new NotesLvAdapter(getContext(), null, 0);
ListView lvNotes = (ListView) rootView.findViewById(R.id.lvNotes);
lvNotes.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
lvNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), NoteEditorActivity.class);
Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id);
intent.putExtra(NotesProvider.CONTENT_ITEM_TYPE, uri);
startActivityForResult(intent, EDITOR_REQUEST_CODE);
}
});
FloatingActionButton fabDelete = (FloatingActionButton) rootView.findViewById(R.id.fabDelete);
fabDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getContext(), NoteEditorActivity.class), EDITOR_REQUEST_CODE);
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
if (getUserVisibleHint()) {
LocalBroadcastManager.getInstance(getActivity().getApplicationContext())
.registerReceiver(httpBroadcastReceiver,
new IntentFilter(HttpService.HTTP_SERVICE_MESSAGE));
sendGetNotesRequest();
}
}
private void sendGetNotesRequest() {
String url = GET_NOTES_URI
+ "username=" + activeUser.getUsername();
sendGetRequest(url, getContext());
}
private Loader<Cursor> restartLoader() {
return getLoaderManager().restartLoader(0, null, this);
}
private void handleHttpResponse(String response, String[] arrayExtra) {
if (response != null && response.equals(USER_NOT_FOUND)) {
getActivity().getContentResolver().delete(NotesProvider.CONTENT_URI, null, null);
restartLoader();
return;
}
if (arrayExtra != null) {
updateSqliteDatabase(arrayExtra);
}
}
private void updateSqliteDatabase(String[] arrayExtra) {
getActivity().getContentResolver().delete(NotesProvider.CONTENT_URI, null, null);
for (String note : arrayExtra) {
insertNote(note);
}
restartLoader();
}
private void insertNote(String note) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.NOTE_TEXT, note);
getActivity().getContentResolver().insert(NotesProvider.CONTENT_URI, values);
restartLoader();
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getContext(), NotesProvider.CONTENT_URI,
null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_REQUEST_CODE && resultCode == RESULT_OK) {
sendPostNotesRequest();
restartLoader();
}
}
private void sendPostNotesRequest() {
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
Cursor cursor = getActivity().getContentResolver()
.query(NotesProvider.CONTENT_URI, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String url = POST_NOTES_URI
+ "username=" + activeUser.getUsername();
sendPostRequest(url, getNotesJson(cursor, json, jsonArray), getContext());
}
}
private String getNotesJson(Cursor cursor, JSONObject json, JSONArray jsonArray) {
String noteText;
try {
do {
noteText = cursor.getString(cursor.getColumnIndex(DatabaseHelper.NOTE_TEXT));
jsonArray.put(cursor.getPosition(), noteText);
} while (cursor.moveToNext());
json = new JSONObject();
json.put("notes", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
@Override
public void onPause() {
super.onPause();
if (!getUserVisibleHint()) {
LocalBroadcastManager.getInstance(getActivity().getApplicationContext())
.unregisterReceiver(httpBroadcastReceiver);
}
}
}
|
package it.angelic.soulissclient.net;
import static it.angelic.soulissclient.model.typicals.Constants.Souliss_T41_Antitheft_Main;
import static it.angelic.soulissclient.model.typicals.Constants.Souliss_T4n_InAlarm;
import static junit.framework.Assert.assertEquals;
import it.angelic.soulissclient.R;
import it.angelic.soulissclient.SoulissClient;
import it.angelic.soulissclient.SoulissDataService;
import it.angelic.soulissclient.Typical4nDetail;
import it.angelic.soulissclient.db.SoulissCommandDTO;
import it.angelic.soulissclient.db.SoulissDBLowHelper;
import it.angelic.soulissclient.db.SoulissTriggerDTO;
import it.angelic.soulissclient.db.SoulissTypicalDTO;
import it.angelic.soulissclient.helpers.SoulissPreferenceHelper;
import it.angelic.soulissclient.model.SoulissNode;
import it.angelic.soulissclient.model.SoulissTrigger;
import it.angelic.soulissclient.model.SoulissTypical;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* Classe per il decode dei pacchetti nativi souliss
*
* This class decodes incoming Souliss packets, starting from decodevNet
*
* @author Ale
*
*/
public class UDPSoulissDecoder {
SoulissPreferenceHelper opzioni;
private SoulissDBLowHelper database;
private SharedPreferences soulissSharedPreference;
private Context context;
public UDPSoulissDecoder(SoulissPreferenceHelper opts, Context ctx) {
this.opzioni = opts;
this.context = ctx;
database = new SoulissDBLowHelper(ctx);
soulissSharedPreference = opts.getContx().getSharedPreferences("SoulissPrefs", Activity.MODE_PRIVATE);
database.open();
}
/**
* processa il pacchetto UDP ricevuto e agisce di condeguenza
*
* @param packet
* incoming datagram
*/
public void decodeVNetDatagram(DatagramPacket packet) {
int checklen = packet.getLength();
// Log.d("UDPDecoder", "** Packet received");
ArrayList<Short> mac = new ArrayList<Short>();
for (int ig = 7; ig < checklen; ig++) {
mac.add((short) (packet.getData()[ig] & 0xFF));
}
// 0xf 0xe 0x17 0x64 0x1 0x11 0x0 0x18 0x0 0x0 0x0 0x3 0xa 0x8 0xa
// il primo byte dev essere la dimensione
if (checklen != packet.getData()[0]) {
StringBuilder dump = new StringBuilder();
for (int ig = 0; ig < checklen; ig++) {
// 0xFF & buf[index]
dump.append("0x" + Long.toHexString(0xFF & packet.getData()[ig]) + " ");
// dump.append(":"+packet.getData()[ig]);
}
Log.e("UDPDecoder", "**WRONG PACKET SIZE: " + packet.getData()[0] + "bytes\n" + "Actual size: " + checklen
+ "\n" + dump.toString());
} else {
decodeMacaco(mac);
}
// Qualcosa ho ricevuto, invia broadcast
Intent i = new Intent();
i.putExtra("MACACO", mac);
i.setAction(Constants.CUSTOM_INTENT_SOULISS_RAWDATA);
opzioni.getContx().sendBroadcast(i);
// resetta backoff irraggiungibilit
opzioni.resetBackOff();
}
/**
* Decodes lower level MaCaCo packet
*
* @param macacoPck
*/
private void decodeMacaco(ArrayList<Short> macacoPck) {
int functionalCode = macacoPck.get(0);
// int putIn = mac.get(1);
// PUTIN :) 2 byte
// STARTOFFSET 1 byte
// NUMBEROF 1 byte
int startOffset = macacoPck.get(3);
int numberOf = macacoPck.get(4);
Log.d("UDPDecoder", "** Macaco IN: Start Offset:" + startOffset + ", Number of " + numberOf);
switch (functionalCode) {
case Constants.Souliss_UDP_function_subscribe_data:
Log.d("UDPDecoder", "** Subscription answer");
decodeStateRequest(macacoPck);
break;
case Constants.Souliss_UDP_function_poll_resp:
Log.d("UDPDecoder", "** Poll answer");
decodeStateRequest(macacoPck);
processTriggers();
break;
case Constants.Souliss_UDP_function_ping_resp:
// assertEquals(mac.size(), 8);
Log.d("UDPDecoder", "** Ping response bytes " + macacoPck.size());
decodePing(macacoPck);
break;
case Constants.Souliss_UDP_function_subscribe_resp:
Log.d("UDPDecoder", "** State request answer");
decodeStateRequest(macacoPck);
processTriggers();
break;
case Constants.Souliss_UDP_function_typreq_resp:// Answer for assigned
// typical logic
Log.d("UDPDecoder", "** TypReq answer");
decodeTypRequest(macacoPck);
break;
case Constants.Souliss_UDP_function_health_resp:// Answer nodes healty
Log.d("UDPDecoder", "** Health answer");
decodeHealthRequest(macacoPck);
break;
case Constants.Souliss_UDP_function_db_struct_resp:// Answer nodes
assertEquals(macacoPck.size(), 9); // healty
Log.w("UDPDecoder", "** DB Structure answer");
decodeDBStructRequest(macacoPck);
break;
case 0x83:
Log.e("UDPDecoder", "** (Functional code not supported)");
break;
case 0x84:
Log.e("UDPDecoder", "** (Data out of range)");
break;
case 0x85:
Log.e("UDPDecoder", "** (Subscription refused)");
break;
default:
Log.e("UDPDecoder", "** Unknown functional code: " + functionalCode);
break;
}
}
private void processTriggers() {
try {
List<SoulissNode> ref = database.getAllNodes();
List<SoulissTrigger> triggers = database.getAllTriggers(context);
Log.i(Constants.TAG, "checked triggers: " + triggers.size());
// logThings(refreshedNodes);
Map<Short, SoulissNode> refreshedNodes = new HashMap<Short, SoulissNode>();
/* Check antifurto */
for (SoulissNode soulissNode : ref) {
refreshedNodes.put(soulissNode.getId(), soulissNode);
if (opzioni.isAntitheftPresent() && opzioni.isAntitheftNotify()) {// giro
// tipici
// solo
// seve
for (SoulissTypical ty : soulissNode.getTypicals()) {
// check Antitheft
if (ty.getTypicalDTO().getTypical() == Souliss_T41_Antitheft_Main
&& ty.getTypicalDTO().getOutput() == Souliss_T4n_InAlarm) {
sendNotification(context, context.getString(R.string.antitheft_notify),
context.getString(R.string.antitheft_notify_desc), R.drawable.shield);
break;
}
}
}
}
for (SoulissTrigger soulissTrigger : triggers) {
SoulissCommandDTO command = soulissTrigger.getCommandDto();
SoulissTriggerDTO src = soulissTrigger.getTriggerDto();
SoulissTypical source = refreshedNodes.get(src.getInputNodeId()).getTypical(src.getInputSlotlot());
// SoulissTypical target =
// refreshedNodes.get(command.getNodeId()).getTypical(command.getSlot());
Calendar now = Calendar.getInstance();
if (!soulissTrigger.getTriggerDto().isActivated()) {
String op = src.getOp();
if (">".compareTo(op) == 0 && source.getTypicalDTO().getOutput() > src.getThreshVal()) {
Log.w(Constants.TAG, "TRIGGERING COMMAND " + command.toString());
soulissTrigger.getTriggerDto().setActive(true);
UDPHelper.issueSoulissCommand("" + command.getNodeId(), "" + command.getSlot(),
SoulissClient.getOpzioni(), command.getType(), "" + command.getCommand());
command.setExecutedTime(now);
soulissTrigger.persist(database);
SoulissDataService.sendNotification(context, command.toString(), soulissTrigger.toString(),
R.drawable.lighthouse);
} else if ("<".compareTo(op) == 0 && source.getTypicalDTO().getOutput() < src.getThreshVal()) {
Log.w(Constants.TAG, "TRIGGERING COMMAND " + command.toString());
soulissTrigger.getTriggerDto().setActive(true);
UDPHelper.issueSoulissCommand("" + command.getNodeId(), "" + command.getSlot(),
SoulissClient.getOpzioni(), command.getType(), "" + command.getCommand());
soulissTrigger.getCommandDto().setExecutedTime(now);
soulissTrigger.persist(database);
SoulissDataService.sendNotification(context, command.toString(), soulissTrigger.toString(),
R.drawable.lighthouse);
} else if ("=".compareTo(op) == 0 && source.getTypicalDTO().getOutput() == src.getThreshVal()) {
Log.w(Constants.TAG, "TRIGGERING COMMAND " + command.toString());
UDPHelper.issueSoulissCommand("" + command.getNodeId(), "" + command.getSlot(),
SoulissClient.getOpzioni(), command.getType(), "" + command.getCommand());
soulissTrigger.getTriggerDto().setActive(true);
soulissTrigger.getCommandDto().setExecutedTime(now);
soulissTrigger.persist(database);
SoulissDataService.sendNotification(context, command.toString(), soulissTrigger.toString(),
R.drawable.lighthouse);
}
}
// vedi se bisogna disattivare
else {
String op = src.getOp();
if (">".compareTo(op) == 0 && source.getTypicalDTO().getOutput() <= src.getThreshVal()) {
Log.w(Constants.TAG, "DEACTIVATE TRIGGER " + command.toString());
soulissTrigger.getTriggerDto().setActive(false);
soulissTrigger.persist(database);
} else if ("<".compareTo(op) == 0 && source.getTypicalDTO().getOutput() >= src.getThreshVal()) {
Log.w(Constants.TAG, "DEACTIVATE TRIGGER " + command.toString());
soulissTrigger.getTriggerDto().setActive(false);
soulissTrigger.persist(database);
} else if ("=".compareTo(op) == 0 && source.getTypicalDTO().getOutput() != src.getThreshVal()) {
Log.w(Constants.TAG, "DEACTIVATE TRIGGER " + command.toString());
soulissTrigger.getTriggerDto().setActive(false);
soulissTrigger.persist(database);
}
}
}
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "DB connection was closed, check trigger impossible");
return;
}
}
/**
* Alla ricezione di una risposta ping, aggiorna il cached address F e`
* locale, se trovo B e` Remoto
*
* @param mac
*/
private void decodePing(ArrayList<Short> mac) {
// int nodes = mac.get(5);
int putIn = mac.get(1);
// se trovo F e` locale, se trovo B e` Remoto
SharedPreferences.Editor editor = soulissSharedPreference.edit();
// if (soulissSharedPreference.contains("cachedAddress"))
// editor.remove("cachedAddress");
boolean alreadyPrivate = soulissSharedPreference.getString("cachedAddress", "").compareTo(
opzioni.getPrefIPAddress()) == 0;
if (putIn == 0xB && !alreadyPrivate) {
opzioni.setCachedAddr(opzioni.getIPPreferencePublic());
editor.putString("cachedAddress", opzioni.getIPPreferencePublic());
Log.w(Constants.TAG, "Refreshing cached address: " + opzioni.getIPPreferencePublic());
} else if (putIn == 0xF) {
opzioni.setCachedAddr(opzioni.getPrefIPAddress());
editor.putString("cachedAddress", opzioni.getPrefIPAddress());
Log.w(Constants.TAG, "Refreshing cached address: " + opzioni.getPrefIPAddress());
} else if (alreadyPrivate) {
Log.w(Constants.TAG,
"Local address already set. I'll NOT overwrite it: "
+ soulissSharedPreference.getString("cachedAddress", ""));
} else
Log.e(Constants.TAG, "Unknown putIn code: " + putIn);
editor.commit();
}
/**
* Sovrascrive la struttura I nodi e la struttura dei tipici e richiama
* UDPHelper.typicalRequest(opzioni, nodes, 0);
*
* @param mac
*/
private void decodeDBStructRequest(ArrayList<Short> mac) {
// Threee static bytes
assertEquals(4, (short) mac.get(4));
final int nodes = mac.get(5);
int maxnodes = mac.get(6);
int maxTypicalXnode = mac.get(7);
int maxrequests = mac.get(8);
Log.i(Constants.TAG, "DB Struct requested,nodes: " + nodes + " maxnodes: " + maxnodes + " maxrequests: "
+ maxrequests);
database.createOrUpdateStructure(nodes, maxTypicalXnode);
// Log.w(Constants.TAG, "Drop DB requested, response: " + mac);
SharedPreferences.Editor editor = soulissSharedPreference.edit();
// sistema configurato
if (soulissSharedPreference.contains("numNodi"))
editor.remove("numNodi");
if (soulissSharedPreference.contains("TipiciXNodo"))
editor.remove("TipiciXNodo");
editor.putInt("numNodi", nodes);
editor.putInt("TipiciXNodo", maxTypicalXnode);
editor.commit();
// FIXME centralizzare sta roba
new Thread(new Runnable() {
@Override
public void run() {
UDPHelper.typicalRequest(opzioni, nodes, 0);
}
}).start();
}
/**
* Definizione dei tipici
*
* @param mac
*/
private void decodeTypRequest(ArrayList<Short> mac) {
try {
assertEquals(Constants.Souliss_UDP_function_typreq_resp, (short) mac.get(0));
SharedPreferences.Editor editor = soulissSharedPreference.edit();
short tgtnode = mac.get(3);
int numberOf = mac.get(4);
int done = 0;
// SoulissNode node = database.getSoulissNode(tgtnode);
int typXnodo = soulissSharedPreference.getInt("TipiciXNodo", 1);
// creates Souliss nodes
for (int j = 0; j < numberOf; j++) {
if (mac.get(5 + j) != 0) {// create only not-empty typicals
SoulissTypicalDTO dto = new SoulissTypicalDTO();
dto.setTypical(mac.get(5 + j));
dto.setSlot(((short) (j % typXnodo)));// magia
dto.setNodeId((short) (j / typXnodo));
// conta solo i master
if (mac.get(5 + j) != it.angelic.soulissclient.model.typicals.Constants.Souliss_T_related)
done++;
dto.persist();
}
}
if (soulissSharedPreference.contains("numTipici"))
editor.remove("numTipici");//unused
editor.putInt("numTipici", done);
editor.commit();
Log.d(Constants.TAG, "Refreshed typicals for node " + tgtnode);
} catch (Exception uy) {
Log.e(Constants.TAG, "decodeTypRequest ERROR", uy);
}
}
/**
* puo giungere in seguito a state request oppure come subscription data
* della publish. Semantica = a typical request. Aggiorna il DB solo se il
* tipico esiste
*
* @param mac
*/
private void decodeStateRequest(ArrayList<Short> mac) {
try {
List<SoulissNode> nodes = database.getAllNodes();
short tgtnode = mac.get(3);
int numberOf = mac.get(4);
int typXnodo = soulissSharedPreference.getInt("TipiciXNodo", 1);
Log.d(Constants.TAG, "---DECODE MACACO OFFSET:"+tgtnode+" NUMOF:"+numberOf);
SoulissTypicalDTO dto = new SoulissTypicalDTO();
//refresh typicals
for (short j = 0; j < numberOf; j++) {
try {
SoulissNode it = nodes.get(j / typXnodo + tgtnode);
it.getTypical((short) (j % typXnodo));
dto.setOutput(mac.get(5 + j));
dto.setSlot(((short) (j % typXnodo)));
dto.setNodeId((short) (j / typXnodo + tgtnode));
// sufficiente una refresh
Log.d(Constants.TAG, "---REFRESHING NODE:"+(j / typXnodo + tgtnode)+" SLOT:"+(j % typXnodo));
dto.refresh();
} catch (NotFoundException e) {
// skipping unexistent typical");
continue;
}
}
// Log.d(Constants.TAG, "Refreshed " + refreshed +
// " typicals STATUS for node " + tgtnode);
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "DB connection was closed, impossible to finish");
return;
} catch (Exception uy) {
Log.e(Constants.TAG, "decodeStateRequest ERROR", uy);
}
}
/**
* Decodes a souliss nodes health request
*
* @param macaco
* packet
*/
private void decodeHealthRequest(ArrayList<Short> mac) {
// Threee static bytes
int tgtnode = mac.get(3);
int numberOf = mac.get(4);
ArrayList<Short> healths = new ArrayList<Short>();
//build an array containing healths
for (int i = 5; i < 5 + numberOf; i++) {
healths.add(Short.valueOf(mac.get(i)));
}
try {
numberOf = database.refreshNodeHealths(healths, tgtnode);
Log.d(Constants.TAG, "Refreshed " + numberOf + " nodes' health");
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "DB connection closed! Can't update healths");
return;
}
}
/**
* Should be moved. Produces Android notification
*
* @param ctx
* @param desc
* @param longdesc
* @param icon
*/
private static void sendNotification(Context ctx, String desc, String longdesc, int icon) {
Intent notificationIntent = new Intent(ctx, Typical4nDetail.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);
NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = ctx.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setContentIntent(contentIntent).setSmallIcon(android.R.drawable.stat_sys_warning)
.setLargeIcon(BitmapFactory.decodeResource(res, icon)).setTicker(desc)
.setWhen(System.currentTimeMillis()).setAutoCancel(true).setContentTitle(desc).setContentText(longdesc);
Notification n = builder.build();
nm.notify(664, n);
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone r = RingtoneManager.getRingtone(ctx, notification);
r.play();
} catch (Exception e) {
Log.e(Constants.TAG, "Unable toplaysounds:" + e.getMessage());
}
}
}
|
package edu.wustl.catissuecore.action;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.ConflictDetailsForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.ParticipantBizLogic;
import edu.wustl.catissuecore.bizlogic.ReportLoaderQueueBizLogic;
import edu.wustl.catissuecore.bizlogic.SiteBizLogic;
import edu.wustl.catissuecore.caties.util.CaTIESConstants;
import edu.wustl.catissuecore.caties.util.CaTIESProperties;
import edu.wustl.catissuecore.caties.util.SiteInfoHandler;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.pathology.ReportLoaderQueue;
import edu.wustl.catissuecore.reportloader.HL7Parser;
import edu.wustl.catissuecore.reportloader.HL7ParserUtil;
import edu.wustl.catissuecore.reportloader.ReportLoaderUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Variables;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.DefaultBizLogic;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.logger.Logger;
public class ConflictResolverAction extends BaseAction
{
/**
* Overrides the execute method of Action class.
* Initializes the various fields in ConflictView.jsp Page.
* @param mapping object
* @param form object
* @param request object
* @param response object
* @return ActionForward object
* @throws Exception object
* */
public ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
HttpSession session = request.getSession();
String participantIdToAssociate = (String) session.getAttribute(Constants.PARTICIPANT_ID_TO_ASSOCIATE);
String specimenCollGrpId = (String) session.getAttribute(Constants.SCG_ID_TO_ASSOCIATE);
String reportQueueId = (String) request.getParameter(Constants.REPORT_ID);
String button = request.getParameter(Constants.CONFLICT_BUTTON);
String errorMessage =null;
// overwrite the existing report
if(button.trim().equalsIgnoreCase(Constants.OVERWRITE_REPORT))
{
overwriteReport(request,reportQueueId);
}
// Ignore new Report
if(button.trim().equalsIgnoreCase(Constants.IGNORE_NEW_REPORT))
{
ignoreNewReport(reportQueueId);
}
// Creating a new Participant
if(button.trim().equalsIgnoreCase(Constants.CREATE_NEW_PARTICIPANT))
{
errorMessage = createNewParticipant(request,reportQueueId);
if(errorMessage!=null)
{
setActionError(request, errorMessage);
}
}
else
{
if(button.trim().equalsIgnoreCase(Constants.USE_SELECTED_PARTICIPANT))
{
if(participantIdToAssociate != null && !participantIdToAssociate.equals(""))
{
// Associate existing participant with Report
createNewSCG(request,reportQueueId,participantIdToAssociate);
}
}
else if(button.trim().equalsIgnoreCase(Constants.USE_SELECTED_SCG)){
if(specimenCollGrpId != null && !specimenCollGrpId.equals(""))
{
// Associate existing SCG with Report
associateSCGWithReport(request,reportQueueId,participantIdToAssociate,specimenCollGrpId);
}
}
}
resetSessionAttributes(session);
return mapping.findForward(Constants.SUCCESS);
}
/**
* To retrive the reportLoaderQueueObject
* @param reportQueueId
* @return
* @throws DAOException
*/
private ReportLoaderQueue getReportQueueObject(String reportQueueId) throws DAOException
{
ReportLoaderQueue reportLoaderQueue =null;
ReportLoaderQueueBizLogic reportLoaderQueueBizLogic = (ReportLoaderQueueBizLogic)BizLogicFactory.getInstance().getBizLogic(ReportLoaderQueue.class.getName());
List reportQueueList = (List)reportLoaderQueueBizLogic.retrieve(ReportLoaderQueue.class.getName(),Constants.SYSTEM_IDENTIFIER, reportQueueId);
if((reportQueueList!=null) && reportQueueList.size()>0)
{
reportLoaderQueue = (ReportLoaderQueue)reportQueueList.get(0);
}
return reportLoaderQueue;
}
/**
* To create new participant and associate it to the report:
* @param request
* @param reportQueueId
* @throws Exception
* @throws Exception
*/
private String createNewParticipant(HttpServletRequest request, String reportQueueId) throws Exception
{
String errorMessage = null;
Site site =null;
ReportLoaderQueue reportLoaderQueue =null;
reportLoaderQueue = getReportQueueObject(reportQueueId);
//retrieve site
String siteName = reportLoaderQueue.getSiteName();
SiteBizLogic siteBizLogic = (SiteBizLogic)BizLogicFactory.getInstance().getBizLogic(Site.class.getName());
List siteList = (List)siteBizLogic.retrieve(Site.class.getName(),Constants.SYSTEM_NAME, siteName);
if((siteList!=null) && siteList.size()>0)
{
site = (Site)siteList.get(0);
}
//retrive the PID
String pidLine = ReportLoaderUtil.getLineFromReport(reportLoaderQueue.getReportText(), CaTIESConstants.PID);
//Participant Object
Participant participant = HL7ParserUtil.parserParticipantInformation(pidLine,site);
ParticipantBizLogic participantBizLogic = (ParticipantBizLogic)BizLogicFactory.getInstance().getBizLogic(Participant.class.getName());
try
{
participantBizLogic.insert(participant,getSessionData(request),Constants.HIBERNATE_DAO);
}
catch(Exception e)
{
//System.out.println("Error Occurred !!!!!");
errorMessage = ApplicationProperties.getValue("errors.caTies.conflict.genericmessage");
//Setting the status to NEW
reportLoaderQueue.setParticipantCollection(null);
reportLoaderQueue.setStatus(CaTIESConstants.PARTICIPANT_CREATION_ERROR);
updateReportLoaderQueue(reportLoaderQueue,request);
return errorMessage;
}
Collection participantColl = new HashSet();
// Adding the new participant
participantColl.add(participant);
reportLoaderQueue.setParticipantCollection(participantColl);
//The new SCG for this participant will be inserted by the FileProcessorThread
//Setting the status to NEW
reportLoaderQueue.setStatus(CaTIESConstants.NEW);
reportLoaderQueue.setSpecimenCollectionGroup(null);
updateReportLoaderQueue(reportLoaderQueue,request);
return errorMessage;
}
/**
* To associate existing participant to the report and to create new SCG:
* @param request
* @param reportQueueId
* @param participantIdToAssociate
* @throws DAOException
*/
private void createNewSCG(HttpServletRequest request,String reportQueueId,String participantIdToAssociate) throws DAOException
{
ReportLoaderQueue reportLoaderQueue =null;
reportLoaderQueue = getReportQueueObject(reportQueueId);
//Changing the status of the report in the queue to NEW
reportLoaderQueue.setStatus(CaTIESConstants.NEW);
//Create new SCG
reportLoaderQueue.setSpecimenCollectionGroup(null);
//removing all participants from CATISSUE_REPORT_PARTICIP_REL other than the selected participant
Collection participantColl = reportLoaderQueue.getParticipantCollection();
Iterator iter = participantColl.iterator();
Set tempColl = new HashSet();
while(iter.hasNext())
{
Participant participant = (Participant)iter.next();
if(participant.getId().toString().equals(participantIdToAssociate.trim()))
{
tempColl.add(participant);
}
}
reportLoaderQueue.setParticipantCollection(tempColl);
//Updating the report queue obj
updateReportLoaderQueue(reportLoaderQueue ,request);
}
/**
* Associate the existing SCG to the report
* @param request
* @param reportQueueId
* @param participantIdToAssociate
* @param specimenCollGrpId
* @throws DAOException
* @throws BizLogicException
* @throws UserNotAuthorizedException
*/
private void associateSCGWithReport(HttpServletRequest request,String reportQueueId,String participantIdToAssociate,String specimenCollGrpId) throws DAOException, BizLogicException, UserNotAuthorizedException
{
Long cprId =null;
ReportLoaderQueue reportLoaderQueue =null;
reportLoaderQueue = getReportQueueObject(reportQueueId);
//Changing the status of the report in the queue to NEW
reportLoaderQueue.setStatus(CaTIESConstants.NEW);
//Associating the SCG
if(specimenCollGrpId != null && !specimenCollGrpId.equals(""))
{
SpecimenCollectionGroup scg=null;
ReportLoaderQueueBizLogic reportLoaderQueueBizLogic = (ReportLoaderQueueBizLogic)BizLogicFactory.getInstance().getBizLogic(ReportLoaderQueue.class.getName());
List scgList = (List)reportLoaderQueueBizLogic.retrieve(SpecimenCollectionGroup.class.getName(),Constants.SYSTEM_IDENTIFIER, specimenCollGrpId);
if((scgList!=null) && scgList.size()>0)
{
scg = (SpecimenCollectionGroup)scgList.get(0);
}
cprId = (Long) scg.getCollectionProtocolRegistration().getId();
reportLoaderQueue.setSpecimenCollectionGroup(scg);
}
//Retrieving participantID if it is null
if(participantIdToAssociate == null || participantIdToAssociate.equals(""))
{
DefaultBizLogic defaultBizLogic=new DefaultBizLogic();
Long partID=(Long)defaultBizLogic.retrieveAttribute(CollectionProtocolRegistration.class.getName(), cprId,Constants.COLUMN_NAME_PARTICIPANT_ID );
participantIdToAssociate = (String)partID.toString();
}
//removing all participants from CATISSUE_REPORT_PARTICIP_REL other than the selected participant
Collection participantColl = reportLoaderQueue.getParticipantCollection();
Iterator iter = participantColl.iterator();
Set tempColl = new HashSet();
Participant participant = null;
while(iter.hasNext())
{
participant = (Participant)iter.next();
if(participant.getId().toString().equals(participantIdToAssociate.trim()))
{
tempColl.add(participant);
}
}
reportLoaderQueue.setParticipantCollection(tempColl);
//Updating the report queue obj
updateReportLoaderQueue(reportLoaderQueue ,request);
}
/**
* updating the reportloaderQueue obj
* @param reportLoaderQueue
* @param request
*/
private void updateReportLoaderQueue(ReportLoaderQueue reportLoaderQueue , HttpServletRequest request)
{
try
{
ReportLoaderQueueBizLogic reportLoaderQueueBizLogic = (ReportLoaderQueueBizLogic)BizLogicFactory.getInstance().getBizLogic(ReportLoaderQueue.class.getName());
reportLoaderQueueBizLogic.update(reportLoaderQueue, reportLoaderQueue, Constants.HIBERNATE_DAO, getSessionData(request));
}
catch(Exception e)
{
Logger.out.error("Error Updating ReportQueue" + e);
}
}
protected SessionDataBean getSessionData(HttpServletRequest request)
{
Object obj = request.getSession().getAttribute(Constants.SESSION_DATA);
/**
* This if loop is specific to Password Security feature.
*/
if(obj == null)
{
obj = request.getSession().getAttribute(Constants.TEMP_SESSION_DATA);
}
if(obj!=null)
{
SessionDataBean sessionData = (SessionDataBean) obj;
return sessionData;
}
return null;
}
/**
* To generate the errors
* @param request
* @param errorMessage
*/
private void setActionError(HttpServletRequest request, String errorMessage)
{
ActionErrors errors = new ActionErrors();
ActionError error = new ActionError("errors.item", errorMessage);
errors.add(ActionErrors.GLOBAL_ERROR, error);
saveErrors(request, errors);
}
protected void resetSessionAttributes(HttpSession session)
{
//Removing the session objects
session.removeAttribute(Constants.PARTICIPANT_ID_TO_ASSOCIATE);
session.removeAttribute(Constants.SCG_ID_TO_ASSOCIATE);
}
/**
* Ignore the new report and use the existing one.
* @param reportQueueId
* @throws DAOException
* @throws UserNotAuthorizedException
* @throws BizLogicException
*/
protected void ignoreNewReport(String reportQueueId) throws DAOException, UserNotAuthorizedException, BizLogicException
{
Long cprId =null;
ReportLoaderQueue reportLoaderQueue =null;
reportLoaderQueue = getReportQueueObject(reportQueueId);
ReportLoaderQueueBizLogic reportLoaderQueueBizLogic = (ReportLoaderQueueBizLogic)BizLogicFactory.getInstance().getBizLogic(ReportLoaderQueue.class.getName());
//deleting the reportloaderQueue object
reportLoaderQueueBizLogic.delete(reportLoaderQueue, Constants.HIBERNATE_DAO);
}
/**To overwrite the existing report
* @param request
* @param reportQueueId
* @throws DAOException
*/
protected void overwriteReport(HttpServletRequest request,String reportQueueId) throws DAOException
{
ReportLoaderQueue reportLoaderQueue =null;
reportLoaderQueue = getReportQueueObject(reportQueueId);
//Changing the status of the report in the queue to NEW
reportLoaderQueue.setStatus(CaTIESConstants.OVERWRITE_REPORT);
updateReportLoaderQueue(reportLoaderQueue,request);
}
}
|
package org.acra.collector;
import java.util.Map;
import java.util.TreeMap;
import org.acra.ACRA;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
final class SharedPreferencesCollector {
public static String collect(Context context) {
final StringBuilder result = new StringBuilder();
final Map<String, SharedPreferences> shrdPrefs = new TreeMap<String, SharedPreferences>();
shrdPrefs.put("default", PreferenceManager.getDefaultSharedPreferences(context));
final String[] shrdPrefsIds = ACRA.getConfig().additionalSharedPreferences();
if (shrdPrefsIds != null) {
for (final String shrdPrefId : shrdPrefsIds) {
shrdPrefs.put(shrdPrefId, context.getSharedPreferences(shrdPrefId, Context.MODE_PRIVATE));
}
}
for (final String prefsId : shrdPrefs.keySet()) {
result.append(prefsId).append("\n");
final SharedPreferences prefs = shrdPrefs.get(prefsId);
if (prefs != null) {
final Map<String, ?> kv = prefs.getAll();
if (kv != null && kv.size() > 0) {
for (final String key : kv.keySet()) {
if(kv.get(key) != null) {
result.append(key).append("=").append(kv.get(key).toString()).append("\n");
} else {
result.append(key).append("=").append("null\n");
}
}
} else {
result.append("empty\n");
}
} else {
result.append("null\n");
}
result.append("\n");
}
return result.toString();
}
}
|
package peergos.shared.user;
import jsinterop.annotations.*;
import peergos.shared.social.*;
import peergos.shared.user.fs.*;
import java.util.*;
import java.util.stream.*;
@JsType
public class SocialState {
public static final String FRIENDS_GROUP_NAME = "friends";
public static final String FOLLOWERS_GROUP_NAME = "followers";
public final List<FollowRequestWithCipherText> pendingIncoming;
public final Set<String> pendingOutgoing;
public final Map<String, FileWrapper> followerRoots;
public final Set<FileWrapper> followingRoots;
public final Map<String, FriendAnnotation> friendAnnotations;
public final Map<String, String> uidToGroupName, groupNameToUid;
public SocialState(List<FollowRequestWithCipherText> pendingIncoming,
Set<String> pendingOutgoing,
Set<String> actualFollowers,
Map<String, FileWrapper> followerRoots,
Set<FileWrapper> followingRoots,
Map<String, FriendAnnotation> friendAnnotations,
Map<String, String> uidToGroupName) {
this.pendingIncoming = pendingIncoming;
this.pendingOutgoing = pendingOutgoing;
Map<String, FileWrapper> actualFollowerRoots = followerRoots.entrySet()
.stream()
.filter(e -> actualFollowers.contains(e.getKey()))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
this.followerRoots = new TreeMap<>(actualFollowerRoots);
TreeSet<FileWrapper> sortedByName = new TreeSet<>((a, b) -> a.getName().compareTo(b.getName()));
sortedByName.addAll(followingRoots);
this.followingRoots = sortedByName;
this.friendAnnotations = friendAnnotations;
this.uidToGroupName = uidToGroupName;
this.groupNameToUid = uidToGroupName.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
}
public Set<String> getFollowers() {
return followerRoots.keySet();
}
public Set<String> getFollowing() {
return followingRoots.stream().map(f -> f.getFileProperties().name).collect(Collectors.toSet());
}
public Set<String> getFriends() {
HashSet<String> res = new HashSet<>(getFollowing());
res.retainAll(getFollowers());
return res;
}
public String getFriendsGroupUid() {
return groupNameToUid.get(FRIENDS_GROUP_NAME);
}
public String getFollowersGroupUid() {
return groupNameToUid.get(FOLLOWERS_GROUP_NAME);
}
}
|
package cn.com.restarter.web;
import cn.com.restarter.service.TaskHandler;
import cn.com.restarter.util.FileModify;
import cn.com.restarter.util.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* Author : ChelseaBlue
* Description :
*/
@Controller
@RequestMapping("/task")
public class TaskController {
/**
* .
*
* @return
*/
@RequestMapping("/index.action")
public String index() {
System.out.println("
return "/index.jsp";
}
/**
* .
*
* @return
*/
@RequestMapping(value = "/restart.action", method = RequestMethod.POST)
@ResponseBody
public String restart() throws Exception {
TaskHandler.restart_sd();
return "success";
}
/**
* .--
*
* @return
*/
@RequestMapping(value = "/restartOne.action", method = RequestMethod.POST)
@ResponseBody
public String restartOne(String url) throws Exception {
TaskHandler.restart_sd_One(url);
return "success";
}
/**
*
*
* @return
*/
@RequestMapping("/downloadlog.action")
public String downloadlog(HttpServletRequest request, HttpServletResponse response) throws Exception {
String url = "C:/restartlog";
FileUtils.downLoadFilesByUrl(request, response, url, "restarter.zip");
return null;
}
/**
*
*
* @return
*/
@RequestMapping("/downloadlogALL.action")
public void downloadlogALL(HttpServletRequest request, HttpServletResponse response, int count) throws Exception {
List<String> listStr = FileModify.readFileByLines(Thread.currentThread()
.getContextClassLoader().getResource("").getPath() + "config.properties");
String url[] = listStr.get(count).split("
FileUtils.downLoadFilesByUrl(request, response, listStr.get(count) + "//servers//AdminServer//logs", url[url.length - 1] + ".zip");
}
/**
*
*
* @return
*/
@RequestMapping("/downloadlogOne.action")
public void downloadlogOne(HttpServletRequest request, HttpServletResponse response,String url) throws Exception {
String urls[] = url.split("
FileUtils.downLoadFilesByUrl(request, response,url + "//servers//AdminServer//logs", urls[urls.length - 1] + ".zip");
}
public static int getCount() {
List<String> listStr = FileModify.readFileByLines(Thread.currentThread()
.getContextClassLoader().getResource("").getPath() + "config.properties");
return listStr.size();
}
/**
*
*
* @return
*/
@RequestMapping(value = "/restartWeblogic.action")
public String restartWeblogic(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> listStr = FileModify.readFileByLines(Thread.currentThread()
.getContextClassLoader().getResource("").getPath() + "config.properties");
listStr.remove(0);
request.setAttribute("weblogiclist",listStr);
return "/restartWeblogic.jsp";
}
}
|
package com.yahoo.io.reader;
import com.google.common.annotations.Beta;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
/**
* A reader with a name. All reader methods are delegated to the wrapped reader.
*
* @author bratseth
*/
@Beta
public class NamedReader extends Reader {
private final String name;
private final Reader reader;
public NamedReader(String name, Reader reader) {
this.name = name;
this.reader = reader;
}
public String getName() { return name; }
public Reader getReader() { return reader; }
/** Returns the name */
@Override
public String toString() {
return name;
}
// The rest is reader method implementations which delegates to the wrapped reader
@Override
public int read(java.nio.CharBuffer charBuffer) throws java.io.IOException { return reader.read(charBuffer); }
@Override
public int read() throws java.io.IOException { return reader.read(); }
@Override
public int read(char[] chars) throws java.io.IOException { return reader.read(chars); }
@Override
public int read(char[] chars, int i, int i1) throws java.io.IOException { return reader.read(chars,i,i1); }
@Override
public long skip(long l) throws java.io.IOException { return reader.skip(l); }
@Override
public boolean ready() throws java.io.IOException { return reader.ready(); }
@Override
public boolean markSupported() { return reader.markSupported(); }
@Override
public void mark(int i) throws java.io.IOException { reader.mark(i); }
@Override
public void reset() throws java.io.IOException { reader.reset(); }
@Override
public void close() throws java.io.IOException { reader.close(); }
/** Convenience method for closing a list of readers. Does nothing if the given reader list is null. */
public static void closeAll(List<NamedReader> readers) {
if (readers==null) return;
for (Reader reader : readers) {
try {
reader.close();
}
catch (IOException e) {
// Nothing to do about it
}
}
}
}
|
package com.jukusoft.rpg.core.path;
public class GamePaths {
public static String getDataDir () {
//TODO: read from GameConfig
return "./data/";
}
public static String getConfigDir () {
return getDataDir() + "config/";
}
public static String getShaderDir () {
return getDataDir() + "shader/";
}
}
|
package com.damnhandy.uri.template;
import static org.junit.Assert.assertEquals;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.junit.Ignore;
import org.junit.Test;
public class UriUtilTest
{
private static final String ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final String DIGIT = "0123456789";
private static final String UNRESERVED = ALPHA + DIGIT + "-._~";
private static final String SUBDELIMS = "!$&'()*+,;=";
private static final String GENDELIMS = ":/?
private void validateFragment(String excpected, String input) throws UnsupportedEncodingException
{
assertEquals(excpected, UriUtil.encodeFragment(input));
}
private void validate(String excpected, String input) throws UnsupportedEncodingException
{
assertEquals(excpected, UriUtil.encode(input));
}
@Test
public void generalNothingToEncode() throws Exception
{
validate(UNRESERVED, UNRESERVED);
}
@Test
public void fragmentNothingToEncode() throws Exception
{
validateFragment(UNRESERVED + SUBDELIMS + "/?:@", UNRESERVED + SUBDELIMS + "/?:@");
}
@Test
@Ignore
public void reservedNothingToEncode() throws Exception
{
validate(UNRESERVED + SUBDELIMS + GENDELIMS, UNRESERVED + SUBDELIMS + GENDELIMS);
}
@Test
public void fragmentWithCharsToEncodeInFragmentButNotInReserved() throws Exception
{
validate("%23%5B%5D", "
}
@Test
public void fragmentWithSomeCharsToEncode() throws Exception
{
validateFragment("%C3%A4%C3%B6", "äö");
}
@Test
public void reservedWithSomeCharsToEncode() throws Exception
{
validate("%C3%A4%C3%B6", "äö");
}
@Test
public void generalWithSomeCharsToEncode() throws Exception
{
assertEquals("XX%C3%A4%22", UriUtil.encodeFragment("XXä\""));
}
@Test
public void exoticHighValueCharacterEncoding() throws Exception
{
// this is the ''
assertEquals("%E8%9A%A0", UriUtil.encodeFragment(Character.valueOf((char) 100000).toString()));
}
/**
* The list of allowed chars is build in a different way then the string in production code!
*/
@Test
public void allowedUnreservedCharacterEncoding() throws Exception
{
ArrayList<Character> UNRESERVED = new ArrayList<Character>();
for (int i = 'a'; i <= 'z'; i++)
{
UNRESERVED.add(Character.valueOf((char) i));
}
for (int i = 'A'; i <= 'Z'; i++)
{
UNRESERVED.add(Character.valueOf((char) i));
}
for (int i = '0'; i <= '9'; i++)
{
UNRESERVED.add(Character.valueOf((char) i));
}
UNRESERVED.add('-');
UNRESERVED.add('.');
UNRESERVED.add('_');
UNRESERVED.add('~');
for (Character character : UNRESERVED)
{
assertEquals(character.toString(), UriUtil.encodeFragment(character.toString()));
}
}
}
|
package com.github.davidmoten.security;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
public class PPKTest {
private static final String content = "Hello World";
@Test
public void testEncryptAndDecrypt() throws UnsupportedEncodingException {
PPK ppk = PPK.publicKey("/public.der").privateKey("/private.der").build();
byte[] encrypted = ppk.encrypt(content, Charsets.UTF_8);
String decrypted = ppk.decrypt(encrypted, Charsets.UTF_8);
assertEquals(content, decrypted);
}
@Test
public void testEncryptAndDecryptSwitchOrder() throws UnsupportedEncodingException {
PPK ppk = PPK.privateKey("/private.der").publicKey("/public.der").build();
byte[] encrypted = ppk.encrypt(content, Charsets.UTF_8);
String decrypted = ppk.decrypt(encrypted, Charsets.UTF_8);
assertEquals(content, decrypted);
}
@Test
public void testBuilder() {
byte[] bytes = PPK.publicKey("/public.der").encrypt(content, Charsets.UTF_8);
assertEquals(content, PPK.privateKey("/private.der").decrypt(bytes, Charsets.UTF_8));
}
@Test
public void testBuilderUsingFiles() {
byte[] bytes = PPK.publicKey(new File("src/test/resources/public.der")).encrypt(content,
Charsets.UTF_8);
assertEquals(content, PPK.privateKey(new File("src/test/resources/private.der"))
.decrypt(bytes, Charsets.UTF_8));
}
@Test
public void testBuilderUsingInputStream() {
byte[] bytes = PPK.publicKey(new File("src/test/resources/public.der"))
.encrypt(new ByteArrayInputStream(content.getBytes(Charsets.UTF_8)));
assertEquals(content, PPK.privateKey(new File("src/test/resources/private.der"))
.decrypt(bytes, Charsets.UTF_8));
}
@Test(expected = RuntimeException.class)
public void testBuilderUsingPublicKeyFileThrowsExceptionWhenFileDoesNotExist() {
PPK.publicKey(new File("src/test/resources/publicDoesNotExist.der"));
}
@Test(expected = RuntimeException.class)
public void testBuilderUsingPrivateKeyFileThrowsExceptionWhenFileDoesNotExist() {
PPK.privateKey(new File("src/test/resources/privateDoesNotExist.der"));
}
@Test
public void testWithStream() {
List<byte[]> list = Lists.newArrayList("hi".getBytes(), "there".getBytes());
PPK ppk = PPK.publicKey("/public.der").build();
List<byte[]> encrypted = list.stream().map(ppk::encrypt).collect(Collectors.toList());
assertEquals(list.size(), encrypted.size());
}
@Test(expected = PublicKeyNotSetException.class)
public void testPublicKeyNotSetThrowsException() {
PPK.privateKey("/private.der").encrypt(content, Charsets.UTF_8);
}
@Test(expected = PrivateKeyNotSetException.class)
public void testPrivateKeyNotSetThrowsException() {
PPK.publicKey("/public.der").decrypt(content.getBytes(), Charsets.UTF_8);
}
@Test
public void testRoundTrip() {
PPK ppk = PPK.publicKey("/public.der").privateKey("/private.der").build();
// result should be the same as bytes
byte[] result = ppk.decrypt(ppk.encrypt(content.getBytes()));
assertTrue(equal(content.getBytes(), result));
}
@Test
public void testLongRoundTrip() {
String s = IntStream.range(0, 10000).mapToObj(x -> "a").collect(Collectors.joining());
PPK ppk = PPK.publicKey("/public.der").privateKey("/private.der").build();
byte[] enc = ppk.encrypt(s, Charsets.UTF_8);
String s2 = ppk.decrypt(enc, Charsets.UTF_8);
assertEquals(s, s2);
}
private static boolean equal(byte[] a, byte[] b) {
if (a == null && b == null)
return true;
if (a == null || b == null)
return false;
if (a.length != b.length)
return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
}
|
package control;
import data.*;
import gui.centerarea.CameraShotBlock;
import gui.centerarea.DirectorShotBlock;
import gui.centerarea.ShotBlock;
import gui.events.DirectorShotBlockUpdatedEvent;
import gui.root.RootCenterArea;
import gui.root.RootPane;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testfx.framework.junit.ApplicationTest;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@PrepareForTest({DirectorTimelineController.class,ShotBlock.class,DirectorShotBlock.class})
public class DirectorTimelineControllerTest extends ApplicationTest {
ControllerManager controllerManager;
DirectorTimelineController directorTimelineController;
private RootPane rootPane;
@Before
public void initialize() {
controllerManager = Mockito.mock(ControllerManager.class);
rootPane = Mockito.mock(RootPane.class);
when(controllerManager.getRootPane()).thenReturn(rootPane);
directorTimelineController = new DirectorTimelineController(controllerManager);
}
@Test
public void addDirectorShotTest() throws InterruptedException {
ScriptingProject scriptMock = Mockito.mock(ScriptingProject.class);
DirectorTimeline timeline = Mockito.mock(DirectorTimeline.class);
when(scriptMock.getDirectorTimeline()).thenReturn(timeline);
when(controllerManager.getScriptingProject()).thenReturn(scriptMock);
TimelineController timelineControllerMock = Mockito.mock(TimelineController.class);
when(controllerManager.getTimelineControl()).thenReturn(timelineControllerMock);
DirectorShot shot1 = Mockito.mock(DirectorShot.class);
DirectorShot shot2 = Mockito.mock(DirectorShot.class);
ArrayList<DirectorShot> collisionList = new ArrayList<>(Arrays.asList(shot1, shot2));
DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
when(timeline.getOverlappingShots(anyObject())).thenReturn(collisionList);
HashMap<DirectorShot, DirectorShotBlock> hashMap = new HashMap<>();
hashMap.put(shot1, shotBlock);
directorTimelineController.setDirectorShotBlockMap(hashMap);
directorTimelineController.setOverlappingShotBlocks(new ArrayList<>(Arrays.asList(shotBlock)));
when(shotBlock.getShot()).thenReturn(shot1);
when(shot1.getCollidesWith()).thenReturn(new ArrayList<>());
List<Integer> cameraList = new ArrayList<>();
cameraList.add(1);
DirectorShot shotToAdd = spy(new DirectorShot(new GeneralShotData("Violas", "Left of conductor", 1, 2),
0.5, 0.5, cameraList));
when(shotToAdd.getCollidesWith()).thenReturn(new ArrayList<Shot>(Arrays.asList(shot1)));
final CountDownLatch[] latch = {new CountDownLatch(1)};
Platform.runLater(() -> {
RootCenterArea rootCenterArea = new RootCenterArea(rootPane);
when(rootPane.getRootCenterArea()).thenReturn(rootCenterArea);
directorTimelineController.addDirectorShot(shotToAdd);
latch[0].countDown();
});
latch[0].await();
verify(controllerManager).setActiveShotBlock(Mockito.any(ShotBlock.class));
verify(timeline).addShot(Mockito.any(DirectorShot.class));
}
@Test
public void addDirectorShotTestFalse() throws InterruptedException {
ScriptingProject scriptMock = Mockito.mock(ScriptingProject.class);
DirectorTimeline timeline = Mockito.mock(DirectorTimeline.class);
when(scriptMock.getDirectorTimeline()).thenReturn(timeline);
when(controllerManager.getScriptingProject()).thenReturn(scriptMock);
TimelineController timelineControllerMock = Mockito.mock(TimelineController.class);
when(controllerManager.getTimelineControl()).thenReturn(timelineControllerMock);
final CountDownLatch[] latch = {new CountDownLatch(1)};
Platform.runLater(() -> {
RootCenterArea rootCenterArea = new RootCenterArea(rootPane);
when(rootPane.getRootCenterArea()).thenReturn(rootCenterArea);
List<Integer> cameraList = new ArrayList<>();
cameraList.add(1);
directorTimelineController.addDirectorShot(new DirectorShot(new GeneralShotData("Violas2", "Left of conductor2", 1, 2),
0.5, 0.5, cameraList));
latch[0].countDown();
});
latch[0].await();
verify(controllerManager).setActiveShotBlock(Mockito.any(ShotBlock.class));
verify(timeline).addShot(Mockito.any(DirectorShot.class));
}
@Test
public void shotChangedHandlerTest() {
// Generate all necessary mocks
ScriptingProject scriptMock = Mockito.mock(ScriptingProject.class);
DirectorShotBlock shotBlockMock = Mockito.mock(DirectorShotBlock.class);
DirectorShotBlock shotBlockMock2 = Mockito.mock(DirectorShotBlock.class);
DirectorShot shotMock = Mockito.mock(DirectorShot.class);
DirectorShot shotMock2 = Mockito.mock(DirectorShot.class);
DirectorShotBlockUpdatedEvent event = Mockito.mock(DirectorShotBlockUpdatedEvent.class);
DirectorTimeline timeline = Mockito.mock(DirectorTimeline.class);
TimelineController timelineMock = Mockito.mock(TimelineController.class);
CameraShotBlock cameraShotBlock = Mockito.mock(CameraShotBlock.class);
ArrayList<CameraShotBlock> shotBlockList = new ArrayList<>(Arrays.asList(cameraShotBlock));
// Mock all the methods
when(shotMock.getBeginCount()).thenReturn(0.0);
when(shotMock.getEndCount()).thenReturn(1.0);
when(shotBlockMock.getBeginCount()).thenReturn(0.0);
when(shotBlockMock.getPaddingBefore()).thenReturn(1.0);
when(event.getDirectorShotBlock()).thenReturn(shotBlockMock);
when(controllerManager.getScriptingProject()).thenReturn(scriptMock);
when(shotBlockMock.getShot()).thenReturn(shotMock);
when(scriptMock.getDirectorTimeline()).thenReturn(timeline);
when(controllerManager.getTimelineControl()).thenReturn(timelineMock);
when(timelineMock.getCameraShotBlocks()).thenReturn(shotBlockList);
when(shotMock.getCollidesWith()).thenReturn(new ArrayList<>(Arrays.asList(shotMock2)));
when(shotBlockMock2.getShot()).thenReturn(shotMock2);
// Hashmap setup
HashMap<DirectorShot, DirectorShotBlock> hashMap = new HashMap<>();
hashMap.put(shotMock, shotBlockMock);
hashMap.put(shotMock2, shotBlockMock2);
directorTimelineController.setDirectorShotBlockMap(hashMap);
// Call method under testing
directorTimelineController.shotChangedHandler(event);
// Verify all the things
verify(controllerManager).setActiveShotBlock(Mockito.any(ShotBlock.class));
verify(scriptMock).changed();
}
@Test
public void removeShotTest() throws Exception {
ScriptingProject scriptSpy = spy(new ScriptingProject("Project", "", 2));
when(controllerManager.getScriptingProject()).thenReturn(scriptSpy);
DirectorShotBlock shotBlockMock = Mockito.mock(DirectorShotBlock.class);
when(controllerManager.getActiveShotBlock()).thenReturn(shotBlockMock);
DirectorShot shotMock = Mockito.mock(DirectorShot.class);
when(shotBlockMock.getShot()).thenReturn(shotMock);
CameraShot cameraShotMock = Mockito.mock(CameraShot.class);
Set<CameraShot> cameraShots = new HashSet<>();
cameraShots.add(cameraShotMock);
when(shotMock.getCameraShots()).thenReturn(cameraShots);
TimelineController timelineControllerMock = Mockito.mock(TimelineController.class);
when(controllerManager.getTimelineControl()).thenReturn(timelineControllerMock);
HashMap<DirectorShot, DirectorShotBlock> hashMap = new HashMap<>();
hashMap.put(shotMock, shotBlockMock);
directorTimelineController.setDirectorShotBlockMap(hashMap);
directorTimelineController.removeShot(shotBlockMock);
verify(shotMock).getCameraShots();
verify(timelineControllerMock).removeCameraShot(cameraShotMock);
}
@Test
public void getControllerManagerTest() {
assertEquals(controllerManager, directorTimelineController.getControllerManager());
}
@Test
public void generateAllShots() throws InterruptedException {
final CountDownLatch[] latch = {new CountDownLatch(1)};
Platform.runLater(() -> {
RootCenterArea rootCenterArea = new RootCenterArea(rootPane);
when(rootPane.getRootCenterArea()).thenReturn(rootCenterArea);
ScriptingProject scriptMock = Mockito.mock(ScriptingProject.class);
DirectorTimeline timeline = Mockito.mock(DirectorTimeline.class);
when(scriptMock.getDirectorTimeline()).thenReturn(timeline);
when(controllerManager.getScriptingProject()).thenReturn(scriptMock);
TimelineController timelineControllerMock = Mockito.mock(TimelineController.class);
when(controllerManager.getTimelineControl()).thenReturn(timelineControllerMock);
List<Integer> cameraList = new ArrayList<>();
cameraList.add(1);
directorTimelineController.addDirectorShot(new DirectorShot(new GeneralShotData("Violas", "Left of conductor", 1, 2),
0.5, 0.5, cameraList));
directorTimelineController.generateAllShots();
verify(timelineControllerMock).addCameraShot(Mockito.anyInt(), Mockito.any(CameraShot.class));
latch[0].countDown();
});
latch[0].await();
}
@Override
public void start(Stage stage) throws Exception {
}
}
|
package de.msquadrat.netstat;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.hamcrest.Matchers.*;
import java.util.EnumMap;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
public class UDPConnectionTest {
@Rule
public ErrorCollector collector = new ErrorCollector();
@Test
public void testGetConnectionType() {
UDPConnection c = mock(UDPConnection.class, CALLS_REAL_METHODS);
assertThat(c.getConnectionType(), is(equalTo(ConnectionType.UDP)));
}
@Test
public void testIsListening() {
EnumMap<ConnectionState, Boolean> expected = new EnumMap<>(ConnectionState.class);
expected.put(ConnectionState.UNKNOWN, false);
expected.put(ConnectionState.ESTABLISHED, false);
expected.put(ConnectionState.SYN_SENT, false);
expected.put(ConnectionState.SYN_RECV, false);
expected.put(ConnectionState.FIN_WAIT1, false);
expected.put(ConnectionState.FIN_WAIT2, false);
expected.put(ConnectionState.TIME_WAIT, false);
expected.put(ConnectionState.CLOSE, true);
expected.put(ConnectionState.CLOSE_WAIT, false);
expected.put(ConnectionState.LAST_ACK, false);
expected.put(ConnectionState.LISTEN, true);
expected.put(ConnectionState.CLOSING, false);
assertThat(expected.size(), is(equalTo(ConnectionState.values().length)));
for (ConnectionState s : ConnectionState.values()) {
UDPConnection c = mock(UDPConnection.class, CALLS_REAL_METHODS);
when(c.getState()).thenReturn(s);
collector.checkThat(s.toString(), c.isListening(), is(equalTo(expected.get(s))));
}
}
}
|
package edu.jhu.prim.util.math;
import org.junit.Ignore;
@Ignore("This is known to fail consistently because of the imprecision of LogAddTable.")
public class LogAddTableTest extends AbstractLogAddSubtractTableTest {
@Override
protected double logAdd(double a, double b) {
return LogAddTable.logAdd(a, b);
}
@Override
protected double logSubtract(double a, double b) {
return LogAddTable.logSubtract(a, b);
}
protected double getToleranceForLogAdd() {
return 1e-6;
}
protected double getToleranceForLogSubtract() {
return 1e-3;
}
}
|
package net.justinwhite.score_model;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
@SuppressWarnings("FieldCanBeLocal")
public class PlayerTest {
private final String name = "First Last";
private final String initials = "FL";
private int score = 88;
private Game<Player> game;
private Player player;
private String newName = "OnlyFirst";
private String newInitials = "O_";
@Before
public void setUp() throws Exception {
game = new Game<>(Player.class);
player = new Player(game, name);
player.setScore(score);
}
// test all the remaining constructors
@Test
public void testPlayer() throws Exception {
player = new Player();
assertNull(player.getGame());
assertEquals("Player X", player.getName());
game = new Game<>(Player.class);
player = new Player(game);
assertSame(game, player.getGame());
assertEquals("Player X", player.getName());
}
@Test
public void testToString() throws Exception {
assertEquals(String.format(
"Name '%s'; Score %s",
name,
score
), player.toString()
);
}
@Test
public void testGetGame() throws Exception {
assertSame(game, player.getGame());
}
@Test
public void testGetInitials() throws Exception {
assertEquals(initials, player.getInitials());
player.setName(newName);
assertEquals(newInitials, player.getInitials());
}
}
|
package nl.tud.dcs.fddg.server;
import nl.tud.dcs.fddg.client.ClientInterface;
import nl.tud.dcs.fddg.game.Field;
import nl.tud.dcs.fddg.game.actions.*;
import nl.tud.dcs.fddg.gui.VisualizerGUI;
import nl.tud.dcs.fddg.server.requests.ActionRequest;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerProcess extends UnicastRemoteObject implements ClientServerInterface, Runnable, ServerInterface {
// internal administration
private int ID;
private Field field;
private Logger logger;
private VisualizerGUI visualizerGUI = null;
private boolean gameStarted;
private boolean gameFinishedByOtherServer;
// client administration
private volatile Map<Integer, ClientInterface> connectedPlayers;
private Map<Integer, Boolean> clientPings;
private int IDCounter;
// server administration
private Map<Integer, ServerInterface> otherServers; //(id, RMI object)
private int requestCounter;
private Map<Integer, ActionRequest> pendingRequests; //(requestID,request)
private Map<Integer, Timer> requestTimers; //(requestID, timer
private Map<Integer, Integer> pendingAcknowledgements; //(requestID, nr of acks still to receive)
private Map<Integer, Integer> serverPings; // (ID, # consecutive pings missed)
// Logging
private PrintWriter writer;
private int amountOfMessagesReceived, amountOfMessagedSent, amountOfPingsSent, amountOfPingsReceived;
/**
* The constructor of the ServerProcess class.
* It requires an ID and a flag indicating whether a GUI should be started or not..
*
* @param id The (unique) ID of the server
* @param useGUI The flag that tells whether this server should run a GUI or not
* @throws RemoteException
*/
public ServerProcess(int id, boolean useGUI, String fieldFile) throws RemoteException, FileNotFoundException {
super();
this.ID = id;
this.field = new Field(fieldFile);
this.logger = Logger.getLogger(ServerProcess.class.getName());
logger.setLevel(Level.ALL);
logger.setUseParentHandlers(false);
Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.ALL);
logger.addHandler(consoleHandler);
this.gameStarted = false;
this.serverPings = new HashMap<Integer, Integer>();
this.gameFinishedByOtherServer = false;
this.connectedPlayers = new ConcurrentHashMap<Integer, ClientInterface>();
this.clientPings = new HashMap<Integer, Boolean>();
this.IDCounter = 0;
this.requestCounter = 0;
this.otherServers = new HashMap<Integer, ServerInterface>();
this.pendingRequests = new HashMap<Integer, ActionRequest>();
this.requestTimers = new HashMap<Integer, Timer>();
this.pendingAcknowledgements = new HashMap<Integer, Integer>();
try {
writer = new PrintWriter("ServerProcess_log_" + this.ID, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
this.amountOfMessagesReceived = 0;
this.amountOfMessagedSent = 0;
this.amountOfPingsReceived = 0;
this.amountOfPingsSent = 0;
// start GUI if necessary
if (useGUI) {
this.visualizerGUI = new VisualizerGUI(field);
}
logger.log(Level.INFO, "Starting server with id " + id);
}
/**
* Main loop of the process.
* It first waits 5 seconds the start the game, then lets the dragons attack every second.
*/
@Override
public void run() {
try {
do {
Thread.sleep(1000);
} while (!gameStarted && !gameFinishedByOtherServer);
while (!gameFinishedByOtherServer && !field.gameHasFinished()) {
// Ping all clients
for (int clientId : connectedPlayers.keySet()) {
ClientInterface ci = connectedPlayers.get(clientId);
amountOfPingsSent++;
try {
ci.ping();
clientPings.put(clientId, true);
} catch (RemoteException e) {
if (clientPings.containsKey(clientId) && !clientPings.get(clientId)) {
clientCrashed(clientId);
} else {
clientPings.put(clientId, false);
}
}
}
// Ping all servers
for (int serverId : otherServers.keySet()) {
amountOfPingsSent++;
try {
otherServers.get(serverId).heartBeat(serverId);
serverPings.put(serverId, 0);
} catch (RemoteException e) {
serverPings.put(serverId, serverPings.get(serverId) + 1);
}
}
// Check if a server has not answered to 2 or more consecutive pings.
for (int serverId : serverPings.keySet()) {
if (serverPings.get(serverId) > 1) {
serverCrashed(serverId);
}
}
//only attack the servers own players (not the others!!!!). Then, no acks are required
Set<Action> actionSet = field.dragonRage(connectedPlayers.keySet());
for (Action a : actionSet) {
broadcastActionToClients(a);
broadcastActionToServers(a);
}
writer.write("Server " + this.ID + " clients " + connectedPlayers.size());
Thread.sleep(1000);
}
if (!gameFinishedByOtherServer) {
// game is finished on this server, so inform all other clients and servers
logger.info("Server " + ID + " finished the game.");
EndOfGameAction endAction = new EndOfGameAction(this.ID);
broadcastActionToClients(endAction);
broadcastActionToServers(endAction);
}
logger.info("Server " + ID + " is going to sleep and exit now");
writer.println("Server " + this.ID + " pings-sent " + amountOfPingsSent);
writer.println("Server " + this.ID + " pings-received " + amountOfPingsReceived);
writer.println("Server " + this.ID + " messages-sent " + amountOfMessagedSent);
writer.println("Server " + this.ID + " messages-received " + amountOfMessagesReceived);
Thread.sleep(1000);
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Broadcast an action to all connected clients
*
* @param action The action to be broadcasted.
*/
public void broadcastActionToClients(Action action) throws RemoteException {
for (ClientInterface client : connectedPlayers.values()) {
amountOfMessagedSent++;
client.performAction(action);
}
}
/**
* Only updates the GUI if there actually is one
*/
private void checkAndUpdateGUI() {
if (visualizerGUI != null)
visualizerGUI.updateGUI();
}
/**
* A client calls this function if it wants to perform one of the following actions:
* MoveAction, HealAction, AttackAction.
*
* @param action The action the client wants to be performed.
* @throws RemoteException
*/
@Override
public void requestAction(Action action) throws RemoteException {
logger.fine("Received action request from client " + action.getSenderId());
amountOfMessagesReceived++;
if (isValidAction(action)) {
if (!otherServers.isEmpty()) {
sendRequestsForAction(action);
}
else {
performAction(action);
}
}
}
/**
* Checks whether the action is valid for this server.
* This is done by checking the validity of the action in the field of this server
* and by checking whether is does not conflict with this server's pending requests.
*
* @param action The action of which the validity needs to be checked
* @return true iff the action can safely be performed on this server
*/
private boolean isValidAction(Action action) {
return action.isValid(field) && checkPendingRequestsForAction(action);
}
/**
* Checks whether there are conflicts between the current request and the pending requests.
*
* @param action The action a client wants to perform
* @return true iff there are no conflicts with the pending actions
*/
private boolean checkPendingRequestsForAction(Action action) {
if (action instanceof MoveAction) {
//check if one of the pending requests also wants to go to the same destination tile
MoveAction move = (MoveAction) action;
for (ActionRequest request : pendingRequests.values())
if (request.getAction() instanceof MoveAction)
if (((MoveAction) request.getAction()).hasSameDestinationAs(move))
return false;
} else if (action instanceof AttackAction) {
//check if there is another attack request for the same dragon
AttackAction attack = (AttackAction) action;
for (ActionRequest request : pendingRequests.values())
if (request.getAction() instanceof AttackAction)
if (((AttackAction) request.getAction()).getDragonId() == attack.getDragonId())
return false;
} else if (action instanceof HealAction) {
//check if there is another heal request for the same target player
HealAction heal = (HealAction) action;
for (ActionRequest request : pendingRequests.values())
if (request.getAction() instanceof HealAction)
if (((HealAction) request.getAction()).getTargetPlayer() == heal.getTargetPlayer())
return false;
}
return true;
}
/**
* Creates an ActionRequest for the action and broadcasts this to the other servers
*
* @param action The action that is requested
*/
private void sendRequestsForAction(Action action) throws RemoteException {
//create request
final ActionRequest request = new ActionRequest(requestCounter++, this.ID, action);
//initialize acknowledgement counter for the request
pendingRequests.put(request.getRequestID(), request);
pendingAcknowledgements.put(request.getRequestID(), otherServers.size());
//init timer to remove request from the data structures when not all acks are received after 5s
Timer timer = new Timer();
requestTimers.put(request.getRequestID(), timer);
timer.schedule(new TimerTask() {
@Override
public void run() {
removeRequest(request.getRequestID());
}
}, 5000);
logger.fine("Sending request " + request.getRequestID() + " to all servers...");
//broadcast the request to the other servers
for (ServerInterface server : otherServers.values()) {
amountOfMessagedSent++;
server.requestAction(request);
}
}
/**
* This function gets called by a client to connect to a server.
*
* @throws RemoteException
*/
@Override
public int register() throws RemoteException {
return IDCounter++;
}
/**
* This function allows a client to connect with a (unique) ID.
*
* @param clientId The ID of the player that wishes to connect.
* @throws RemoteException
*/
@Override
public void connect(int clientId, String clientName) throws RemoteException {
logger.log(Level.INFO, "Client " + clientName + " connected");
amountOfPingsReceived++;
try {
ClientInterface ci = (ClientInterface) Naming.lookup(clientName);
field.addPlayer(clientId);
ci.initializeField(field);
AddPlayerAction apa = new AddPlayerAction(clientId, field.getPlayer(clientId).getxPos(), field.getPlayer(clientId).getyPos());
broadcastActionToClients(apa);
broadcastActionToServers(apa); //inform other servers
// Now the broadcast is done, add the player to the player map (so he doesn't add himself again on the field).
connectedPlayers.put(clientId, ci);
} catch (Exception e) {
e.printStackTrace();
}
if (!gameStarted) {
logger.log(Level.INFO, "Game started on server " + ID);
gameStarted = true;
}
checkAndUpdateGUI();
}
/**
* Function that is called when a client's server crashed and it select another one
*
* @param clientID The id of de client of which the server crashed
* @param clientName The name of the remote object of the client
* @throws java.rmi.RemoteException
*/
@Override
public void reconnect(int clientID, String clientName) throws RemoteException {
amountOfPingsReceived++;
try {
if (!connectedPlayers.containsKey(clientID)) {
connectedPlayers.put(clientID, (ClientInterface) Naming.lookup(clientName));
}
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* This function sends a heartbeat to a remote machine, identified by its (unique) ID.
*
* @param remoteId The ID of the remote machine.
* @throws RemoteException
*/
@Override
public void heartBeat(int remoteId) throws RemoteException {
amountOfPingsReceived++;
}
/**
* This function send back a reply whenever a "ping" comes in.
*
* @throws RemoteException
*/
@Override
public void pong() throws RemoteException {
amountOfPingsReceived++;
}
/**
* This server gets called when a client hasn't responded to two consecutive heartbeats.
*
* @param clientId The ID of the client that probably has crashed.
*/
public void clientCrashed(int clientId) throws RemoteException {
logger.info("Client " + clientId + " has crashed, removing him now");
//remove it from connectedPlayers
connectedPlayers.remove(clientId);
//make, perform and broadcast deleteUnitAction to all other clients
DeleteUnitAction delAction = new DeleteUnitAction(clientId);
performAction(delAction);
//broadcast deleteUnitAction to all other servers
broadcastActionToServers(delAction);
}
/**
* This function gets called when a server suspects a peer server has dropped.
*
* @param serverId The ID of the server that probably has crashed.
*/
public void serverCrashed(int serverId) throws RemoteException {
logger.info("Server " + serverId + " has crashed, removing him now");
//remove it from otherServers and the serverPings.
otherServers.remove(serverId);
serverPings.remove(serverId);
}
/**
* Binds this server to the registry and connects to all other servers.
*
* @param serverURLs The URLs of all servers
* @throws MalformedURLException
* @throws RemoteException
*/
public void registerAndConnectToAll(String[] serverURLs) throws MalformedURLException, RemoteException {
Naming.rebind(serverURLs[ID], this);
for (int i = 0; i < serverURLs.length; i++)
if (i != ID)
connectToServer(serverURLs[i]);
}
/**
* Blocking method that waits until the server (identified by the serverURL) is online.
*
* @param serverURL The URL of the server we are waiting for
* @throws RemoteException
* @throws MalformedURLException
*/
private void connectToServer(String serverURL) throws RemoteException, MalformedURLException {
int id = Integer.parseInt(serverURL.substring(serverURL.lastIndexOf("/") + 1));
while (true) {
try {
otherServers.put(id, (ServerInterface) Naming.lookup(serverURL));
logger.info("Connected to server: " + serverURL);
break;
} catch (NotBoundException ignoredException) {
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Method that one server calls on all other servers to request a certain action.
*
* @param request A request containing the id and the action the server wants to perform
* @throws java.rmi.RemoteException
*/
@Override
public void requestAction(ActionRequest request) throws RemoteException {
amountOfMessagesReceived++;
if (isValidAction(request.getAction())) {
int senderID = request.getSenderID();
int requestID = request.getRequestID();
logger.fine("Acknowledging request " + requestID + " to server " + senderID);
otherServers.get(senderID).acknowledgeRequest(requestID);
}
}
/**
* Method that is used to acknowledge a request send by another server
*
* @param requestID The id of the request
* @throws java.rmi.RemoteException
*/
@Override
public void acknowledgeRequest(int requestID) throws RemoteException {
logger.finer("Received acknowledgement for request " + requestID);
//decrement pending acknowledgement counter (if the request still exists)
if (pendingAcknowledgements.containsKey(requestID)) {
int newCount = pendingAcknowledgements.get(requestID) - 1;
pendingAcknowledgements.put(requestID, newCount);
//if all acknowledgements are received, remove the request and perform the action
if (newCount == 0) {
logger.fine("All acknowledgements for request " + requestID + " received");
Action action = pendingRequests.get(requestID).getAction();
//perform action on local field + connected clients
performAction(action);
broadcastActionToServers(action);
//cleanup
removeRequest(requestID);
}
}
}
/**
* Broadcast an action to all other servers
*
* @param action The action to be broadcasted.
*/
private void broadcastActionToServers(Action action) throws RemoteException {
for (ServerInterface server : otherServers.values()) {
amountOfMessagedSent++;
server.performAction(action);
}
}
/**
* Removes the request with requestID from the pending requests (and acknowledgement counter).
* It also stops and removes the timer associated with the request
*
* @param requestID The id of the request to be removed
*/
private void removeRequest(int requestID) {
requestTimers.get(requestID).cancel();
requestTimers.remove(requestID);
pendingAcknowledgements.remove(requestID);
pendingRequests.remove(requestID);
}
/**
* Method that indicates that the server should perform a certain action.
* This method is only invoked when all other servers have acknowledged the request for the action.
*
* @param action The action that should be executed
* @throws java.rmi.RemoteException
*/
@Override
public void performAction(Action action) throws RemoteException {
logger.fine("Performing action from " + action.getSenderId());
//perform the action on the local field
action.perform(field);
//if a dragon is killed, the action is changed to a DeleteUnitAction
if (action instanceof AttackAction) {
AttackAction aa = (AttackAction) action;
int dragonID = aa.getDragonId();
if (field.getDragon(dragonID).getCurHitPoints() <= 0) {
field.removeDragon(dragonID);
action = new DeleteUnitAction(dragonID);
}
} else if (action instanceof AddPlayerAction) {
//increment this server's IDcounter
int newPlayerID = ((AddPlayerAction) action).getPlayerId();
if (newPlayerID >= IDCounter) {
IDCounter = newPlayerID + 1;
}
}
checkAndUpdateGUI();
broadcastActionToClients(action);
if (action instanceof EndOfGameAction) {
logger.info("Server " + action.getSenderId() + " finished the game.");
gameFinishedByOtherServer = true;
}
}
}
|
package com.example.fw;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ApplicationManager {
public WebDriver driver;
public String baseUrl;
private NavigationHelper navigationHelper;
private GroupHelper groupHelper;
private ContactHelper contactHelper;
public ApplicationManager() {
driver = new FirefoxDriver();
baseUrl = "http://localhost/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// explicit initialization
// navigationHelper = new NavigationHelper(this);
// groupHelper = new GroupHelper(this);
// contactHelper = new ContactHelper(this);
}
public void stop() {
driver.quit();
}
public NavigationHelper getNavigationHelper() {
if (navigationHelper == null) {
navigationHelper = new NavigationHelper(this);
}
return navigationHelper;
}
public GroupHelper getGroupHelper() {
if (groupHelper == null) {
groupHelper = new GroupHelper(this);
}
return groupHelper;
}
public ContactHelper getContactHelper() {
if (contactHelper == null) {
contactHelper = new ContactHelper(this);
}
return contactHelper;
}
}
|
/**
* This file was automatically generated by the Mule Development Kit
*/
package org.mule.modules;
import com.amazonaws.services.dynamodbv2.model.TableStatus;
import org.junit.Assert;
import org.mule.api.MuleEvent;
import org.mule.construct.Flow;
import org.mule.tck.junit4.FunctionalTestCase;
import org.mule.tck.junit4.AbstractMuleTestCase;
import org.junit.Test;
public class DynamoDBConnectorTest extends FunctionalTestCase
{
@Override
protected String getConfigResources()
{
return "mule-config.xml";
}
@Test
public void shouldCreateTable() throws Exception
{
runFlowAndExpect("Should_Create_Table", TableStatus.ACTIVE.toString());
}
/**
* Run the flow specified by name and assert equality on the expected output
*
* @param flowName The name of the flow to run
* @param expect The expected output
*/
protected <T> void runFlowAndExpect(String flowName, T expect) throws Exception
{
Flow flow = lookupFlowConstruct(flowName);
MuleEvent event = FunctionalTestCase.getTestEvent(null);
MuleEvent responseEvent = flow.process(event);
Assert.assertEquals(expect, responseEvent.getMessage().getPayload());
}
/**
* Run the flow specified by name using the specified payload and assert
* equality on the expected output
*
* @param flowName The name of the flow to run
* @param expect The expected output
* @param payload The payload of the input event
*/
protected <T, U> void runFlowWithPayloadAndExpect(String flowName, T expect, U payload) throws Exception
{
Flow flow = lookupFlowConstruct(flowName);
MuleEvent event = FunctionalTestCase.getTestEvent(payload);
MuleEvent responseEvent = flow.process(event);
Assert.assertEquals(expect, responseEvent.getMessage().getPayload());
}
/**
* Retrieve a flow by name from the registry
*
* @param name Name of the flow to retrieve
*/
protected Flow lookupFlowConstruct(String name)
{
return (Flow) FunctionalTestCase.muleContext.getRegistry().lookupFlowConstruct(name);
}
}
|
package org.openremote.security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Unit tests for shared implementation in abstract {@link org.openremote.security.KeyManager}
* class.
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
public class KeyManagerTest
{
// TODO : test loading zero file behavior
// TODO : test saving with non-ascii password
@AfterSuite public void clearSecurityProvider()
{
Provider p = Security.getProvider("BC");
if (p != null)
{
Assert.fail("Tests did not properly remove BouncyCastle provider.");
}
}
/**
* Very basic test runs on StorageType enum to ensure implementation consistency.
*/
@Test public void testStorageTypes()
{
Assert.assertTrue(
KeyManager.Storage.PKCS12.name().equals(KeyManager.Storage.PKCS12.toString())
);
Assert.assertTrue(
KeyManager.Storage.PKCS12.name().equals(KeyManager.Storage.PKCS12.getStorageName())
);
Assert.assertTrue(
KeyManager.Storage.JCEKS.name().equals(KeyManager.Storage.JCEKS.toString())
);
Assert.assertTrue(
KeyManager.Storage.JCEKS.name().equals(KeyManager.Storage.JCEKS.getStorageName())
);
Assert.assertTrue(
KeyManager.Storage.BKS.name().equals(KeyManager.Storage.BKS.toString())
);
Assert.assertTrue(
KeyManager.Storage.BKS.name().equals(KeyManager.Storage.BKS.getStorageName())
);
}
/**
* Tests keystore save when file descriptor is null.
*
* @throws Exception if test fails
*/
@Test public void testSaveWithNullFile() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
char[] storePW = new char[] { 'f', 'o', 'o'};
try
{
keyMgr.save(null, storePW);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests storing an empty keystore.
*
* @throws Exception if test fails for any reason
*/
@Test public void testEmptyKeystore() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
char[] password = new char[] { 'f', 'o', 'o' };
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
keyMgr.save(dest.toURI(), password);
KeyStore keystore = KeyStore.getInstance(KeyManager.DEFAULT_KEYSTORE_STORAGE.getStorageName());
keystore.load(new FileInputStream(dest), new char[] { 'f', 'o', 'o' } );
Assert.assertTrue(keystore.size() == 0);
}
/**
* Tests storing an empty keystore with empty keystore password.
*
* @throws Exception if test fails for any reason
*/
@Test public void testEmptyKeystoreWithEmptyPassword() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
try
{
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
keyMgr.save(dest.toURI(), new char[] {});
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests storing an empty keystore with null keystore password.
*
* @throws Exception if test fails for any reason
*/
@Test public void testEmptyKeystoreWithNullPassword() throws Exception
{
TestKeyManager keyMgr = new TestKeyManager();
try
{
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
keyMgr.save(dest.toURI(), null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test error behavior when file path is incorrectly defined.
*/
@Test public void testSaveWithBrokenFile() throws Exception
{
TestKeyManager mgr = new TestKeyManager();
File f = new File("
char[] pw = new char[] { 'p' };
try
{
mgr.save(f.toURI(), pw);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test behavior when loading keystore with wrong password.
*
* @throws Exception if test fails
*/
@Test public void testWrongPassword() throws Exception
{
JCEKSStorage ks = new JCEKSStorage();
File f = File.createTempFile("openremote", "tmp");
f.deleteOnExit();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] {'a'}, "test")
),
new KeyStore.PasswordProtection(new char[] {'b'})
);
char[] password = new char[] { 'f', 'o', 'o' };
ks.save(f.toURI(), password);
try
{
ks.load(f.toURI(), new char[] { 0 });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests saving and loading secret keys with BouncyCastle UBER storage.
*
* @throws Exception if test fails
*/
@Test public void testLoadExistingKeyStoreUBER() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
char[] pw = new char[] { '1' };
mgr.save(f.toURI(), pw);
pw = new char[] { '1' };
KeyStore keystore = KeyStore.getInstance(KeyManager.Storage.UBER.getStorageName());
keystore.load(new FileInputStream(f), pw);
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)keystore.getEntry(
"test", new KeyStore.PasswordProtection(new char[] {'b'})
);
Assert.assertTrue(Arrays.equals(entry.getSecretKey().getEncoded(), new byte[] {'a'}));
}
finally
{
Security.removeProvider("BC");
}
}
@Test public void testLoadExistingKeyStoreJCEKS() throws Exception
{
JCEKSStorage mgr = new JCEKSStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
char[] pw = new char[] { '1' };
mgr.save(f.toURI(), pw);
pw = new char[] { '1' };
KeyStore keystore = KeyStore.getInstance(KeyManager.Storage.JCEKS.getStorageName());
keystore.load(new FileInputStream(f), pw);
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)keystore.getEntry(
"test", new KeyStore.PasswordProtection(new char[] {'b'})
);
Assert.assertTrue(Arrays.equals(entry.getSecretKey().getEncoded(), new byte[] { 'a' }));
}
/**
* Tests error behavior when null file descriptor is used.
*
* @throws Exception if test fails
*/
@Test public void testLoadingNullFile() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] {'a'}, "foo")),
new KeyStore.PasswordProtection(new char[] {'b'})
);
char[] pw = new char[] { '1' };
try
{
mgr.load(null, pw);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests the error handling behavior when null password is given.
*
* @throws Exception if test fails
*/
@Test public void testLoadingWithNullPassword() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
try
{
mgr.load(f.toURI(), null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests load behavior when an existing keystore has been corrupted.
*
* @throws Exception if test fails
*/
@Test public void testCorruptJCEKS() throws Exception
{
JCEKSStorage ks = new JCEKSStorage();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
char[] password = new char[] { 'f', 'o', 'o' };
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
ks.add(
"foobar",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
ks.save(f.toURI(), password);
FileOutputStream fout = new FileOutputStream(f);
BufferedOutputStream bout = new BufferedOutputStream(fout);
bout.write("Add some garbage".getBytes());
bout.close();
password = new char[] { 'f', 'o', 'o' };
try
{
ks.load(f.toURI(), password);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test behavior when a secret key is added to storage that does not
* support them.
*
* @throws Exception if test fails
*/
@Test public void testAddingSecretKeyToPKCS12() throws Exception
{
PKCS12Storage ks = new PKCS12Storage();
try
{
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests adding a secret key to JCEKS storage.
*
* @throws Exception if test fails
*/
@Test public void testAddingSecretKeyToJCEKS() throws Exception
{
JCEKSStorage ks = new JCEKSStorage();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
char[] password = new char[] { 'f', 'o', 'o' };
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
ks.save(dest.toURI(), password);
}
/**
* Tests adding a secret key to BouncyCastle UBER storage.
*
* @throws Exception if test fails
*/
@Test public void testAddingSecretKeyToUBER() throws Exception
{
// UBER implementation requires "BC" to be available as security provider...
try
{
Security.addProvider(new BouncyCastleProvider());
UBERStorage ks = new UBERStorage();
ks.add(
"alias",
new KeyStore.SecretKeyEntry(
new SecretKeySpec(new byte[] { 'a' }, "test")
),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
char[] password = new char[] { 'f', 'o', 'o' };
File dest = File.createTempFile("openremote", "tmp");
dest.deleteOnExit();
ks.save(dest.toURI(), password);
Assert.assertTrue(ks.getStorageType().getStorageName().equals("UBER"));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test implementation behavior when requested keystore algorithm is not available.
*
* @throws Exception if test fails
*/
@Test public void testAddingSecretKeyToUnavailableBKS() throws Exception
{
try
{
new UnavailableBKS();
Assert.fail("should not get here...");
}
catch (KeyManager.ConfigurationException e)
{
// expected...
}
}
/**
* Tests error handling behavior on add() with null alias.
*
* @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)
*/
@Test public void testAddNullAlias() throws Exception
{
TestKeyManager mgr = new TestKeyManager();
try
{
mgr.add(
null,
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests error handling behavior on add() with empty alias.
*
* @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)
*/
@Test public void testAddEmptyAlias() throws Exception
{
TestKeyManager mgr = new TestKeyManager();
try
{
mgr.add(
"",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests error handling behavior on add() with empty alias.
*
* @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)
*/
@Test public void testAddNullEntry() throws Exception
{
TestKeyManager mgr = new TestKeyManager();
try
{
mgr.add(
"test",
null,
new KeyStore.PasswordProtection(new char[] {'b'})
);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests error behavior when null file descriptor is used.
*
* @throws Exception if test fails
*/
@Test public void testLoadingNullFile() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] {'a'}, "foo")),
new KeyStore.PasswordProtection(new char[] {'b'})
);
char[] pw = new char[] { '1' };
try
{
mgr.load(null, pw);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests the error handling behavior when null password is given.
*
* @throws Exception if test fails
*/
@Test public void testLoadingWithNullPassword() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
UBERStorage mgr = new UBERStorage();
mgr.add(
"test",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")),
new KeyStore.PasswordProtection(new char[] { 'b' })
);
File dir = new File(System.getProperty("user.dir"));
File f = new File(dir, "test.keystore." + UUID.randomUUID());
f.deleteOnExit();
try
{
mgr.load(f.toURI(), null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
private static class TestKeyManager extends KeyManager
{
// no op, just to test abstract superclass implementation...
}
private static class JCEKSStorage extends KeyManager
{
private static Provider findJCEKSProvider()
{
Map<String, String> props = new HashMap<String, String>();
props.put("keystore.jceks", "");
Provider[] providers = Security.getProviders(props);
if (providers.length == 0)
{
Assert.fail("Cannot find a security provider for Sun JCEKS");
return null;
}
else
{
return providers[0];
}
}
JCEKSStorage()
{
super(StorageType.JCEKS, findJCEKSProvider());
}
}
/**
* UBER keystorage from BouncyCastle.
*/
private static class UBERStorage extends KeyManager
{
UBERStorage()
{
super(StorageType.UBER, new BouncyCastleProvider());
}
}
/**
* Test KeyManager implementation that attempts to load/create a keystore of a type
* that is not available in the security provider.
*/
private static class UnavailableBKS extends KeyManager
{
UnavailableBKS()
{
super(StorageType.BKS, new EmptyProvider());
}
}
/**
* PKCS12 storage from a default security prover.
*/
private static class PKCS12Storage extends KeyManager
{
PKCS12Storage()
{
super(StorageType.PKCS12, null);
}
}
private static class BrokenStorageManager extends KeyManager
{
BrokenStorageManager()
{
super(null, new BouncyCastleProvider());
}
}
/**
* An empty test security provider used for some test cases.
*/
private static class EmptyProvider extends Provider
{
EmptyProvider()
{
super("Empty Test Provider", 0.0, "Testing");
}
}
}
|
package seedu.scheduler.logic;
import com.google.common.eventbus.Subscribe;
import guitests.GuiRobot;
import javafx.scene.input.KeyCode;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import seedu.scheduler.commons.core.EventsCenter;
import seedu.scheduler.logic.commands.*;
import seedu.scheduler.commons.events.ui.JumpToListRequestEvent;
import seedu.scheduler.commons.events.ui.ShowHelpRequestEvent;
import seedu.scheduler.commons.events.model.SchedulerChangedEvent;
import seedu.scheduler.model.Scheduler;
import seedu.scheduler.model.Model;
import seedu.scheduler.model.ModelManager;
import seedu.scheduler.model.ReadOnlyScheduler;
import seedu.scheduler.model.entry.*;
import seedu.scheduler.model.entry.UniqueEntryList.DuplicateEntryException;
import seedu.scheduler.model.tag.Tag;
import seedu.scheduler.model.tag.UniqueTagList;
import seedu.scheduler.storage.StorageManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static seedu.scheduler.commons.core.Messages.*;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyScheduler latestSavedScheduler;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(SchedulerChangedEvent abce) {
latestSavedScheduler = new Scheduler(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setup() {
model = new ModelManager();
String tempSchedulerFile = saveFolder.getRoot().getPath() + "TempScheduler.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempSchedulerFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedScheduler = new Scheduler(model.getScheduler()); // last saved assumed to be up to date before.
helpShown = false;
targetedJumpIndex = -1; // non yet
}
@After
public void teardown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() throws Exception {
String invalidCommand = " ";
assertCommandBehavior(invalidCommand,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command and confirms that the result message is correct.
* Both the 'scheduler' and the 'last shown list' are expected to be empty.
* @see #assertCommandBehavior(String, String, ReadOnlyScheduler, List)
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception {
assertCommandBehavior(inputCommand, expectedMessage, new Scheduler(), Collections.emptyList());
}
/**
* Executes the command and confirms that the result message is correct and
* also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal scheduler data are same as those in the {@code expectedScheduler} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedScheduler} was saved to the storage file. <br>
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage,
ReadOnlyScheduler expectedScheduler,
List<? extends ReadOnlyEntry> expectedShownList) throws Exception {
//Execute the command
CommandResult result = logic.execute(inputCommand);
if (inputCommand.equals("clear")) {
GuiRobot robot = new GuiRobot();
robot.type(KeyCode.ENTER).sleep(500);
}
//Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getFilteredEntryList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedScheduler, model.getScheduler());
assertEquals(expectedScheduler, latestSavedScheduler);
}
@Test
public void execute_unknownCommandWord() throws Exception {
String unknownCommand = "uicfhmowqewca";
assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() throws Exception {
assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
}
@Test
public void execute_exit() throws Exception {
assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT);
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addEntry(helper.generateEntry(1));
model.addEntry(helper.generateEntry(2));
model.addEntry(helper.generateEntry(3));
//NEEDFIX
//assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new Scheduler(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
assertCommandBehavior(
"add test g/1231", expectedMessage);
}
//@@author A0126090N
@Test
public void execute_add_invalidEntryData() throws Exception {
assertCommandBehavior(
"add []\\[;]", Name.MESSAGE_NAME_CONSTRAINTS);
assertCommandBehavior(
"add Valid Name et/01:02 st/01:02", String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
assertCommandBehavior(
"add Valid Name st/25:02", StartTime.MESSAGE_START_TIME_CONSTRAINTS);
}
//@@author
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Entry toBeAdded = helper.adam();
Scheduler expectedAB = new Scheduler();
expectedAB.addEntry(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getEntryList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Entry toBeAdded = helper.adam();
Scheduler expectedAB = new Scheduler();
expectedAB.addEntry(toBeAdded);
// setup starting state
model.addEntry(toBeAdded); // entry already in internal scheduler
// execute command and verify result
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_ENTRY,
expectedAB,
expectedAB.getEntryList());
}
@Test
public void execute_addUndoRedo() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Entry toBeAdded = helper.adam();
List<Entry> threeEntrys = helper.generateEntryList(3);
Scheduler expectedAB = helper.generateScheduler(threeEntrys);
expectedAB.addEntry(toBeAdded);
helper.addToModel(model, threeEntrys);
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getEntryList());
expectedAB.removeEntry(toBeAdded);
assertCommandBehavior("undo",
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getEntryList());
expectedAB.addEntry(toBeAdded);
assertCommandBehavior("redo",
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getEntryList());
}
@Test
public void execute_list_showsAllEntrys() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
Scheduler expectedAB = helper.generateScheduler(2);
List<? extends ReadOnlyEntry> expectedList = expectedAB.getEntryList();
// prepare scheduler state
helper.addToModel(model, 2);
//NEED TO FIX
/*
assertCommandBehavior("list",
ListCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
*/
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single entry in the shown list, using visible index.
* @param commandWord to test assuming it targets a single entry in the last shown list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception {
assertCommandBehavior(commandWord , expectedMessage); //index missing
assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandBehavior(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single entry in the shown list, using visible index.
* @param commandWord to test assuming it targets a single entry in the last shown list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_ENTRY_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Entry> entryList = helper.generateEntryList(2);
// set AB state to 2 entrys
model.resetData(new Scheduler());
for (Entry p : entryList) {
model.addEntry(p);
}
if(commandWord == "delete"){
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getScheduler(), entryList);
} else if(commandWord == "edit"){
assertCommandBehavior(commandWord + " 3 name", expectedMessage, model.getScheduler(), entryList);
}
//@@author A0126090N
else if(commandWord == "mark"){
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getScheduler(), entryList);
}
else if(commandWord == "m"){
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getScheduler(), entryList);
}
//@@author
}
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
@Test
public void execute_select_jumpsToCorrectEntry() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Entry> threeEntrys = helper.generateEntryList(3);
Scheduler expectedAB = helper.generateScheduler(threeEntrys);
helper.addToModel(model, threeEntrys);
assertCommandBehavior("select 2",
String.format(SelectCommand.MESSAGE_SELECT_ENTRY_SUCCESS, 2),
expectedAB,
expectedAB.getEntryList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredEntryList().get(1), threeEntrys.get(1));
}
//@@author A0126090N
@Test
public void execute_markedInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkedCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("mark", expectedMessage);
}
@Test
public void execute_markedIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("mark");
}
@Test
public void execute_markedAdvancedInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkedCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("m", expectedMessage);
}
@Test
public void execute_markedAdvancedIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("m");
}
//@@author
@Test
public void execute_delete_removesCorrectEntry() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Entry> threeEntrys = helper.generateEntryList(3);
Scheduler expectedAB = helper.generateScheduler(threeEntrys);
expectedAB.removeEntry(threeEntrys.get(1));
helper.addToModel(model, threeEntrys);
assertCommandBehavior("delete 2",
String.format(DeleteCommand.MESSAGE_DELETE_ENTRY_SUCCESS, threeEntrys.get(1)),
expectedAB,
expectedAB.getEntryList());
}
//@@author A0126090N
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
//@@author
//@@author A0152962B
@Test
public void execute_editToDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
List<Entry> threeEntrys = helper.generateEntryList(3);
Entry toEditTo = helper.adam();
threeEntrys.add(toEditTo);
Scheduler expectedAB = helper.generateScheduler(threeEntrys);
helper.addToModel(model, threeEntrys);
assertCommandBehavior(helper.generateEditCommand(toEditTo, 2),
String.format(EditCommand.MESSAGE_DUPLICATE_ENTRY, toEditTo),
expectedAB,
expectedAB.getEntryList());
}
@Test
public void execute_editIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("edit");
}
@Test
public void execute_editInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("edit", expectedMessage);
}
@Test
public void execute_edit_editsCorrectEntry() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Entry> threeEntrys = helper.generateEntryList(3);
Scheduler expectedAB = helper.generateScheduler(threeEntrys);
Entry toEditTo = helper.adam();
expectedAB.editEntry(toEditTo, threeEntrys.get(1));
helper.addToModel(model, threeEntrys);
assertCommandBehavior(helper.generateEditCommand(toEditTo, 2),//"edit 2 Adam Brown st/11:11 et/11:15 sd/01-02-2034 ed/01-02-2035 t/tag1 t/tag2",
String.format(EditCommand.MESSAGE_SUCCESS, toEditTo),
expectedAB,
expectedAB.getEntryList());
}
//@@author
@Test
public void execute_find_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandBehavior("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Entry pTarget1 = helper.generateEntryWithName("bla bla KEY bla");
Entry pTarget2 = helper.generateEntryWithName("bla KEY bla bceofeia");
Entry p1 = helper.generateEntryWithName("KE Y");
Entry p2 = helper.generateEntryWithName("KEYKEYKEY sduauo");
List<Entry> fourEntrys = helper.generateEntryList(p1, pTarget1, p2, pTarget2);
Scheduler expectedAB = helper.generateScheduler(fourEntrys);
List<Entry> expectedList = helper.generateEntryList(pTarget1, pTarget2);
helper.addToModel(model, fourEntrys);
assertCommandBehavior("find KEY",
Command.getMessageForEntryListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Entry p1 = helper.generateEntryWithName("bla bla KEY bla");
Entry p2 = helper.generateEntryWithName("bla KEY bla bceofeia");
Entry p3 = helper.generateEntryWithName("key key");
Entry p4 = helper.generateEntryWithName("KEy sduauo");
List<Entry> fourEntrys = helper.generateEntryList(p3, p1, p4, p2);
Scheduler expectedAB = helper.generateScheduler(fourEntrys);
List<Entry> expectedList = fourEntrys;
helper.addToModel(model, fourEntrys);
assertCommandBehavior("find KEY",
Command.getMessageForEntryListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Entry pTarget1 = helper.generateEntryWithName("bla bla KEY bla");
Entry pTarget2 = helper.generateEntryWithName("bla rAnDoM bla bceofeia");
Entry pTarget3 = helper.generateEntryWithName("key key");
Entry p1 = helper.generateEntryWithName("sduauo");
List<Entry> fourEntrys = helper.generateEntryList(pTarget1, p1, pTarget2, pTarget3);
Scheduler expectedAB = helper.generateScheduler(fourEntrys);
List<Entry> expectedList = helper.generateEntryList(pTarget1, pTarget2, pTarget3);
helper.addToModel(model, fourEntrys);
assertCommandBehavior("find key rAnDoM",
Command.getMessageForEntryListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper{
Entry adam() throws Exception {
Name name = new Name("Adam Brown");
StartTime privateStartTime = new StartTime("11:11");
EndTime endTime = new EndTime("11:15");
Date privateDate = new Date("01-02-2034");
EndDate privateEndDate = new EndDate("01-02-2035");
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("tag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new Entry(name, privateStartTime, endTime, privateDate, privateEndDate, tags);
}
/**
* Generates a valid entry using the given seed.
* Running this function with the same parameter values guarantees the returned entry will have the same state.
* Each unique seed will generate a unique Entry object.
*
* @param seed used to generate the entry data field values
*/
Entry generateEntry(int seed) throws Exception {
Random random = new Random();
String[] num ={"00", "01", "02", "03", "04", "05", "06", "07", "08", "09",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28"};
return new Entry(
new Name("Entry " + seed),
new StartTime(num[random.nextInt(24)] + ":00"),
new EndTime(num[random.nextInt(24)] + ":00"),
new Date(num[random.nextInt(28)+1] + "-" + num[random.nextInt(12)+1] + "-2016"),
new EndDate(num[random.nextInt(28)+1] + "-" + num[random.nextInt(12)+1] + "-2017"),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))
);
}
/** Generates the correct add command based on the entry given */
String generateAddCommand(Entry e) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append(e.getName().toString());
cmd.append(" st/").append(e.getStartTime());
cmd.append(" et/").append(e.getEndTime());
cmd.append(" sd/").append(e.getDate());
cmd.append(" ed/").append(e.getEndDate());
UniqueTagList tags = e.getTags();
for(Tag t: tags){
cmd.append(" t/").append(t.tagName);
}
return cmd.toString();
}
//@@author A0152962B
/** Generates the correct edit command based on the entry and index given */
String generateEditCommand(Entry e, int index) {
StringBuffer cmd = new StringBuffer();
cmd.append("edit ");
cmd.append(Integer.toString(index) + " ");
cmd.append(e.getName().toString());
cmd.append(" st/").append(e.getStartTime());
cmd.append(" et/").append(e.getEndTime());
cmd.append(" sd/").append(e.getDate());
cmd.append(" ed/").append(e.getEndDate());
UniqueTagList tags = e.getTags();
for(Tag t: tags){
cmd.append(" t/").append(t.tagName);
}
return cmd.toString();
}
//@@author
/**
* Generates an Scheduler with auto-generated entrys.
*/
Scheduler generateScheduler(int numGenerated) throws Exception{
Scheduler scheduler = new Scheduler();
addToScheduler(scheduler, numGenerated);
return scheduler;
}
/**
* Generates an Scheduler based on the list of Entrys given.
*/
Scheduler generateScheduler(List<Entry> entrys) throws Exception{
Scheduler scheduler = new Scheduler();
addToScheduler(scheduler, entrys);
return scheduler;
}
/**
* Adds auto-generated Entry objects to the given Scheduler
* @param scheduler The Scheduler to which the Entrys will be added
*/
void addToScheduler(Scheduler scheduler, int numGenerated) throws Exception{
addToScheduler(scheduler, generateEntryList(numGenerated));
}
/**
* Adds the given list of Entrys to the given Scheduler
*/
void addToScheduler(Scheduler scheduler, List<Entry> entrysToAdd) throws Exception{
for(Entry p: entrysToAdd){
scheduler.addEntry(p);
}
}
/**
* Adds auto-generated Entry objects to the given model
* @param model The model to which the Entrys will be added
*/
void addToModel(Model model, int numGenerated) throws Exception{
addToModel(model, generateEntryList(numGenerated));
}
/**
* Adds the given list of Entrys to the given model
*/
void addToModel(Model model, List<Entry> entrysToAdd) throws Exception{
for(Entry p: entrysToAdd){
model.addEntry(p);
}
}
/**
* Generates a list of Entrys based on the flags.
*/
List<Entry> generateEntryList(int numGenerated) throws Exception{
List<Entry> entrys = new ArrayList<>();
for(int i = 1; i <= numGenerated; i++){
entrys.add(generateEntry(i));
}
return entrys;
}
List<Entry> generateEntryList(Entry... entrys) {
return Arrays.asList(entrys);
}
/**
* Generates a Entry object with given name. Other fields will have some dummy values.
*/
Entry generateEntryWithName(String name) throws Exception {
return new Entry(
new Name(name),
new StartTime("11:11"),
new EndTime("11:11"),
new Date("01-02-2034"),
new EndDate("02-02-2034"),
new UniqueTagList(new Tag("tag"))
);
}
}
}
|
package org.apache.lucene.analysis;
import junit.framework.TestCase;
import java.io.StringReader;
import java.util.ArrayList;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Hits;
public class TestStopAnalyzer extends TestCase {
private StopAnalyzer stopAnalyzer = new StopAnalyzer();
public Token[] tokensFromAnalyzer(Analyzer analyzer, String text)
throws Exception {
TokenStream stream =
analyzer.tokenStream("contents", new StringReader(text));
ArrayList tokenList = new ArrayList();
while (true) {
Token token = stream.next();
if (token == null) break;
tokenList.add(token);
}
return (Token[]) tokenList.toArray(new Token[0]);
}
public void testPhraseQuery() throws Exception {
RAMDirectory directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, stopAnalyzer, true);
Document doc = new Document();
doc.add(Field.Text("field", "the stop words are here"));
writer.addDocument(doc);
writer.close();
IndexSearcher searcher = new IndexSearcher(directory);
// valid exact phrase query
PhraseQuery query = new PhraseQuery();
query.add(new Term("field","stop"));
query.add(new Term("field","words"));
Hits hits = searcher.search(query);
assertEquals(1, hits.length());
// currently StopAnalyzer does not leave "holes", so this matches.
query = new PhraseQuery();
query.add(new Term("field", "words"));
query.add(new Term("field", "here"));
hits = searcher.search(query);
assertEquals(1, hits.length());
searcher.close();
}
}
|
package pitt.search.semanticvectors;
import org.apache.lucene.index.IndexModifier;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.FSDirectory;
import java.io.File;
import ch.akuhn.edu.mit.tedlab.*;
/**
* Interface to Adrian Kuhn and David Erni's implementation of SVDLIBJ, a native Java version
* of Doug Rhodes' SVDLIBC, which was in turn based on SVDPACK, by Michael Berry, Theresa Do,
* Gavin O'Brien, Vijay Krishna and Sowmini Varadhan.
*
* This class will produce two files, svd_termvectors.bin and svd_docvectors.bin from a Lucene index
* Command line arguments are consistent with the rest of the Semantic Vectors Package
*
*/
public class LSA {
static boolean le = false;
static String[] theTerms;
/**
* Prints the following usage message:
* <code>
* <br> LSA class in package pitt.search.semanticvectors
* <br> Usage: java pitt.search.semanticvectors.LSA PATH_TO_LUCENE_INDEX
* <br> LSA creates svd_termvectors and svd_docvectors files in local directory.
* <br> Other parameters that can be changed include vector length,
* <br> (number of dimensions), seed length (number of non-zero
* <br> entries in basic vectors) and minimum term frequency.
* <br>
* <br> To change these use the following command line arguments:
* <br> -dimension [number of dimensions]
* <br> -minfrequency [minimum term frequency]
* <br> -numnonalphabetchars [number non-alphabet characters (-1 for any number)]
* </code>
*/
public static void usage() {
String usageMessage = "\nLSA class in package pitt.search.semanticvectors"
+ "\nUsage: java pitt.search.semanticvectors.LSA PATH_TO_LUCENE_INDEX"
+ "\nBuildIndex creates svd_termvectors and svd_docvectors files in local directory."
+ "\nOther parameters that can be changed include vector length,"
+ "\n (number of dimensions), seed length (number of non-zero"
+ "\n entries in basic vectors), and minimum term frequency."
+ "\nTo change these use the command line arguments "
+ "\n -dimension [number of dimensions]"
+ "\n -minfrequency [minimum term frequency]"
+ "\n -numnonalphabetchars [number non-alphabet characters (-1 for any number)]";
System.out.println(usageMessage);
}
/**
* Builds term vector and document vector stores from a Lucene index, using SVD to reduce dimensions
* @param args
* @see LSA#usage
*/
/* Converts a dense matrix to a sparse one (without affecting the dense one) */
static SMat smatFromIndex(String fileName) throws Exception {
SMat S;
int i, j, n;
//initiate IndexReader and LuceneUtils
File file = new File(fileName);
IndexReader indexReader = IndexReader.open(file);
pitt.search.semanticvectors.LuceneUtils lUtils = new pitt.search.semanticvectors.LuceneUtils(fileName);
int[][] index;
int nonalphabet = Flags.maxnonalphabetchars;
int minfreq = Flags.minfrequency;
String[] desiredFields = Flags.contentsfields;
TermEnum terms = indexReader.terms();
int tc = 0;
while(terms.next()){
if (lUtils.termFilter(terms.term(),desiredFields,nonalphabet,minfreq))
tc++;
}
System.err.println("There are " + tc + " terms (and " + indexReader.numDocs() + " docs)");
theTerms = new String[tc];
index = new int[tc][];
terms = indexReader.terms();
tc = 0;
int nonzerovals = 0;
while(terms.next()){
org.apache.lucene.index.Term term = terms.term();
if (lUtils.termFilter(term,desiredFields,nonalphabet,minfreq))
{ theTerms[tc] = term.text();
/**
* create matrix of nonzero indices
*/
TermDocs td = indexReader.termDocs(term);
int count =0;
while (td.next())
{ count ++;
nonzerovals++;
}
index[tc] = new int[count];
/**
* fill in matrix of nonzero indices
*/
td = indexReader.termDocs(term);
count = 0;
while (td.next())
{index[tc][count++] = td.doc();}
tc++; //next term
}
}
/**
* initialize "SVDLIBJ" sparse data structure
*/
S = new SMat(indexReader.numDocs(),tc, nonzerovals);
/**
* populate "SVDLIBJ" sparse data structure
*/
terms = indexReader.terms();
tc = 0;
int nonzerocounter = 0;
int nn= 0;
while(terms.next()){
org.apache.lucene.index.Term term = terms.term();
if (lUtils.termFilter(term,desiredFields,nonalphabet,minfreq))
{
TermDocs td = indexReader.termDocs(term);
S.pointr[tc] = nn; // index of first non-zero entry (document) of each column (term)
while (td.next())
{ /** public int[] pointr; For each col (plus 1), index of
* first non-zero entry. we'll represent the matrix as a
* document x term matrix such that terms are columns
* (otherwise it would be difficult to extract this
* information from the lucene index)
*/
int rowindex = td.doc();
float value = td.freq();
/**
* if log-entropy weighting is to be used
*/
if (le)
{float entropy = lUtils.getEntropy(term);
float log1plus = (float) Math.log10(1+value);
value = entropy*log1plus;
}
S.rowind[nn] = td.doc(); //set row index to document number
S.value[nn] = value; //set value to frequency (with/without weighting)
nn++;
}
tc++;
}
}
S.pointr[S.cols] = S.vals;
return S;
}
public static void main(String[] args) throws Exception
{
try {
args = Flags.parseCommandLineFlags(args);
} catch (IllegalArgumentException e) {
usage();
throw e;
}
// Only one argument should remain, the path to the Lucene index.
if (args.length != 1) {
usage();
throw (new IllegalArgumentException("After parsing command line flags, there were " + args.length
+ " arguments, instead of the expected 1."));
}
System.err.println("Seedlength = " + Flags.seedlength);
System.err.println("Dimension = " + Flags.dimension);
System.err.println("Minimum frequency = " + Flags.minfrequency);
System.err.println("Number non-alphabet characters = " + Flags.maxnonalphabetchars);
le = Flags.termweight.equals("logentropy");
if (le)
System.err.println("Term weighting: log-entropy");
SMat A = smatFromIndex(args[0]);
Svdlib svd = new Svdlib();
System.err.println("Starting SVD using algorithm LAS2");
SVDRec svdR = svd.svdLAS2A(A, Flags.dimension);
DMat vT = svdR.Vt;
DMat uT = svdR.Ut;
// Open file and write headers.
String termFile = "svd_termvectors.bin";
FSDirectory fsDirectory = FSDirectory.getDirectory(".");
IndexOutput outputStream = fsDirectory.createOutput(termFile);
float[] tmpVector = new float[Flags.dimension];
int counter = 0;
System.err.println("Write vectors incrementally to file " + termFile);
// Write header giving number of dimensions for all vectors.
outputStream.writeString("-dimensions");
outputStream.writeInt(Flags.dimension);
int cnt;
// Write out term vectors
for (cnt = 0; cnt < vT.cols; cnt++)
{
outputStream.writeString(theTerms[cnt]);
float[] termVector = new float[Flags.dimension];
for (int i = 0; i < Flags.dimension; i++)
termVector[i] = (float) vT.value[i][cnt];
termVector = VectorUtils.getNormalizedVector(termVector);
for (int i = 0; i < Flags.dimension; ++i) {
outputStream.writeInt(Float.floatToIntBits(termVector[i]));
}
}
System.err.println("Wrote "+cnt+" term vectors to "+termFile);
outputStream.flush();
outputStream.close();
/*
* Write document vectors
*/
// Open file and write headers.
String docFile = "svd_docvectors.bin";
outputStream = fsDirectory.createOutput(docFile);
tmpVector = new float[Flags.dimension];
counter = 0;
System.err.println("Write vectors incrementally to file " + docFile);
// Write header giving number of dimensions for all vectors.
outputStream.writeString("-dimensions");
outputStream.writeInt(Flags.dimension);
//initiate IndexReader and LuceneUtils
File file = new File(args[0]);
IndexReader indexReader = IndexReader.open(file);
// Write out document vectors
for (cnt = 0; cnt < uT.cols; cnt++)
{
String thePath = indexReader.document(cnt).get("path");
outputStream.writeString(thePath);
float[] docVector = new float[Flags.dimension];
for (int i = 0; i < Flags.dimension; i++)
docVector[i] = (float) uT.value[i][cnt];
docVector = VectorUtils.getNormalizedVector(docVector);
for (int i = 0; i < Flags.dimension; ++i) {
outputStream.writeInt(Float.floatToIntBits(docVector[i]));
}
}
System.err.println("Wrote "+cnt+" document vectors to "+docFile);
outputStream.flush();
outputStream.close();
}
}
|
package edu.umd.cs.findbugs;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;
import edu.umd.cs.pugh.visitclass.BetterVisitor;
import edu.umd.cs.pugh.visitclass.Constants2;
public class SerializableIdiom extends BetterVisitor implements Detector, Constants2 {
boolean sawSerialVersionUID;
boolean isSerializable;
int synchronizedMethods;
boolean writeObjectIsSynchronized;
private BugReporter bugReporter;
public SerializableIdiom(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
classContext.getJavaClass().accept(this);
}
public void report() {
}
public void visitJavaClass(JavaClass obj) {
int flags = obj.getAccessFlags();
boolean isAbstract = (flags & ACC_ABSTRACT) != 0
|| (flags & ACC_INTERFACE) != 0;
super.visitJavaClass(obj);
sawSerialVersionUID = false;
constant_pool.accept(this);
isSerializable = false;
String [] interface_names = obj.getInterfaceNames();
for(int i=0; i < interface_names.length; i++) {
if (interface_names[i].equals("java.io.Serializable")) {
isSerializable = true;
}
}
isSerializable = isSerializable
|| Repository.instanceOf(obj,"java.io.Serializable");
Field[] fields = obj.getFields();
for(int i = 0; i < fields.length; i++) fields[i].accept(this);
if (isSerializable && !isAbstract && !sawSerialVersionUID)
bugReporter.reportBug(new BugInstance("SE_NO_SERIALVERSIONID", NORMAL_PRIORITY).addClass(this));
synchronizedMethods = 0;
writeObjectIsSynchronized = false;
Method[] methods = obj.getMethods();
for(int i = 0; i < methods.length; i++) methods[i].accept(this);
if (writeObjectIsSynchronized && synchronizedMethods == 0)
bugReporter.reportBug(new BugInstance("WS_WRITEOBJECT_SYNC", NORMAL_PRIORITY).addClass(this));
}
public void visit(Method obj) {
int accessFlags = obj.getAccessFlags();
boolean isSynchronized = (accessFlags & ACC_SYNCHRONIZED) != 0;
// System.out.println(methodName + isSynchronized);
if (!isSynchronized) return;
if (methodName.equals("readObject"))
bugReporter.reportBug(new BugInstance("RS_READOBJECT_SYNC", NORMAL_PRIORITY).addClass(this));
else if (methodName.equals("writeObject"))
writeObjectIsSynchronized = true;
else synchronizedMethods++;
}
public void visit(Field obj) {
// System.out.println("Saw " + betterClassName + "." + fieldName);
super.visit(obj);
if (!fieldName.equals("serialVersionUID")) return;
// System.out.println("Saw " + betterClassName + "." + fieldName);
int flags = obj.getAccessFlags();
if ((flags & ACC_STATIC) == 0) {
bugReporter.reportBug(new BugInstance("SE_NONSTATIC_SERIALVERSIONID", NORMAL_PRIORITY)
.addClass(this)
.addVisitedField(this));
return;
}
sawSerialVersionUID = true;
}
}
|
package de.hpi.fgis.tpch;
import java.io.Serializable;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple5;
import org.apache.flink.core.fs.FileSystem.WriteMode;
/**
* Flink job solving the Shipping Priority Query (Q3) of the TPC-H benchmark partially.<br/>
* <br/>
* <b>Query:</b>
<pre>
select l.ORDERKEY, sum(EXTENDEDPRICE*(1-DISCOUNT)) as revenue
from
ORDERS o,
LINEITEM l
where
l.ORDERKEY = o.ORDERKEY
and ORDERDATE < date '[DATE]'
and SHIPDATE > date '[DATE]'
group by
l.ORDERKEY
order by
revenue desc
</pre>
*/
public class Q3 {
public static void main(String[] args) throws Exception {
// get job parameters
final String lineItemFile = args[0];
final String ordersFile = args[1];
final String resultFile = args[2];
final String DATE = "1995-03-15";
// set up the execution environment
final ExecutionEnvironment env = ExecutionEnvironment
.getExecutionEnvironment();
// load lineitems
DataSet<LineItem> lineItems = env.readTextFile(lineItemFile)
// map to lineitem
.map(new MapFunction<String, LineItem>() {
@Override
public LineItem map(String line) throws Exception {
return new LineItem(line);
}
})
// filter by SHIPDATE>DATE
.filter(new FilterFunction<LineItem>() {
@Override
public boolean filter(LineItem li) throws Exception {
return li.SHIPDATE().compareTo(DATE) > 0;
}
});
// aggregate sum(PRICE *(1-DISCOUNT)) by ORDERKEY
DataSet<Tuple2<Integer, Double>> lineItemRevenue = lineItems
.map(new MapFunction<Q3.LineItem, Tuple2<Integer, Double>>() {
@Override
public Tuple2<Integer, Double> map(LineItem li) throws Exception {
return new Tuple2<Integer, Double>(li.ORDERKEY(), li.PRICE() * (1 - li.DISCOUNT()));
}
}).groupBy(0).sum(1);
// load orders
DataSet<Order> orders = env.readTextFile(ordersFile)
// map to order
.map(new MapFunction<String, Order>() {
@Override
public Order map(String line) throws Exception {
return new Order(line);
}
// filter by SHIPDATE>DATE
}).filter(new FilterFunction<Order>() {
@Override
public boolean filter(Order order) throws Exception {
return order.ORDERDATE().compareTo(DATE) < 0;
}
});
// join by ORDERKEY
DataSet<Tuple2<Integer, Double>> joined = lineItemRevenue
.join(orders)
.where(0)
.equalTo(0)
// modify / cleanup tuple format
.map(new MapFunction<Tuple2<Tuple2<Integer, Double>, Order>, Tuple2<Integer, Double>>() {
@Override
public Tuple2<Integer, Double> map(Tuple2<Tuple2<Integer, Double>,Order> value) throws Exception {
return value.f0;
}
})
// sort by revenue (desc) <-- only partition-wise
.sortPartition(1, org.apache.flink.api.common.operators.Order.DESCENDING)
;
// save results
joined.writeAsCsv(resultFile, "\n", "\t", WriteMode.OVERWRITE);
/*/
//*/
|
package com.kevinejohn.RNMixpanel;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class RNMixpanelModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
ReactApplicationContext reactContext;
MixpanelAPI mixpanel;
public RNMixpanelModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
// Get lifecycle notifications to flush mixpanel on pause or destroy
reactContext.addLifecycleEventListener(this);
}
@Override
public String getName() {
return "RNMixpanel";
}
@ReactMethod
public void sharedInstanceWithToken(final String token) {
mixpanel = MixpanelAPI.getInstance(reactContext, token);
}
// Is there a better way to convert ReadableMap to JSONObject?
// I only found this:
static JSONObject reactToJSON(ReadableMap readableMap) throws JSONException {
JSONObject jsonObject = new JSONObject();
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
while(iterator.hasNextKey()){
String key = iterator.nextKey();
ReadableType valueType = readableMap.getType(key);
switch (valueType){
case Null:
jsonObject.put(key,JSONObject.NULL);
break;
case Boolean:
jsonObject.put(key, readableMap.getBoolean(key));
break;
case Number:
jsonObject.put(key, readableMap.getDouble(key));
break;
case String:
jsonObject.put(key, readableMap.getString(key));
break;
case Map:
jsonObject.put(key, reactToJSON(readableMap.getMap(key)));
break;
case Array:
jsonObject.put(key, reactToJSON(readableMap.getArray(key)));
break;
}
}
return jsonObject;
}
static JSONArray reactToJSON(ReadableArray readableArray) throws JSONException {
JSONArray jsonArray = new JSONArray();
for(int i=0; i < readableArray.size(); i++) {
ReadableType valueType = readableArray.getType(i);
switch (valueType){
case Null:
jsonArray.put(JSONObject.NULL);
break;
case Boolean:
jsonArray.put(readableArray.getBoolean(i));
break;
case Number:
jsonArray.put(readableArray.getDouble(i));
break;
case String:
jsonArray.put(readableArray.getString(i));
break;
case Map:
jsonArray.put(reactToJSON(readableArray.getMap(i)));
break;
case Array:
jsonArray.put(reactToJSON(readableArray.getArray(i)));
break;
}
}
return jsonArray;
}
@ReactMethod
public void track(final String name) {
mixpanel.track(name);
}
@ReactMethod
public void trackWithProperties(final String name, final ReadableMap properties) {
JSONObject obj = null;
try {
obj = RNMixpanelModule.reactToJSON(properties);
} catch (JSONException e) {
e.printStackTrace();
}
mixpanel.track(name, obj);
}
@ReactMethod
public void createAlias(final String old_id) {
mixpanel.alias(old_id, mixpanel.getDistinctId());
}
@ReactMethod
public void identify(final String user_id) {
mixpanel.identify(user_id);
mixpanel.getPeople().identify(user_id);
}
@ReactMethod
public void timeEvent(final String event) {
mixpanel.timeEvent(event);
}
@ReactMethod
public void registerSuperProperties(final ReadableMap properties) {
JSONObject obj = null;
try {
obj = RNMixpanelModule.reactToJSON(properties);
} catch (JSONException e) {
e.printStackTrace();
}
mixpanel.registerSuperProperties(obj);
}
@ReactMethod
public void registerSuperPropertiesOnce(final ReadableMap properties) {
JSONObject obj = null;
try {
obj = RNMixpanelModule.reactToJSON(properties);
} catch (JSONException e) {
e.printStackTrace();
}
mixpanel.registerSuperPropertiesOnce(obj);
}
@ReactMethod
public void set(final ReadableMap properties) {
JSONObject obj = null;
try {
obj = RNMixpanelModule.reactToJSON(properties);
} catch (JSONException e) {
e.printStackTrace();
}
mixpanel.getPeople().set(obj);
}
@ReactMethod
public void setOnce(final ReadableMap properties) {
JSONObject obj = null;
try {
obj = RNMixpanelModule.reactToJSON(properties);
} catch (JSONException e) {
e.printStackTrace();
}
mixpanel.getPeople().setOnce(obj);
}
// Android only
@ReactMethod
public void setPushRegistrationId(final String token) {
mixpanel.getPeople().setPushRegistrationId(token);
}
// Android only
@ReactMethod
public void clearPushRegistrationId() {
mixpanel.getPeople().clearPushRegistrationId();
}
@ReactMethod
public void trackCharge(final double charge) {
mixpanel.getPeople().trackCharge(charge, null);
}
@ReactMethod
public void trackChargeWithProperties(final double charge, final ReadableMap properties) {
JSONObject obj = null;
try {
obj = RNMixpanelModule.reactToJSON(properties);
} catch (JSONException e) {
e.printStackTrace();
}
mixpanel.getPeople().trackCharge(charge, obj);
}
@ReactMethod
public void increment(final String property, final double count) {
mixpanel.getPeople().increment(property, count);
}
@ReactMethod
public void reset() {
mixpanel.reset();
mixpanel.flush();
}
@ReactMethod
public void flush() {
mixpanel.flush();
}
@ReactMethod
public void initPushHandling(final String gcmSenderId) {
mixpanel.getPeople().initPushHandling(gcmSenderId);
}
@Override
public void onHostResume() {
// Actvity `onResume`
}
@Override
public void onHostPause() {
// Actvity `onPause`
if (mixpanel != null) {
mixpanel.flush();
}
}
@Override
public void onHostDestroy() {
// Actvity `onDestroy`
if (mixpanel != null) {
mixpanel.flush();
}
}
// @ReactMethod
// public void getDistinctId(Callback callback) {
// callback.invoke(mixpanel.getDistinctId());
}
|
package com.reactlibrary;
import android.app.Activity;
import android.widget.Toast;
import android.content.Intent;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
public class RNGooglePlacePickerModule extends ReactContextBaseJavaModule implements ActivityEventListener {
private final ReactApplicationContext reactContext;
private Callback mCallback;
WritableMap response;
private static final int REQUEST_PLACE_PICKER = 1;
public RNGooglePlacePickerModule(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addActivityEventListener(this);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNGooglePlacePicker";
}
@ReactMethod
public void show(final Callback callback) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
response.putString("error", "can't find current Activity");
callback.invoke(response);
return;
}
try {
PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(currentActivity);
mCallback = callback;
currentActivity.startActivityForResult(intent, REQUEST_PLACE_PICKER);
} catch (GooglePlayServicesRepairableException e) {
response = Arguments.createMap();
response.putString("error", "GooglePlayServicesRepairableException");
callback.invoke(response);
GooglePlayServicesUtil
.getErrorDialog(e.getConnectionStatusCode(), currentActivity, 0);
} catch (GooglePlayServicesNotAvailableException e) {
response = Arguments.createMap();
response.putString("error", "Google Play Services is not available.");
callback.invoke(response);
Toast.makeText(currentActivity, "Google Play Services is not available.",
Toast.LENGTH_LONG)
.show();
}
}
// removed @Override temporarily just to get it working on different versions of RN
public void onActivityResult(final Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (mCallback == null || requestCode != REQUEST_PLACE_PICKER) {
return;
}
response = Arguments.createMap();
if (resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(data, reactContext);
final CharSequence address = place.getAddress();
final LatLng coordinate = place.getLatLng();
final CharSequence name = place.getName();
final CharSequence id = place.getId();
response.putString("address", address.toString());
response.putDouble("latitude", coordinate.latitude);
response.putDouble("longitude", coordinate.longitude);
response.putString("name", name.toString());
response.putString("google_id", id.toString());
mCallback.invoke(response);
} else {
response.putBoolean("didCancel", true);
mCallback.invoke(response);
return;
}
}
// removed @Override temporarily just to get it working on different versions of RN
// Ignored, required to implement ActivityEventListener for RN < 0.33
public void onActivityResult(int requestCode, int resultCode, Intent data) {
this.onActivityResult(null, requestCode, resultCode, data);
}
/**
* Called when a new intent is passed to the activity
*/
@Override
public void onNewIntent(Intent intent){
// ToDo
}
}
|
package com.tanguyantoine.react;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.RatingCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class MusicControlModule extends ReactContextBaseJavaModule {
static MusicControlModule INSTANCE;
private boolean init = false;
protected MediaSessionCompat session;
private MediaMetadataCompat.Builder md;
private PlaybackStateCompat.Builder pb;
private NotificationCompat.Builder nb;
protected MusicControlNotification notification;
private MusicControlListener.VolumeListener volume;
private MusicControlReceiver receiver;
private boolean remoteVolume = false;
private Thread artworkThread;
private boolean isPlaying = false;
private long controls = 0;
public MusicControlModule(ReactApplicationContext context) {
super(context);
}
@Override
public String getName() {
return "MusicControlManager";
}
@Override
public Map<String, Object> getConstants() {
Map<String, Object> map = new HashMap<>();
map.put("STATE_ERROR", PlaybackStateCompat.STATE_ERROR);
map.put("STATE_STOPPED", PlaybackStateCompat.STATE_STOPPED);
map.put("STATE_PLAYING", PlaybackStateCompat.STATE_PLAYING);
map.put("STATE_PAUSED", PlaybackStateCompat.STATE_PAUSED);
map.put("STATE_BUFFERING", PlaybackStateCompat.STATE_BUFFERING);
return map;
}
public void init() {
INSTANCE = this;
ReactApplicationContext context = getReactApplicationContext();
ComponentName compName = new ComponentName(context, MusicControlReceiver.class);
session = new MediaSessionCompat(context, "MusicControl", compName, null);
session.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
session.setCallback(new MusicControlListener(context));
volume = new MusicControlListener.VolumeListener(context, true, 100, 100);
if(remoteVolume) {
session.setPlaybackToRemote(volume);
} else {
session.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
}
md = new MediaMetadataCompat.Builder();
pb = new PlaybackStateCompat.Builder();
pb.setActions(controls);
nb = new NotificationCompat.Builder(context);
nb.setStyle(new NotificationCompat.MediaStyle().setMediaSession(session.getSessionToken()));
notification = new MusicControlNotification(context);
notification.updateActions(controls);
IntentFilter filter = new IntentFilter();
filter.addAction(MusicControlNotification.REMOVE_NOTIFICATION);
filter.addAction(MusicControlNotification.MEDIA_BUTTON);
filter.addAction(Intent.ACTION_MEDIA_BUTTON);
receiver = new MusicControlReceiver(this, context.getPackageName());
context.registerReceiver(receiver, filter);
context.startService(new Intent(context, MusicControlNotification.NotificationService.class));
isPlaying = false;
init = true;
}
public void destroy() {
notification.hide();
session.release();
getReactApplicationContext().unregisterReceiver(receiver);
if(artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt();
artworkThread = null;
session = null;
notification = null;
volume = null;
receiver = null;
md = null;
pb = null;
nb = null;
init = false;
}
@ReactMethod
public void enableBackgroundMode(boolean enable) {
// Nothing?
}
@ReactMethod
public void setNowPlaying(ReadableMap metadata) {
if(!init) init();
if(artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt();
String title = metadata.hasKey("title") ? metadata.getString("title") : null;
String artist = metadata.hasKey("artist") ? metadata.getString("artist") : null;
String album = metadata.hasKey("album") ? metadata.getString("album") : null;
String genre = metadata.hasKey("genre") ? metadata.getString("genre") : null;
String description = metadata.hasKey("description") ? metadata.getString("description") : null;
String date = metadata.hasKey("date") ? metadata.getString("date") : null;
RatingCompat rating = metadata.hasKey("rating") ? RatingCompat.newPercentageRating(metadata.getInt("rating")) : RatingCompat.newUnratedRating(RatingCompat.RATING_PERCENTAGE);
final String artwork = metadata.hasKey("artwork") ? metadata.getString("artwork") : null;
long duration = metadata.hasKey("duration") ? (long)(metadata.getDouble("duration") * 1000) : 0;
int notificationColor = metadata.hasKey("color") ? metadata.getInt("color") : NotificationCompat.COLOR_DEFAULT;
md.putText(MediaMetadataCompat.METADATA_KEY_TITLE, title);
md.putText(MediaMetadataCompat.METADATA_KEY_ARTIST, artist);
md.putText(MediaMetadataCompat.METADATA_KEY_ALBUM, album);
md.putText(MediaMetadataCompat.METADATA_KEY_GENRE, genre);
md.putText(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, description);
md.putText(MediaMetadataCompat.METADATA_KEY_DATE, date);
md.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration);
md.putRating(MediaMetadataCompat.METADATA_KEY_RATING, rating);
nb.setContentTitle(title);
nb.setContentText(artist);
nb.setContentInfo(album);
nb.setColor(notificationColor);
if(artwork != null) {
artworkThread = new Thread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = loadArtwork(artwork);
md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap);
nb.setLargeIcon(bitmap);
session.setMetadata(md.build());
notification.show(nb, isPlaying);
artworkThread = null;
}
});
artworkThread.start();
} else {
md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, null);
nb.setLargeIcon(null);
}
session.setMetadata(md.build());
session.setActive(true);
notification.show(nb, isPlaying);
}
@ReactMethod
public void setPlayback(ReadableMap info) {
if(!init) init();
long elapsedTime = info.hasKey("elapsedTime") ? (long)(info.getDouble("elapsedTime") * 1000) : 0;
long bufferedTime = info.hasKey("bufferedTime") ? (long)(info.getDouble("bufferedTime") * 1000) : 0;
float speed = info.hasKey("speed") ? (float)info.getDouble("speed") : 1;
int state = info.hasKey("state") ? info.getInt("state") : PlaybackStateCompat.STATE_NONE;
int maxVol = info.hasKey("maxVolume") ? info.getInt("maxVol") : 100;
int vol = info.hasKey("volume") ? info.getInt("volume") : maxVol;
pb.setState(state, elapsedTime, speed);
pb.setBufferedPosition(bufferedTime);
isPlaying = state == PlaybackStateCompat.STATE_PLAYING || state == PlaybackStateCompat.STATE_BUFFERING;
notification.show(nb, isPlaying);
PlaybackStateCompat playbackState = pb.build();
session.setPlaybackState(playbackState);
if(remoteVolume) {
session.setPlaybackToRemote(volume.create(null, maxVol, vol));
} else {
session.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
}
}
@ReactMethod
public void resetNowPlaying() {
if(!init) return;
if(artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt();
artworkThread = null;
md = new MediaMetadataCompat.Builder();
pb = new PlaybackStateCompat.Builder();
notification.hide();
session.setActive(false);
}
@ReactMethod
public void enableControl(String control, boolean enable) {
if(!init) init();
long controlValue;
switch(control) {
case "nextTrack":
controlValue = PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
break;
case "previousTrack":
controlValue = PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
break;
case "play":
controlValue = PlaybackStateCompat.ACTION_PLAY;
break;
case "pause":
controlValue = PlaybackStateCompat.ACTION_PAUSE;
break;
case "togglePlayPause":
controlValue = PlaybackStateCompat.ACTION_PLAY_PAUSE;
break;
case "stop":
controlValue = PlaybackStateCompat.ACTION_STOP;
break;
case "seek":
controlValue = PlaybackStateCompat.ACTION_SEEK_TO;
break;
case "seekForward":
controlValue = PlaybackStateCompat.ACTION_FAST_FORWARD;
break;
case "seekBackward":
controlValue = PlaybackStateCompat.ACTION_REWIND;
break;
case "rate":
controlValue = PlaybackStateCompat.ACTION_SET_RATING;
break;
case "volume":
volume = volume.create(enable, null, null);
if(remoteVolume) {
session.setPlaybackToRemote(volume);
} else {
session.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
}
return;
case "remoteVolume":
remoteVolume = enable;
if(enable) {
session.setPlaybackToRemote(volume);
} else {
session.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
}
default:
// Unknown control type, let's just ignore it
return;
}
if(enable) {
controls |= controlValue;
} else {
controls &= ~controlValue;
}
notification.updateActions(controls);
pb.setActions(controls);
session.setPlaybackState(pb.build());
}
private Bitmap loadArtwork(String url) {
Bitmap bitmap = null;
try {
if(url.matches("^(https?|ftp)://.*$")) { // URL
URLConnection con = new URL(url).openConnection();
con.connect();
InputStream input = con.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
input.close();
} else { // File
bitmap = BitmapFactory.decodeFile(url);
}
} catch(IOException ex) {
Log.w("MusicControl", "Could not load the artwork", ex);
}
return bitmap;
}
}
|
package com.capitalone.dashboard.logging;
import com.capitalone.dashboard.model.RequestLog;
import com.capitalone.dashboard.repository.RequestLogRepository;
import com.capitalone.dashboard.settings.ApiSettings;
import com.mongodb.util.JSON;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
//import org.springframework.util.MimeType;
public class LoggingFilter implements Filter {
private static final Logger LOGGER = Logger.getLogger(LoggingFilter.class);
@Autowired
private RequestLogRepository requestLogRepository;
@Autowired
private ApiSettings settings;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (httpServletRequest.getMethod().equals(HttpMethod.PUT.toString()) ||
(httpServletRequest.getMethod().equals(HttpMethod.POST.toString())) ||
(httpServletRequest.getMethod().equals(HttpMethod.DELETE.toString()))) {
Map<String, String> requestMap = this.getTypesafeRequestMap(httpServletRequest);
BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpServletRequest);
BufferedResponseWrapper bufferedResponse = new BufferedResponseWrapper(httpServletResponse);
long startTime = System.currentTimeMillis();
RequestLog requestLog = new RequestLog();
requestLog.setClient(httpServletRequest.getRemoteAddr());
requestLog.setEndpoint(httpServletRequest.getRequestURI());
requestLog.setMethod(httpServletRequest.getMethod());
requestLog.setParameter(requestMap.toString());
requestLog.setRequestSize(httpServletRequest.getContentLengthLong());
requestLog.setRequestContentType(httpServletRequest.getContentType());
chain.doFilter(bufferedRequest, bufferedResponse);
requestLog.setResponseContentType(httpServletResponse.getContentType());
try {
if ((httpServletRequest.getContentType() != null) && (new MimeType(httpServletRequest.getContentType()).match(new MimeType(APPLICATION_JSON_VALUE)))) {
requestLog.setRequestBody(JSON.parse(bufferedRequest.getRequestBody()));
}
if ((bufferedResponse.getContentType() != null) && (new MimeType(bufferedResponse.getContentType()).match(new MimeType(APPLICATION_JSON_VALUE)))){
requestLog.setResponseBody(JSON.parse(bufferedResponse.getContent()));
}
} catch (MimeTypeParseException e) {
LOGGER.error("Invalid MIME Type detected. Request MIME type=" + httpServletRequest.getContentType() + ". Response MIME Type=" + bufferedResponse.getContentType());
}
requestLog.setResponseSize(bufferedResponse.getContent().length());
requestLog.setResponseCode(bufferedResponse.getStatus());
long endTime = System.currentTimeMillis();
requestLog.setResponseTime(endTime - startTime);
requestLog.setTimestamp(endTime);
try {
requestLogRepository.save(requestLog);
} catch (RuntimeException re) {
LOGGER.info(requestLog.toString());
}
} else {
if (settings.isCorsEnabled()) {
String clientOrigin = httpServletRequest.getHeader("Origin");
String corsWhitelist = settings.getCorsWhitelist();
if (!StringUtils.isEmpty(corsWhitelist)) {
List<String> incomingURLs = Arrays.asList(corsWhitelist.trim().split(","));
if (incomingURLs.contains(clientOrigin)) {
//adds headers to response to allow CORS
httpServletResponse.addHeader("Access-Control-Allow-Origin", clientOrigin);
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type");
httpServletResponse.addHeader("Access-Control-Max-Age", "1");
}
}
}
chain.doFilter(request, response);
}
}
private Map<String, String> getTypesafeRequestMap(HttpServletRequest request) {
Map<String, String> typesafeRequestMap = new HashMap<>();
Enumeration<?> requestParamNames = request.getParameterNames();
if (requestParamNames != null) {
while (requestParamNames.hasMoreElements()) {
String requestParamName = (String) requestParamNames.nextElement();
String requestParamValue = request.getParameter(requestParamName);
typesafeRequestMap.put(requestParamName, requestParamValue);
}
}
return typesafeRequestMap;
}
@Override
public void destroy() {
}
private static final class BufferedRequestWrapper extends HttpServletRequestWrapper {
private ByteArrayInputStream bais = null;
private ByteArrayOutputStream baos = null;
private BufferedServletInputStream bsis = null;
private byte[] buffer = null;
public BufferedRequestWrapper(HttpServletRequest req) throws IOException {
super(req);
// Read InputStream and store its content in a buffer.
this.baos = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int letti;
try (InputStream is = req.getInputStream()) {
while ((letti = is.read(buf)) > 0) {
this.baos.write(buf, 0, letti);
}
}
this.buffer = this.baos.toByteArray();
}
@Override
public ServletInputStream getInputStream() {
this.bais = new ByteArrayInputStream(this.buffer);
this.bsis = new BufferedServletInputStream(this.bais);
return this.bsis;
}
String getRequestBody() throws IOException {
String line;
StringBuilder inputBuffer = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(this.getInputStream()))) {
do {
line = reader.readLine();
if (null != line) {
inputBuffer.append(line);
}
} while (line != null);
}
return inputBuffer.toString();
}
}
private static final class BufferedServletInputStream extends ServletInputStream {
private ByteArrayInputStream bais;
public BufferedServletInputStream(ByteArrayInputStream bais) {
this.bais = bais;
}
@Override
public int available() {
return this.bais.available();
}
@Override
public int read() {
return this.bais.read();
}
@Override
public int read(byte[] buf, int off, int len) {
return this.bais.read(buf, off, len);
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
}
public class TeeServletOutputStream extends ServletOutputStream {
private final TeeOutputStream targetStream;
public TeeServletOutputStream(OutputStream one, OutputStream two) {
targetStream = new TeeOutputStream(one, two);
}
@Override
public void write(int arg0) throws IOException {
this.targetStream.write(arg0);
}
public void flush() throws IOException {
super.flush();
this.targetStream.flush();
}
public void close() throws IOException {
super.close();
this.targetStream.close();
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
}
public class BufferedResponseWrapper implements HttpServletResponse {
private HttpServletResponse original;
private TeeServletOutputStream teeStream;
private ByteArrayOutputStream bos;
private PrintWriter teeWriter;
public BufferedResponseWrapper(HttpServletResponse response) {
original = response;
}
public String getContent() {
return (bos == null) ? "" : bos.toString();
}
@Override
public PrintWriter getWriter() throws IOException {
if (this.teeWriter == null) {
this.teeWriter = new PrintWriter(new OutputStreamWriter(getOutputStream()));
}
return this.teeWriter;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (LoggingFilter.BufferedResponseWrapper.this.teeStream == null) {
bos = new ByteArrayOutputStream();
LoggingFilter.BufferedResponseWrapper.this.teeStream = new TeeServletOutputStream(original.getOutputStream(), bos);
}
return LoggingFilter.BufferedResponseWrapper.this.teeStream;
}
@Override
public String getCharacterEncoding() {
return original.getCharacterEncoding();
}
@Override
public String getContentType() {
return original.getContentType();
}
@Override
public void setCharacterEncoding(String charset) {
original.setCharacterEncoding(charset);
}
@Override
public void setContentLength(int len) {
original.setContentLength(len);
}
@Override
public void setContentLengthLong(long l) {
}
@Override
public void setContentType(String type) {
original.setContentType(type);
}
@Override
public void setBufferSize(int size) {
original.setBufferSize(size);
}
@Override
public int getBufferSize() {
return original.getBufferSize();
}
@Override
public void flushBuffer() throws IOException {
if (teeStream != null) {
teeStream.flush();
}
if (this.teeWriter != null) {
this.teeWriter.flush();
}
}
@Override
public void resetBuffer() {
original.resetBuffer();
}
@Override
public boolean isCommitted() {
return original.isCommitted();
}
@Override
public void reset() {
original.reset();
}
@Override
public void setLocale(Locale loc) {
original.setLocale(loc);
}
@Override
public Locale getLocale() {
return original.getLocale();
}
@Override
public void addCookie(Cookie cookie) {
original.addCookie(cookie);
}
@Override
public boolean containsHeader(String name) {
return original.containsHeader(name);
}
@Override
public String encodeURL(String url) {
return original.encodeURL(url);
}
@Override
public String encodeRedirectURL(String url) {
return original.encodeRedirectURL(url);
}
@SuppressWarnings("deprecation")
@Override
public String encodeUrl(String url) {
return original.encodeUrl(url);
}
@SuppressWarnings("deprecation")
@Override
public String encodeRedirectUrl(String url) {
return original.encodeRedirectUrl(url);
}
@Override
public void sendError(int sc, String msg) throws IOException {
original.sendError(sc, msg);
}
@Override
public void sendError(int sc) throws IOException {
original.sendError(sc);
}
@Override
public void sendRedirect(String location) throws IOException {
original.sendRedirect(location);
}
@Override
public void setDateHeader(String name, long date) {
original.setDateHeader(name, date);
}
@Override
public void addDateHeader(String name, long date) {
original.addDateHeader(name, date);
}
@Override
public void setHeader(String name, String value) {
original.setHeader(name, value);
}
@Override
public void addHeader(String name, String value) {
original.addHeader(name, value);
}
@Override
public void setIntHeader(String name, int value) {
original.setIntHeader(name, value);
}
@Override
public void addIntHeader(String name, int value) {
original.addIntHeader(name, value);
}
@Override
public void setStatus(int sc) {
original.setStatus(sc);
}
@SuppressWarnings("deprecation")
@Override
public void setStatus(int sc, String sm) {
original.setStatus(sc, sm);
}
@Override
public int getStatus() {
return original.getStatus();
}
@Override
public String getHeader(String s) {
return null;
}
@Override
public Collection<String> getHeaders(String s) {
return null;
}
@Override
public Collection<String> getHeaderNames() {
return null;
}
}
}
|
package de.joerghoh.cq5.healthcheck;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SystemHealthStatus {
private Logger log = LoggerFactory.getLogger(SystemHealthStatus.class);
private List<HealthStatus> results;
private int status;
private String monitoringMessage;
public SystemHealthStatus (int status, List<HealthStatus> items, String message) {
this.status = status;
results = items;
monitoringMessage = message;
}
public String getStatus() {
switch (status) {
case HealthStatusProvider.OK: return "OK";
case HealthStatusProvider.WARN: return "WARN";
case HealthStatusProvider.CRITICAL: return "CRITICAL";
default: log.error("Invalid status: " + status); return "UNKNOWN";
}
}
public List<HealthStatus> getDetails() {
return results;
}
public String getMonitoringMessage () {
return monitoringMessage;
}
}
|
package net.Ox4a42.volksempfaenger.feedparser;
public class Enclosure {
private String title, url, mime;
private int size;
private FeedItem feedItem;
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
public String getMime() {
return mime;
}
public int getSize() {
return size;
}
public FeedItem getFeedItem() {
return feedItem;
}
public void setTitle(String title) {
this.title = title;
}
public void setUrl(String url) {
this.url = url;
}
public void setMime(String mime) {
this.mime = mime;
}
public void setSize(int size) {
this.size = size;
}
public void setFeedItem(FeedItem feedItem) {
this.feedItem = feedItem;
}
}
|
package org.pmiops.workbench.db.dao;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryParameterValue;
import com.google.cloud.bigquery.TableResult;
import com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.inject.Provider;
import org.pmiops.workbench.api.BigQueryService;
import org.pmiops.workbench.cdr.ConceptBigQueryService;
import org.pmiops.workbench.cohortbuilder.CohortQueryBuilder;
import org.pmiops.workbench.cohortbuilder.ParticipantCriteria;
import org.pmiops.workbench.config.CdrBigQuerySchemaConfig;
import org.pmiops.workbench.config.CdrBigQuerySchemaConfigService;
import org.pmiops.workbench.config.WorkbenchConfig;
import org.pmiops.workbench.db.model.Cohort;
import org.pmiops.workbench.db.model.CommonStorageEnums;
import org.pmiops.workbench.db.model.ConceptSet;
import org.pmiops.workbench.db.model.DataSet;
import org.pmiops.workbench.db.model.DataSetValues;
import org.pmiops.workbench.exceptions.BadRequestException;
import org.pmiops.workbench.exceptions.NotFoundException;
import org.pmiops.workbench.exceptions.ServerErrorException;
import org.pmiops.workbench.model.DataSetRequest;
import org.pmiops.workbench.model.Domain;
import org.pmiops.workbench.model.DomainValuePair;
import org.pmiops.workbench.model.KernelTypeEnum;
import org.pmiops.workbench.model.PrePackagedConceptSetEnum;
import org.pmiops.workbench.model.SearchRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/*
* A subclass to store the associated set of selects and joins for values for the data set builder.
*
* This is used to store the data pulled out of the linking table in bigquery.
*/
/*
* A subclass used to store a source and a standard concept ID column name.
*/
class DomainConceptIds {
private String sourceConceptIdColumn;
private String standardConceptIdColumn;
DomainConceptIds(String sourceConceptIdColumn, String standardConceptIdColumn) {
this.sourceConceptIdColumn = sourceConceptIdColumn;
this.standardConceptIdColumn = standardConceptIdColumn;
}
public String getSourceConceptIdColumn() {
return this.sourceConceptIdColumn;
}
public String getStandardConceptIdColumn() {
return this.standardConceptIdColumn;
}
}
@Service
public class DataSetServiceImpl implements DataSetService {
@VisibleForTesting
private static class ValuesLinkingPair {
private List<String> selects;
private List<String> joins;
private ValuesLinkingPair(List<String> selects, List<String> joins) {
this.selects = selects;
this.joins = joins;
}
private List<String> getSelects() {
return this.selects;
}
private List<String> getJoins() {
return this.joins;
}
}
private CohortQueryBuilder cohortQueryBuilder;
private ConceptBigQueryService conceptBigQueryService;
private BigQueryService bigQueryService;
private CdrBigQuerySchemaConfigService cdrBigQuerySchemaConfigService;
private Provider<WorkbenchConfig> configProvider;
@Autowired DataSetDao dataSetDao;
@Autowired ConceptSetDao conceptSetDao;
@Autowired CohortDao cohortDao;
@Autowired
@VisibleForTesting
public DataSetServiceImpl(
BigQueryService bigQueryService,
CdrBigQuerySchemaConfigService cdrBigQuerySchemaConfigService,
CohortDao cohortDao,
ConceptBigQueryService conceptBigQueryService,
ConceptSetDao conceptSetDao,
CohortQueryBuilder cohortQueryBuilder,
Provider<WorkbenchConfig> configProvider) {
this.bigQueryService = bigQueryService;
this.cdrBigQuerySchemaConfigService = cdrBigQuerySchemaConfigService;
this.cohortDao = cohortDao;
this.conceptBigQueryService = conceptBigQueryService;
this.conceptSetDao = conceptSetDao;
this.cohortQueryBuilder = cohortQueryBuilder;
this.configProvider = configProvider;
}
@Override
public DataSet saveDataSet(
String name,
Boolean includesAllParticipants,
String description,
long workspaceId,
List<Long> cohortIdList,
List<Long> conceptIdList,
List<DataSetValues> values,
PrePackagedConceptSetEnum prePackagedConceptSetEnum,
long creatorId,
Timestamp creationTime) {
DataSet dataSetDb = new DataSet();
dataSetDb.setName(name);
dataSetDb.setVersion(1);
dataSetDb.setIncludesAllParticipants(includesAllParticipants);
dataSetDb.setDescription(description);
dataSetDb.setWorkspaceId(workspaceId);
dataSetDb.setInvalid(false);
dataSetDb.setCreatorId(creatorId);
dataSetDb.setCreationTime(creationTime);
dataSetDb.setCohortSetId(cohortIdList);
dataSetDb.setConceptSetId(conceptIdList);
dataSetDb.setValues(values);
dataSetDb.setPrePackagedConceptSetEnum(prePackagedConceptSetEnum);
dataSetDb = dataSetDao.save(dataSetDb);
return dataSetDb;
}
@Override
public Map<String, QueryJobConfiguration> generateQuery(DataSetRequest dataSet) {
CdrBigQuerySchemaConfig bigQuerySchemaConfig = cdrBigQuerySchemaConfigService.getConfig();
boolean includesAllParticipants =
Optional.of(dataSet.getIncludesAllParticipants()).orElse(false);
Map<String, QueryJobConfiguration> dataSetUtil = new HashMap<>();
List<Cohort> cohortsSelected = this.cohortDao.findAllByCohortIdIn(dataSet.getCohortIds());
List<org.pmiops.workbench.db.model.ConceptSet> conceptSetsSelected =
this.conceptSetDao.findAllByConceptSetIdIn(dataSet.getConceptSetIds());
if (((cohortsSelected == null || cohortsSelected.size() == 0) && !includesAllParticipants)
|| conceptSetsSelected == null
|| ((conceptSetsSelected.size() == 0
&& dataSet.getPrePackagedConceptSet().equals(PrePackagedConceptSetEnum.NONE))
&& dataSet.getValues().size() == 0)) {
throw new BadRequestException("Data Sets must include at least one cohort and concept.");
}
Map<String, QueryParameterValue> cohortParameters = new HashMap<>();
// Below constructs the union of all cohort queries
String cohortQueries =
cohortsSelected.stream()
.map(
c -> {
String cohortDefinition = c.getCriteria();
if (cohortDefinition == null) {
throw new NotFoundException(
String.format(
"Not Found: No Cohort definition matching cohortId: %s",
c.getCohortId()));
}
SearchRequest searchRequest =
new Gson().fromJson(cohortDefinition, SearchRequest.class);
QueryJobConfiguration participantIdQuery =
cohortQueryBuilder.buildParticipantIdQuery(
new ParticipantCriteria(searchRequest));
QueryJobConfiguration participantQueryConfig =
bigQueryService.filterBigQueryConfig(participantIdQuery);
AtomicReference<String> participantQuery =
new AtomicReference<>(participantQueryConfig.getQuery());
participantQueryConfig
.getNamedParameters()
.forEach(
(npKey, npValue) -> {
String newKey = npKey + "_" + c.getCohortId();
participantQuery.getAndSet(
participantQuery
.get()
.replaceAll("\\b".concat(npKey).concat("\\b"), newKey));
cohortParameters.put(newKey, npValue);
});
return participantQuery.get();
})
.collect(Collectors.joining(" UNION DISTINCT "));
List<Domain> domainList =
dataSet.getValues().stream().map(value -> value.getDomain()).collect(Collectors.toList());
// If pre packaged all survey concept set is selected create a temp concept set with concept ids
// of all survey question
if (PrePackagedConceptSetEnum.SURVEY.equals(dataSet.getPrePackagedConceptSet())
|| PrePackagedConceptSetEnum.BOTH.equals(dataSet.getPrePackagedConceptSet())) {
conceptSetsSelected.add(handlePrePackagedSurveyConceptSet());
}
for (Domain d : domainList) {
Map<String, Map<String, QueryParameterValue>> queryMap = new HashMap<>();
String query = "SELECT ";
// VALUES HERE:
Optional<List<DomainValuePair>> valueSetOpt =
Optional.of(
dataSet.getValues().stream()
.filter(valueSet -> valueSet.getDomain() == d)
.collect(Collectors.toList()));
if (!valueSetOpt.isPresent()) {
continue;
}
ValuesLinkingPair valuesLinkingPair = this.getValueSelectsAndJoins(valueSetOpt.get(), d);
query =
query
.concat(valuesLinkingPair.getSelects().stream().collect(Collectors.joining(", ")))
.concat(" ")
.concat(
valuesLinkingPair.getJoins().stream()
.distinct()
.collect(Collectors.joining(" ")));
// CONCEPT SETS HERE:
conceptSetsSelected.stream()
.map(conceptSet -> conceptSet.getDomain())
.distinct()
.filter(cs -> d != Domain.PERSON)
.forEach(
domain -> {
if (conceptSetsSelected.stream()
.filter(conceptSet -> conceptSet.getDomain() == domain)
.mapToLong(conceptSet -> conceptSet.getConceptIds().size())
.sum()
== 0) {
throw new BadRequestException("Concept Sets must contain at least one concept");
}
});
String conceptSetQueries =
conceptSetsSelected.stream()
.filter(cs -> d == cs.getDomainEnum())
.filter(cs -> d != Domain.PERSON)
.flatMap(cs -> cs.getConceptIds().stream().map(cid -> Long.toString(cid)))
.collect(Collectors.joining(", "));
String conceptSetListQuery = " IN (" + conceptSetQueries + ")";
if (d != Domain.PERSON) {
Optional<DomainConceptIds> domainConceptIds =
bigQuerySchemaConfig.cohortTables.values().stream()
.filter(config -> d.toString().equals(config.domain))
.map(
tableConfig ->
new DomainConceptIds(
getColumnName(tableConfig, "source"),
getColumnName(tableConfig, "standard")))
.findFirst();
if (!domainConceptIds.isPresent()) {
throw new ServerErrorException(
"Couldn't find source and standard columns for domain: " + d.toString());
}
DomainConceptIds columnNames = domainConceptIds.get();
// This adds the where clauses for cohorts and concept sets.
query =
query.concat(
" WHERE \n("
+ columnNames.getStandardConceptIdColumn()
+ conceptSetListQuery
+ " OR \n"
+ columnNames.getSourceConceptIdColumn()
+ conceptSetListQuery
+ ")");
if (!includesAllParticipants) {
query = query.concat(" \nAND (PERSON_ID IN (" + cohortQueries + "))");
}
} else if (!includesAllParticipants) {
query = query.concat(" \nWHERE PERSON_ID IN (" + cohortQueries + ")");
}
queryMap.put(query, cohortParameters);
QueryJobConfiguration queryJobConfiguration =
bigQueryService.filterBigQueryConfig(
QueryJobConfiguration.newBuilder(query)
.setNamedParameters(cohortParameters)
.setUseLegacySql(false)
.build());
dataSetUtil.put(d.toString(), queryJobConfiguration);
}
return dataSetUtil;
}
@Override
public List<String> generateCodeCellPerDomainFromQueryAndKernelType(
KernelTypeEnum kernelTypeEnum,
String dataSetName,
Map<String, QueryJobConfiguration> queryJobConfigurationMap) {
String prerequisites;
switch (kernelTypeEnum) {
case R:
prerequisites =
"install.packages(\"reticulate\")\n"
+ "library(reticulate)\n"
+ "pd <- reticulate::import(\"pandas\")";
break;
case PYTHON:
prerequisites = "import pandas";
break;
default:
throw new BadRequestException(
"Kernel Type " + kernelTypeEnum.toString() + " not supported");
}
return queryJobConfigurationMap.entrySet().stream()
.map(
entry ->
prerequisites
+ "\n\n"
+ convertQueryToString(
entry.getValue(),
Domain.fromValue(entry.getKey()),
dataSetName,
kernelTypeEnum))
.collect(Collectors.toList());
}
private String getColumnName(CdrBigQuerySchemaConfig.TableConfig config, String type) {
Optional<CdrBigQuerySchemaConfig.ColumnConfig> conceptColumn =
config.columns.stream().filter(column -> type.equals(column.domainConcept)).findFirst();
if (!conceptColumn.isPresent()) {
throw new ServerErrorException("Domain not supported");
}
return conceptColumn.get().name;
}
@VisibleForTesting
public ValuesLinkingPair getValueSelectsAndJoins(List<DomainValuePair> valueSetList, Domain d) {
List<String> values =
valueSetList.stream()
.map(valueSet -> valueSet.getValue().toUpperCase())
.collect(Collectors.toList());
values.add(0, "CORE_TABLE_FOR_DOMAIN");
String domainAsName = d.toString().charAt(0) + d.toString().substring(1).toLowerCase();
String valuesQuery =
"SELECT * FROM `${projectId}.${dataSetId}.ds_linking` "
+ "WHERE DOMAIN = @pDomain AND DENORMALIZED_NAME in unnest(@pValuesList)";
Map<String, QueryParameterValue> valuesQueryParams = new HashMap<>();
valuesQueryParams.put("pDomain", QueryParameterValue.string(domainAsName));
valuesQueryParams.put(
"pValuesList", QueryParameterValue.array(values.toArray(new String[0]), String.class));
TableResult valuesLinking =
bigQueryService.executeQuery(
bigQueryService.filterBigQueryConfig(
QueryJobConfiguration.newBuilder(valuesQuery)
.setNamedParameters(valuesQueryParams)
.setUseLegacySql(false)
.build()));
List<String> valueJoins = new ArrayList<>();
List<String> valueSelects = new ArrayList<>();
valuesLinking
.getValues()
.forEach(
(value) -> {
valueJoins.add(value.get("JOIN_VALUE").getStringValue());
if (!value.get("OMOP_SQL").getStringValue().equals("CORE_TABLE_FOR_DOMAIN")) {
valueSelects.add(value.get("OMOP_SQL").getStringValue());
}
});
return new ValuesLinkingPair(valueSelects, valueJoins);
}
private static String convertQueryToString(
QueryJobConfiguration queryJobConfiguration,
Domain domain,
String prefix,
KernelTypeEnum kernelTypeEnum) {
// Define [namespace]_sql, [namespace]_query_config, and [namespace]_df variables
String namespace =
prefix.toLowerCase().replaceAll(" ", "_") + "_" + domain.toString().toLowerCase() + "_";
String sqlSection;
String namedParamsSection;
String dataFrameSection;
String displayHeadSection;
switch (kernelTypeEnum) {
case PYTHON:
sqlSection = namespace + "sql = \"\"\"" + queryJobConfiguration.getQuery() + "\"\"\"";
namedParamsSection =
namespace
+ "query_config = {\n"
+ " \'query\': {\n"
+ " \'parameterMode\': \'NAMED\',\n"
+ " \'queryParameters\': [\n"
+ queryJobConfiguration.getNamedParameters().entrySet().stream()
.map(
entry ->
convertNamedParameterToString(
entry.getKey(), entry.getValue(), KernelTypeEnum.PYTHON))
.collect(Collectors.joining(",\n"))
+ "\n"
+ " ]\n"
+ " }\n"
+ "}\n\n";
dataFrameSection =
namespace
+ "df = pandas.read_gbq("
+ namespace
+ "sql, dialect=\"standard\", configuration="
+ namespace
+ "query_config)";
displayHeadSection = namespace + "df.head(5)";
break;
case R:
sqlSection = namespace + "sql <- \"" + queryJobConfiguration.getQuery() + "\"";
namedParamsSection =
namespace
+ "query_config <- list(\n"
+ " query = list(\n"
+ " parameterMode = 'NAMED',\n"
+ " queryParameters = list(\n"
+ queryJobConfiguration.getNamedParameters().entrySet().stream()
.map(
entry ->
convertNamedParameterToString(
entry.getKey(), entry.getValue(), KernelTypeEnum.R))
.collect(Collectors.joining(",\n"))
+ "\n"
+ " )\n"
+ " )\n"
+ ")";
dataFrameSection =
namespace
+ "df <- pd$read_gbq("
+ namespace
+ "sql, dialect=\"standard\", configuration="
+ namespace
+ "query_config)";
displayHeadSection = "head(" + namespace + "df, 5)";
break;
default:
throw new BadRequestException("Language " + kernelTypeEnum.toString() + " not supported.");
}
return sqlSection
+ "\n\n"
+ namedParamsSection
+ "\n\n"
+ dataFrameSection
+ "\n\n"
+ displayHeadSection;
}
// BigQuery api returns parameter values either as a list or an object.
// To avoid warnings on our cast to list, we suppress those warnings here,
// as they are expected.
@SuppressWarnings("unchecked")
private static String convertNamedParameterToString(
String key, QueryParameterValue namedParameterValue, KernelTypeEnum kernelTypeEnum) {
if (namedParameterValue == null) {
return "";
}
boolean isArrayParameter = namedParameterValue.getArrayType() != null;
List<QueryParameterValue> arrayValues =
Optional.ofNullable(namedParameterValue.getArrayValues()).orElse(new ArrayList<>());
switch (kernelTypeEnum) {
case PYTHON:
return " {\n"
+ " 'name': \""
+ key
+ "\",\n"
+ " 'parameterType': {'type': \""
+ namedParameterValue.getType().toString()
+ "\""
+ (isArrayParameter
? ",'arrayType': {'type': \"" + namedParameterValue.getArrayType() + "\"},"
: "")
+ "},\n"
+ " \'parameterValue\': {"
+ (isArrayParameter
? "\'arrayValues\': ["
+ arrayValues.stream()
.map(arrayValue -> "{\'value\': " + arrayValue.getValue() + "}")
.collect(Collectors.joining(","))
+ "]"
: "'value': \"" + namedParameterValue.getValue() + "\"")
+ "}\n"
+ " }";
case R:
return " list(\n"
+ " name = \""
+ key
+ "\",\n"
+ " parameterType = list(type = \""
+ namedParameterValue.getType().toString()
+ "\""
+ (isArrayParameter
? ", arrayType = list(type = " + namedParameterValue.getArrayType() + "),"
: "")
+ "),\n"
+ " parameterValue = list("
+ (isArrayParameter
? "arrayValues = list("
+ arrayValues.stream()
.map(arrayValue -> "list(value = " + arrayValue.getValue() + ")")
.collect(Collectors.joining(","))
+ ")"
: "value = \"" + namedParameterValue.getValue() + "\"")
+ ")\n"
+ " )";
default:
throw new BadRequestException("Language not supported");
}
}
private ConceptSet handlePrePackagedSurveyConceptSet() {
List<Long> conceptIds = conceptBigQueryService.getSurveyQuestionConceptIds();
ConceptSet surveyConceptSets = new ConceptSet();
surveyConceptSets.setName("All Surveys");
surveyConceptSets.setDomain(CommonStorageEnums.domainToStorage(Domain.SURVEY));
Set<Long> conceptIdsSet = new HashSet<Long>();
conceptIdsSet.addAll(conceptIds);
surveyConceptSets.setConceptIds(conceptIdsSet);
return surveyConceptSets;
}
}
|
package net.x4a42.volksempfaenger.feedparser;
import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Stack;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class FeedParser {
private final String TAG = getClass().getSimpleName();
public static Feed parse(Reader reader) throws XmlPullParserException,
IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(reader);
ParserHelper parserHelper = new ParserHelper(parser);
return parserHelper.getFeed();
}
private static class ParserHelper {
private static final String TAG = "ParserHelper";
private XmlPullParser parser;
private Feed feed = new Feed();
private FeedItem feedItem;
Stack<String> parents = new Stack<String>();
private boolean currentItemHasSummary;
private static final String ATOM_NS = "http:
private static final String ATOM_FEED = ATOM_NS + ":feed";
private static final String ATOM_TITLE = ATOM_NS + ":title";
private static final String ATOM_ENTRY = ATOM_NS + ":entry";
private static final String ATOM_LINK = ATOM_NS + ":link";
private static final String ATOM_SUMMARY = ATOM_NS + ":summary";
private static final String ATOM_CONTENT = ATOM_NS + ":content";
private static final String ATOM_PUBLISHED = ATOM_NS + ":published";
private static final String ATOM_SUBTITLE = ATOM_NS + ":subtitle";
private static final String ATOM_ATTR_HREF = "href";
private static final String ATOM_ATTR_REL = "rel";
private static final String ATOM_ATTR_TYPE = "type";
private static final String ATOM_ATTR_LENGTH = "length";
private static final String ATOM_REL_ENCLOSURE = "enclosure";
private static final String ATOM_REL_ALTERNATE = "alternate";
private static final String ATOM_REL_SELF = "self";
private static final String RSS_TOPLEVEL = "rss";
private static final String RSS_CHANNEL = "channel";
private static final String RSS_ITEM = "item";
private static final String RSS_TITLE = "title";
private static final String RSS_LINK = "link";
private static final String RSS_DESCRIPTION = "description";
private static final String RSS_ENCLOSURE = "enclosure";
private static final String RSS_PUB_DATE = "pubDate";
private static final String RSS2_NS = "http://backend.userland.com/RSS2";
private static final String RSS_TOPLEVEL_NS = RSS2_NS + ":"
+ RSS_TOPLEVEL;
private static final String RSS_CHANNEL_NS = RSS2_NS + ":"
+ RSS_CHANNEL;
private static final String RSS_ITEM_NS = RSS2_NS + ":" + RSS_ITEM;
private static final String RSS_TITLE_NS = RSS2_NS + ":" + RSS_TITLE;
private static final String RSS_LINK_NS = RSS2_NS + ":" + RSS_LINK;
private static final String RSS_DESCRIPTION_NS = RSS2_NS + ":"
+ RSS_DESCRIPTION;
private static final String RSS_ENCLOSURE_NS = RSS2_NS + ":"
+ RSS_ENCLOSURE;
private static final String RSS_PUB_DATE_NS = RSS2_NS + ":"
+ RSS_PUB_DATE;
private static final String MIME_HTML = "text/html";
private static final String MIME_XHTML = "text/xhtml";
public ParserHelper(XmlPullParser parser)
throws XmlPullParserException, IOException {
this.parser = parser;
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
onStartTag();
break;
case XmlPullParser.TEXT:
onText();
break;
case XmlPullParser.END_TAG:
onEndTag();
break;
}
eventType = parser.next();
}
}
public Feed getFeed() {
return feed;
}
private void onStartTag() {
String fullName = parser.getNamespace() + ":" + parser.getName();
if (fullName.equals(ATOM_ENTRY)) {
feedItem = new FeedItem();
feedItem.setFeed(feed);
currentItemHasSummary = false;
} else if (fullName.equals(ATOM_LINK)) {
String rel = parser.getAttributeValue("", ATOM_ATTR_REL);
if (rel == null) {
} else if (rel.equals(ATOM_REL_ENCLOSURE)) {
if (parents.peek().equals(ATOM_ENTRY)) {
Enclosure enclosure = new Enclosure();
enclosure.setFeedItem(feedItem);
enclosure.setUrl(parser.getAttributeValue("",
ATOM_ATTR_HREF));
enclosure.setMime(parser.getAttributeValue("",
ATOM_ATTR_TYPE));
enclosure.setTitle(parser
.getAttributeValue("", "title"));
String length = parser.getAttributeValue("",
ATOM_ATTR_LENGTH);
if (length != null) {
enclosure.setSize(Long.parseLong(length));
}
feedItem.getEnclosures().add(enclosure);
}
} else if (rel.equals(ATOM_REL_ALTERNATE)) {
String type = parser.getAttributeValue("", ATOM_ATTR_TYPE);
if (parents.peek().equals(ATOM_ENTRY)) {
if (type == null || type.equals(MIME_HTML)
|| type.equals(MIME_XHTML)) {
// actually there can be multiple "alternate links"
// this uses the LAST alternate link as the URL for
// the FeedItem
feedItem.setUrl(parser.getAttributeValue("",
ATOM_ATTR_HREF));
}
} else if (parents.peek().equals(ATOM_FEED)) {
if (type == null || type.equals(MIME_HTML)
|| type.equals(MIME_XHTML)) {
// same issue as above with multiple alternate links
feed.setWebsite(parser.getAttributeValue("",
ATOM_ATTR_HREF));
}
}
} else if (rel.equals(ATOM_REL_SELF)) {
if (parents.peek().equals(ATOM_FEED)) {
feed.setUrl(parser
.getAttributeValue("", ATOM_ATTR_HREF));
}
}
}
parents.push(fullName);
}
private void onText() {
if (parents.peek().equals(ATOM_TITLE)) {
String copy = parents.pop();
if (parents.peek().equals(ATOM_FEED)) {
// feed title
feed.setTitle(parser.getText());
} else if (parents.peek().equals(ATOM_ENTRY)) {
// entry title
feedItem.setTitle(parser.getText());
}
parents.push(copy);
} else if (parents.peek().equals(ATOM_SUMMARY)) {
String copy = parents.pop();
if (parents.peek().equals(ATOM_ENTRY)) {
currentItemHasSummary = true;
feedItem.setDescription(parser.getText());
}
parents.push(copy);
} else if (parents.peek().equals(ATOM_CONTENT)) {
if (!currentItemHasSummary
&& (parents.peek().equals(ATOM_ENTRY))) {
feedItem.setDescription(parser.getText());
}
} else if (parents.peek().equals(ATOM_PUBLISHED)) {
String copy = parents.pop();
if (parents.peek().equals(ATOM_ENTRY)) {
try {
feedItem.setDate(parseAtomDate(parser.getText()));
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
parents.push(copy);
} else if (parents.peek().equals(ATOM_SUBTITLE)) {
feed.setDescription(parser.getText());
}
}
private void onEndTag() {
String fullName = parents.pop();
if (fullName.equals(ATOM_ENTRY)) {
feed.getItems().add(feedItem);
feedItem = null;
}
}
private Date parseAtomDate(String datestring)
throws java.text.ParseException, IndexOutOfBoundsException {
// original version by Chad Okere (ceothrow1 at gmail dotcom)
Date d = new Date();
// if there is no time zone, we don't need to do any special
// parsing.
if (datestring.endsWith("Z")) {
try {
SimpleDateFormat s = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");// spec for RFC3339
d = s.parse(datestring);
} catch (java.text.ParseException pe) {// try again with
// optional decimals
SimpleDateFormat s = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");// spec for
// RFC3339 (with
// fractional
// seconds)
s.setLenient(true);
d = s.parse(datestring);
}
return d;
}
// step one, split off the timezone.
String firstpart = datestring.substring(0,
datestring.lastIndexOf('-'));
String secondpart = datestring.substring(datestring
.lastIndexOf('-'));
// step two, remove the colon from the timezone offset
secondpart = secondpart.substring(0, secondpart.indexOf(':'))
+ secondpart.substring(secondpart.indexOf(':') + 1);
datestring = firstpart + secondpart;
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");// spec
// for
// RFC3339
try {
d = s.parse(datestring);
} catch (java.text.ParseException pe) { // try again with optional
// decimals
s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"); // spec
// for
// RFC3339
// (with
// fractional
// seconds)
s.setLenient(true);
d = s.parse(datestring);
}
return d;
}
}
}
|
package nitezh.ministock.domain;
import android.content.Context;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nitezh.ministock.PreferenceStorage;
import nitezh.ministock.Storage;
public class AndroidWidgetRepository implements WidgetRepository {
private final Context context;
private final Storage appStorage;
public AndroidWidgetRepository(Context context) {
this.context = context;
this.appStorage = PreferenceStorage.getInstance(context);
}
@Override
public Widget getWidget(int id) {
return new AndroidWidget(this.context, id);
}
@Override
public List<Integer> getIds() {
List<Integer> ids = new ArrayList<>();
for (String rawId : this.appStorage.getString("appWidgetIds", "").split(",")) {
if (!rawId.equals("")) {
ids.add(Integer.parseInt(rawId));
}
}
return ids;
}
private void setIds(List<Integer> ids) {
List<String> rawIds = new ArrayList<>();
for (Integer id : ids) {
rawIds.add(String.valueOf(id));
}
this.appStorage.putString("appWidgetIds", TextUtils.join(",", rawIds));
this.appStorage.apply();
}
private void addWidgetId(int newId) {
List<Integer> ids = this.getIds();
if (ids.contains(newId)) {
return;
}
ids.add(newId);
this.setIds(ids);
}
@Override
public Widget addWidget(int id, int size) {
Widget widget = getWidget(id);
if (this.getIds().contains(id)) {
return widget;
}
this.addWidgetId(id);
widget.setSize(size);
widget.enableDailyChangeView();
if (widget.isNarrow()) {
widget.enablePercentChangeView();
}
widget.setStock1("^DJI");
widget.setStock1Summary("Dow Jones Industrial Average");
widget.save();
return widget;
}
@Override
public void delWidget(int oldId) {
List<Integer> ids = this.getIds();
if (!ids.contains(oldId)) {
return;
}
ids.remove(oldId);
this.setIds(ids);
}
@Override
public boolean isEmpty() {
return this.getIds().isEmpty();
}
@Override
public Set<String> getWidgetsStockSymbols() {
Storage widgetPreferences;
Set<String> widgetStockSymbols = new HashSet<>();
for (int appWidgetId : this.getIds()) {
widgetPreferences = this.getWidget(appWidgetId).getStorage();
if (widgetPreferences != null) {
for (int i = 1; i < 11; i++) {
String stockSymbol = widgetPreferences.getString("Stock" + i, "");
if (!stockSymbol.equals("")) widgetStockSymbols.add(stockSymbol);
}
}
}
return widgetStockSymbols;
}
}
|
package nu.validator.servlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nu.validator.gnu.xml.aelfred2.SAXDriver;
import nu.validator.htmlparser.common.DoctypeExpectation;
import nu.validator.htmlparser.common.DocumentMode;
import nu.validator.htmlparser.common.DocumentModeHandler;
import nu.validator.htmlparser.common.XmlViolationPolicy;
import nu.validator.htmlparser.sax.HtmlParser;
import nu.validator.htmlparser.sax.HtmlSerializer;
import nu.validator.io.BoundedInputStream;
import nu.validator.io.StreamBoundException;
import nu.validator.messages.GnuMessageEmitter;
import nu.validator.messages.JsonMessageEmitter;
import nu.validator.messages.MessageEmitterAdapter;
import nu.validator.messages.TextMessageEmitter;
import nu.validator.messages.TooManyErrorsException;
import nu.validator.messages.XhtmlMessageEmitter;
import nu.validator.messages.XmlMessageEmitter;
import nu.validator.source.SourceCode;
import nu.validator.spec.Spec;
import nu.validator.spec.html5.Html5SpecBuilder;
import nu.validator.xml.AttributesImpl;
import nu.validator.xml.AttributesPermutingXMLReaderWrapper;
import nu.validator.xml.CharacterUtil;
import nu.validator.xml.ContentTypeParser;
import nu.validator.xml.ForbiddenCharacterFilter;
import nu.validator.xml.IdFilter;
import nu.validator.xml.LocalCacheEntityResolver;
import nu.validator.xml.NamespaceDroppingXMLReaderWrapper;
import nu.validator.xml.NullEntityResolver;
import nu.validator.xml.PrudentHttpEntityResolver;
import nu.validator.xml.SystemErrErrorHandler;
import nu.validator.xml.TypedInputSource;
import nu.validator.xml.WiretapXMLReaderWrapper;
import nu.validator.xml.XhtmlSaxEmitter;
import org.apache.log4j.Logger;
import org.apache.xml.serializer.Method;
import org.apache.xml.serializer.OutputPropertiesFactory;
import org.apache.xml.serializer.Serializer;
import org.apache.xml.serializer.SerializerFactory;
import org.whattf.checker.DebugChecker;
import org.whattf.checker.NormalizationChecker;
import org.whattf.checker.TextContentChecker;
import org.whattf.checker.UncheckedSubtreeWarner;
import org.whattf.checker.UsemapChecker;
import org.whattf.checker.jing.CheckerValidator;
import org.whattf.checker.table.TableChecker;
import org.xml.sax.ContentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import com.hp.hpl.jena.iri.IRI;
import com.hp.hpl.jena.iri.IRIException;
import com.hp.hpl.jena.iri.IRIFactory;
import com.ibm.icu.text.Normalizer;
import com.thaiopensource.relaxng.impl.CombineValidator;
import com.thaiopensource.util.PropertyMap;
import com.thaiopensource.util.PropertyMapBuilder;
import com.thaiopensource.validate.IncorrectSchemaException;
import com.thaiopensource.validate.Schema;
import com.thaiopensource.validate.SchemaReader;
import com.thaiopensource.validate.ValidateProperty;
import com.thaiopensource.validate.Validator;
import com.thaiopensource.validate.auto.AutoSchemaReader;
import com.thaiopensource.validate.rng.CompactSchemaReader;
import com.thaiopensource.validate.rng.RngProperty;
/**
* @version $Id: VerifierServletTransaction.java,v 1.10 2005/07/24 07:32:48
* hsivonen Exp $
* @author hsivonen
*/
class VerifierServletTransaction implements DocumentModeHandler {
private enum OutputFormat {
HTML, XHTML, TEXT, XML, JSON, RELAXED, SOAP, UNICORN, GNU
}
private static final Logger log4j = Logger.getLogger(VerifierServletTransaction.class);
private static final Pattern SPACE = Pattern.compile("\\s+");
private static final Pattern JS_IDENTIFIER = Pattern.compile("[\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}_\\$][\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}_\\$\\p{Mn}\\p{Mc}\\p{Nd}\\p{Pc}]*");
private static final String[] JS_RESERVED_WORDS = { "abstract", "boolean",
"break", "byte", "case", "catch", "char", "class", "const",
"continue", "debugger", "default", "delete", "do", "double",
"else", "enum", "export", "extends", "final", "finally", "float",
"for", "function", "goto", "if", "implements", "import", "in",
"instanceof", "int", "interface", "long", "native", "new",
"package", "private", "protected", "public", "return", "short",
"static", "super", "switch", "synchronized", "this", "throw",
"throws", "transient", "try", "typeof", "var", "void", "volatile",
"while", "with" };
private static final String[] CHARSETS = { "UTF-8", "UTF-16",
"Windows-1250", "Windows-1251", "Windows-1252", "Windows-1253",
"Windows-1254", "Windows-1255", "Windows-1256", "Windows-1257",
"Windows-1258", "ISO-8859-1", "ISO-8859-2", "ISO-8859-3",
"ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7",
"ISO-8859-8", "ISO-8859-9", "ISO-8859-13", "ISO-8859-15", "KOI8-R",
"TIS-620", "GBK", "GB18030", "Big5", "Big5-HKSCS", "Shift_JIS",
"ISO-2022-JP", "EUC-JP", "ISO-2022-KR", "EUC-KR" };
private static final char[][] CHARSET_DESCRIPTIONS = {
"UTF-8 (Global)".toCharArray(), "UTF-16 (Global)".toCharArray(),
"Windows-1250 (Central European)".toCharArray(),
"Windows-1251 (Cyrillic)".toCharArray(),
"Windows-1252 (Western)".toCharArray(),
"Windows-1253 (Greek)".toCharArray(),
"Windows-1254 (Turkish)".toCharArray(),
"Windows-1255 (Hebrew)".toCharArray(),
"Windows-1256 (Arabic)".toCharArray(),
"Windows-1257 (Baltic)".toCharArray(),
"Windows-1258 (Vietnamese)".toCharArray(),
"ISO-8859-1 (Western)".toCharArray(),
"ISO-8859-2 (Central European)".toCharArray(),
"ISO-8859-3 (South European)".toCharArray(),
"ISO-8859-4 (Baltic)".toCharArray(),
"ISO-8859-5 (Cyrillic)".toCharArray(),
"ISO-8859-6 (Arabic)".toCharArray(),
"ISO-8859-7 (Greek)".toCharArray(),
"ISO-8859-8 (Hebrew)".toCharArray(),
"ISO-8859-9 (Turkish)".toCharArray(),
"ISO-8859-13 (Baltic)".toCharArray(),
"ISO-8859-15 (Western)".toCharArray(),
"KOI8-R (Russian)".toCharArray(), "TIS-620 (Thai)".toCharArray(),
"GBK (Chinese, simplified)".toCharArray(),
"GB18030 (Chinese, simplified)".toCharArray(),
"Big5 (Chinese, traditional)".toCharArray(),
"Big5-HKSCS (Chinese, traditional)".toCharArray(),
"Shift_JIS (Japanese)".toCharArray(),
"ISO-2022-JP (Japanese)".toCharArray(),
"EUC-JP (Japanese)".toCharArray(),
"ISO-2022-KR (Korean)".toCharArray(),
"EUC-KR (Korean)".toCharArray() };
protected static final int HTML5_SCHEMA = 3;
protected static final int XHTML1STRICT_SCHEMA = 2;
protected static final int XHTML1TRANSITIONAL_SCHEMA = 1;
protected static final int XHTML5_SCHEMA = 7;
private static final char[] SERVICE_TITLE = (System.getProperty(
"nu.validator.servlet.service-name", "Validator.nu") + " ").toCharArray();
private static final char[] VERSION = "3".toCharArray();
private static final char[] RESULTS_TITLE = "Validation results".toCharArray();
private static final char[] FOR = " for ".toCharArray();
private static final char[] ABOUT_THIS_SERVICE = "About this service".toCharArray();
private static final Map pathMap = new HashMap();
private static Spec html5spec;
private static int[] presetDoctypes;
private static String[] presetLabels;
private static String[] presetUrls;
private static String[] presetNamespaces;
private static final String[] KNOWN_CONTENT_TYPES = {
"application/atom+xml", "application/docbook+xml",
"application/xhtml+xml", "application/xv+xml" };
private static final String[] NAMESPACES_FOR_KNOWN_CONTENT_TYPES = {
"http:
"http:
private static final String[] ALL_CHECKERS = {
"http:
"http://c.validator.nu/text-content/",
"http:
private static final String[] ALL_CHECKERS_HTML4 = {
"http:
"http:
private long start = System.currentTimeMillis();
protected final HttpServletRequest request;
private final HttpServletResponse response;
private IRIFactory iriFactory;
protected String document = null;
private ParserMode parser = ParserMode.AUTO;
private boolean laxType = false;
protected ContentHandler contentHandler;
protected XhtmlSaxEmitter emitter;
protected MessageEmitterAdapter errorHandler;
private AttributesImpl attrs = new AttributesImpl();
private OutputStream out;
private PropertyMap jingPropertyMap;
protected LocalCacheEntityResolver entityResolver;
private static long lastModified;
private static String[] preloadedSchemaUrls;
private static Schema[] preloadedSchemas;
private final static String ABOUT_PAGE = System.getProperty(
"nu.validator.servlet.about-page", "http://about.validator.nu/");
private final static String STYLE_SHEET = System.getProperty(
"nu.validator.servlet.style-sheet",
"http://about.validator.nu/style.css");
private final static String SCRIPT = System.getProperty(
"nu.validator.servlet.script",
"http://about.validator.nu/script.js");
private static final long SIZE_LIMIT = Integer.parseInt(System.getProperty(
"nu.validator.servlet.max-file-size", "2097152"));
private String schemaUrls = null;
protected Validator validator = null;
private BufferingRootNamespaceSniffer bufferingRootNamespaceSniffer = null;
private String contentType = null;
protected HtmlParser htmlParser = null;
protected SAXDriver xmlParser = null;
protected XMLReader reader;
protected TypedInputSource documentInput;
protected PrudentHttpEntityResolver httpRes;
protected ContentTypeParser contentTypeParser;
private Set<String> loadedValidatorUrls = new HashSet<String>();
private boolean checkNormalization = false;
private boolean rootNamespaceSeen = false;
private OutputFormat outputFormat;
private String postContentType;
private boolean methodIsGet;
private SourceCode sourceCode = new SourceCode();
private boolean showSource;
private String charsetOverride = null;
private Set<String> filteredNamespaces = new LinkedHashSet<String>(); // linked
// for
// stability
static {
try {
log4j.debug("Starting static initializer.");
String presetPath = System.getProperty("nu.validator.servlet.presetconfpath");
File presetFile = new File(presetPath);
lastModified = presetFile.lastModified();
BufferedReader r = new BufferedReader(new InputStreamReader(
new FileInputStream(presetFile), "UTF-8"));
String line;
List<String> doctypes = new LinkedList<String>();
List<String> namespaces = new LinkedList<String>();
List<String> labels = new LinkedList<String>();
List<String> urls = new LinkedList<String>();
log4j.debug("Starting to loop over config file lines.");
while ((line = r.readLine()) != null) {
if ("".equals(line.trim())) {
break;
}
String s[] = line.split("\t");
doctypes.add(s[0]);
namespaces.add(s[1]);
labels.add(s[2]);
urls.add(s[3]);
}
log4j.debug("Finished reading config.");
String[] presetDoctypesAsStrings = doctypes.toArray(new String[0]);
presetNamespaces = namespaces.toArray(new String[0]);
presetLabels = labels.toArray(new String[0]);
presetUrls = urls.toArray(new String[0]);
log4j.debug("Converted config to arrays.");
for (int i = 0; i < presetNamespaces.length; i++) {
String str = presetNamespaces[i];
if ("-".equals(str)) {
presetNamespaces[i] = null;
} else {
presetNamespaces[i] = presetNamespaces[i].intern();
}
}
log4j.debug("Prepared namespace array.");
presetDoctypes = new int[presetDoctypesAsStrings.length];
for (int i = 0; i < presetDoctypesAsStrings.length; i++) {
presetDoctypes[i] = Integer.parseInt(presetDoctypesAsStrings[i]);
}
log4j.debug("Parsed doctype numbers into ints.");
String prefix = System.getProperty("nu.validator.servlet.cachepathprefix");
log4j.debug("The cache path prefix is: " + prefix);
String cacheConfPath = System.getProperty("nu.validator.servlet.cacheconfpath");
log4j.debug("The cache config path is: " + cacheConfPath);
r = new BufferedReader(new InputStreamReader(new FileInputStream(
cacheConfPath), "UTF-8"));
while ((line = r.readLine()) != null) {
if ("".equals(line.trim())) {
break;
}
String s[] = line.split("\t");
pathMap.put(s[0], prefix + s[1]);
}
log4j.debug("Cache config read.");
ErrorHandler eh = new SystemErrErrorHandler();
LocalCacheEntityResolver er = new LocalCacheEntityResolver(pathMap,
new NullEntityResolver());
er.setAllowRnc(true);
PropertyMapBuilder pmb = new PropertyMapBuilder();
pmb.put(ValidateProperty.ERROR_HANDLER, eh);
pmb.put(ValidateProperty.ENTITY_RESOLVER, er);
pmb.put(ValidateProperty.XML_READER_CREATOR,
new VerifierServletXMLReaderCreator(eh, er));
RngProperty.CHECK_ID_IDREF.add(pmb);
PropertyMap pMap = pmb.toPropertyMap();
log4j.debug("Parsing set up. Starting to read schemas.");
SortedMap<String, Schema> schemaMap = new TreeMap<String, Schema>();
for (int i = 0; i < presetUrls.length; i++) {
String[] urls1 = SPACE.split(presetUrls[i]);
for (int j = 0; j < urls1.length; j++) {
String url = urls1[j];
if (schemaMap.get(url) == null && !isCheckerUrl(url)) {
Schema sch = schemaByUrl(url, er, pMap);
schemaMap.put(url, sch);
}
}
}
log4j.debug("Schemas read.");
preloadedSchemaUrls = new String[schemaMap.size()];
preloadedSchemas = new Schema[schemaMap.size()];
int i = 0;
for (Iterator iter = schemaMap.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
preloadedSchemaUrls[i] = entry.getKey().toString().intern();
preloadedSchemas[i] = (Schema) entry.getValue();
i++;
}
log4j.debug("Reading spec.");
html5spec = Html5SpecBuilder.parseSpec();
log4j.debug("Spec read.");
log4j.debug("Initialization complete.");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected static String scrub(CharSequence s) {
return Normalizer.normalize(
CharacterUtil.prudentlyScrubCharacterData(s), Normalizer.NFC);
}
private static boolean isCheckerUrl(String url) {
if ("http://c.validator.nu/all/".equals(url)
|| "http://hsivonen.iki.fi/checkers/all/".equals(url)) {
return true;
} else if ("http://c.validator.nu/all-html4/".equals(url)
|| "http://hsivonen.iki.fi/checkers/all-html4/".equals(url)) {
return true;
}
for (int i = 0; i < ALL_CHECKERS.length; i++) {
if (ALL_CHECKERS[i].equals(url)) {
return true;
}
}
return false;
}
/**
* @param request
* @param response
*/
VerifierServletTransaction(HttpServletRequest request,
HttpServletResponse response) {
this.request = request;
this.response = response;
this.iriFactory = IRIFactory.iriImplementation();
}
protected boolean willValidate() {
if (methodIsGet) {
return document != null;
} else { // POST
return true;
}
}
void service() throws ServletException, IOException {
this.methodIsGet = "GET".equals(request.getMethod())
|| "HEAD".equals(request.getMethod());
this.out = response.getOutputStream();
request.setCharacterEncoding("utf-8");
if (!methodIsGet) {
postContentType = request.getContentType();
if (postContentType == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Content-Type missing");
return;
} else if (postContentType.trim().toLowerCase().startsWith(
"application/x-www-form-urlencoded")) {
response.sendError(
HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
"application/x-www-form-urlencoded not supported. Please use multipart/form-data.");
return;
}
}
String outFormat = request.getParameter("out");
if (outFormat == null) {
outputFormat = OutputFormat.HTML;
} else {
if ("html".equals(outFormat)) {
outputFormat = OutputFormat.HTML;
} else if ("xhtml".equals(outFormat)) {
outputFormat = OutputFormat.XHTML;
} else if ("text".equals(outFormat)) {
outputFormat = OutputFormat.TEXT;
} else if ("gnu".equals(outFormat)) {
outputFormat = OutputFormat.GNU;
} else if ("xml".equals(outFormat)) {
outputFormat = OutputFormat.XML;
} else if ("json".equals(outFormat)) {
outputFormat = OutputFormat.JSON;
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Unsupported output format");
return;
}
}
if (!methodIsGet) {
document = scrubUrl(request.getHeader("Content-Location"));
}
if (document == null) {
document = scrubUrl(request.getParameter("doc"));
}
document = ("".equals(document)) ? null : document;
String callback = null;
if (outputFormat == OutputFormat.JSON) {
callback = request.getParameter("callback");
if (callback != null) {
Matcher m = JS_IDENTIFIER.matcher(callback);
if (m.matches()) {
if (Arrays.binarySearch(JS_RESERVED_WORDS, callback) >= 0) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Callback is a reserved word.");
return;
}
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Callback is not a valid ECMA 262 IdentifierName.");
return;
}
}
}
String methodCheck = request.getHeader("Method-Check");
if (willValidate()) {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
} else if (methodCheck != null) {
// XXX revisit if anne changes the access-control stuff to use
// OPTIONS
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
response.setHeader("Allow", "POST");
return;
} else if (outputFormat == OutputFormat.HTML
|| outputFormat == OutputFormat.XHTML) {
response.setDateHeader("Last-Modified", lastModified);
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"No input document");
return;
}
setup();
showSource = (request.getParameter("showsource") != null);
String charset = request.getParameter("charset");
if (charset != null) {
charset = scrub(charset.trim());
if (!"".equals(charset)) {
charsetOverride = charset;
}
}
String nsfilter = request.getParameter("nsfilter");
if (nsfilter != null) {
String[] nsfilterArr = SPACE.split(nsfilter);
for (int i = 0; i < nsfilterArr.length; i++) {
String ns = nsfilterArr[i];
if (ns.length() > 0) {
filteredNamespaces.add(ns);
}
}
}
boolean errorsOnly = ("error".equals(request.getParameter("level")));
try {
if (outputFormat == OutputFormat.HTML
|| outputFormat == OutputFormat.XHTML) {
if (outputFormat == OutputFormat.HTML) {
response.setContentType("text/html; charset=utf-8");
contentHandler = new HtmlSerializer(out);
} else {
response.setContentType("application/xhtml+xml");
Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML);
Serializer ser = SerializerFactory.getSerializer(props);
ser.setOutputStream(out);
contentHandler = new ForbiddenCharacterFilter(
ser.asContentHandler());
}
emitter = new XhtmlSaxEmitter(contentHandler);
errorHandler = new MessageEmitterAdapter(sourceCode,
showSource, new XhtmlMessageEmitter(contentHandler));
PageEmitter.emit(contentHandler, this);
} else {
if (outputFormat == OutputFormat.TEXT) {
response.setContentType("text/plain; charset=utf-8");
errorHandler = new MessageEmitterAdapter(sourceCode,
showSource, new TextMessageEmitter(out));
} else if (outputFormat == OutputFormat.GNU) {
response.setContentType("text/plain; charset=utf-8");
errorHandler = new MessageEmitterAdapter(sourceCode,
showSource, new GnuMessageEmitter(out));
} else if (outputFormat == OutputFormat.XML) {
response.setContentType("application/xml");
Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML);
Serializer ser = SerializerFactory.getSerializer(props);
ser.setOutputStream(out);
errorHandler = new MessageEmitterAdapter(sourceCode,
showSource, new XmlMessageEmitter(
new ForbiddenCharacterFilter(
ser.asContentHandler())));
} else if (outputFormat == OutputFormat.JSON) {
if (callback == null) {
response.setContentType("application/json");
} else {
response.setContentType("application/javascript");
}
errorHandler = new MessageEmitterAdapter(sourceCode,
showSource, new JsonMessageEmitter(
new nu.validator.json.Serializer(out),
callback));
} else {
throw new RuntimeException("Unreachable.");
}
errorHandler.setErrorsOnly(errorsOnly);
validate();
}
} catch (SAXException e) {
throw new ServletException(e);
}
}
/**
* @throws ServletException
*/
protected void setup() throws ServletException {
String preset = request.getParameter("preset");
if (preset != null && !"".equals(preset)) {
schemaUrls = preset;
} else {
schemaUrls = request.getParameter("schema");
}
if (schemaUrls == null) {
schemaUrls = "";
}
String parserStr = request.getParameter("parser");
if ("html".equals(parserStr)) {
parser = ParserMode.HTML_AUTO;
} else if ("xmldtd".equals(parserStr)) {
parser = ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION;
} else if ("xml".equals(parserStr)) {
parser = ParserMode.XML_NO_EXTERNAL_ENTITIES;
} else if ("html5".equals(parserStr)) {
parser = ParserMode.HTML;
} else if ("html4".equals(parserStr)) {
parser = ParserMode.HTML401_STRICT;
} else if ("html4tr".equals(parserStr)) {
parser = ParserMode.HTML401_TRANSITIONAL;
} // else auto
laxType = (request.getParameter("laxtype") != null);
}
private boolean isHtmlUnsafePreset() {
if ("".equals(schemaUrls)) {
return false;
}
boolean preset = false;
for (int i = 0; i < presetUrls.length; i++) {
if (presetUrls[i].equals(schemaUrls)) {
preset = true;
break;
}
}
if (!preset) {
return false;
}
return !(schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-basic.rnc")
|| schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-strict.rnc")
|| schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-transitional.rnc")
|| schemaUrls.startsWith("http:
}
/**
* @throws SAXException
*/
@SuppressWarnings("deprecation")
void validate() throws SAXException {
if (!willValidate()) {
return;
}
try {
out.flush();
} catch (IOException e1) {
throw new SAXException(e1);
}
httpRes = new PrudentHttpEntityResolver(SIZE_LIMIT, laxType,
errorHandler);
contentTypeParser = new ContentTypeParser(errorHandler, laxType);
entityResolver = new LocalCacheEntityResolver(pathMap, httpRes);
setAllowRnc(true);
boolean stats = (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML);
try {
this.errorHandler.start(document);
PropertyMapBuilder pmb = new PropertyMapBuilder();
pmb.put(ValidateProperty.ERROR_HANDLER, errorHandler);
pmb.put(ValidateProperty.ENTITY_RESOLVER, entityResolver);
pmb.put(ValidateProperty.XML_READER_CREATOR,
new VerifierServletXMLReaderCreator(errorHandler,
entityResolver));
RngProperty.CHECK_ID_IDREF.add(pmb);
jingPropertyMap = pmb.toPropertyMap();
tryToSetupValidator();
setAllowRnc(false);
loadDocAndSetupParser();
reader.setErrorHandler(errorHandler);
// XXX set xml:id filter separately
contentType = documentInput.getType();
sourceCode.initialize(documentInput);
if (validator == null) {
checkNormalization = true;
}
if (checkNormalization) {
reader.setFeature(
"http://xml.org/sax/features/unicode-normalization-checking",
true);
}
WiretapXMLReaderWrapper wiretap = new WiretapXMLReaderWrapper(
reader);
ContentHandler recorder = sourceCode.getLocationRecorder();
wiretap.setWiretapContentHander(recorder);
wiretap.setWiretapLexicalHandler((LexicalHandler) recorder);
reader = wiretap;
if (htmlParser != null) {
htmlParser.addCharacterHandler(sourceCode);
htmlParser.setMappingLangToXmlLang(true);
htmlParser.setErrorHandler(errorHandler.getExactErrorHandler());
htmlParser.setTreeBuilderErrorHandlerOverride(errorHandler);
errorHandler.setHtml(true);
} else if (xmlParser != null) {
// this must be after wiretap!
if (!filteredNamespaces.isEmpty()) {
reader = new NamespaceDroppingXMLReaderWrapper(reader,
filteredNamespaces);
}
xmlParser.setErrorHandler(errorHandler.getExactErrorHandler());
xmlParser.lockErrorHandler();
} else {
throw new RuntimeException("Bug. Unreachable.");
}
reader = new AttributesPermutingXMLReaderWrapper(reader); // make RNG validation better
if (charsetOverride != null) {
String charset = documentInput.getEncoding();
if (charset == null) {
errorHandler.warning(new SAXParseException(
"Overriding document character encoding from none to \u201C"
+ charsetOverride + "\u201D.", null));
} else {
errorHandler.warning(new SAXParseException(
"Overriding document character encoding from \u201C"
+ charset + "\u201D to \u201C"
+ charsetOverride + "\u201D.", null));
}
documentInput.setEncoding(charsetOverride);
}
reader.parse(documentInput);
} catch (TooManyErrorsException e) {
log4j.debug("TooManyErrorsException", e);
errorHandler.fatalError(e);
} catch (SAXException e) {
log4j.debug("SAXException", e);
} catch (IOException e) {
stats = false;
log4j.info("IOException", e);
errorHandler.ioError(e);
} catch (IncorrectSchemaException e) {
log4j.debug("IncorrectSchemaException", e);
errorHandler.schemaError(e);
} catch (RuntimeException e) {
stats = false;
log4j.error("RuntimeException, doc: " + document + " schema: "
+ schemaUrls + " lax: " + laxType, e);
errorHandler.internalError(
e,
"Oops. That was not supposed to happen. A bug manifested itself in the application internals. Unable to continue. Sorry. The admin was notified.");
} catch (Error e) {
stats = false;
log4j.error("Error, doc: " + document + " schema: " + schemaUrls
+ " lax: " + laxType, e);
errorHandler.internalError(
e,
"Oops. That was not supposed to happen. A bug manifested itself in the application internals. Unable to continue. Sorry. The admin was notified.");
} finally {
errorHandler.end(successMessage(), failureMessage());
}
if (stats) {
StatsEmitter.emit(contentHandler, this);
}
}
/**
* @return
* @throws SAXException
*/
protected String successMessage() throws SAXException {
return "The document validates according to the specified schema(s).";
}
protected String failureMessage() throws SAXException {
return "There were errors.";
}
/**
* @throws SAXException
* @throws IOException
* @throws IncorrectSchemaException
*/
protected void tryToSetupValidator() throws SAXException, IOException,
IncorrectSchemaException {
validator = validatorByUrls(schemaUrls);
}
/**
* @throws SAXException
* @throws IOException
* @throws IncorrectSchemaException
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
*/
protected void loadDocAndSetupParser() throws SAXException, IOException,
IncorrectSchemaException, SAXNotRecognizedException,
SAXNotSupportedException {
switch (parser) {
case HTML_AUTO:
case HTML:
case HTML401_STRICT:
case HTML401_TRANSITIONAL:
if (isHtmlUnsafePreset()) {
String message = "The chosen preset schema is not appropriate for HTML.";
SAXException se = new SAXException(message);
errorHandler.schemaError(se);
throw se;
}
setAllowGenericXml(false);
setAllowHtml(true);
setAcceptAllKnownXmlTypes(false);
setAllowXhtml(false);
loadDocumentInput();
newHtmlParser();
DoctypeExpectation doctypeExpectation;
int schemaId;
switch (parser) {
case HTML:
doctypeExpectation = DoctypeExpectation.HTML;
schemaId = HTML5_SCHEMA;
break;
case HTML401_STRICT:
doctypeExpectation = DoctypeExpectation.HTML401_STRICT;
schemaId = XHTML1STRICT_SCHEMA;
break;
case HTML401_TRANSITIONAL:
doctypeExpectation = DoctypeExpectation.HTML401_TRANSITIONAL;
schemaId = XHTML1TRANSITIONAL_SCHEMA;
break;
default:
doctypeExpectation = DoctypeExpectation.AUTO;
schemaId = 0;
break;
}
htmlParser.setDoctypeExpectation(doctypeExpectation);
htmlParser.setDocumentModeHandler(this);
reader = htmlParser;
if (validator == null) {
validator = validatorByDoctype(schemaId);
}
if (validator != null) {
reader.setContentHandler(validator.getContentHandler());
}
break;
case XML_NO_EXTERNAL_ENTITIES:
case XML_EXTERNAL_ENTITIES_NO_VALIDATION:
setAllowGenericXml(true);
setAllowHtml(false);
setAcceptAllKnownXmlTypes(true);
setAllowXhtml(true);
loadDocumentInput();
setupXmlParser();
break;
default:
setAllowGenericXml(true);
setAllowHtml(true);
setAcceptAllKnownXmlTypes(true);
setAllowXhtml(true);
loadDocumentInput();
if ("text/html".equals(documentInput.getType())) {
if (isHtmlUnsafePreset()) {
String message = "The Content-Type was \u201Ctext/html\u201D, but the chosen preset schema is not appropriate for HTML.";
SAXException se = new SAXException(message);
errorHandler.schemaError(se);
throw se;
}
errorHandler.info("The Content-Type was \u201Ctext/html\u201D. Using the HTML parser.");
newHtmlParser();
htmlParser.setDoctypeExpectation(DoctypeExpectation.AUTO);
htmlParser.setDocumentModeHandler(this);
reader = htmlParser;
if (validator != null) {
reader.setContentHandler(validator.getContentHandler());
}
} else {
errorHandler.info("The Content-Type was \u201C"
+ documentInput.getType()
+ "\u201D. Using the XML parser (not resolving external entities).");
setupXmlParser();
}
break;
}
}
protected void newHtmlParser() {
htmlParser = new HtmlParser();
htmlParser.setStreamabilityViolationPolicy(XmlViolationPolicy.FATAL);
htmlParser.setXmlnsPolicy(XmlViolationPolicy.ALTER_INFOSET);
htmlParser.setMappingLangToXmlLang(true);
htmlParser.setHtml4ModeCompatibleWithXhtml1Schemata(true);
}
protected Validator validatorByDoctype(int schemaId) throws SAXException,
IOException, IncorrectSchemaException {
if (schemaId == 0) {
return null;
}
for (int i = 0; i < presetDoctypes.length; i++) {
if (presetDoctypes[i] == schemaId) {
return validatorByUrls(presetUrls[i]);
}
}
throw new RuntimeException("Doctype mappings not initialized properly.");
}
/**
* @param entityResolver2
* @return
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
*/
protected void setupXmlParser() throws SAXNotRecognizedException,
SAXNotSupportedException {
xmlParser = new SAXDriver();
xmlParser.setCharacterHandler(sourceCode);
reader = new IdFilter(xmlParser);
reader.setFeature("http://xml.org/sax/features/string-interning", true);
reader.setFeature(
"http://xml.org/sax/features/external-general-entities",
parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION);
reader.setFeature(
"http://xml.org/sax/features/external-parameter-entities",
parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION);
if (parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION) {
reader.setEntityResolver(entityResolver);
} else {
reader.setEntityResolver(new NullEntityResolver());
}
if (validator == null) {
bufferingRootNamespaceSniffer = new BufferingRootNamespaceSniffer(
this);
reader.setContentHandler(bufferingRootNamespaceSniffer);
} else {
reader.setContentHandler(new RootNamespaceSniffer(this,
validator.getContentHandler()));
reader.setDTDHandler(validator.getDTDHandler());
}
}
/**
* @param validator
* @return
* @throws SAXException
* @throws IOException
* @throws IncorrectSchemaException
*/
private Validator validatorByUrls(String schemaList) throws SAXException,
IOException, IncorrectSchemaException {
Validator validator = null;
String[] schemas = SPACE.split(schemaList);
for (int i = schemas.length - 1; i > -1; i
String url = schemas[i];
if ("http://c.validator.nu/all/".equals(url)
|| "http://hsivonen.iki.fi/checkers/all/".equals(url)) {
for (int j = 0; j < ALL_CHECKERS.length; j++) {
validator = combineValidatorByUrl(validator,
ALL_CHECKERS[j]);
}
} else if ("http://c.validator.nu/all-html4/".equals(url)
|| "http://hsivonen.iki.fi/checkers/all-html4/".equals(url)) {
for (int j = 0; j < ALL_CHECKERS_HTML4.length; j++) {
validator = combineValidatorByUrl(validator,
ALL_CHECKERS_HTML4[j]);
}
} else {
validator = combineValidatorByUrl(validator, url);
}
}
return validator;
}
/**
* @param validator
* @param url
* @return
* @throws SAXException
* @throws IOException
* @throws IncorrectSchemaException
*/
private Validator combineValidatorByUrl(Validator validator, String url)
throws SAXException, IOException, IncorrectSchemaException {
if (!"".equals(url)) {
Validator v = validatorByUrl(url);
if (validator == null) {
validator = v;
} else {
validator = new CombineValidator(v, validator);
}
}
return validator;
}
/**
* @param url
* @return
* @throws SAXException
* @throws IOException
* @throws IncorrectSchemaException
*/
private Validator validatorByUrl(String url) throws SAXException,
IOException, IncorrectSchemaException {
if (loadedValidatorUrls.contains(url)) {
return null;
}
loadedValidatorUrls.add(url);
if ("http://c.validator.nu/table/".equals(url)
|| "http://hsivonen.iki.fi/checkers/table/".equals(url)) {
return new CheckerValidator(new TableChecker(), jingPropertyMap);
} else if ("http://c.validator.nu/nfc/".equals(url)
|| "http://hsivonen.iki.fi/checkers/nfc/".equals(url)) {
this.checkNormalization = true;
return new CheckerValidator(new NormalizationChecker(),
jingPropertyMap);
} else if ("http://c.validator.nu/debug/".equals(url)
|| "http://hsivonen.iki.fi/checkers/debug/".equals(url)) {
return new CheckerValidator(new DebugChecker(), jingPropertyMap);
} else if ("http://c.validator.nu/text-content/".equals(url)
|| "http://hsivonen.iki.fi/checkers/text-content/".equals(url)) {
return new CheckerValidator(new TextContentChecker(),
jingPropertyMap);
} else if ("http://c.validator.nu/usemap/".equals(url)
|| "http://n.validator.nu/checkers/usemap/".equals(url)) {
return new CheckerValidator(new UsemapChecker(), jingPropertyMap);
} else if ("http://c.validator.nu/unchecked/".equals(url)) {
return new CheckerValidator(new UncheckedSubtreeWarner(),
jingPropertyMap);
}
if ("http://s.validator.nu/xhtml5-rdf-svg-mathml.rnc".equals(url)
|| "http://s.validator.nu/html5/html5full.rnc".equals(url)
|| "http://s.validator.nu/html5/xhtml5full-xhtml.rnc".equals(url)
|| "http://syntax.whattf.org/relaxng/xhtml5full-xhtml.rnc".equals(url)
|| "http://syntax.whattf.org/relaxng/html5full.rnc".equals(url)) {
errorHandler.setSpec(html5spec);
}
Schema sch = schemaByUrl(url);
Validator validator = sch.createValidator(jingPropertyMap);
return validator;
}
/**
* @param url
* @return
* @throws SAXException
* @throws IOException
* @throws IncorrectSchemaException
*/
private Schema schemaByUrl(String url) throws SAXException, IOException,
IncorrectSchemaException {
int i = Arrays.binarySearch(preloadedSchemaUrls, url);
if (i > -1) {
return preloadedSchemas[i];
}
TypedInputSource schemaInput = (TypedInputSource) entityResolver.resolveEntity(
null, url);
SchemaReader sr = null;
if ("application/relax-ng-compact-syntax".equals(schemaInput.getType())) {
sr = CompactSchemaReader.getInstance();
} else {
sr = new AutoSchemaReader();
}
Schema sch = sr.createSchema(schemaInput, jingPropertyMap);
return sch;
}
/**
* @param url
* @return
* @throws SAXException
* @throws IOException
* @throws IncorrectSchemaException
*/
private static Schema schemaByUrl(String url, EntityResolver resolver,
PropertyMap pMap) throws SAXException, IOException,
IncorrectSchemaException {
log4j.debug("Will load schema: " + url);
TypedInputSource schemaInput = (TypedInputSource) resolver.resolveEntity(
null, url);
SchemaReader sr = null;
if ("application/relax-ng-compact-syntax".equals(schemaInput.getType())) {
sr = CompactSchemaReader.getInstance();
} else {
sr = new AutoSchemaReader();
}
Schema sch = sr.createSchema(schemaInput, pMap);
return sch;
}
/**
* @throws SAXException
*/
void emitTitle(boolean markupAllowed) throws SAXException {
if (willValidate()) {
emitter.characters(RESULTS_TITLE);
if (document != null && document.length() > 0) {
emitter.characters(FOR);
emitter.characters(scrub(document));
}
} else {
emitter.characters(SERVICE_TITLE);
if (markupAllowed) {
emitter.startElement("span");
emitter.characters(VERSION);
emitter.endElement("span");
}
}
}
void emitForm() throws SAXException {
attrs.clear();
attrs.addAttribute("method", "get");
attrs.addAttribute("action", request.getRequestURL().toString());
if (isSimple()) {
attrs.addAttribute("class", "simple");
}
// attrs.addAttribute("onsubmit", "formSubmission()");
emitter.startElement("form", attrs);
emitFormContent();
emitter.endElement("form");
}
protected boolean isSimple() {
return false;
}
/**
* @throws SAXException
*/
protected void emitFormContent() throws SAXException {
FormEmitter.emit(contentHandler, this);
}
void emitSchemaField() throws SAXException {
attrs.clear();
attrs.addAttribute("name", "schema");
attrs.addAttribute("id", "schema");
// attrs.addAttribute("onchange", "schemaChanged();");
attrs.addAttribute("pattern", "(?:https?://.+(?:\\s+https?://.+)*)?");
attrs.addAttribute("title",
"Space-separated list of schema IRIs. (Leave blank to let the service guess.)");
if (schemaUrls != null) {
attrs.addAttribute("value", scrub(schemaUrls));
}
emitter.startElement("input", attrs);
emitter.endElement("input");
}
void emitDocField() throws SAXException {
attrs.clear();
attrs.addAttribute("type", "url");
attrs.addAttribute("name", "doc");
attrs.addAttribute("id", "doc");
attrs.addAttribute("pattern", "(?:https?:
attrs.addAttribute("title",
"Absolute IRI (http or https only) of the document to be checked.");
if (document != null) {
attrs.addAttribute("value", scrub(document));
}
emitter.startElement("input", attrs);
emitter.endElement("input");
}
private String scrubUrl(String urlStr) {
if (urlStr == null) {
return null;
}
try {
IRI iri = iriFactory.construct(urlStr);
return iri.toASCIIString();
} catch (IRIException e) {
return null;
} catch (MalformedURLException e) {
return null;
}
}
/**
* @throws SAXException
*
*/
void emitSchemaDuration() throws SAXException {
}
/**
* @throws SAXException
*
*/
void emitDocDuration() throws SAXException {
}
/**
* @throws SAXException
*
*/
void emitTotalDuration() throws SAXException {
emitter.characters("" + (System.currentTimeMillis() - start));
}
/**
* @throws SAXException
*
*/
void emitPresetOptions() throws SAXException {
for (int i = 0; i < presetUrls.length; i++) {
emitter.option(presetLabels[i], presetUrls[i], false);
}
}
/**
* @throws SAXException
*
*/
void emitParserOptions() throws SAXException {
emitter.option("Automatically from Content-Type", "",
(parser == ParserMode.AUTO));
emitter.option("XML; don\u2019t load external entities", "xml",
(parser == ParserMode.XML_NO_EXTERNAL_ENTITIES));
emitter.option("XML; load external entities", "xmldtd",
(parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION));
emitter.option("HTML; flavor from doctype", "html",
(parser == ParserMode.HTML_AUTO));
emitter.option("HTML5", "html5", (parser == ParserMode.HTML));
emitter.option("HTML 4.01 Strict", "html4",
(parser == ParserMode.HTML401_STRICT));
emitter.option("HTML 4.01 Transitional", "html4tr",
(parser == ParserMode.HTML401_TRANSITIONAL));
}
/**
* @throws SAXException
*
*/
void emitLaxTypeField() throws SAXException {
emitter.checkbox("laxtype", "yes", laxType);
}
/**
* @throws SAXException
*
*/
void emitShowSourceField() throws SAXException {
emitter.checkbox("showsource", "yes", showSource);
}
void rootNamespace(String namespace, Locator locator) throws SAXException {
if (validator == null) {
int index = -1;
for (int i = 0; i < presetNamespaces.length; i++) {
if (namespace.equals(presetNamespaces[i])) {
index = i;
break;
}
}
if (index == -1) {
String message = "Cannot find preset schema for namespace: \u201C"
+ namespace + "\u201D.";
SAXException se = new SAXException(message);
errorHandler.schemaError(se);
throw se;
}
String label = presetLabels[index];
String urls = presetUrls[index];
errorHandler.info("Using the preset for " + label
+ " based on the root namespace.");
try {
validator = validatorByUrls(urls);
} catch (IOException ioe) {
// At this point the schema comes from memory.
throw new RuntimeException(ioe);
} catch (IncorrectSchemaException e) {
// At this point the schema comes from memory.
throw new RuntimeException(e);
}
if (bufferingRootNamespaceSniffer == null) {
throw new RuntimeException(
"Bug! bufferingRootNamespaceSniffer was null.");
}
bufferingRootNamespaceSniffer.setContentHandler(validator.getContentHandler());
}
if (!rootNamespaceSeen) {
rootNamespaceSeen = true;
if (contentType != null) {
int i;
if ((i = Arrays.binarySearch(KNOWN_CONTENT_TYPES, contentType)) > -1) {
if (!NAMESPACES_FOR_KNOWN_CONTENT_TYPES[i].equals(namespace)) {
String message = "\u201C"
+ contentType
+ "\u201D is not an appropriate Content-Type for a document whose root namespace is \u201C"
+ namespace + "\u201D.";
SAXParseException spe = new SAXParseException(message,
locator);
errorHandler.warning(spe);
}
}
}
}
}
public void documentMode(DocumentMode mode, String publicIdentifier,
String systemIdentifier, boolean html4SpecificAdditionalErrorChecks)
throws SAXException {
if (validator == null) {
try {
if ("-//W3C//DTD XHTML 1.0 Transitional//EN".equals(publicIdentifier)) {
errorHandler.info("XHTML 1.0 Transitional doctype seen. Appendix C is not supported. Proceeding anyway for your convenience. The parser is still an HTML parser, so namespace processing is not performed and \u201Cxml:*\u201D attributes are not supported. Using the schema for XHTML 1.0 Transitional."
+ (html4SpecificAdditionalErrorChecks ? " HTML4-specific tokenization errors are enabled."
: ""));
validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA);
} else if ("-//W3C//DTD XHTML 1.0 Strict//EN".equals(publicIdentifier)) {
errorHandler.info("XHTML 1.0 Strict doctype seen. Appendix C is not supported. Proceeding anyway for your convenience. The parser is still an HTML parser, so namespace processing is not performed and \u201Cxml:*\u201D attributes are not supported. Using the schema for XHTML 1.0 Strict."
+ (html4SpecificAdditionalErrorChecks ? " HTML4-specific tokenization errors are enabled."
: ""));
validator = validatorByDoctype(XHTML1STRICT_SCHEMA);
} else if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)) {
errorHandler.info("HTML 4.01 Transitional doctype seen. Using the schema for XHTML 1.0 Transitional."
+ (html4SpecificAdditionalErrorChecks ? ""
: " HTML4-specific tokenization errors are not enabled."));
validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA);
} else if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) {
errorHandler.info("HTML 4.01 Strict doctype seen. Using the schema for XHTML 1.0 Strict."
+ (html4SpecificAdditionalErrorChecks ? ""
: " HTML4-specific tokenization errors are not enabled."));
validator = validatorByDoctype(XHTML1STRICT_SCHEMA);
} else if ("-//W3C//DTD HTML 4.0 Transitional//EN".equals(publicIdentifier)) {
errorHandler.info("Legacy HTML 4.0 Transitional doctype seen. Please consider using HTML 4.01 Transitional instead. Proceeding anyway for your convenience with the schema for XHTML 1.0 Transitional."
+ (html4SpecificAdditionalErrorChecks ? ""
: " HTML4-specific tokenization errors are not enabled."));
validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA);
} else if ("-//W3C//DTD HTML 4.0//EN".equals(publicIdentifier)) {
errorHandler.info("Legacy HTML 4.0 Strict doctype seen. Please consider using HTML 4.01 instead. Proceeding anyway for your convenience with the schema for XHTML 1.0 Strict."
+ (html4SpecificAdditionalErrorChecks ? ""
: " HTML4-specific tokenization errors are not enabled."));
validator = validatorByDoctype(XHTML1STRICT_SCHEMA);
} else {
errorHandler.info("Using the schema for HTML5."
+ (html4SpecificAdditionalErrorChecks ? " HTML4-specific tokenization errors are enabled."
: ""));
validator = validatorByDoctype(HTML5_SCHEMA);
}
} catch (IOException ioe) {
// At this point the schema comes from memory.
throw new RuntimeException(ioe);
} catch (IncorrectSchemaException e) {
// At this point the schema comes from memory.
throw new RuntimeException(e);
}
ContentHandler ch = validator.getContentHandler();
ch.setDocumentLocator(htmlParser.getDocumentLocator());
ch.startDocument();
reader.setContentHandler(ch);
} else {
if (html4SpecificAdditionalErrorChecks) {
errorHandler.info("HTML4-specific tokenization errors are enabled.");
}
}
}
/**
* @param acceptAllKnownXmlTypes
* @see nu.validator.xml.ContentTypeParser#setAcceptAllKnownXmlTypes(boolean)
*/
protected void setAcceptAllKnownXmlTypes(boolean acceptAllKnownXmlTypes) {
contentTypeParser.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes);
httpRes.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes);
}
/**
* @param allowGenericXml
* @see nu.validator.xml.ContentTypeParser#setAllowGenericXml(boolean)
*/
protected void setAllowGenericXml(boolean allowGenericXml) {
contentTypeParser.setAllowGenericXml(allowGenericXml);
httpRes.setAllowGenericXml(allowGenericXml);
}
/**
* @param allowHtml
* @see nu.validator.xml.ContentTypeParser#setAllowHtml(boolean)
*/
protected void setAllowHtml(boolean allowHtml) {
contentTypeParser.setAllowHtml(allowHtml);
httpRes.setAllowHtml(allowHtml);
}
/**
* @param allowRnc
* @see nu.validator.xml.ContentTypeParser#setAllowRnc(boolean)
*/
protected void setAllowRnc(boolean allowRnc) {
contentTypeParser.setAllowRnc(allowRnc);
httpRes.setAllowRnc(allowRnc);
entityResolver.setAllowRnc(allowRnc);
}
/**
* @param allowXhtml
* @see nu.validator.xml.ContentTypeParser#setAllowXhtml(boolean)
*/
protected void setAllowXhtml(boolean allowXhtml) {
contentTypeParser.setAllowXhtml(allowXhtml);
httpRes.setAllowXhtml(allowXhtml);
}
/**
* @throws SAXException
* @throws IOException
*/
protected void loadDocumentInput() throws SAXException, IOException {
if (methodIsGet) {
documentInput = (TypedInputSource) entityResolver.resolveEntity(
null, document);
errorHandler.setLoggingOk(true);
} else { // POST
long len = request.getContentLength();
if (len > SIZE_LIMIT) {
throw new StreamBoundException("Resource size exceeds limit.");
}
documentInput = contentTypeParser.buildTypedInputSource(document,
null, postContentType);
documentInput.setByteStream(len < 0 ? new BoundedInputStream(
request.getInputStream(), SIZE_LIMIT, document)
: request.getInputStream());
}
}
void emitStyle() throws SAXException {
attrs.clear();
attrs.addAttribute("href", STYLE_SHEET);
attrs.addAttribute("rel", "stylesheet");
emitter.startElement("link", attrs);
emitter.endElement("link");
}
void emitScript() throws SAXException {
attrs.clear();
attrs.addAttribute("src", SCRIPT);
emitter.startElement("script", attrs);
emitter.endElement("script");
}
void emitAbout() throws SAXException {
attrs.clear();
attrs.addAttribute("href", ABOUT_PAGE);
emitter.startElement("a", attrs);
emitter.characters(ABOUT_THIS_SERVICE);
emitter.endElement("a");
}
void emitNsfilterField() throws SAXException {
attrs.clear();
attrs.addAttribute("name", "nsfilter");
attrs.addAttribute("id", "nsfilter");
attrs.addAttribute("pattern", "(?:.+:.+(?:\\s+.+:.+)*)?");
attrs.addAttribute("title",
"Space-separated namespace URIs for vocabularies to be filtered out.");
if (!filteredNamespaces.isEmpty()) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String ns : filteredNamespaces) {
if (!first) {
sb.append(' ');
}
sb.append(ns);
first = false;
}
attrs.addAttribute("value", scrub(sb));
}
emitter.startElement("input", attrs);
emitter.endElement("input");
}
void maybeEmitNsfilterField() throws SAXException {
NsFilterEmitter.emit(contentHandler, this);
}
void emitCharsetOptions() throws SAXException {
boolean found = false;
for (int i = 0; i < CHARSETS.length; i++) {
String charset = CHARSETS[i];
boolean selected = charset.equalsIgnoreCase(charsetOverride); // XXX
// use
// ASCII-caseinsensitivity
emitter.option(CHARSET_DESCRIPTIONS[i], charset, selected);
if (selected) {
found = true;
}
}
if (!found && charsetOverride != null) {
emitter.option(charsetOverride, charsetOverride, true);
}
}
void maybeEmitCharsetField() throws SAXException {
CharsetEmitter.emit(contentHandler, this);
}
}
|
package org.bouncycastle.jce.provider;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Hashtable;
import javax.crypto.KeyAgreementSpi;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.params.DESParameters;
import org.bouncycastle.util.Strings;
/**
* Diffie-Hellman key agreement. There's actually a better way of doing this
* if you are using long term public keys, see the light-weight version for
* details.
*/
public class JCEDHKeyAgreement
extends KeyAgreementSpi
{
private BigInteger x;
private BigInteger p;
private BigInteger g;
private BigInteger result;
private static final Hashtable algorithms = new Hashtable();
static
{
Integer i64 = new Integer(64);
Integer i192 = new Integer(192);
Integer i128 = new Integer(128);
Integer i256 = new Integer(256);
algorithms.put("DES", i64);
algorithms.put("DESEDE", i192);
algorithms.put("BLOWFISH", i128);
algorithms.put("AES", i256);
}
private byte[] bigIntToBytes(
BigInteger r)
{
byte[] tmp = r.toByteArray();
if (tmp[0] == 0)
{
byte[] ntmp = new byte[tmp.length - 1];
System.arraycopy(tmp, 1, ntmp, 0, ntmp.length);
return ntmp;
}
return tmp;
}
protected Key engineDoPhase(
Key key,
boolean lastPhase)
throws InvalidKeyException, IllegalStateException
{
if (x == null)
{
throw new IllegalStateException("Diffie-Hellman not initialised.");
}
if (!(key instanceof DHPublicKey))
{
throw new InvalidKeyException("DHKeyAgreement doPhase requires DHPublicKey");
}
DHPublicKey pubKey = (DHPublicKey)key;
if (!pubKey.getParams().getG().equals(g) || !pubKey.getParams().getP().equals(p))
{
throw new InvalidKeyException("DHPublicKey not for this KeyAgreement!");
}
if (lastPhase)
{
result = ((DHPublicKey)key).getY().modPow(x, p);
return null;
}
else
{
result = ((DHPublicKey)key).getY().modPow(x, p);
}
return new JCEDHPublicKey(result, pubKey.getParams());
}
protected byte[] engineGenerateSecret()
throws IllegalStateException
{
if (x == null)
{
throw new IllegalStateException("Diffie-Hellman not initialised.");
}
return bigIntToBytes(result);
}
protected int engineGenerateSecret(
byte[] sharedSecret,
int offset)
throws IllegalStateException, ShortBufferException
{
if (x == null)
{
throw new IllegalStateException("Diffie-Hellman not initialised.");
}
byte[] secret = bigIntToBytes(result);
if (sharedSecret.length - offset < secret.length)
{
throw new ShortBufferException("DHKeyAgreement - buffer too short");
}
System.arraycopy(secret, 0, sharedSecret, offset, secret.length);
return secret.length;
}
protected SecretKey engineGenerateSecret(
String algorithm)
{
if (x == null)
{
throw new IllegalStateException("Diffie-Hellman not initialised.");
}
String algKey = Strings.toUpperCase(algorithm);
byte[] res = bigIntToBytes(result);
if (algorithms.containsKey(algKey))
{
Integer length = (Integer)algorithms.get(algKey);
byte[] key = new byte[length.intValue() / 8];
System.arraycopy(res, 0, key, 0, key.length);
if (algKey.startsWith("DES"))
{
DESParameters.setOddParity(key);
}
return new SecretKeySpec(key, algorithm);
}
return new SecretKeySpec(res, algorithm);
}
protected void engineInit(
Key key,
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
if (!(key instanceof DHPrivateKey))
{
throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey for initialisation");
}
DHPrivateKey privKey = (DHPrivateKey)key;
if (params != null)
{
if (!(params instanceof DHParameterSpec))
{
throw new InvalidAlgorithmParameterException("DHKeyAgreement only accepts DHParameterSpec");
}
DHParameterSpec p = (DHParameterSpec)params;
this.p = p.getP();
this.g = p.getG();
}
else
{
this.p = privKey.getParams().getP();
this.g = privKey.getParams().getG();
}
this.x = this.result = privKey.getX();
}
protected void engineInit(
Key key,
SecureRandom random)
throws InvalidKeyException
{
if (!(key instanceof DHPrivateKey))
{
throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey");
}
DHPrivateKey privKey = (DHPrivateKey)key;
this.p = privKey.getParams().getP();
this.g = privKey.getParams().getG();
this.x = this.result = privKey.getX();
}
}
|
package org.objectweb.proactive.core.mop;
import org.apache.log4j.Logger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Hashtable;
public class MOPClassLoader extends URLClassLoader {
static Logger logger = Logger.getLogger(MOPClassLoader.class.getName());
// retreives the optionnal byteCodeManipulator JVM arg
// ASM is used by default
public static String BYTE_CODE_MANIPULATOR = ((System.getProperty(
"byteCodeManipulator") != null)
? ((System.getProperty("byteCodeManipulator").equals("BCEL")) ? "BCEL"
: "ASM")
: "ASM");
protected static Hashtable classDataCache = new Hashtable();
protected static MOPClassLoader mopCl = null;
// public static synchronized MOPClassLoader getMOPClassLoader(
// ClassLoader parent, URL[] urls) {
// if (MOPClassLoader.mopCl == null) {
// MOPClassLoader.mopCl = new MOPClassLoader(parent, urls);
// return MOPClassLoader.mopCl;
/**
* Return the unique MOPClassLoader for the current JVM
* Create it if it does not exist
*/
public static synchronized MOPClassLoader getMOPClassLoader() {
if (MOPClassLoader.mopCl == null) {
MOPClassLoader.mopCl = MOPClassLoader.createMOPClassLoader();
}
return MOPClassLoader.mopCl;
}
/**
* Get the bytecode of a stub given its name. If the stub can not be found
* the cache, the MOPClassLoader tries to generate it.
* @param classname The name of the stub class
* @return An array representing the bytecode of the stub, null if the
* stub could not be found or created
*/
public byte[] getClassData(String classname) {
byte[] cb = null;
cb = (byte[]) classDataCache.get(classname);
if (cb == null) {
logger.info(
"MOPClassLoader: class not found, trying to generate it");
try {
this.loadClass(classname);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
cb = (byte[]) classDataCache.get(classname);
}
//return (byte[]) classDataCache.get(classname);
return cb;
}
private MOPClassLoader(ClassLoader parent, URL[] urls) {
super(urls, parent);
}
public void launchMain(String[] args) throws Throwable {
try {
// Looks up the class that contains main
Class cl = Class.forName(args[0], true, this);
// Looks up method main
Class[] argTypes = { args.getClass() };
Method mainMethod = cl.getMethod("main", argTypes);
// And calls it
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
Object[] mainArgs = { newArgs };
mainMethod.invoke(null, mainArgs);
} catch (ClassNotFoundException e) {
logger.error("Launcher: cannot find class " + args[0]);
} catch (NoSuchMethodException e) {
logger.error("Launcher: class " + args[0] +
" does not contain have method void 'public void main (String[])'");
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
return;
}
protected static MOPClassLoader createMOPClassLoader() {
// Gets the current classloader
ClassLoader currentClassLoader = null;
try {
Class c = Class.forName(
"org.objectweb.proactive.core.mop.MOPClassLoader");
currentClassLoader = c.getClassLoader();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
URL[] urls = null;
// Checks if the current classloader is actually an instance of
// java.net.URLClassLoader, or of one of its subclasses.
if (currentClassLoader instanceof java.net.URLClassLoader) {
// Retrieves the set of URLs from the current classloader
urls = ((URLClassLoader) currentClassLoader).getURLs();
} else {
urls = new URL[0];
// System.out.println("Current classloader is of type " +
// currentClassLoader.getClass().getName() +
// ", which is not compatible with URLClassLoader. Cannot install MOPClassLoader");
// return null;
}
// Creates a new MOPClassLoader
return new MOPClassLoader(currentClassLoader, urls);
}
protected Class findClass(String name) throws ClassNotFoundException {
return super.findClass(name);
}
public Class loadClass(String name) throws ClassNotFoundException {
return this.loadClass(name, null, false);
}
public Class loadClass(String name, ClassLoader cl)
throws ClassNotFoundException {
return this.loadClass(name, cl, false);
}
protected synchronized Class loadClass(String name, ClassLoader cl,
boolean resolve) throws ClassNotFoundException {
if (this.getParent() != null) {
try {
return this.getParent().loadClass(name);
} catch (ClassNotFoundException e) {
// proceeding
}
}
try {
if (cl != null) {
return cl.loadClass(name);
} else {
return Class.forName(name);
}
} catch (ClassNotFoundException e) {
// Test if the name of the class is actually a request for
// a stub class to be created
if (Utils.isStubClassName(name)) {
logger.info("Generating class : " + name);
String classname = Utils.convertStubClassNameToClassName(name);
//ASM is now the default bytecode manipulator
byte[] data = null;
if (BYTE_CODE_MANIPULATOR.equals("ASM")) {
ASMBytecodeStubBuilder bsb = new ASMBytecodeStubBuilder(classname);
long start_time = System.currentTimeMillis();
data = bsb.create();
MOPClassLoader.classDataCache.put(name, data);
} else if (BYTE_CODE_MANIPULATOR.equals("BCEL")) {
BytecodeStubBuilder bsb = new BytecodeStubBuilder(classname);
long start_time = System.currentTimeMillis();
data = bsb.create();
MOPClassLoader.classDataCache.put(name, data);
} else {
// that shouldn't happen, unless someone manually sets the BYTE_CODE_MANIPULATOR static variable
logger.error(
"byteCodeManipulator argument is optionnal. If specified, it can only be set to BCEL.");
logger.error(
"Any other setting will result in the use of ASM, the default bytecode manipulator framework");
}
// System.out.println ("Classfile created with length "+data.length);
// Now, try to define the class
// We use the method defineClass, as redefined in class SecureClassLoader,
// so that we can specify a SourceCode object
// Class c = this.defineClass(name, data, 0, data.length, this.getClass().getProtectionDomain().getCodeSource());
// this.getParent().findClass("toto");
// Class c = this.getParent().defineClass(name, data, 0, data.length, this.getClass().getProtectionDomain());
// The following code invokes defineClass on the parent classloader by Reflection
// System.out.println("XXXXXXXXXXXXXXX");
try {
Class clc = Class.forName("java.lang.ClassLoader");
Class[] argumentTypes = new Class[5];
argumentTypes[0] = name.getClass();
argumentTypes[1] = data.getClass();
argumentTypes[2] = Integer.TYPE;
argumentTypes[3] = Integer.TYPE;
argumentTypes[4] = Class.forName(
"java.security.ProtectionDomain");
Method m = clc.getDeclaredMethod("defineClass",
argumentTypes);
m.setAccessible(true);
Object[] effectiveArguments = new Object[5];
effectiveArguments[0] = name;
effectiveArguments[1] = data;
effectiveArguments[2] = new Integer(0);
effectiveArguments[3] = new Integer(data.length);
effectiveArguments[4] = this.getClass().getProtectionDomain();
// System.out.println("");
if (this.getParent() == null) {
return (Class) m.invoke(Thread.currentThread()
.getContextClassLoader(),
effectiveArguments);
} else {
return (Class) m.invoke(this.getParent(),
effectiveArguments);
}
} catch (Exception ex) {
ex.printStackTrace();
throw new ClassNotFoundException(ex.getMessage());
}
} else {
System.out.println("Cannot generate class " + name);
throw e;
}
}
}
}
// static Logger logger = Logger.getLogger(MOPClassLoader.class.getName());
// // retreives the optionnal byteCodeManipulator JVM arg
// // ASM is used by default
// public static String BYTE_CODE_MANIPULATOR =
// ((System.getProperty("byteCodeManipulator") != null)
// ? ((System.getProperty("byteCodeManipulator").equals("BCEL")) ? "BCEL" : "ASM")
// : "ASM");
// protected static Hashtable classDataCache = new Hashtable();
// public static byte[] getClassData(String classname) {
// return (byte[]) classDataCache.get(classname);
// public MOPClassLoader(ClassLoader parent, URL[] urls) {
// super(urls, parent);
// public void launchMain(String[] args) throws Throwable {
// try {
// // Looks up the class that contains main
// Class cl = Class.forName(args[0], true, this);
// // Looks up method main
// Class[] argTypes = { args.getClass()};
// Method mainMethod = cl.getMethod("main", argTypes);
// // And calls it
// String[] newArgs = new String[args.length - 1];
// System.arraycopy(args, 1, newArgs, 0, args.length - 1);
// Object[] mainArgs = { newArgs };
// mainMethod.invoke(null, mainArgs);
// } catch (ClassNotFoundException e) {
// logger.error("Launcher: cannot find class " + args[0]);
// } catch (NoSuchMethodException e) {
// logger.error(
// "Launcher: class " + args[0] + " does not contain have method void 'public void main (String[])'");
// } catch (InvocationTargetException e) {
// throw e.getTargetException();
// return;
// public static MOPClassLoader createMOPClassLoader() {
// // Gets the current classloader
// ClassLoader currentClassLoader = null;
// try {
// Class c = Class.forName("org.objectweb.proactive.core.mop.MOPClassLoader");
// currentClassLoader = c.getClassLoader();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// // Checks if the current classloader is actually an instance of
// // java.net.URLClassLoader, or of one of its subclasses.
// if (currentClassLoader instanceof java.net.URLClassLoader) {
// // System.out.println ("Current classloader is of type "+currentClassLoader.getClass().getName()+", compatible with URLClassLoader");
// } else {
// logger.error(
// "Current classloader is of type "
// + currentClassLoader.getClass().getName()
// + ", which is not compatible with URLClassLoader. Cannot install MOPClassLoader");
// return null;
// // Retrieves the set of URLs from the current classloader
// URL[] urls = ((URLClassLoader) currentClassLoader).getURLs();
// // Creates a new MOPClassLoader
// return new MOPClassLoader(currentClassLoader, urls);
// protected Class findClass(String name) throws ClassNotFoundException {
// return super.findClass(name);
// public Class loadClass(String name) throws ClassNotFoundException {
// return this.loadClass(name, null, false);
// public Class loadClass(String name, ClassLoader cl) throws ClassNotFoundException {
// return this.loadClass(name, cl, false);
// protected synchronized Class loadClass(String name, ClassLoader cl, boolean resolve) throws ClassNotFoundException {
// if (this.getParent() != null) {
// try {
// return this.getParent().loadClass(name);
// } catch (ClassNotFoundException e) {
// // proceeding
// try {
// return cl.loadClass(name);
// } catch (ClassNotFoundException e) {
// // Test if the name of the class is actually a request for
// // a stub class to be created
// if (Utils.isStubClassName(name)) {
// logger.info("Generating class: " + name);
// String classname = Utils.convertStubClassNameToClassName(name);
// //ASM is now the default bytecode manipulator
// byte[] data = null;
// if (BYTE_CODE_MANIPULATOR.equals("ASM")) {
// ASMBytecodeStubBuilder bsb = new ASMBytecodeStubBuilder(classname);
// long start_time = System.currentTimeMillis();
// data = bsb.create();
// MOPClassLoader.classDataCache.put(name, data);
// } else if (BYTE_CODE_MANIPULATOR.equals("BCEL")) {
// BytecodeStubBuilder bsb = new BytecodeStubBuilder(classname);
// long start_time = System.currentTimeMillis();
// data = bsb.create();
// MOPClassLoader.classDataCache.put(name, data);
// } else {
// // that shouldn't happen, unless someone manually sets the BYTE_CODE_MANIPULATOR static variable
// logger.error(
// "byteCodeManipulator argument is optionnal. If specified, it can only be set to BCEL.");
// logger.error(
// "Any other setting will result in the use of ASM, the default bytecode manipulator framework");
// // System.out.println ("Classfile created with length "+data.length);
// // Now, try to define the class
// // We use the method defineClass, as redefined in class SecureClassLoader,
// // so that we can specify a SourceCode object
// // Class c = this.defineClass(name, data, 0, data.length, this.getClass().getProtectionDomain().getCodeSource());
// // this.getParent().findClass("toto");
// // Class c = this.getParent().defineClass(name, data, 0, data.length, this.getClass().getProtectionDomain());
// // The following code invokes defineClass on the parent classloader by Reflection
// try {
// Class clc = Class.forName("java.lang.ClassLoader");
// Class[] argumentTypes = new Class[5];
// argumentTypes[0] = name.getClass();
// argumentTypes[1] = data.getClass();
// argumentTypes[2] = Integer.TYPE;
// argumentTypes[3] = Integer.TYPE;
// argumentTypes[4] = Class.forName("java.security.ProtectionDomain");
// Method m = clc.getDeclaredMethod("defineClass", argumentTypes);
// m.setAccessible(true);
// Object[] effectiveArguments = new Object[5];
// effectiveArguments[0] = name;
// effectiveArguments[1] = data;
// effectiveArguments[2] = new Integer(0);
// effectiveArguments[3] = new Integer(data.length);
// effectiveArguments[4] = this.getClass().getProtectionDomain();
// return (Class) m.invoke(this.getParent(), effectiveArguments);
// } catch (Exception ex) {
// throw new ClassNotFoundException(ex.getMessage());
// } else {
// logger.error("Cannot generate class " + name);
// throw e;
|
package org.opencms.module;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.importexport.CmsExport;
import org.opencms.importexport.CmsImport;
import org.opencms.importexport.I_CmsImportExportHandler;
import org.opencms.main.CmsException;
import org.opencms.main.I_CmsConstants;
import org.opencms.main.OpenCms;
import org.opencms.report.CmsHtmlReport;
import org.opencms.report.I_CmsReport;
import org.opencms.security.CmsSecurityException;
import org.opencms.workplace.I_CmsWpConstants;
import org.opencms.xml.CmsXmlValidationErrorHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.digester.Digester;
import org.dom4j.Document;
import org.dom4j.Element;
import org.xml.sax.SAXException;
public class CmsModuleImportExportHandler extends Object implements I_CmsImportExportHandler {
/** The name of the module import project. */
public static final String C_IMPORT_MODULE_PROJECT_NAME = "ImportModule";
/** The VFS resources to be exported additionally with the module.<p> */
private List m_additionalResources;
/** The description of this import/export handler.<p> */
private String m_description;
/** The name of the export file in the real file system.<p> */
private String m_fileName;
/** The module imported with the digester. */
private CmsModule m_importedModule;
/** The (package) name of the module to be exported.<p> */
private String m_moduleName;
/**
* Creates a new Cms module import/export handler.<p>
*/
public CmsModuleImportExportHandler() {
super();
m_description = C_DEFAULT_DESCRIPTION;
}
/**
* Reads a module object from an external file source.<p>
*
* @param importResource the name of the input source
* @return the imported module
* @throws CmsConfigurationException if the module could not be imported
*/
public static CmsModule readModuleFromImport(String importResource) throws CmsConfigurationException {
// instantiate Digester and enable XML validation
Digester digester = new Digester();
digester.setValidating(false);
digester.setRuleNamespaceURI(null);
digester.setErrorHandler(new CmsXmlValidationErrorHandler());
// add this class to the Digester
CmsModuleImportExportHandler handler = new CmsModuleImportExportHandler();
digester.push(handler);
CmsModuleXmlHandler.addXmlDigesterRules(digester);
InputStream stream = null;
ZipFile importZip = null;
try {
File file = new File(importResource);
if (file.isFile()) {
importZip = new ZipFile(importResource);
ZipEntry entry = importZip.getEntry("manifest.xml");
stream = importZip.getInputStream(entry);
} else if (file.isDirectory()) {
file = new File(file, "manifest.xml");
stream = new FileInputStream(file);
}
// start the parsing process
digester.parse(stream);
} catch (IOException e) {
OpenCms.getLog(CmsModuleImportExportHandler.class).error("IO error reading module import", e);
throw new CmsConfigurationException(CmsConfigurationException.C_CONFIGURATION_ERROR, e);
} catch (SAXException e) {
OpenCms.getLog(CmsModuleImportExportHandler.class).error("SAX error reading module import", e);
throw new CmsConfigurationException(CmsConfigurationException.C_CONFIGURATION_ERROR, e);
} finally {
try {
if (importZip != null) {
importZip.close();
}
if (stream != null) {
stream.close();
}
} catch (Exception e) {
// noop
}
}
CmsModule importedModule = handler.getModule();
// the digester must have set the module now
if (importedModule == null) {
throw new CmsConfigurationException("Could not import module from source '" + importResource + "' is already installed", CmsConfigurationException.C_CONFIGURATION_ERROR);
}
return importedModule;
}
/**
* @see org.opencms.importexport.I_CmsImportExportHandler#exportData(org.opencms.file.CmsObject, org.opencms.report.I_CmsReport)
*/
public void exportData(CmsObject cms, I_CmsReport report) throws CmsException {
report.print(report.key("report.export_module_begin"), I_CmsReport.C_FORMAT_HEADLINE);
if (report instanceof CmsHtmlReport) {
report.println(" <i>" + getModuleName() + "</i>", I_CmsReport.C_FORMAT_HEADLINE);
} else {
report.println(" " + getModuleName(), I_CmsReport.C_FORMAT_HEADLINE);
}
if ((cms == null) || !cms.isAdmin()) {
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
if (! OpenCms.getModuleManager().hasModule(getModuleName())) {
// module not available
throw new CmsConfigurationException("No module '" + getModuleName() + "' available for export", CmsConfigurationException.C_CONFIGURATION_ERROR);
}
// generate module XML
CmsModule module = OpenCms.getModuleManager().getModule(getModuleName());
if (! module.getVersion().isUpdated()) {
// increment version number if not recently updated
module.getVersion().increment();
}
// reset update status so that all following exports auto-increment the number
module.getVersion().setUpdated(false);
Element moduleElement = CmsModuleXmlHandler.generateXml(module);
// export the module using the standard export
new CmsExport(cms, getFileName(), getAdditionalResources(), false, false, moduleElement, false, 0, report);
report.println(report.key("report.export_module_end"), I_CmsReport.C_FORMAT_HEADLINE);
}
/**
* Returns the VFS resources to be exported additionally with the module.<p>
*
* @return the VFS resources to be exported additionally with the module
*/
public String[] getAdditionalResources() {
return (String[]) m_additionalResources.toArray();
}
/**
* @see org.opencms.importexport.I_CmsImportExportHandler#getDescription()
*/
public String getDescription() {
return m_description;
}
/**
* Returns the name of the export file in the real file system.<p>
*
* @return the name of the export file in the real file system
*/
public String getFileName() {
return m_fileName;
}
/**
* Returns the (package) name of the module to be exported.<p>
*
* @return the (package) name of the module to be exported
*/
public String getModuleName() {
return m_moduleName;
}
/**
* Returns the VFS resources to be exported additionally with the module as a list.<p>
*
* @return the VFS resources to be exported additionally with the module as a list
*/
public List getResourcesAsList() {
return m_additionalResources;
}
/**
* @see org.opencms.importexport.I_CmsImportExportHandler#importData(org.opencms.file.CmsObject, java.lang.String, java.lang.String, org.opencms.report.I_CmsReport)
*/
public synchronized void importData(CmsObject cms, String importFile, String importPath, I_CmsReport report)
throws CmsException {
CmsProject previousProject = cms.getRequestContext().currentProject();
try {
CmsProject importProject = null;
try {
cms.getRequestContext().saveSiteRoot();
cms.getRequestContext().setSiteRoot("/");
try {
// try to read a (leftover) module import project
importProject = cms.readProject(C_IMPORT_MODULE_PROJECT_NAME);
} catch (CmsException e) {
// create a Project to import the module
importProject = cms.createProject(C_IMPORT_MODULE_PROJECT_NAME, "A System generated project to import the module " + getModuleName(), OpenCms.getDefaultUsers().getGroupAdministrators(), OpenCms.getDefaultUsers().getGroupAdministrators(), I_CmsConstants.C_PROJECT_TYPE_TEMPORARY);
}
cms.getRequestContext().setCurrentProject(importProject);
// copy the root folder to the project
cms.copyResourceToProject("/");
} finally {
cms.getRequestContext().restoreSiteRoot();
}
importFile = importFile.replace('\\', '/');
String moduleZipName = importFile.substring(importFile.lastIndexOf('/') + 1);
String modulePackageName;
if (moduleZipName.toLowerCase().endsWith(".zip")) {
modulePackageName = moduleZipName.substring(0, moduleZipName.lastIndexOf('.'));
int pos = modulePackageName.lastIndexOf('_');
if (pos > 0) {
modulePackageName = modulePackageName.substring(0, pos);
}
} else {
modulePackageName = moduleZipName;
}
report.print(report.key("report.import_module_begin"), I_CmsReport.C_FORMAT_HEADLINE);
if (report instanceof CmsHtmlReport) {
report.println(" <i>" + modulePackageName + "</i>", I_CmsReport.C_FORMAT_HEADLINE);
} else {
report.println(" " + modulePackageName, I_CmsReport.C_FORMAT_HEADLINE);
}
importModule(cms, importFile, report);
report.println(report.key("report.publish_project_begin"), I_CmsReport.C_FORMAT_HEADLINE);
// now unlock and publish the project
cms.unlockProject(importProject.getId());
cms.publishProject(report);
report.println(report.key("report.publish_project_end"), I_CmsReport.C_FORMAT_HEADLINE);
report.println(report.key("report.import_module_end"), I_CmsReport.C_FORMAT_HEADLINE);
} finally {
cms.getRequestContext().setCurrentProject(previousProject);
}
}
/**
* @see org.opencms.importexport.I_CmsImportExportHandler#matches(org.dom4j.Document)
*/
public boolean matches(Document manifest) {
Element rootElement = manifest.getRootElement();
boolean hasModuleNode = (rootElement.selectNodes("./module/name").size() > 0);
return (hasModuleNode);
}
/**
* Sets the VFS resources to be exported additionally with the module.<p>
*
* @param resources the VFS resources to be exported additionally with the module
*/
public void setAdditionalResources(String[] resources) {
m_additionalResources = Arrays.asList(resources);
}
/**
* @see org.opencms.importexport.I_CmsImportExportHandler#setDescription(java.lang.String)
*/
public void setDescription(String description) {
m_description = description;
}
/**
* Sets the name of the export file in the real file system.<p>
*
* @param fileName the name of the export file in the real file system
*/
public void setFileName(String fileName) {
m_fileName = fileName;
}
/**
* Will be called by the digester if a module was imported.<p>
*
* @param moduleHandler contains the imported module
*/
public void setModule(CmsModuleXmlHandler moduleHandler) {
m_importedModule = moduleHandler.getModule();
}
/**
* Sets the (package) name of the module to be exported.<p>
*
* @param moduleName the (package) name of the module to be exported
*/
public void setModuleName(String moduleName) {
m_moduleName = moduleName;
}
/**
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
try {
if (m_additionalResources != null) {
m_additionalResources.clear();
}
m_additionalResources = null;
} catch (Exception e) {
// noop
} finally {
super.finalize();
}
}
/**
* Returns the module imported with the digester.<p>
*
* @return the module imported with the digester
*/
private CmsModule getModule() {
return m_importedModule;
}
private synchronized void importModule(CmsObject cms, String importResource, I_CmsReport report)
throws CmsSecurityException, CmsConfigurationException, CmsException {
if ((cms == null) || !cms.isAdmin()) {
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
// read the module from the import file
CmsModule importedModule = readModuleFromImport(importResource);
// check if the module is already istalled
if (OpenCms.getModuleManager().hasModule(importedModule.getName())) {
throw new CmsConfigurationException("The module '" + importedModule.getName() + "' is already installed", CmsConfigurationException.C_CONFIGURATION_ERROR);
}
// check the module dependencies
List dependencies = OpenCms.getModuleManager().checkDependencies(importedModule, CmsModuleManager.C_DEPENDENCY_MODE_IMPORT);
if (dependencies.size() > 0) {
// some dependencies not fullfilled
String missingModules = "";
Iterator it = dependencies.iterator();
while (it.hasNext()) {
CmsModuleDependency dependency = (CmsModuleDependency)it.next();
missingModules += "Module: " + dependency.getName() + " Version: " + dependency.getVersion() + "\n";
}
throw new CmsConfigurationException("The following dependencies for the module are not fulfilled:\n" + missingModules, CmsConfigurationException.C_CONFIGURATION_ERROR);
}
Vector exclusion = new Vector();
// add all default directories to the exclusion list
// this prevents modification of these directories
exclusion.add(I_CmsWpConstants.C_VFS_PATH_SYSTEM);
exclusion.add(I_CmsWpConstants.C_VFS_PATH_MODULES);
exclusion.add(I_CmsWpConstants.C_VFS_PATH_WORKPLACE);
exclusion.add(I_CmsWpConstants.C_VFS_PATH_GALLERIES);
exclusion.add(I_CmsWpConstants.C_VFS_PATH_HELP);
exclusion.add(I_CmsWpConstants.C_VFS_PATH_LOCALES);
exclusion.add(I_CmsWpConstants.C_VFS_PATH_SCRIPTS);
exclusion.add(I_CmsWpConstants.C_VFS_PATH_SYSTEMPICS);
exclusion.add(I_CmsWpConstants.C_VFS_GALLERY_PICS);
exclusion.add(I_CmsWpConstants.C_VFS_GALLERY_HTML);
exclusion.add(I_CmsWpConstants.C_VFS_GALLERY_DOWNLOAD);
exclusion.add(I_CmsWpConstants.C_VFS_GALLERY_EXTERNALLINKS);
// import the module resources
CmsImport cmsImport = new CmsImport(cms, importResource, "/", report);
cmsImport.importResources(exclusion, new Vector(), new Vector(), null, null);
// finally add the imported module to the module manager
OpenCms.getModuleManager().addModule(cms, importedModule);
}
}
|
package org.opencms.ui.actions;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.ui.I_CmsDialogContext;
import org.opencms.ui.contextmenu.CmsMenuItemVisibilityMode;
import org.opencms.ui.contextmenu.CmsStandardVisibilityCheck;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
/**
* Class representing an abstract gallery dialog action.<p>
*/
public abstract class A_CmsGalleryDialogAction extends A_CmsWorkplaceAction {
/** Logger instance for this class. */
static final Log LOG = CmsLog.getLog(A_CmsGalleryDialogAction.class);
/**
* @see org.opencms.ui.contextmenu.I_CmsHasMenuItemVisibility#getVisibility(org.opencms.file.CmsObject, java.util.List)
*/
public CmsMenuItemVisibilityMode getVisibility(CmsObject cms, List<CmsResource> resources) {
if (resources.size() == 1) {
CmsResource resource = resources.get(0);
if (resource.isFolder()) {
String type = OpenCms.getResourceManager().getResourceType(resource).getTypeName();
if (Arrays.asList(getSupportedGalleryTypes()).contains(type)) {
return CmsStandardVisibilityCheck.VISIBLE.getVisibility(cms, resources);
}
} else {
CmsResource parentGallery = getParentGallery(cms, resource);
if (parentGallery != null) {
List<CmsResource> parentList = new ArrayList<CmsResource>();
parentList.add(parentGallery);
return getVisibility(cms, parentList);
}
}
}
return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
}
/**
* Returns the gallery.<p>
*
* @param context the dialog context
* @return the gallery
*/
protected CmsResource getGallery(I_CmsDialogContext context) {
CmsResource resource = context.getResources().get(0);
return resource.isFolder() ? resource : getParentGallery(context.getCms(), resource);
}
/**
* Returns the gallery types supported by this dialog action.
*
* @return the gallery types
*/
abstract protected String[] getSupportedGalleryTypes();
/**
* If the context of this gallery dialog action is a gallery item, returns the parent gallery.<p>
*
* @param cms the CMS object
* @param resource the resource that has opened the context menu
* @return the parent gallery
*/
private CmsResource getParentGallery(CmsObject cms, CmsResource resource) {
String parentFolder = CmsResource.getParentFolder(resource.getRootPath());
parentFolder = cms.getRequestContext().removeSiteRoot(parentFolder);
CmsResource parentGallery = null;
try {
parentGallery = cms.readResource(parentFolder);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
return parentGallery;
}
}
|
package org.openhab.habdroid.model;
import java.util.ArrayList;
public class OpenHABNFCActionList {
private ArrayList<String> actionNames;
private ArrayList<String> actionCommands;
public OpenHABNFCActionList(OpenHABWidget openHABWidget) {
actionNames = new ArrayList<String>();
actionCommands = new ArrayList<String>();
if (openHABWidget.getItem() != null) {
// If widget have mappings, we will populate names and commands with values
// from this mappings
if (openHABWidget.hasMappings()) {
// Else we only can do it for Switch widget with On/Off/Toggle commands
for (int i = 0; i < openHABWidget.getMappings().size(); i++) {
actionNames.add(openHABWidget.getMappings().get(i).getLabel());
actionCommands.add(openHABWidget.getMappings().get(i).getCommand());
}
} else if (openHABWidget.getType().equals("Switch")) {
if (openHABWidget.getItem().getType().equals("SwitchItem")) {
actionNames.add("On");
actionCommands.add("ON");
actionNames.add("Off");
actionCommands.add("OFF");
actionNames.add("Toggle");
actionCommands.add("TOGGLE");
} else if (openHABWidget.getItem().getType().equals("RollershutterItem")) {
actionNames.add("Up");
actionCommands.add("UP");
actionNames.add("Down");
actionCommands.add("DOWN");
}
}
}
}
public String[] getNames() {
return this.actionNames.toArray(new String[this.actionNames.size()]);
}
public String[] getCommands() {
return this.actionCommands.toArray(new String[this.actionCommands.size()]);
}
}
|
package fi.nls.oskari.cache;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.util.Collections;
import java.util.Set;
/**
* Manages Jedis connections using JedisPool (connection pool)
*/
public class JedisManager {
public static final String CLUSTERED_ENV_PROFILE = "redis-session";
public static String ERROR_REDIS_COMMUNICATION_FAILURE = "redis_communication_failure";
public static String PUBSUB_CHANNEL_PREFIX = "oskari_";
public static final int EXPIRY_TIME_DAY = 86400;
private final static Logger log = LogFactory.getLogger(JedisManager.class);
private static final JedisManager instance = new JedisManager();
private static volatile JedisPool pool;
private static final String KEY_REDIS_HOSTNAME = "redis.hostname";
private static final String KEY_REDIS_PORT = "redis.port";
private static final String KEY_REDIS_POOL_SIZE = "redis.pool.size";
private static Boolean isClustered = null;
/**
* Blocking construction of instances from other classes by making constructor private
*/
private JedisManager() {}
public static String getHost() {
return PropertyUtil.get(KEY_REDIS_HOSTNAME, "localhost");
}
public static int getPort() {
return ConversionHelper.getInt(PropertyUtil.get(KEY_REDIS_PORT), 6379);
}
public static int getPoolSize() {
return ConversionHelper.getInt(PropertyUtil.get(KEY_REDIS_POOL_SIZE), 30);
}
public static void connect() {
JedisManager.connect(getPoolSize(), getHost(), getPort());
}
/**
* Connects configured connection pool to a Redis server
*/
public static void connect(final int poolSize, final String host, final int port) {
if(pool != null) {
log.warn("Pool already created! Connect called multiple times. Tried connecting to:", host);
return;
}
final JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setMaxIdle(poolSize / 2);
poolConfig.setMinIdle(1);
poolConfig.setTimeBetweenEvictionRunsMillis(-1);
poolConfig.setTestOnBorrow(true);
final JedisPool oldPool = pool;
pool = new JedisPool(poolConfig, host, port);
log.debug("Created Redis connection pool with host", host, "port", port);
if (null != oldPool) {
log.debug("Closing old Jedis pool");
oldPool.close();
}
}
public static void shutdown() {
pool.close();
}
/**
* Destroys the pool
*/
public void release() {
pool.destroy();
}
/**
* Gets Jedis connection from the pool
* @return Jedis instance or ServiceRuntimeExceptionin
*/
public Jedis getJedis() {
return getJedis(false);
}
public Jedis getJedis(boolean throwException) {
try {
return pool.getResource();
} catch (Exception e) {
log.error("Getting Jedis connection from the pool failed:", e.getMessage());
if (e.getCause() != null) {
log.debug(e, "Cause:", e.getCause().getMessage());
}
if(throwException) {
throw new ServiceRuntimeException("Getting Jedis connection from the pool failed: " + e.getMessage(),
e.getCause(), ERROR_REDIS_COMMUNICATION_FAILURE);
}
}
return null;
}
/**
* Thread-safe String GET for Redis
*
* @param key
* @return string
*/
public static String getNecessary(String key) {
return get(key, true);
}
/**
* Thread-safe String GET for Redis
* throws new runtime exception, if any exception found
* @param key
* @return string
*/
public static String get(String key) {
return get(key, false);
}
/**
* Thread-safe String GET for Redis
*
* @param key
* @param throwException throws new runtime exception, if any exception found
* @return string
*/
public static String get(String key, boolean throwException) {
try (Jedis jedis = instance.getJedis(throwException)) {
if (jedis == null) {
return null;
}
return jedis.get(key);
} catch (JedisConnectionException e) {
log.error("Failed to get", key);
if (throwException) {
throw new ServiceRuntimeException("Failed to get " + key + " returning broken connection...: " + e.getMessage(),
e.getCause(), ERROR_REDIS_COMMUNICATION_FAILURE);
}
return null;
} catch (Exception e) {
log.error("Getting", key, "from Redis failed:", e.getMessage());
if (throwException) {
throw new ServiceRuntimeException("Getting" + key + "from Redis failed: " + e.getMessage(),
e.getCause(), ERROR_REDIS_COMMUNICATION_FAILURE);
}
return null;
}
}
/**
* Thread-safe byte[] GET for Redis
*
* @param key
* @return bytes
*/
public static byte[] get(byte[] key) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.get(key);
} catch(JedisConnectionException e) {
log.error("Failed to get", key);
log.error("Broken connection closed");
return null;
} catch (Exception e) {
log.error("Getting", key, "from Redis failed:", e.getMessage());
return null;
}
}
/**
* Thread-safe String SETEX for Redis
*
* @param key
* @param seconds
* @param value
* @return string
*/
public static String setex(String key, int seconds, String value) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.setex(key, seconds, value);
} catch(JedisConnectionException e) {
log.error("Failed to set", key);
return null;
} catch (Exception e) {
log.error("Setting", key, "to Redis failed:", e.getMessage());
return null;
}
}
/**
* Thread-safe byte[] SETEX for Redis
*
* @param key
* @param seconds
* @param value
* @return string
*/
public static String setex(byte[] key, int seconds, byte[] value) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.setex(key, seconds, value);
} catch(JedisConnectionException e) {
log.error("Failed to set", key);
return null;
} catch (Exception e) {
log.error("Setting", key, "to Redis failed:", e.getMessage());
return null;
}
}
/**
* Thread-safe KEYS
*
* @param pattern
* @return keys
*/
public static Set<String> keys(String pattern) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return Collections.emptySet();
}
return jedis.keys(pattern + "*");
} catch(JedisConnectionException e) {
log.error("Failed to run KEYS", pattern);
return null;
} catch (Exception e) {
log.error("Running KEYS", pattern + "on Redis failed:", e.getMessage());
return null;
}
}
/**
* Thread-safe String HKEYS for Redis
*
* @param key
* @return set of string
*/
public static Set<String> hkeys(String key) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return Collections.emptySet();
}
return jedis.hkeys(key);
} catch(JedisConnectionException e) {
log.error("Failed to hkeys", key);
return null;
} catch (Exception e) {
log.error("Getting HKEYS", key + "on Redis failed:", e.getMessage());
return null;
}
}
/**
* Thread-safe String HGET for Redis
*
* @param key
* @param field
* @return string
*/
public static String hget(String key, String field) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.hget(key, field);
} catch(JedisConnectionException e) {
log.error("Failed to hget", key);
return null;
} catch (Exception e) {
log.error("Getting HGET", key + "on Redis failed:", e.getMessage());
return null;
}
}
/**
* Thread-safe Long HSET for Redis
*
* @param key
* @param field
* @param value
* @return Long or null when there was an exception
*/
public static Long hset(String key, String field, String value) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.hset(key, field, value);
} catch(JedisConnectionException e) {
log.error("Failed to hset", key);
return null;
} catch (Exception e) {
log.error("Setting", key, "failed miserably");
return null;
}
}
/**
* Thread-safe Long HDEL for Redis
*
* @param key
* @param fields
* @return Long or null when there was an exception
*/
public static Long hdel(String key, String... fields) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.hdel(key, fields);
} catch(JedisConnectionException e) {
log.error("Failed to hdel", key);
return null;
} catch (Exception e) {
log.error("Removing", key, "with fields:", fields, "failed miserably");
return null;
}
}
/**
* Thread-safe Long HINCRBY for Redis
*
* @param key
* @param field
* @return Long or null when there was an exception
*/
public static Long hincrBy(String key, String field, long increment) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.hincrBy(key, field, increment);
} catch(JedisConnectionException e) {
log.error("Failed to hincrBy", key, field);
return null;
} catch (Exception e) {
log.error("Incrementing", key, field, "failed miserably");
return null;
}
}
/**
* Thread-safe Long DEL for Redis
*
* @param keys
* @return long
*/
public static Long del(String... keys) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
return jedis.del(keys);
} catch(JedisConnectionException e) {
log.error("Failed to delete", keys);
return null;
} catch (Exception e) {
log.error("Deleting", keys, "failed miserably");
return null;
}
}
/**
* Thread-safe Long DEL with key set
*
* @param key
* @return long
*/
public static Long delAll(String key) {
try (Jedis jedis = instance.getJedis()){
if (jedis == null) {
return null;
}
Set<String> keys = jedis.keys(key + "*");
if(keys.size() > 0) {
return jedis.del(keys.toArray(new String[keys.size()]));
}
return 0L;
} catch(JedisConnectionException e) {
log.error("Failed to del", key + "*");
return null;
} catch (Exception e) {
log.error("Deleting", key + "* failed miserably");
return null;
}
}
/**
* Returns length of string for a key (0 if key doesn't exist).
* -1 means system level error.
* @param key
* @return
*/
public static long getValueStringLength(String key) {
try (Jedis jedis = instance.getJedis()){
if (jedis == null) {
return -1;
}
return jedis.strlen(key);
} catch(JedisConnectionException e) {
log.error("Failed to strlen", key);
} catch (Exception e) {
log.error("Getting key length", key + " failed miserably");
}
return -1;
}
/**
* Returns the number of elements inside the list after the push operation.
* -1 means system level error.
* @param key
* @param values
* @return
*/
public static long pushToList(String key, String ...values) {
try (Jedis jedis = instance.getJedis()){
if (jedis == null) {
return -1;
}
return jedis.rpush(key, values);
} catch(JedisConnectionException e) {
log.error("Failed to rpush", key);
} catch (Exception e) {
log.error("Adding to list", key + " failed miserably");
}
return -1;
}
/**
* Removes and returns the last element from the list.
* @param key
* @return
*/
public static String popList(String key) {
return popList(key, false);
}
/**
* Removes and returns an item from list.
* With head is true uses the first element, with false the last element.
* @param key the list key
* @param head
* @return
*/
public static String popList(String key, boolean head) {
try (Jedis jedis = instance.getJedis()){
if (jedis == null) {
return null;
}
String value;
if(head) {
value = jedis.lpop(key);
} else {
value = jedis.rpop(key);
}
if("nil".equalsIgnoreCase(value)) {
// If the key does not exist or the list is already empty the special value 'nil' is returned.
return null;
}
return value;
} catch(JedisConnectionException e) {
log.error("Failed to lpop", key);
} catch (Exception e) {
log.error("Popping from list", key + " failed miserably");
}
return null;
}
/**
* Thread-safe PUBLISH
*
* @param channel
* @param message
* @return long
*/
public static Long publish(final String channel, final String message) {
try (Jedis jedis = instance.getJedis()) {
if (jedis == null) {
return null;
}
log.debug("Sending to", PUBSUB_CHANNEL_PREFIX + channel, "msg:", message);
return jedis.publish(PUBSUB_CHANNEL_PREFIX + channel, message);
} catch(JedisConnectionException e) {
log.error("Failed to publish on:", channel);
return null;
} catch (Exception e) {
log.error("Publishing on:", channel, "failed miserably");
return null;
}
}
/**
* Thread-safe SUBSCRIBE
* @deprecated Use org.oskari.cluster.ClusterManager.getClientFor("[funcId]").addListener() instead
*
* @param subscriber
* @param pChannel channel to subscribe to
*/
@Deprecated
public static void subscribe(final JedisSubscriber subscriber, final String pChannel) {
new Thread(() -> {
String channel = PUBSUB_CHANNEL_PREFIX + pChannel;
// "Make sure the subscriber and publisher threads do not share the same Jedis connection."
// A client subscribed to one or more channels should not issue commands,
// although it can subscribe and unsubscribe to and from other channels.
// NOTE!! create a new client for subscriptions instead of using pool to make sure clients don't conflict
try (Jedis jedis = new Jedis(getHost(), getPort())) {
if (jedis == null) {
return;
}
log.warn("Subscribing on", channel);
// Subscribe is a blocking action hence the thread
// Also we don't care about pooling here since
// the client remains blocked for subscription
jedis.subscribe(subscriber, channel);
} catch (Exception e) {
log.error(e,"Subscribing on:", channel, "failed");
}
}).start();
}
public static boolean isClusterEnv() {
if (isClustered == null) {
final String[] configuredProfiles = PropertyUtil.getCommaSeparatedList("oskari.profiles");
isClustered = hasClusterProfile(configuredProfiles);
}
return isClustered;
}
protected static boolean hasClusterProfile(String[] configuredProfiles) {
if (configuredProfiles == null) {
return false;
}
for (String profile: configuredProfiles) {
if (CLUSTERED_ENV_PROFILE.equalsIgnoreCase(profile.trim())) {
return true;
}
}
return false;
}
}
|
package purejavacomm;
// FIXME move javadoc comments for input stream to SerialPort.java
import java.io.*;
import java.util.*;
import com.sun.jna.Platform;
import jtermios.*;
import static jtermios.JTermios.JTermiosLogging.*;
import static jtermios.JTermios.*;
import com.sun.jna.Platform;
public class PureJavaSerialPort extends SerialPort {
final boolean USE_POLL;
final boolean RAW_READ_MODE;
private Thread m_Thread;
private volatile SerialPortEventListener m_EventListener;
private volatile OutputStream m_OutputStream;
private volatile InputStream m_InputStream;
private volatile int m_FD = -1;
private volatile boolean m_HaveNudgePipe = false;
private volatile int m_PipeWrFD = 0;
private volatile int m_PipeRdFD = 0;
private byte[] m_NudgeData = { 0 };
private volatile int m_BaudRate;
private volatile int m_DataBits;
private volatile int m_FlowControlMode;
private volatile int m_Parity;
private volatile int m_StopBits;
private volatile boolean m_ReceiveTimeOutEnabled;
private volatile int m_ReceiveTimeOutValue;
private volatile boolean m_ReceiveThresholdEnabled;
private volatile int m_ReceiveThresholdValue;
private volatile boolean m_NotifyOnDataAvailable;
private volatile boolean m_DataAvailableNotified;
private volatile boolean m_NotifyOnOutputEmpty;
private volatile boolean m_OutputEmptyNotified;
private volatile boolean m_NotifyOnRI;
private volatile boolean m_NotifyOnCTS;
private volatile boolean m_NotifyOnDSR;
private volatile boolean m_NotifyOnCD;
private volatile boolean m_NotifyOnOverrunError;
private volatile boolean m_NotifyOnParityError;
private volatile boolean m_NotifyOnFramingError;
private volatile boolean m_NotifyOnBreakInterrupt;
private volatile boolean m_ThreadRunning;
private volatile boolean m_ThreadStarted;
private int[] m_ioctl = { 0 };
private int m_ControlLineStates;
// we cache termios in m_Termios because we don't rely on reading it back with tcgetattr()
// which for Mac OS X / CRTSCTS does not work, it is also more efficient
private Termios m_Termios = new Termios();
private int m_MinVTIME;
private void sendDataEvents(boolean read, boolean write) {
if (read && m_NotifyOnDataAvailable && !m_DataAvailableNotified) {
m_DataAvailableNotified = true;
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DATA_AVAILABLE, false, true));
}
if (write && m_NotifyOnOutputEmpty && !m_OutputEmptyNotified) {
m_OutputEmptyNotified = true;
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.OUTPUT_BUFFER_EMPTY, false, true));
}
}
private synchronized void sendNonDataEvents() {
if (ioctl(m_FD, TIOCMGET, m_ioctl) < 0)
return; //FIXME decide what to with errors in the background thread
int oldstates = m_ControlLineStates;
m_ControlLineStates = m_ioctl[0];
int newstates = m_ControlLineStates;
int changes = oldstates ^ newstates;
if (changes == 0)
return;
int line;
if (m_NotifyOnCTS && (((line = TIOCM_CTS) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CTS, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnDSR && (((line = TIOCM_DSR) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DSR, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnRI && (((line = TIOCM_RI) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.RI, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnCD && (((line = TIOCM_CD) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CD, (oldstates & line) != 0, (newstates & line) != 0));
}
@Override
synchronized public void addEventListener(SerialPortEventListener eventListener) throws TooManyListenersException {
checkState();
if (eventListener == null)
throw new IllegalArgumentException("eventListener cannot be null");
if (m_EventListener != null)
throw new TooManyListenersException();
m_EventListener = eventListener;
if (!m_ThreadStarted) {
m_ThreadStarted = true;
m_Thread.start();
}
}
@Override
synchronized public int getBaudRate() {
checkState();
return m_BaudRate;
}
@Override
synchronized public int getDataBits() {
checkState();
return m_DataBits;
}
@Override
synchronized public int getFlowControlMode() {
checkState();
return m_FlowControlMode;
}
@Override
synchronized public int getParity() {
checkState();
return m_Parity;
}
@Override
synchronized public int getStopBits() {
checkState();
return m_StopBits;
}
@Override
synchronized public boolean isCD() {
checkState();
return getControlLineState(TIOCM_CD);
}
@Override
synchronized public boolean isCTS() {
checkState();
return getControlLineState(TIOCM_CTS);
}
@Override
synchronized public boolean isDSR() {
checkState();
return getControlLineState(TIOCM_DSR);
}
@Override
synchronized public boolean isDTR() {
checkState();
return getControlLineState(TIOCM_DTR);
}
@Override
synchronized public boolean isRI() {
checkState();
return getControlLineState(TIOCM_RI);
}
@Override
synchronized public boolean isRTS() {
checkState();
return getControlLineState(TIOCM_RTS);
}
@Override
synchronized public void notifyOnBreakInterrupt(boolean x) {
checkState();
m_NotifyOnBreakInterrupt = x;
}
@Override
synchronized public void notifyOnCTS(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_CTS);
m_NotifyOnCTS = x;
nudgePipe();
}
@Override
synchronized public void notifyOnCarrierDetect(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_CD);
m_NotifyOnCD = x;
nudgePipe();
}
@Override
synchronized public void notifyOnDSR(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_DSR);
m_NotifyOnDSR = x;
nudgePipe();
}
@Override
synchronized public void notifyOnDataAvailable(boolean x) {
checkState();
m_NotifyOnDataAvailable = x;
nudgePipe();
}
@Override
synchronized public void notifyOnFramingError(boolean x) {
checkState();
m_NotifyOnFramingError = x;
}
@Override
synchronized public void notifyOnOutputEmpty(boolean x) {
checkState();
m_NotifyOnOutputEmpty = x;
nudgePipe();
}
@Override
synchronized public void notifyOnOverrunError(boolean x) {
checkState();
m_NotifyOnOverrunError = x;
}
@Override
synchronized public void notifyOnParityError(boolean x) {
checkState();
m_NotifyOnParityError = x;
}
@Override
synchronized public void notifyOnRingIndicator(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_RI);
m_NotifyOnRI = x;
nudgePipe();
}
@Override
synchronized public void removeEventListener() {
checkState();
m_EventListener = null;
}
@Override
synchronized public void sendBreak(int duration) {
checkState();
// FIXME POSIX does not specify how duration is interpreted
// Opengroup POSIX says:
// If the terminal is using asynchronous serial data transmission, tcsendbreak()
// shall cause transmission of a continuous stream of zero-valued bits for a specific duration.
// If duration is 0, it shall cause transmission of zero-valued bits for at least 0.25 seconds,
// and not more than 0.5 seconds. If duration is not 0, it shall send zero-valued bits for an implementation-defined period of time.
// From the man page for Linux tcsendbreak:
// The effect of a non-zero duration with tcsendbreak() varies.
// SunOS specifies a break of duration*N seconds,
// where N is at least 0.25, and not more than 0.5. Linux, AIX, DU, Tru64 send a break of duration milliseconds.
// FreeBSD and NetBSD and HP-UX and MacOS ignore the value of duration.
// Under Solaris and Unixware, tcsendbreak() with non-zero duration behaves like tcdrain().
tcsendbreak(m_FD, duration);
}
@Override
synchronized public void setDTR(boolean x) {
checkState();
setControlLineState(TIOCM_DTR, x);
}
@Override
synchronized public void setRTS(boolean x) {
checkState();
setControlLineState(TIOCM_RTS, x);
}
@Override
synchronized public void disableReceiveFraming() {
checkState();
// Not supported
}
@Override
synchronized public void disableReceiveThreshold() {
checkState();
m_ReceiveThresholdEnabled = false;
}
@Override
synchronized public void disableReceiveTimeout() {
checkState();
m_ReceiveTimeOutEnabled = false;
}
@Override
synchronized public void enableReceiveFraming(int arg0) throws UnsupportedCommOperationException {
checkState();
throw new UnsupportedCommOperationException();
}
@Override
synchronized public void enableReceiveThreshold(int value) throws UnsupportedCommOperationException {
checkState();
if (m_ReceiveThresholdValue < 0)
throw new IllegalArgumentException("threshold" + value + " < 0 ");
m_ReceiveThresholdEnabled = true;
m_ReceiveThresholdValue = value;
}
@Override
synchronized public int getInputBufferSize() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public int getOutputBufferSize() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public void enableReceiveTimeout(int value) throws UnsupportedCommOperationException {
if (m_ReceiveThresholdValue < 0)
throw new IllegalArgumentException("threshold" + value + " < 0 ");
checkState();
m_ReceiveTimeOutEnabled = true;
m_ReceiveTimeOutValue = value;
}
@Override
synchronized public void setFlowControlMode(int mode) throws UnsupportedCommOperationException {
checkState();
synchronized (m_Termios) {
m_Termios.c_iflag &= ~IXANY;
if ((mode & (FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_RTSCTS_OUT)) != 0)
m_Termios.c_cflag |= CRTSCTS;
else
m_Termios.c_cflag &= ~CRTSCTS;
if ((mode & FLOWCONTROL_XONXOFF_IN) != 0)
m_Termios.c_iflag |= IXOFF;
else
m_Termios.c_iflag &= ~IXOFF;
if ((mode & FLOWCONTROL_XONXOFF_OUT) != 0)
m_Termios.c_iflag |= IXON;
else
m_Termios.c_iflag &= ~IXON;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
m_FlowControlMode = mode;
}
}
@Override
synchronized public void setSerialPortParams(int baudRate, int dataBits, int stopBits, int parity) throws UnsupportedCommOperationException {
checkState();
synchronized (m_Termios) {
Termios prev = new Termios();// (termios);
// save a copy in case we need to restore it
prev.set(m_Termios);
try {
checkReturnCode(setspeed(m_FD, m_Termios, baudRate));
int db;
switch (dataBits) {
case SerialPort.DATABITS_5:
db = CS5;
break;
case SerialPort.DATABITS_6:
db = CS6;
break;
case SerialPort.DATABITS_7:
db = CS7;
break;
case SerialPort.DATABITS_8:
db = CS8;
break;
default:
throw new UnsupportedCommOperationException("dataBits = " + dataBits);
}
int sb;
switch (stopBits) {
case SerialPort.STOPBITS_1:
sb = 1;
break;
case SerialPort.STOPBITS_2:
sb = 2;
break;
default:
throw new UnsupportedCommOperationException("stopBits = " + stopBits);
}
int fi = m_Termios.c_iflag;
int fc = m_Termios.c_cflag;
switch (parity) {
case SerialPort.PARITY_NONE:
fc &= ~PARENB;
fi &= ~(INPCK | ISTRIP);
break;
case SerialPort.PARITY_EVEN:
fc |= PARENB;
fc &= ~PARODD;
fi &= ~(INPCK | ISTRIP);
break;
case SerialPort.PARITY_ODD:
fc |= PARENB;
fc |= PARODD;
fi &= ~(INPCK | ISTRIP);
break;
default:
throw new UnsupportedCommOperationException("parity = " + parity);
}
// update the hardware
fc &= ~CSIZE; /* Mask the character size bits */
fc |= db; /* Set data bits */
if (sb == 2)
fc |= CSTOPB;
else
fc &= ~CSTOPB;
m_Termios.c_cflag = fc;
m_Termios.c_iflag = fi;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
// finally everything went ok, so we can update our settings
m_BaudRate = baudRate;
m_Parity = parity;
m_DataBits = dataBits;
m_StopBits = stopBits;
} catch (UnsupportedCommOperationException e) {
m_Termios.set(prev);
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
throw e;
} catch (IllegalStateException e) {
m_Termios.set(prev);
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
throw e;
}
}
}
private static int min(int a, int b) {
return a < b ? a : b;
}
private static int max(int a, int b) {
return a > b ? a : b;
}
@Override
synchronized public OutputStream getOutputStream() throws IOException {
checkState();
if (m_OutputStream == null) {
m_OutputStream = new OutputStream() {
private byte[] m_Buffer = new byte[2048];
@Override
final public void write(int b) throws IOException {
checkState();
byte[] buf = { (byte) b };
write(buf, 0, 1);
}
@Override
final public void write(byte[] buffer, int offset, int length) throws IOException {
if (buffer == null)
throw new IllegalArgumentException();
if (offset < 0 || length < 0 || offset + length > buffer.length)
throw new IndexOutOfBoundsException("buffer.lengt " + buffer.length + " offset " + offset + " length " + length);
checkState();
while (length > 0) {
int n = min(length, min(m_Buffer.length, buffer.length - offset));
if (offset > 0) {
System.arraycopy(buffer, offset, m_Buffer, 0, n);
n = jtermios.JTermios.write(m_FD, m_Buffer, n);
} else
n = jtermios.JTermios.write(m_FD, buffer, n);
if (n < 0) {
PureJavaSerialPort.this.close();
throw new IOException();
}
length -= n;
offset += n;
}
m_OutputEmptyNotified = false;
}
@Override
final public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
final public void flush() throws IOException {
checkState();
if (tcdrain(m_FD) < 0) {
close();
throw new IOException();
}
}
};
}
return m_OutputStream;
}
synchronized public InputStream getInputStream() throws IOException {
checkState();
if (m_InputStream == null) {
m_InputStream = new InputStream() {
private int[] m_Available = { 0 };
private byte[] m_Buffer = new byte[2048];
private int m_VTIME = 0;
private int m_VMIN = 0;
private int[] m_ReadPollFD;
private byte[] m_Nudge;
private FDSet m_ReadFDSet;
private TimeVal m_ReadTimeVal;
{ // initialized block instead of construct in anonymous class
m_ReadFDSet = newFDSet();
m_ReadTimeVal = new TimeVal();
m_ReadPollFD = new int[4];
m_ReadPollFD[0] = m_FD;
m_ReadPollFD[1] = POLLIN_IN;
m_ReadPollFD[2] = m_PipeRdFD;
m_ReadPollFD[3] = POLLIN_IN;
m_Nudge = new byte[1];
}
@Override
final public int available() throws IOException {
checkState();
if (ioctl(m_FD, FIONREAD, m_Available) < 0) {
PureJavaSerialPort.this.close();
throw new IOException();
}
return m_Available[0];
}
@Override
final public int read() throws IOException {
checkState();
byte[] buf = { 0 };
int n = read(buf, 0, 1);
return n > 0 ? buf[0] & 0xFF : -1;
}
//THINGS TO TEST:
//-breakout from blocking read even without timeout
@Override
final public int read(byte[] buffer, int offset, int length) throws IOException {
if (buffer == null)
throw new IllegalArgumentException("buffer null");
if (offset < 0 || length < 0 || offset + length > buffer.length)
throw new IndexOutOfBoundsException("buffer.lengt " + buffer.length + " offset " + offset + " length " + length);
if (length == 0)
return 0;
checkState();
// Now configure VTIME and VMIN
int bytesReceived = 0;
long T0 = m_ReceiveTimeOutEnabled ? System.currentTimeMillis() : 0;
long T1 = T0;
while (true) {
int bytesLeft = length - bytesReceived;
int timeLeft = 0;
int vtime;
int vmin;
boolean pollingRead = (m_ReceiveTimeOutEnabled && m_ReceiveTimeOutValue == 0) || (m_ReceiveThresholdEnabled && m_ReceiveThresholdValue == 0);
if (pollingRead) {
// This is Kusti's interpretation of the JavaComm javadoc for getInputStream()
vtime = 0;
vmin = 0;
} else {
if (RAW_READ_MODE) {
vtime = min(255, ((m_ReceiveTimeOutEnabled ? m_ReceiveTimeOutValue : 0) + 99) / 100);
vmin = min(255, m_ReceiveThresholdEnabled ? m_ReceiveThresholdValue : 1);
} else {
// calculate VTIME value
// MAX_VALUE ???? minVTIME
timeLeft = m_ReceiveTimeOutEnabled ? max(0, m_ReceiveTimeOutValue - ((int) (T1 - T0))) : Integer.MAX_VALUE;
vtime = m_ReceiveTimeOutEnabled ? timeLeft : m_MinVTIME;
// roundup to 1/10th of sec
vtime = (vtime + 99) / 100;
// if overflow divide timeout to equal slices
if (vtime > 255)
vtime = vtime / (vtime / 256 + 1);
// calculate VMIN value
vmin = min(255, min(bytesLeft, m_ReceiveThresholdEnabled ? m_ReceiveThresholdValue : 1));
}
}
// to avoid unnecessary calls to OS we only call tcsetattr() if necessary
if (vtime != m_VTIME || vmin != m_VMIN) {
synchronized (m_Termios) {
m_VTIME = vtime;
m_VMIN = vmin;
m_Termios.c_cc[VTIME] = (byte) m_VTIME;
m_Termios.c_cc[VMIN] = (byte) m_VMIN;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
}
}
int bytesRead = 0;
boolean dataAvailable = false;
if (!RAW_READ_MODE && !pollingRead) {
// do a select()/poll(), just in case this read was
// called when no data is available
// so that we will not hang for ever in a read
if (USE_POLL) {
int n;
if (m_HaveNudgePipe)
n = poll(m_ReadPollFD, 2, timeLeft);
else
n = poll(m_ReadPollFD, 1, timeLeft);
if (n < 0 || m_FD < 0) // the port closed while we were blocking in poll
throw new IOException();
if ((m_ReadPollFD[3] & POLLIN_OUT) != 0)
jtermios.JTermios.read(m_PipeRdFD, m_Nudge, 1);
int re = m_ReadPollFD[1];
if ((re & POLLNVAL_OUT) != 0)
throw new IOException();
dataAvailable = (re & POLLIN_OUT) != 0;
} else {
FD_ZERO(m_ReadFDSet);
FD_SET(m_FD, m_ReadFDSet);
int maxFD = m_FD;
if (m_HaveNudgePipe) {
FD_SET(m_PipeRdFD, m_ReadFDSet);
if (m_PipeRdFD > maxFD)
maxFD = m_PipeRdFD;
}
if (timeLeft >= 1000) {
int t = timeLeft / 1000;
m_ReadTimeVal.tv_sec = t;
m_ReadTimeVal.tv_usec = (timeLeft - t * 1000) * 1000;
} else {
m_ReadTimeVal.tv_sec = 0;
m_ReadTimeVal.tv_usec = timeLeft * 1000;
}
//System.err.println(maxFD + " " + m_PipeRdFD + " " + m_FD);
if (select(maxFD + 1, m_ReadFDSet, null, null, m_ReadTimeVal) < 0)
throw new IOException();
if (m_FD < 0) // the port closed while we were blocking in select
throw new IOException();
dataAvailable = FD_ISSET(m_FD, m_ReadFDSet);
}
}
// at this point data is either available or we take our chances in raw mode
if (RAW_READ_MODE || pollingRead || dataAvailable) {
if (offset > 0) {
bytesRead = jtermios.JTermios.read(m_FD, m_Buffer, bytesLeft);
if (bytesRead > 0)
System.arraycopy(m_Buffer, 0, buffer, offset, bytesRead);
} else
bytesRead = jtermios.JTermios.read(m_FD, buffer, bytesLeft);
}
if (bytesRead < 0)
throw new IOException();
bytesReceived += bytesRead;
offset += bytesRead;
if (pollingRead)
break;
if (!m_ReceiveThresholdEnabled && bytesReceived > 0)
break;
if (m_ReceiveThresholdEnabled && bytesReceived >= min(m_ReceiveThresholdValue, length))
break;
T1 = m_ReceiveTimeOutEnabled ? System.currentTimeMillis() : 0;
if (m_ReceiveTimeOutEnabled && T1 - T0 >= m_ReceiveTimeOutValue)
break;
}
m_DataAvailableNotified = false;
return bytesReceived;
}
};
}
return m_InputStream;
}
@Override
synchronized public int getReceiveFramingByte() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public int getReceiveThreshold() {
checkState();
return m_ReceiveThresholdValue;
}
@Override
synchronized public int getReceiveTimeout() {
checkState();
return m_ReceiveTimeOutValue;
}
@Override
synchronized public boolean isReceiveFramingEnabled() {
checkState();
// Not supported
return false;
}
@Override
synchronized public boolean isReceiveThresholdEnabled() {
checkState();
return m_ReceiveThresholdEnabled;
}
@Override
synchronized public boolean isReceiveTimeoutEnabled() {
checkState();
return m_ReceiveTimeOutEnabled;
}
@Override
synchronized public void setInputBufferSize(int arg0) {
checkState();
// Not supported
}
@Override
synchronized public void setOutputBufferSize(int arg0) {
checkState();
// Not supported
}
private void nudgePipe() {
if (m_HaveNudgePipe)
write(m_PipeWrFD, m_NudgeData, 1);
}
@Override
synchronized public void close() {
int fd = m_FD;
if (fd != -1) {
m_FD = -1;
nudgePipe();
int flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
int fcres = fcntl(fd, F_SETFL, flags);
if (fcres != 0) // not much we can do if this fails, so just log it
log = log && log(1, "fcntl(%d,%d,%d) returned %d\n", m_FD, F_SETFL, flags, fcres);
if (m_Thread != null)
m_Thread.interrupt();
int err = jtermios.JTermios.close(fd);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
if (m_HaveNudgePipe) {
err = jtermios.JTermios.close(m_PipeRdFD);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
err = jtermios.JTermios.close(m_PipeWrFD);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
}
long t0 = System.currentTimeMillis();
while (m_ThreadRunning) {
try {
Thread.sleep(5);
if (System.currentTimeMillis() - t0 > 2000)
break;
} catch (InterruptedException e) {
break;
}
}
super.close();
}
}
/* package */PureJavaSerialPort(String name, int timeout) throws PortInUseException {
super();
boolean usepoll = false;
if (Platform.isLinux()) {
String key1 = "purejavacomm.use_poll";
String key2 = "purejavacomm.usepoll";
if (System.getProperty(key1) != null) {
usepoll = Boolean.getBoolean(key1);
log = log && log(1, "use of '%s' is deprecated, use '%s' instead\n", key1, key2);
} else if (System.getProperty(key2) != null)
usepoll = Boolean.getBoolean(key2);
else
usepoll = true;
}
USE_POLL = usepoll;
RAW_READ_MODE = Boolean.getBoolean("purejavacomm.rawreadmode");
this.name = name;
// unbelievable, sometimes quickly closing and re-opening fails on Windows
// so try a few times
int tries = 100;
long T0 = System.currentTimeMillis();
while ((m_FD = open(name, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
if (tries-- < 0 || System.currentTimeMillis() - T0 >= timeout)
throw new PortInUseException();
}
m_MinVTIME = Integer.getInteger("purejavacomm.minvtime", 100);
int flags = fcntl(m_FD, F_GETFL, 0);
flags &= ~O_NONBLOCK;
checkReturnCode(fcntl(m_FD, F_SETFL, flags));
m_BaudRate = 9600;
m_DataBits = SerialPort.DATABITS_8;
m_FlowControlMode = SerialPort.FLOWCONTROL_NONE;
m_Parity = SerialPort.PARITY_NONE;
m_StopBits = SerialPort.STOPBITS_1;
checkReturnCode(tcgetattr(m_FD, m_Termios));
cfmakeraw(m_FD, m_Termios);
m_Termios.c_cflag |= CLOCAL | CREAD;
m_Termios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
m_Termios.c_oflag &= ~OPOST;
m_Termios.c_cc[VSTART] = (byte) DC1;
m_Termios.c_cc[VSTOP] = (byte) DC3;
m_Termios.c_cc[VMIN] = 0;
m_Termios.c_cc[VTIME] = 0;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
try {
setSerialPortParams(m_BaudRate, m_DataBits, m_StopBits, m_Parity);
} catch (UnsupportedCommOperationException e) {
// This really should not happen
e.printStackTrace();
}
try {
setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException e) {
// This really should not happen
e.printStackTrace();
}
checkReturnCode(ioctl(m_FD, TIOCMGET, m_ioctl));
m_ControlLineStates = m_ioctl[0];
String nudgekey = "purejavacomm.usenudgepipe";
if (System.getProperty(nudgekey) == null || Boolean.getBoolean(nudgekey)) {
int[] pipes = new int[2];
if (pipe(pipes) == 0) {
m_HaveNudgePipe = true;
m_PipeRdFD = pipes[0];
m_PipeWrFD = pipes[1];
checkReturnCode(fcntl(m_PipeRdFD, F_SETFL, fcntl(m_PipeRdFD, F_GETFL, 0) | O_NONBLOCK));
}
}
Runnable runnable = new Runnable() {
public void run() {
try {
m_ThreadRunning = true;
final int TIMEOUT = Integer.getInteger("purejavacomm.pollperiod", 10);
TimeVal timeout = null;
FDSet rset = null;
FDSet wset = null;
int[] pollfd = null;
byte[] nudge = null;
if (USE_POLL) {
pollfd = new int[4];
nudge = new byte[1];
pollfd[0] = m_FD;
pollfd[2] = m_PipeRdFD;
} else {
rset = newFDSet();
wset = newFDSet();
timeout = new TimeVal();
int t = TIMEOUT * 1000;
timeout.tv_sec = t / 1000000;
timeout.tv_usec = t - timeout.tv_sec * 1000000;
}
while (m_FD >= 0) {
boolean read = (m_NotifyOnDataAvailable && !m_DataAvailableNotified);
boolean write = (m_NotifyOnOutputEmpty && !m_OutputEmptyNotified);
int n = 0;
boolean pollCtrlLines = m_NotifyOnCTS || m_NotifyOnDSR || m_NotifyOnRI || m_NotifyOnCD;
if (read || write || (!pollCtrlLines && m_HaveNudgePipe)) {
if (USE_POLL) {
int e = 0;
if (read)
e |= POLLIN_IN;
if (write)
e |= POLLOUT_IN;
pollfd[1] = e;
pollfd[3] = POLLIN_IN;
if (m_HaveNudgePipe)
n = poll(pollfd, 2, -1);
else
n = poll(pollfd, 1, TIMEOUT);
int re = pollfd[3];
if ((re & POLLNVAL_OUT) != 0) {
log = log && log(1, "poll() returned POLLNVAL, errno %d\n", errno());
break;
}
if ((re & POLLIN_OUT) != 0)
read(m_PipeRdFD, nudge, 1);
re = pollfd[1];
if ((re & POLLNVAL_OUT) != 0) {
log = log && log(1, "poll() returned POLLNVAL, errno %d\n", errno());
break;
}
read = read && (re & POLLIN_OUT) != 0;
write = write && (re & POLLOUT_OUT) != 0;
} else {
FD_ZERO(rset);
FD_ZERO(wset);
if (read)
FD_SET(m_FD, rset);
if (write)
FD_SET(m_FD, wset);
if (m_HaveNudgePipe)
FD_SET(m_PipeRdFD, rset);
n = select(m_FD + 1, rset, wset, null, m_HaveNudgePipe ? null : timeout);
read = read && FD_ISSET(m_FD, rset);
write = write && FD_ISSET(m_FD, wset);
}
if (m_FD < 0)
break;
if (n < 0) {
log = log && log(1, "select() or poll() returned %d, errno %d\n", n, errno());
close();
break;
}
} else {
Thread.sleep(TIMEOUT);
}
if (m_EventListener != null) {
if (read || write)
sendDataEvents(read, write);
if (pollCtrlLines)
sendNonDataEvents();
}
}
} catch (InterruptedException ie) {
} finally {
m_ThreadRunning = false;
}
}
};
m_Thread = new Thread(runnable, getName());
m_Thread.setDaemon(true);
}
synchronized private void updateControlLineState(int line) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new IllegalStateException();
m_ControlLineStates = (m_ioctl[0] & line) + (m_ControlLineStates & ~line);
}
synchronized private boolean getControlLineState(int line) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new IllegalStateException();
return (m_ioctl[0] & line) != 0;
}
synchronized private void setControlLineState(int line, boolean state) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new IllegalStateException();
if (state)
m_ioctl[0] |= line;
else
m_ioctl[0] &= ~line;
if (ioctl(m_FD, TIOCMSET, m_ioctl) == -1)
throw new IllegalStateException();
}
private void checkState() {
if (m_FD < 0)
throw new IllegalStateException("File descriptor is " + m_FD + " < 0, maybe closed by previous error condition");
}
private void checkReturnCode(int code) {
if (code != 0) {
String msg = String.format("JTermios call returned %d at %s", code, lineno(1)); // 1 qas implicit 0
log = log && log(1, "%s\n", msg);
try {
close();
} catch (Exception e) {
StackTraceElement st = e.getStackTrace()[0];
String msg2 = String.format("close threw %s at class %s line% d", e.getClass().getName(), st.getClassName(), st.getLineNumber());
log = log && log(1, "%s\n", msg2);
}
throw new IllegalStateException(msg);
}
}
}
|
package purejavacomm;
// FIXME move javadoc comments for input stream to SerialPort.java
import java.io.*;
import java.util.*;
import com.sun.jna.Platform;
import jtermios.*;
import static jtermios.JTermios.JTermiosLogging.*;
import static jtermios.JTermios.*;
import com.sun.jna.Platform;
public class PureJavaSerialPort extends SerialPort {
final boolean USE_POLL;
final boolean RAW_READ_MODE;
private Thread m_Thread;
private volatile SerialPortEventListener m_EventListener;
private volatile OutputStream m_OutputStream;
private volatile InputStream m_InputStream;
private volatile int m_FD = -1;
private volatile boolean m_HaveNudgePipe = false;
private volatile int m_PipeWrFD = 0;
private volatile int m_PipeRdFD = 0;
private byte[] m_NudgeData = { 0 };
private volatile int m_BaudRate;
private volatile int m_DataBits;
private volatile int m_FlowControlMode;
private volatile int m_Parity;
private volatile int m_StopBits;
private volatile boolean m_ReceiveTimeOutEnabled;
private volatile int m_ReceiveTimeOutValue;
private volatile boolean m_ReceiveThresholdEnabled;
private volatile int m_ReceiveThresholdValue;
private volatile boolean m_NotifyOnDataAvailable;
private volatile boolean m_DataAvailableNotified;
private volatile boolean m_NotifyOnOutputEmpty;
private volatile boolean m_OutputEmptyNotified;
private volatile boolean m_NotifyOnRI;
private volatile boolean m_NotifyOnCTS;
private volatile boolean m_NotifyOnDSR;
private volatile boolean m_NotifyOnCD;
private volatile boolean m_NotifyOnOverrunError;
private volatile boolean m_NotifyOnParityError;
private volatile boolean m_NotifyOnFramingError;
private volatile boolean m_NotifyOnBreakInterrupt;
private volatile boolean m_ThreadRunning;
private volatile boolean m_ThreadStarted;
private int[] m_ioctl = { 0 };
private int m_ControlLineStates;
// we cache termios in m_Termios because we don't rely on reading it back with tcgetattr()
// which for Mac OS X / CRTSCTS does not work, it is also more efficient
private Termios m_Termios = new Termios();
private int m_MinVTIME;
private void sendDataEvents(boolean read, boolean write) {
if (read && m_NotifyOnDataAvailable && !m_DataAvailableNotified) {
m_DataAvailableNotified = true;
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DATA_AVAILABLE, false, true));
}
if (write && m_NotifyOnOutputEmpty && !m_OutputEmptyNotified) {
m_OutputEmptyNotified = true;
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.OUTPUT_BUFFER_EMPTY, false, true));
}
}
private synchronized void sendNonDataEvents() {
if (ioctl(m_FD, TIOCMGET, m_ioctl) < 0)
return; //FIXME decide what to with errors in the background thread
int oldstates = m_ControlLineStates;
m_ControlLineStates = m_ioctl[0];
int newstates = m_ControlLineStates;
int changes = oldstates ^ newstates;
if (changes == 0)
return;
int line;
if (m_NotifyOnCTS && (((line = TIOCM_CTS) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CTS, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnDSR && (((line = TIOCM_DSR) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DSR, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnRI && (((line = TIOCM_RI) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.RI, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnCD && (((line = TIOCM_CD) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CD, (oldstates & line) != 0, (newstates & line) != 0));
}
@Override
synchronized public void addEventListener(SerialPortEventListener eventListener) throws TooManyListenersException {
checkState();
if (eventListener == null)
throw new IllegalArgumentException("eventListener cannot be null");
if (m_EventListener != null)
throw new TooManyListenersException();
m_EventListener = eventListener;
if (!m_ThreadStarted) {
m_ThreadStarted = true;
m_Thread.start();
}
}
@Override
synchronized public int getBaudRate() {
checkState();
return m_BaudRate;
}
@Override
synchronized public int getDataBits() {
checkState();
return m_DataBits;
}
@Override
synchronized public int getFlowControlMode() {
checkState();
return m_FlowControlMode;
}
@Override
synchronized public int getParity() {
checkState();
return m_Parity;
}
@Override
synchronized public int getStopBits() {
checkState();
return m_StopBits;
}
@Override
synchronized public boolean isCD() {
checkState();
return getControlLineState(TIOCM_CD);
}
@Override
synchronized public boolean isCTS() {
checkState();
return getControlLineState(TIOCM_CTS);
}
@Override
synchronized public boolean isDSR() {
checkState();
return getControlLineState(TIOCM_DSR);
}
@Override
synchronized public boolean isDTR() {
checkState();
return getControlLineState(TIOCM_DTR);
}
@Override
synchronized public boolean isRI() {
checkState();
return getControlLineState(TIOCM_RI);
}
@Override
synchronized public boolean isRTS() {
checkState();
return getControlLineState(TIOCM_RTS);
}
@Override
synchronized public void notifyOnBreakInterrupt(boolean x) {
checkState();
m_NotifyOnBreakInterrupt = x;
}
@Override
synchronized public void notifyOnCTS(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_CTS);
m_NotifyOnCTS = x;
nudgePipe();
}
@Override
synchronized public void notifyOnCarrierDetect(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_CD);
m_NotifyOnCD = x;
nudgePipe();
}
@Override
synchronized public void notifyOnDSR(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_DSR);
m_NotifyOnDSR = x;
nudgePipe();
}
@Override
synchronized public void notifyOnDataAvailable(boolean x) {
checkState();
m_NotifyOnDataAvailable = x;
nudgePipe();
}
@Override
synchronized public void notifyOnFramingError(boolean x) {
checkState();
m_NotifyOnFramingError = x;
}
@Override
synchronized public void notifyOnOutputEmpty(boolean x) {
checkState();
m_NotifyOnOutputEmpty = x;
nudgePipe();
}
@Override
synchronized public void notifyOnOverrunError(boolean x) {
checkState();
m_NotifyOnOverrunError = x;
}
@Override
synchronized public void notifyOnParityError(boolean x) {
checkState();
m_NotifyOnParityError = x;
}
@Override
synchronized public void notifyOnRingIndicator(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_RI);
m_NotifyOnRI = x;
nudgePipe();
}
@Override
synchronized public void removeEventListener() {
checkState();
m_EventListener = null;
}
@Override
synchronized public void sendBreak(int duration) {
checkState();
// FIXME POSIX does not specify how duration is interpreted
// Opengroup POSIX says:
// If the terminal is using asynchronous serial data transmission, tcsendbreak()
// shall cause transmission of a continuous stream of zero-valued bits for a specific duration.
// If duration is 0, it shall cause transmission of zero-valued bits for at least 0.25 seconds,
// and not more than 0.5 seconds. If duration is not 0, it shall send zero-valued bits for an implementation-defined period of time.
// From the man page for Linux tcsendbreak:
// The effect of a non-zero duration with tcsendbreak() varies.
// SunOS specifies a break of duration*N seconds,
// where N is at least 0.25, and not more than 0.5. Linux, AIX, DU, Tru64 send a break of duration milliseconds.
// FreeBSD and NetBSD and HP-UX and MacOS ignore the value of duration.
// Under Solaris and Unixware, tcsendbreak() with non-zero duration behaves like tcdrain().
tcsendbreak(m_FD, duration);
}
@Override
synchronized public void setDTR(boolean x) {
checkState();
setControlLineState(TIOCM_DTR, x);
}
@Override
synchronized public void setRTS(boolean x) {
checkState();
setControlLineState(TIOCM_RTS, x);
}
@Override
synchronized public void disableReceiveFraming() {
checkState();
// Not supported
}
@Override
synchronized public void disableReceiveThreshold() {
checkState();
m_ReceiveThresholdEnabled = false;
}
@Override
synchronized public void disableReceiveTimeout() {
checkState();
m_ReceiveTimeOutEnabled = false;
}
@Override
synchronized public void enableReceiveFraming(int arg0) throws UnsupportedCommOperationException {
checkState();
throw new UnsupportedCommOperationException();
}
@Override
synchronized public void enableReceiveThreshold(int value) throws UnsupportedCommOperationException {
checkState();
if (m_ReceiveThresholdValue < 0)
throw new IllegalArgumentException("threshold" + value + " < 0 ");
m_ReceiveThresholdEnabled = true;
m_ReceiveThresholdValue = value;
}
@Override
synchronized public int getInputBufferSize() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public int getOutputBufferSize() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public void enableReceiveTimeout(int value) throws UnsupportedCommOperationException {
if (m_ReceiveThresholdValue < 0)
throw new IllegalArgumentException("threshold" + value + " < 0 ");
checkState();
m_ReceiveTimeOutEnabled = true;
m_ReceiveTimeOutValue = value;
}
@Override
synchronized public void setFlowControlMode(int mode) throws UnsupportedCommOperationException {
checkState();
synchronized (m_Termios) {
m_Termios.c_iflag &= ~IXANY;
if ((mode & (FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_RTSCTS_OUT)) != 0)
m_Termios.c_cflag |= CRTSCTS;
else
m_Termios.c_cflag &= ~CRTSCTS;
if ((mode & FLOWCONTROL_XONXOFF_IN) != 0)
m_Termios.c_iflag |= IXOFF;
else
m_Termios.c_iflag &= ~IXOFF;
if ((mode & FLOWCONTROL_XONXOFF_OUT) != 0)
m_Termios.c_iflag |= IXON;
else
m_Termios.c_iflag &= ~IXON;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
m_FlowControlMode = mode;
}
}
@Override
synchronized public void setSerialPortParams(int baudRate, int dataBits, int stopBits, int parity) throws UnsupportedCommOperationException {
checkState();
synchronized (m_Termios) {
Termios prev = new Termios();// (termios);
// save a copy in case we need to restore it
prev.set(m_Termios);
try {
checkReturnCode(setspeed(m_FD, m_Termios, baudRate));
int db;
switch (dataBits) {
case SerialPort.DATABITS_5:
db = CS5;
break;
case SerialPort.DATABITS_6:
db = CS6;
break;
case SerialPort.DATABITS_7:
db = CS7;
break;
case SerialPort.DATABITS_8:
db = CS8;
break;
default:
throw new UnsupportedCommOperationException("dataBits = " + dataBits);
}
int sb;
switch (stopBits) {
case SerialPort.STOPBITS_1:
sb = 1;
break;
case SerialPort.STOPBITS_2:
sb = 2;
break;
default:
throw new UnsupportedCommOperationException("stopBits = " + stopBits);
}
int fi = m_Termios.c_iflag;
int fc = m_Termios.c_cflag;
switch (parity) {
case SerialPort.PARITY_NONE:
fc &= ~PARENB;
fi &= ~(INPCK | ISTRIP);
break;
case SerialPort.PARITY_EVEN:
fc |= PARENB;
fc &= ~PARODD;
fi &= ~(INPCK | ISTRIP);
break;
case SerialPort.PARITY_ODD:
fc |= PARENB;
fc |= PARODD;
fi &= ~(INPCK | ISTRIP);
break;
default:
throw new UnsupportedCommOperationException("parity = " + parity);
}
// update the hardware
fc &= ~CSIZE; /* Mask the character size bits */
fc |= db; /* Set data bits */
if (sb == 2)
fc |= CSTOPB;
else
fc &= ~CSTOPB;
m_Termios.c_cflag = fc;
m_Termios.c_iflag = fi;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
// finally everything went ok, so we can update our settings
m_BaudRate = baudRate;
m_Parity = parity;
m_DataBits = dataBits;
m_StopBits = stopBits;
} catch (UnsupportedCommOperationException e) {
m_Termios.set(prev);
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
throw e;
} catch (IllegalStateException e) {
m_Termios.set(prev);
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
throw e;
}
}
}
private static int min(int a, int b) {
return a < b ? a : b;
}
private static int max(int a, int b) {
return a > b ? a : b;
}
@Override
synchronized public OutputStream getOutputStream() throws IOException {
checkState();
if (m_OutputStream == null) {
m_OutputStream = new OutputStream() {
private byte[] m_Buffer = new byte[2048];
@Override
final public void write(int b) throws IOException {
checkState();
byte[] buf = { (byte) b };
write(buf, 0, 1);
}
@Override
final public void write(byte[] buffer, int offset, int length) throws IOException {
if (buffer == null)
throw new IllegalArgumentException();
if (offset < 0 || length < 0 || offset + length > buffer.length)
throw new IndexOutOfBoundsException("buffer.lengt " + buffer.length + " offset " + offset + " length " + length);
checkState();
while (length > 0) {
int n = min(length, min(m_Buffer.length, buffer.length - offset));
if (offset > 0) {
System.arraycopy(buffer, offset, m_Buffer, 0, n);
n = jtermios.JTermios.write(m_FD, m_Buffer, n);
} else
n = jtermios.JTermios.write(m_FD, buffer, n);
if (n < 0) {
PureJavaSerialPort.this.close();
throw new IOException();
}
length -= n;
offset += n;
}
m_OutputEmptyNotified = false;
}
@Override
final public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
final public void flush() throws IOException {
checkState();
if (tcdrain(m_FD) < 0) {
close();
throw new IOException();
}
}
};
}
return m_OutputStream;
}
synchronized public InputStream getInputStream() throws IOException {
checkState();
if (m_InputStream == null) {
m_InputStream = new InputStream() {
private int[] m_Available = { 0 };
private byte[] m_Buffer = new byte[2048];
private int m_VTIME = 0;
private int m_VMIN = 0;
private int[] m_ReadPollFD;
private byte[] m_Nudge;
private FDSet m_ReadFDSet;
private TimeVal m_ReadTimeVal;
{ // initialized block instead of construct in anonymous class
m_ReadFDSet = newFDSet();
m_ReadTimeVal = new TimeVal();
m_ReadPollFD = new int[4];
m_ReadPollFD[0] = m_FD;
m_ReadPollFD[1] = POLLIN_IN;
m_ReadPollFD[2] = m_PipeRdFD;
m_ReadPollFD[3] = POLLIN_IN;
m_Nudge = new byte[1];
}
@Override
final public int available() throws IOException {
checkState();
if (ioctl(m_FD, FIONREAD, m_Available) < 0) {
PureJavaSerialPort.this.close();
throw new IOException();
}
return m_Available[0];
}
@Override
final public int read() throws IOException {
checkState();
byte[] buf = { 0 };
int n = read(buf, 0, 1);
return n > 0 ? buf[0] & 0xFF : -1;
}
//THINGS TO TEST:
//-breakout from blocking read even without timeout
@Override
final public int read(byte[] buffer, int offset, int length) throws IOException {
if (buffer == null)
throw new IllegalArgumentException("buffer null");
if (offset < 0 || length < 0 || offset + length > buffer.length)
throw new IndexOutOfBoundsException("buffer.lengt " + buffer.length + " offset " + offset + " length " + length);
if (length == 0)
return 0;
checkState();
// Now configure VTIME and VMIN
int bytesReceived = 0;
int minBytesRequired = 1;
if (m_ReceiveThresholdEnabled)
minBytesRequired = m_ReceiveThresholdValue < length ? m_ReceiveThresholdValue : length;
long T0 = m_ReceiveTimeOutEnabled ? System.currentTimeMillis() : 0;
long T1 = T0;
while (true) {
int bytesLeft = length - bytesReceived;
int timeLeft = 0;
int vtime;
int vmin;
boolean pollingRead = (m_ReceiveTimeOutEnabled && m_ReceiveTimeOutValue == 0) || (m_ReceiveThresholdEnabled && m_ReceiveThresholdValue == 0);
if (pollingRead) {
// This is Kusti's interpretation of the JavaComm javadoc for getInputStream()
vtime = 0;
vmin = 0;
} else {
if (RAW_READ_MODE) {
vtime = min(255, ((m_ReceiveTimeOutEnabled ? m_ReceiveTimeOutValue : 0) + 99) / 100);
vmin = min(255, m_ReceiveThresholdEnabled ? m_ReceiveThresholdValue : 1);
} else {
// calculate VTIME value
// MAX_VALUE ???? minVTIME
timeLeft = m_ReceiveTimeOutEnabled ? max(0, m_ReceiveTimeOutValue - ((int) (T1 - T0))) : Integer.MAX_VALUE;
vtime = m_ReceiveTimeOutEnabled ? timeLeft : m_MinVTIME;
// roundup to 1/10th of sec
vtime = (vtime + 99) / 100;
// if overflow divide timeout to equal slices
if (vtime > 255)
vtime = vtime / (vtime / 256 + 1);
// calculate VMIN value
vmin = min(255, min(bytesLeft, m_ReceiveThresholdEnabled ? m_ReceiveThresholdValue : 1));
}
}
// to avoid unnecessary calls to OS we only call tcsetattr() if necessary
if (vtime != m_VTIME || vmin != m_VMIN) {
synchronized (m_Termios) {
m_VTIME = vtime;
m_VMIN = vmin;
m_Termios.c_cc[VTIME] = (byte) m_VTIME;
m_Termios.c_cc[VMIN] = (byte) m_VMIN;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
}
}
int bytesRead = 0;
boolean dataAvailable = false;
if (!RAW_READ_MODE && !pollingRead) {
// do a select()/poll(), just in case this read was
// called when no data is available
// so that we will not hang for ever in a read
if (USE_POLL) {
int n;
if (m_HaveNudgePipe)
n = poll(m_ReadPollFD, 2, timeLeft);
else
n = poll(m_ReadPollFD, 1, timeLeft);
if (n < 0 || m_FD < 0) // the port closed while we were blocking in poll
throw new IOException();
if ((m_ReadPollFD[3] & POLLIN_OUT) != 0)
jtermios.JTermios.read(m_PipeRdFD, m_Nudge, 1);
int re = m_ReadPollFD[1];
if ((re & POLLNVAL_OUT) != 0)
throw new IOException();
dataAvailable = (re & POLLIN_OUT) != 0;
} else {
FD_ZERO(m_ReadFDSet);
FD_SET(m_FD, m_ReadFDSet);
int maxFD = m_FD;
if (m_HaveNudgePipe) {
FD_SET(m_PipeRdFD, m_ReadFDSet);
if (m_PipeRdFD > maxFD)
maxFD = m_PipeRdFD;
}
if (timeLeft >= 1000) {
int t = timeLeft / 1000;
m_ReadTimeVal.tv_sec = t;
m_ReadTimeVal.tv_usec = (timeLeft - t * 1000) * 1000;
} else {
m_ReadTimeVal.tv_sec = 0;
m_ReadTimeVal.tv_usec = timeLeft * 1000;
}
//System.err.println(maxFD + " " + m_PipeRdFD + " " + m_FD);
if (select(maxFD + 1, m_ReadFDSet, null, null, m_ReadTimeVal) < 0)
throw new IOException();
if (m_FD < 0) // the port closed while we were blocking in select
throw new IOException();
dataAvailable = FD_ISSET(m_FD, m_ReadFDSet);
}
}
// at this point data is either available or we take our chances in raw mode
if (RAW_READ_MODE || dataAvailable || pollingRead) {
if (offset > 0) {
bytesRead = jtermios.JTermios.read(m_FD, m_Buffer, bytesLeft);
if (bytesRead > 0)
System.arraycopy(m_Buffer, 0, buffer, offset, bytesRead);
} else
bytesRead = jtermios.JTermios.read(m_FD, buffer, bytesLeft);
}
if (bytesRead < 0)
throw new IOException();
bytesReceived += bytesRead;
if (bytesReceived >= minBytesRequired)
break;
if (m_ReceiveTimeOutEnabled) {
if (T1 - T0 >= m_ReceiveTimeOutValue)
break;
T1 = m_ReceiveTimeOutEnabled ? System.currentTimeMillis() : 0;
}
if (pollingRead)
break;
offset += bytesRead;
}
m_DataAvailableNotified = false;
return bytesReceived;
}
};
}
return m_InputStream;
}
@Override
synchronized public int getReceiveFramingByte() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public int getReceiveThreshold() {
checkState();
return m_ReceiveThresholdValue;
}
@Override
synchronized public int getReceiveTimeout() {
checkState();
return m_ReceiveTimeOutValue;
}
@Override
synchronized public boolean isReceiveFramingEnabled() {
checkState();
// Not supported
return false;
}
@Override
synchronized public boolean isReceiveThresholdEnabled() {
checkState();
return m_ReceiveThresholdEnabled;
}
@Override
synchronized public boolean isReceiveTimeoutEnabled() {
checkState();
return m_ReceiveTimeOutEnabled;
}
@Override
synchronized public void setInputBufferSize(int arg0) {
checkState();
// Not supported
}
@Override
synchronized public void setOutputBufferSize(int arg0) {
checkState();
// Not supported
}
private void nudgePipe() {
if (m_HaveNudgePipe)
write(m_PipeWrFD, m_NudgeData, 1);
}
@Override
synchronized public void close() {
int fd = m_FD;
if (fd != -1) {
m_FD = -1;
nudgePipe();
int flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
int fcres = fcntl(fd, F_SETFL, flags);
if (fcres != 0) // not much we can do if this fails, so just log it
log = log && log(1, "fcntl(%d,%d,%d) returned %d\n", m_FD, F_SETFL, flags, fcres);
if (m_Thread != null)
m_Thread.interrupt();
int err = jtermios.JTermios.close(fd);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
if (m_HaveNudgePipe) {
err = jtermios.JTermios.close(m_PipeRdFD);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
err = jtermios.JTermios.close(m_PipeWrFD);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
}
long t0 = System.currentTimeMillis();
while (m_ThreadRunning) {
try {
Thread.sleep(5);
if (System.currentTimeMillis() - t0 > 2000)
break;
} catch (InterruptedException e) {
break;
}
}
super.close();
}
}
/* package */PureJavaSerialPort(String name, int timeout) throws PortInUseException {
super();
boolean usepoll = false;
if (Platform.isLinux()) {
String key1 = "purejavacomm.use_poll";
String key2 = "purejavacomm.usepoll";
if (System.getProperty(key1) != null) {
usepoll = Boolean.getBoolean(key1);
log = log && log(1, "use of '%s' is deprecated, use '%s' instead\n", key1, key2);
} else if (System.getProperty(key2) != null)
usepoll = Boolean.getBoolean(key2);
else
usepoll = true;
}
USE_POLL = usepoll;
RAW_READ_MODE = Boolean.getBoolean("purejavacomm.rawreadmode");
this.name = name;
// unbelievable, sometimes quickly closing and re-opening fails on Windows
// so try a few times
int tries = 100;
long T0 = System.currentTimeMillis();
while ((m_FD = open(name, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
if (tries-- < 0 || System.currentTimeMillis() - T0 >= timeout)
throw new PortInUseException();
}
m_MinVTIME = Integer.getInteger("purejavacomm.minvtime", 100);
int flags = fcntl(m_FD, F_GETFL, 0);
flags &= ~O_NONBLOCK;
checkReturnCode(fcntl(m_FD, F_SETFL, flags));
m_BaudRate = 9600;
m_DataBits = SerialPort.DATABITS_8;
m_FlowControlMode = SerialPort.FLOWCONTROL_NONE;
m_Parity = SerialPort.PARITY_NONE;
m_StopBits = SerialPort.STOPBITS_1;
checkReturnCode(tcgetattr(m_FD, m_Termios));
cfmakeraw(m_FD, m_Termios);
m_Termios.c_cflag |= CLOCAL | CREAD;
m_Termios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
m_Termios.c_oflag &= ~OPOST;
m_Termios.c_cc[VSTART] = (byte) DC1;
m_Termios.c_cc[VSTOP] = (byte) DC3;
m_Termios.c_cc[VMIN] = 0;
m_Termios.c_cc[VTIME] = 0;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
try {
setSerialPortParams(m_BaudRate, m_DataBits, m_StopBits, m_Parity);
} catch (UnsupportedCommOperationException e) {
// This really should not happen
e.printStackTrace();
}
try {
setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException e) {
// This really should not happen
e.printStackTrace();
}
checkReturnCode(ioctl(m_FD, TIOCMGET, m_ioctl));
m_ControlLineStates = m_ioctl[0];
String nudgekey = "purejavacomm.usenudgepipe";
if (System.getProperty(nudgekey) == null || Boolean.getBoolean(nudgekey)) {
int[] pipes = new int[2];
if (pipe(pipes) == 0) {
m_HaveNudgePipe = true;
m_PipeRdFD = pipes[0];
m_PipeWrFD = pipes[1];
checkReturnCode(fcntl(m_PipeRdFD, F_SETFL, fcntl(m_PipeRdFD, F_GETFL, 0) | O_NONBLOCK));
}
}
Runnable runnable = new Runnable() {
public void run() {
try {
m_ThreadRunning = true;
final int TIMEOUT = Integer.getInteger("purejavacomm.pollperiod", 10);
TimeVal timeout = null;
FDSet rset = null;
FDSet wset = null;
int[] pollfd = null;
byte[] nudge = null;
if (USE_POLL) {
pollfd = new int[4];
nudge = new byte[1];
pollfd[0] = m_FD;
pollfd[2] = m_PipeRdFD;
} else {
rset = newFDSet();
wset = newFDSet();
timeout = new TimeVal();
int t = TIMEOUT * 1000;
timeout.tv_sec = t / 1000000;
timeout.tv_usec = t - timeout.tv_sec * 1000000;
}
while (m_FD >= 0) {
boolean read = (m_NotifyOnDataAvailable && !m_DataAvailableNotified);
boolean write = (m_NotifyOnOutputEmpty && !m_OutputEmptyNotified);
int n = 0;
boolean pollCtrlLines = m_NotifyOnCTS || m_NotifyOnDSR || m_NotifyOnRI || m_NotifyOnCD;
if (read || write || (!pollCtrlLines && m_HaveNudgePipe)) {
if (USE_POLL) {
int e = 0;
if (read)
e |= POLLIN_IN;
if (write)
e |= POLLOUT_IN;
pollfd[1] = e;
pollfd[3] = POLLIN_IN;
if (m_HaveNudgePipe)
n = poll(pollfd, 2, -1);
else
n = poll(pollfd, 1, TIMEOUT);
int re = pollfd[3];
if ((re & POLLNVAL_OUT) != 0) {
log = log && log(1, "poll() returned POLLNVAL, errno %d\n", errno());
break;
}
if ((re & POLLIN_OUT) != 0)
read(m_PipeRdFD, nudge, 1);
re = pollfd[1];
if ((re & POLLNVAL_OUT) != 0) {
log = log && log(1, "poll() returned POLLNVAL, errno %d\n", errno());
break;
}
read = read && (re & POLLIN_OUT) != 0;
write = write && (re & POLLOUT_OUT) != 0;
} else {
FD_ZERO(rset);
FD_ZERO(wset);
if (read)
FD_SET(m_FD, rset);
if (write)
FD_SET(m_FD, wset);
if (m_HaveNudgePipe)
FD_SET(m_PipeRdFD, rset);
n = select(m_FD + 1, rset, wset, null, m_HaveNudgePipe ? null : timeout);
read = read && FD_ISSET(m_FD, rset);
write = write && FD_ISSET(m_FD, wset);
}
if (m_FD < 0)
break;
if (n < 0) {
log = log && log(1, "select() or poll() returned %d, errno %d\n", n, errno());
close();
break;
}
} else {
Thread.sleep(TIMEOUT);
}
if (m_EventListener != null) {
if (read || write)
sendDataEvents(read, write);
if (pollCtrlLines)
sendNonDataEvents();
}
}
} catch (InterruptedException ie) {
} finally {
m_ThreadRunning = false;
}
}
};
m_Thread = new Thread(runnable, getName());
m_Thread.setDaemon(true);
}
synchronized private void updateControlLineState(int line) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new IllegalStateException();
m_ControlLineStates = (m_ioctl[0] & line) + (m_ControlLineStates & ~line);
}
synchronized private boolean getControlLineState(int line) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new IllegalStateException();
return (m_ioctl[0] & line) != 0;
}
synchronized private void setControlLineState(int line, boolean state) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new IllegalStateException();
if (state)
m_ioctl[0] |= line;
else
m_ioctl[0] &= ~line;
if (ioctl(m_FD, TIOCMSET, m_ioctl) == -1)
throw new IllegalStateException();
}
private void checkState() {
if (m_FD < 0)
throw new IllegalStateException("File descriptor is " + m_FD + " < 0, maybe closed by previous error condition");
}
private void checkReturnCode(int code) {
if (code != 0) {
String msg = String.format("JTermios call returned %d at %s", code, lineno(1)); // 1 qas implicit 0
log = log && log(1, "%s\n", msg);
try {
close();
} catch (Exception e) {
StackTraceElement st = e.getStackTrace()[0];
String msg2 = String.format("close threw %s at class %s line% d", e.getClass().getName(), st.getClassName(), st.getLineNumber());
log = log && log(1, "%s\n", msg2);
}
throw new IllegalStateException(msg);
}
}
}
|
package h2o.common.schedule;
import h2o.common.Tools;
import h2o.common.concurrent.Door;
import h2o.common.concurrent.Locks;
import h2o.common.concurrent.OneTimeInitVar;
import h2o.common.concurrent.RunUtil;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
public class Dispatcher {
private final Door door = new Door( true );
private final OneTimeInitVar<Boolean> f = new OneTimeInitVar<Boolean>("Has started");
private final OneTimeInitVar<Long> firstDelay = new OneTimeInitVar<Long>( f , 0L );
private final OneTimeInitVar<Long> okSleepTime = new OneTimeInitVar<Long>( f , 100L );
private final OneTimeInitVar<Long> freeSleepTime = new OneTimeInitVar<Long>( f , 60000L );
private final OneTimeInitVar<Long> errSleepTime = new OneTimeInitVar<Long>( f , 60000L );
private final OneTimeInitVar<RepetitiveTask> task = new OneTimeInitVar<RepetitiveTask>( f , null);
private volatile boolean stop = false;
private volatile boolean running = false;
private volatile boolean interruptible = false;
private final Lock lock = Locks.newLock();
public void stop() {
stop = true;
}
public boolean isRunning() {
return running;
}
public void wakeup() {
door.open();
}
private Future<?> startTask() {
f.setVar(true);
running = true;
return RunUtil.call( new Runnable() {
public void run() {
try {
sleep(firstDelay.getVar());
while( !stop ) {
long st;
try {
int r = task.getVar().doTask();
if( r == 0 ) {
st = freeSleepTime.getVar();
} else if(r == 1 ) {
st = okSleepTime.getVar();
} else if(r == 2 ) {
st = 0;
} else if(r < 0 ) {
st = -1;
} else if(r == 9 ) {
break;
} else {
st = r;
}
} catch( InterruptedException e ) {
if( interruptible ) {
throw e;
} else {
Thread.currentThread().interrupt();
st = errSleepTime.getVar();
}
} catch( Throwable e) {
Tools.log.debug("Dispatcher-run",e);
st = errSleepTime.getVar();
}
sleep(st);
}
} catch( InterruptedException e ) {
Tools.log.error("InterruptedException", e);
}
stop = true;
running = false;
}
} );
}
private void sleep( long st ) throws InterruptedException {
if( st != 0 ) {
try {
door.close();
if( st > 0L ) {
door.await(st, TimeUnit.MILLISECONDS);
} else {
door.await();
}
} catch( InterruptedException e) {
if( interruptible ) {
throw e;
} else {
Thread.currentThread().interrupt();
}
} catch (Throwable e) {
Tools.log.debug("Sleepping", e);
} finally {
door.open();
}
}
}
public Future<?> start() {
lock.lock();
try {
return this.startTask();
} finally {
lock.unlock();
}
}
public Future<?> start( RepetitiveTask task ) {
lock.lock();
try {
return this.start(task , -1 , -1 , -1);
} finally {
lock.unlock();
}
}
public Future<?> start( RepetitiveTask task , long freeSleepTime , long okSleepTime , long errSleepTime ) {
lock.lock();
try {
this.task.setVar(task);
if( freeSleepTime > 0 ) this.freeSleepTime.setVar(freeSleepTime) ;
if( okSleepTime > 0 ) this.okSleepTime.setVar(okSleepTime);
if( errSleepTime > 0 ) this.errSleepTime.setVar(errSleepTime);
return this.start();
} finally {
lock.unlock();
}
}
public void setTask(RepetitiveTask task) {
this.task.setVar(task);
}
public void setFirstDelay(long firstDelay) {
this.firstDelay.setVar(firstDelay);
}
public void setFreeSleepTime(long freeSleepTime) {
this.freeSleepTime.setVar(freeSleepTime) ;
}
public void setOkSleepTime(long okSleepTime) {
this.okSleepTime.setVar(okSleepTime);
}
public void setErrSleepTime(long errSleepTime) {
this.errSleepTime.setVar(errSleepTime);
}
public void setInterruptible( boolean interruptible ) {
this.interruptible = interruptible;
}
}
|
package io.hawt.aether;
import io.hawt.config.ConfigFacade;
import io.hawt.config.URLHandler;
import io.hawt.util.MBeanSupport;
import io.hawt.util.Strings;
import org.apache.maven.repository.internal.MavenRepositorySystemSession;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.collection.DependencyCollectionException;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.DependencyNode;
import org.sonatype.aether.repository.Authentication;
import org.sonatype.aether.repository.LocalRepository;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.repository.RepositoryPolicy;
import org.sonatype.aether.resolution.ArtifactRequest;
import org.sonatype.aether.resolution.ArtifactResolutionException;
import org.sonatype.aether.resolution.ArtifactResult;
import org.sonatype.aether.resolution.DependencyRequest;
import org.sonatype.aether.resolution.DependencyResolutionException;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.graph.PreorderNodeListGenerator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A facade for working with Aether over JMX
*/
public class AetherFacade extends MBeanSupport implements AetherFacadeMXBean {
private static final transient Logger LOG = LoggerFactory.getLogger(AetherFacade.class);
public static final String AETHER_MBEAN_NAME = "hawtio:type=AetherFacade";
protected static String DEFAULT_EXTENSION = "jar";
protected static String DEFAULT_CLASSIFIER = "";
private LocalRepository localRepository;
private String localRepoDir;
private RepositorySystem repositorySystem;
private List<RemoteRepository> remoteRepositories;
private List<RemoteRepository> defaultRemoteRepositories = Arrays.asList(
new RemoteRepository("central", "default", "http://repo2.maven.org/maven2/"),
new RemoteRepository("public.fusesource.com", "default", "http://repo.fusesource.com/nexus/content/groups/public"),
new RemoteRepository("snapshots.fusesource.com", "default", "http://repo.fusesource.com/nexus/content/groups/public-snapshots"),
new RemoteRepository("public.sonatype.com", "default", "https://oss.sonatype.org/content/groups/public"),
new RemoteRepository("maven1.java.net", "default", "http://download.java.net/maven/1"),
new RemoteRepository("com.springsource.repository.bundles.release", "default", "http://repository.springsource.com/maven/bundles/release"),
new RemoteRepository("com.springsource.repository.bundles.external", "default", "http://repository.springsource.com/maven/bundles/external"),
new RemoteRepository("com.springsource.repository.libraries.release", "default", "http://repository.springsource.com/maven/libraries/release"),
new RemoteRepository("com.springsource.repository.libraries.external", "default", "http://repository.springsource.com/maven/libraries/external")
);
@Override
public void init() throws Exception {
ConfigFacade.getSingleton().addUrlHandler("mvn", new URLHandler() {
@Override
public InputStream openStream(String url) {
try {
return new OpenMavenURL(url).getInputStream();
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Could not parse URL: " + url + " for remote URLs " + getRemoteUrlsText() + ". " + e, e);
} catch (IOException e) {
throw new IllegalArgumentException("Could not read URL: " + url + " for remote URLs " + getRemoteUrlsText() + ". " + e, e);
}
}
});
super.init();
}
protected String getRemoteUrlsText() {
StringBuilder buffer = new StringBuilder();
List<RemoteRepository> list = getRemoteRepositories();
for (RemoteRepository repo : list) {
String url = repo.getUrl();
if (Strings.isNotBlank(url)) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(url);
}
}
return buffer.toString();
}
@Override
public String resolveArtifactUrlToFileName(String mvnUrl) throws MalformedURLException, ComponentLookupException, DependencyCollectionException, PlexusContainerException, DependencyResolutionException, ArtifactResolutionException {
MavenURL mavenUrl = new MavenURL(mvnUrl);
ArtifactResult result = resolveArtifact(mavenUrl.getGroup(), mavenUrl.getArtifact(), mavenUrl.getVersion(), mavenUrl.getType(), mavenUrl.getClassifier());
return artifactResultToFilePath(result);
}
@Override
public String resolveArtifactUrlAndRepositoriesToFileName(String mvnUrl, String repositoryUrls) throws MalformedURLException, ComponentLookupException, DependencyCollectionException, PlexusContainerException, DependencyResolutionException, ArtifactResolutionException {
MavenURL mavenUrl = new MavenURL(mvnUrl);
ArtifactResult result = resolveArtifactFromUrls(mavenUrl.getGroup(), mavenUrl.getArtifact(), mavenUrl.getVersion(), mavenUrl.getType(), mavenUrl.getClassifier(), splitRepoUrlsWithComma(repositoryUrls));
return artifactResultToFilePath(result);
}
protected static String artifactResultToFilePath(ArtifactResult result) {
if (result != null) {
Artifact artifact = result.getArtifact();
if (artifact != null) {
File file = artifact.getFile();
if (file != null) {
return file.getAbsolutePath();
}
}
}
return null;
}
@Override
public String resolveUrlToFileName(String mvnUrl) throws MalformedURLException, ComponentLookupException, DependencyCollectionException, PlexusContainerException, DependencyResolutionException, ArtifactResolutionException {
MavenURL mavenUrl = new MavenURL(mvnUrl);
AetherResult result = resolve(mavenUrl.getGroup(), mavenUrl.getArtifact(), mavenUrl.getVersion(), mavenUrl.getType(), mavenUrl.getClassifier());
return aetherResultToFilePath(result);
}
@Override
public String resolveUrlAndRepositoriesToFileName(String mvnUrl, String repositoryUrls) throws MalformedURLException, ComponentLookupException, DependencyCollectionException, PlexusContainerException, DependencyResolutionException, ArtifactResolutionException {
MavenURL mavenUrl = new MavenURL(mvnUrl);
AetherResult result = resolveFromUrls(mavenUrl.getGroup(), mavenUrl.getArtifact(), mavenUrl.getVersion(), mavenUrl.getType(), mavenUrl.getClassifier(), splitRepoUrlsWithComma(repositoryUrls));
return aetherResultToFilePath(result);
}
public static List<String> splitRepoUrlsWithComma(String repos) {
if (Strings.isNotBlank(repos)) {
String[] array = repos.split(",");
if (array != null) {
return Arrays.asList(array);
}
}
return Arrays.asList();
}
protected static String aetherResultToFilePath(AetherResult result) {
if (result != null) {
List<File> files = result.getFiles();
if (files.size() > 0) {
File file = files.get(0);
return file.getAbsolutePath();
}
}
return null;
}
@Override
public String resolveJson(String mavenCoords) throws ComponentLookupException, DependencyCollectionException, PlexusContainerException, ArtifactResolutionException, DependencyResolutionException {
// TODO we should really use the MavenURL parser??
AetherResult result = resolve(mavenCoords);
return result.jsonString();
}
@Override
public String resolveJson(String groupId, String artifactId, String version, String extension, String classifier) throws ComponentLookupException, DependencyCollectionException, PlexusContainerException, ArtifactResolutionException, DependencyResolutionException {
AetherResult result = resolve(groupId, artifactId, version, extension, classifier);
return result.jsonString();
}
public AetherResult resolve(String mavenCoords) throws PlexusContainerException, ComponentLookupException, DependencyCollectionException, ArtifactResolutionException, DependencyResolutionException {
String[] split = mavenCoords.split(":");
if (split.length < 2) {
throw new IllegalArgumentException("Expecting string of format 'groupId:artifactId:version' but got '" + mavenCoords + "'");
}
String extension = DEFAULT_EXTENSION;
String classifier = DEFAULT_CLASSIFIER;
if (split.length > 3) {
extension = split[3];
}
if (split.length > 4) {
classifier = split[4];
}
return resolve(split[0], split[1], split[2], extension, classifier);
}
/**
* Resolves the given artifact without using Aether directly
*/
public ArtifactResult resolveArtifact(String groupId, String artifactId, String version, String extension, String classifier) throws DependencyCollectionException, ArtifactResolutionException, DependencyResolutionException, PlexusContainerException, ComponentLookupException {
List<RemoteRepository> repositories = getRemoteRepositories();
return resolveArtifact(groupId, artifactId, version, extension, classifier, repositories);
}
/**
* Resolves the given artifact without using Aether directly
*/
public ArtifactResult resolveArtifactFromUrls(String groupId, String artifactId, String version, String extension, String classifier, List<String> repositoryUrls) throws DependencyCollectionException, ArtifactResolutionException, DependencyResolutionException, PlexusContainerException, ComponentLookupException {
List<RemoteRepository> repositories = urlsToRemoteRepositories(repositoryUrls);
LOG.info("resolveArtifactFromUrls: " + groupId + "/" + artifactId + "/" + version + "/" + extension + "/" + classifier + " in remote repos: " + repositories);
return resolveArtifact(groupId, artifactId, version, extension, classifier, repositories);
}
public List<RemoteRepository> urlsToRemoteRepositories(List<String> repositoryUrls) {
List<RemoteRepository> repositories = new ArrayList<>();
int count = 1;
for (String repositoryUrl : repositoryUrls) {
RemoteRepository repo = createRemoteRepositoryFromUrl(repositoryUrl, count++);
if (repo != null) {
repositories.add(repo);
}
}
if (repositories.isEmpty()) {
return getRemoteRepositories();
}
return repositories;
}
public static RemoteRepository createRemoteRepositoryFromUrl(String repositoryUrl, int count) {
if (repositoryUrl == null) {
return null;
}
String text = repositoryUrl.trim();
if (Strings.isBlank(text)) {
return null;
}
// let's first extract authentication information
Authentication authentication = getAuthentication(text);
if (authentication != null) {
text = text.replaceFirst(String.format("%s:%s@", authentication.getUsername(), authentication.getPassword()), "");
}
String id = null;
boolean snapshot = false;
while (true) {
int idx = text.lastIndexOf('@');
if (idx <= 0) {
break;
}
String postfix = text.substring(idx + 1);
if (postfix.equals("snapshots")) {
snapshot = true;
} else if (postfix.equals("noreleases")) {
// TODO
} else if (postfix.startsWith("id=")) {
id = postfix.substring(3);
} else {
LOG.warn("Unknown postfix: @" + postfix + " on repository URL: " + text);
break;
}
text = text.substring(0, idx);
}
if (Strings.isBlank(id)) {
id = "repo" + count;
}
RemoteRepository repository = new RemoteRepository(id, "default", text);
RepositoryPolicy policy = new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_DAILY, RepositoryPolicy.CHECKSUM_POLICY_WARN);
repository.setPolicy(snapshot, policy);
repository.setAuthentication(authentication);
return repository;
}
/*
* Get the {@link Authentication} instance if the URL contains credentials, otherwise return null
*/
protected static Authentication getAuthentication(String text) {
Authentication authentication = null;
try {
URL url = new URL(text);
String authority = url.getUserInfo();
if (Strings.isNotBlank(authority)) {
String[] parts = authority.split(":");
if (parts.length == 2) {
authentication = new Authentication(parts[0], parts[1]);
}
}
} catch (MalformedURLException e) {
LOG.warn("{} does not look like a valid repository URL", text);
}
return authentication;
}
public ArtifactResult resolveArtifact(String groupId, String artifactId, String version, String extension, String classifier, List<RemoteRepository> repositories) throws PlexusContainerException, ComponentLookupException, ArtifactResolutionException {
RepositorySystemSession session = newSession();
RepositorySystem system = getRepositorySystem();
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(new DefaultArtifact(groupId, artifactId, classifier, extension, version));
request.setRepositories(repositories);
return system.resolveArtifact(session, request);
}
public AetherResult resolve(String groupId, String artifactId, String version, String extension, String classifier) throws PlexusContainerException, ComponentLookupException, DependencyCollectionException, ArtifactResolutionException, DependencyResolutionException {
List<RemoteRepository> repos = getRemoteRepositories();
return resolve(groupId, artifactId, version, extension, classifier, repos);
}
public AetherResult resolveFromUrls(String groupId, String artifactId, String version, String extension, String classifier, List<String> repositoryUrls) throws PlexusContainerException, ComponentLookupException, DependencyCollectionException, DependencyResolutionException {
List<RemoteRepository> repositories = urlsToRemoteRepositories(repositoryUrls);
LOG.info("resolveFromUrls: " + groupId + "/" + artifactId + "/" + version + "/" + extension + "/" + classifier + " in remote repositories: " + repositories);
return resolve(groupId, artifactId, version, extension, classifier, repositories);
}
public AetherResult resolve(String groupId, String artifactId, String version, String extension, String classifier, List<RemoteRepository> repos) throws PlexusContainerException, ComponentLookupException, DependencyCollectionException, DependencyResolutionException {
if (Strings.isBlank(extension) || extension.equals("bundle")) {
extension = DEFAULT_EXTENSION;
}
if (classifier == null) {
classifier = DEFAULT_CLASSIFIER;
}
RepositorySystemSession session = newSession();
Dependency dependency = new Dependency(new DefaultArtifact(groupId, artifactId, classifier, extension, version), "runtime");
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(dependency);
RemoteRepository[] repoArray = new RemoteRepository[repos.size()];
repos.toArray(repoArray);
for (RemoteRepository repo : repoArray) {
collectRequest.addRepository(repo);
}
RepositorySystem system = getRepositorySystem();
DependencyNode rootNode = system.collectDependencies(session, collectRequest).getRoot();
DependencyRequest dependencyRequest = new DependencyRequest();
dependencyRequest.setRoot(rootNode);
system.resolveDependencies(session, dependencyRequest);
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
rootNode.accept(nlg);
return new AetherResult(rootNode, nlg.getFiles(), nlg.getClassPath());
}
public LocalRepository getLocalRepository() {
if (localRepository == null) {
localRepository = new LocalRepository(getLocalRepoDir());
}
return localRepository;
}
public String getLocalRepoDir() {
if (localRepoDir == null) {
localRepoDir = System.getProperty("user.home", ".") + "/.m2/repository";
}
return localRepoDir;
}
public void setLocalRepoDir(String localRepoDir) {
this.localRepoDir = localRepoDir;
}
public RepositorySystem getRepositorySystem() throws PlexusContainerException, ComponentLookupException {
if (repositorySystem == null) {
repositorySystem = newManualSystem();
}
return repositorySystem;
}
public void setRepositorySystem(RepositorySystem repositorySystem) {
this.repositorySystem = repositorySystem;
}
public List<RemoteRepository> getRemoteRepositories() {
if (remoteRepositories == null) {
remoteRepositories = new ArrayList<RemoteRepository>();
remoteRepositories.addAll(defaultRemoteRepositories);
}
return remoteRepositories;
}
public void setRemoteRepositories(List<RemoteRepository> remoteRepositories) {
this.remoteRepositories = remoteRepositories;
}
@Override
protected String getDefaultObjectName() {
return AETHER_MBEAN_NAME;
}
protected RepositorySystem newManualSystem() throws PlexusContainerException, ComponentLookupException {
/*
val locator = new DefaultServiceLocator()
locator.setServices(classOf[WagonProvider], new ManualWagonProvider())
locator.addService(classOf[RepositoryConnectorFactory], classOf[WagonRepositoryConnectorFactory])
return locator.getService(classOf[RepositorySystem])
*/
return new DefaultPlexusContainer().lookup(RepositorySystem.class);
}
protected RepositorySystemSession newSession() throws PlexusContainerException, ComponentLookupException {
MavenRepositorySystemSession session = new MavenRepositorySystemSession();
session.setLocalRepositoryManager(getRepositorySystem().newLocalRepositoryManager(getLocalRepository()));
session.setTransferListener(new ConsoleTransferListener(System.out));
session.setRepositoryListener(new ConsoleRepositoryListener());
// uncomment to generate dirty trees
// session.setDependencyGraphTransformer( null )
return session;
}
}
|
package radlab.rain.workload.httptest;
import java.io.IOException;
import org.apache.http.HttpStatus;
import radlab.rain.Generator;
import radlab.rain.IScoreboard;
import radlab.rain.LoadProfile;
import radlab.rain.Operation;
import radlab.rain.util.HttpTransport;
public class BurstUrlOperation extends Operation
{
// These references will be set by the Generator.
protected HttpTransport _http;
private int _burstSize = 1;
public static String NAME = "BurstUrl";
public BurstUrlOperation(boolean interactive, IScoreboard scoreboard)
{
super(interactive, scoreboard);
this._operationName = NAME;
this._operationIndex = BurstUrlGenerator.PING_URL;
}
/**
* Returns the Generator that created this operation.
*
* @return The Generator that created this operation.
*/
public BurstUrlGenerator getGenerator()
{
return (BurstUrlGenerator) this._generator;
}
public void setName( String val )
{
this._operationName = val;
}
@Override
public void cleanup()
{
}
@Override
public void execute() throws Throwable
{
// Fetch the base url
StringBuilder response = this._http.fetchUrl( this.getGenerator()._baseUrl );
this.trace( this.getGenerator()._baseUrl );
if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK )
{
String errorMessage = "Url GET ERROR - Received an empty/failed response";
throw new IOException (errorMessage);
}
// Do burst for base url/1 to /burst size
for( int i = 0; i < this._burstSize; i++ )
{
String url = this.getGenerator()._baseUrl + "/" + (i+1);
response = this._http.fetchUrl( url );
this.trace( url );
if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK )
{
String errorMessage = "Url GET ERROR - Received an empty response";
throw new IOException (errorMessage);
}
}
// Once we get here mark the operation as successful
this.setFailed( false );
}
@Override
public void prepare(Generator generator)
{
this._generator = generator;
BurstUrlGenerator specificUrlGenerator = (BurstUrlGenerator) generator;
LoadProfile currentLoadProfile = generator.getLatestLoadProfile();
if( currentLoadProfile != null )
this.setGeneratedDuringProfile( currentLoadProfile );
this._http = specificUrlGenerator.getHttpTransport();
// Set the burst count
this._burstSize = specificUrlGenerator.getBurstSize();
}
}
|
package org.intermine.api.bag;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.intermine.api.profile.BagState;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.TagManager;
import org.intermine.api.profile.TagManager.TagNameException;
import org.intermine.api.profile.TagManager.TagNamePermissionException;
import org.intermine.api.profile.TagManagerFactory;
import org.intermine.api.tag.TagNames;
import org.intermine.api.tag.TagTypes;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.query.ObjectStoreBag;
import org.intermine.objectstore.query.ObjectStoreBagsForObject;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
/**
* A BagManager provides access to all global and/or user bags and methods to fetch them by
* type, etc.
* @author Richard Smith
*
*/
public class BagManager
{
private static final Logger LOG = Logger.getLogger(BagManager.class);
private final Profile superProfile;
private final TagManager tagManager;
private final Model model;
private final ObjectStore osProduction;
/**
* The BagManager references the super user profile to fetch global bags.
* @param superProfile the super user profile
* @param model the object model
*/
public BagManager(Profile superProfile, Model model) {
this.superProfile = superProfile;
if (superProfile == null) {
String msg = "Unable to retrieve superuser profile. Check that the superuser profile "
+ "in the MINE.properties file matches the superuser in the userprofile database.";
LOG.error(msg);
throw new RuntimeException(msg);
}
this.model = model;
this.tagManager = new TagManagerFactory(superProfile.getProfileManager()).getTagManager();
this.osProduction = superProfile.getProfileManager().getProductionObjectStore();
}
/**
* Fetch globally available bags - superuser public bags that are available to everyone.
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getGlobalBags() {
return getBagsWithTag(superProfile, TagNames.IM_PUBLIC);
}
/**
* Get global bags/lists that have a specific tag
* @param tag
* @return
*/
public Map<String, InterMineBag> getGlobalBagsWithTag(String tag) {
return getBagsWithTag(superProfile, tag);
}
public Map<String, InterMineBag> getGlobalBagsWithTags(List<String> tags) {
return getBagsWithTags(superProfile, tags);
}
/**
* Fetch bags from given protocol with a particular tag assigned to them.
* @param profile the user to fetch bags from
* @param tag the tag to filter
* @return a map from bag name to bag
*/
protected Map<String, InterMineBag> getBagsWithTag(Profile profile, String tag) {
Map<String, InterMineBag> bagsWithTag = new HashMap<String, InterMineBag>();
for (Map.Entry<String, InterMineBag> entry : profile.getSavedBags().entrySet()) {
InterMineBag bag = entry.getValue();
List<Tag> tags = tagManager.getTags(tag, bag.getName(), TagTypes.BAG,
profile.getUsername());
if (tags.size() > 0) {
bagsWithTag.put(entry.getKey(), entry.getValue());
}
}
return bagsWithTag;
}
/**
* Give me profile bags matching a set of tags
* @param profile The profile these bags must belong to.
* @param tags The tags each bag must have.
* @return The bags of a profile with all of the required tags.
*/
protected Map<String, InterMineBag> getBagsWithTags(Profile profile, List<String> tags) {
Map<String, InterMineBag> bagsWithTags = new HashMap<String, InterMineBag>();
outer:
for (Map.Entry<String, InterMineBag> entry : profile.getSavedBags().entrySet()) {
// gimme the bag
InterMineBag bag = entry.getValue();
// bag's tags
List<Tag> bagTags = getTagsForBag(bag, profile);
// do we have a winner?
inner:
for (String requiredTag : tags) {
for (Tag bagTag : bagTags) {
if (bagTag.getTagName().equals(requiredTag)) {
continue inner;
}
}
continue outer;
}
bagsWithTags.put(entry.getKey(), entry.getValue());
}
return bagsWithTags;
}
public void addTagsToBag(Collection<String> tags, InterMineBag bag, Profile profile)
throws TagNameException, TagNamePermissionException {
for (String tag: tags) {
tagManager.addTag(tag, bag, profile);
}
}
/**
* Return true if the bag is public.
* @param bag The bag in question.
* @return True if tagged with "im:public"
*/
public boolean isPublic(InterMineBag bag) {
return tagManager.hasTag(TagNames.IM_PUBLIC, bag);
}
/**
* Get a list of tags for a given bag.
* @param bag The bag to get tags for.
* @param profile The profile whose tags we are looking for.
* @return A list of Tag objects
*/
public List<Tag> getTagsForBag(InterMineBag bag, Profile profile) {
List<Tag> tags = new ArrayList<Tag>(tagManager.getTags(TagNames.IM_PUBLIC, bag.getName(), TagTypes.BAG, null));
tags.addAll(tagManager.getObjectTags(bag, profile));
return tags;
}
/**
* Fetch bags for the given profile.
* @param profile the user to fetch bags for
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getUserBags(Profile profile) {
return profile.getSavedBags();
}
/**
* Return true if there is at least one bag for the given profile in the 'not_current' state.
* @param profile the user to fetch bags for
* @return a map from bag name to bag
*/
public boolean isAnyBagNotCurrent(Profile profile) {
Map<String, InterMineBag> savedBags = profile.getSavedBags();
for (InterMineBag bag : savedBags.values()) {
if (bag.getState().equals(BagState.NOT_CURRENT.toString())) {
return true;
}
}
return false;
}
/**
* Return true if there is at least one bag for the given profile in the 'to_upgrade' state.
* @param profile the user to fetch bags for
* @return a map from bag name to bag
*/
public boolean isAnyBagToUpgrade(Profile profile) {
Map<String, InterMineBag> savedBags = profile.getSavedBags();
for (InterMineBag bag : savedBags.values()) {
if (bag.getState().equals(BagState.TO_UPGRADE.toString())) {
return true;
}
}
return false;
}
/**
* Fetch all global bags and user bags combined in the same map. If user has a bag with the
* same name as a global bag the user's bag takes precedence.
* @param profile the user to fetch bags for
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getUserAndGlobalBags(Profile profile) {
// add global bags first, any user bags with same name take precedence
Map<String, InterMineBag> allBags = Collections.synchronizedSortedMap(
new TreeMap<String, InterMineBag>());
allBags.putAll(getGlobalBags());
if (profile != null) {
Map<String, InterMineBag> savedBags = profile.getSavedBags();
allBags.putAll(savedBags);
}
return allBags;
}
/**
* Get the bags this user has access to, as long as they are current.
*/
public Map<String, InterMineBag> getCurrentBags(Profile profile) {
Map<String, InterMineBag> ret = Collections.synchronizedSortedMap(
new TreeMap<String, InterMineBag>(getUserAndGlobalBags(profile)));
synchronized(ret) {
Iterator<InterMineBag> bags = ret.values().iterator();
while (bags.hasNext()) {
InterMineBag bag = bags.next();
if (!bag.isCurrent()) {
bags.remove();
}
}
}
return ret;
}
/**
* Order a map of bags by im:order:n tag
* @param bags unordered
* @return an ordered Map of InterMineBags
*/
public Map<String, InterMineBag> orderBags(Map<String, InterMineBag> bags) {
Map<String, InterMineBag> bagsOrdered = new TreeMap<String, InterMineBag>(new ByTagOrder());
bagsOrdered.putAll(bags);
return bagsOrdered;
}
/**
* Fetch a global bag by name.
* @param bagName the name of bag to fetch
* @return the bag or null if not found
*/
public InterMineBag getGlobalBag(String bagName) {
return getGlobalBags().get(bagName);
}
/**
* Fetch a user bag by name.
* @param profile the user to fetch bags for
* @param bagName the name of bag to fetch
* @return the bag or null if not found
*/
public InterMineBag getUserBag(Profile profile, String bagName) {
return getUserBags(profile).get(bagName);
}
/**
* Fetch a global or user bag by name. If user has a bag with the same name as a global bag
* the user's bag takes precedence.
* @param profile the user to fetch bags for
* @param bagName the name of bag to fetch
* @return the bag or null if not found
*/
public InterMineBag getUserOrGlobalBag(Profile profile, String bagName) {
return getUserAndGlobalBags(profile).get(bagName);
}
/**
* Fetch global and user bags of the specified type or a subclass of the specified type.
* @param profile the user to fetch bags for
* @param type an unqualified class name
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getUserOrGlobalBagsOfType(Profile profile, String type) {
return getUserOrGlobalBagsOfType(profile, type, false);
}
/**
* Fetch global and user bags current of the specified type or a subclass of the specified type.
* @param profile the user to fetch bags for
* @param type an unqualified class name
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getCurrentUserOrGlobalBagsOfType(Profile profile,
String type) {
return getUserOrGlobalBagsOfType(profile, type, true);
}
/**
* Fetch global and user bags of the specified type or a subclass of the specified type.
* @param profile the user to fetch bags for
* @param type an unqualified class name
* @param onlyCurrent if true return only the current bags
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getUserOrGlobalBagsOfType(Profile profile, String type,
boolean onlyCurrent) {
return filterBagsByType(getUserAndGlobalBags(profile), type, onlyCurrent);
}
/**
* Fetch user bags curent of the specified type or a subclass of the specified type.
* @param profile the user to fetch bags for
* @param type an unqualified class name
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getCurrentUserBagsOfType(Profile profile, String type) {
return filterBagsByType(getUserBags(profile), type, true);
}
private Map<String, InterMineBag> filterBagsByType(Map<String, InterMineBag> bags,
String type, boolean onlyCurrent) {
Set<String> classAndSubs = new HashSet<String>();
classAndSubs.add(type);
ClassDescriptor bagTypeCld = model.getClassDescriptorByName(type);
if (bagTypeCld == null) {
throw new NullPointerException("Could not find ClassDescriptor for name " + type);
}
for (ClassDescriptor cld : model.getAllSubs(bagTypeCld)) {
classAndSubs.add(cld.getUnqualifiedName());
}
Map<String, InterMineBag> bagsOfType = new HashMap<String, InterMineBag>();
for (Map.Entry<String, InterMineBag> entry : bags.entrySet()) {
InterMineBag bag = entry.getValue();
if (classAndSubs.contains(bag.getType())) {
if ((onlyCurrent && bag.isCurrent()) || !onlyCurrent) {
bagsOfType.put(entry.getKey(), bag);
}
}
}
return bagsOfType;
}
/**
* Fetch global bags that contain the given id.
* @param id the id to search bags for
* @return bags containing the given id
*/
public Collection<InterMineBag> getGlobalBagsContainingId(Integer id) {
return getBagsContainingId(getGlobalBags(), id);
}
/**
* Fetch user bags that contain the given id.
* @param id the id to search bags for
* @param profile the user to fetch bags from
* @return bags containing the given id
*/
public Collection<InterMineBag> getUserBagsContainingId(Profile profile, Integer id) {
return getBagsContainingId(getUserBags(profile), id);
}
/**
* Fetch the current user or global bags that contain the given id. If user has a bag
* with the same name as a global bag the user's bag takes precedence.
* Only current bags are included.
* @param id the id to search bags for
* @param profile the user to fetch bags from
* @return bags containing the given id
*/
public Collection<InterMineBag> getCurrentUserOrGlobalBagsContainingId(Profile profile,
Integer id) {
HashSet<InterMineBag> bagsContainingId = new HashSet<InterMineBag>();
for (InterMineBag bag: getGlobalBagsContainingId(id)) {
if (bag.isCurrent()) {
bagsContainingId.add(bag);
}
}
for (InterMineBag bag: getUserBagsContainingId(profile, id)) {
if (bag.isCurrent()) {
bagsContainingId.add(bag);
}
}
return bagsContainingId;
}
private Collection<InterMineBag> getBagsContainingId(Map<String, InterMineBag> imBags,
Integer id) {
Collection<ObjectStoreBag> objectStoreBags = getObjectStoreBags(imBags.values());
Map<Integer, InterMineBag> osBagIdToInterMineBag =
getOsBagIdToInterMineBag(imBags.values());
// this searches bags for an object
ObjectStoreBagsForObject osbo = new ObjectStoreBagsForObject(id, objectStoreBags);
// run query
Query q = new Query();
q.addToSelect(osbo);
Collection<InterMineBag> bagsContainingId = new HashSet<InterMineBag>();
// this should return all bags with that object
Results res = osProduction.executeSingleton(q);
Iterator<Object> resIter = res.iterator();
while (resIter.hasNext()) {
Integer osBagId = (Integer) resIter.next();
if (osBagIdToInterMineBag.containsKey(osBagId)) {
bagsContainingId.add(osBagIdToInterMineBag.get(osBagId));
}
}
return bagsContainingId;
}
private Map<Integer, InterMineBag> getOsBagIdToInterMineBag(Collection<InterMineBag> imBags) {
Map<Integer, InterMineBag> osBagIdToInterMineBag = new HashMap<Integer, InterMineBag>();
for (InterMineBag imBag : imBags) {
osBagIdToInterMineBag.put(new Integer(imBag.getOsb().getBagId()), imBag);
}
return osBagIdToInterMineBag;
}
private Collection<ObjectStoreBag> getObjectStoreBags(Collection<InterMineBag> imBags) {
Set<ObjectStoreBag> objectStoreBags = new HashSet<ObjectStoreBag>();
for (InterMineBag imBag : imBags) {
objectStoreBags.add(imBag.getOsb());
}
return objectStoreBags;
}
/**
* Compare lists based on their im:order:n tag
* @author radek
*
*/
public class ByTagOrder implements Comparator<String>
{
/**
* For a list of tags corresponding to a bag, give us the order set in im:order:n
* @param tags
* @return
*/
private Integer resolveOrderFromTagsList(List<Tag> tags) {
for (Tag t : tags) {
String name = t.getTagName();
if (name.startsWith("im:order:")) {
return Integer.parseInt(name.replaceAll("[^0-9]", ""));
}
}
return Integer.MAX_VALUE;
}
@Override
public int compare(String aK, String bK) {
// get the order from the tags for the bags for the superduper profile
Integer aO = resolveOrderFromTagsList(tagManager.getTags(null, aK, TagTypes.BAG, null));
Integer bO = resolveOrderFromTagsList(tagManager.getTags(null, bK, TagTypes.BAG, null));
if (aO < bO) {
return -1;
} else {
if (aO > bO) {
return 1;
} else {
CaseInsensitiveComparator cic = new CaseInsensitiveComparator();
return cic.compare(aK, bK);
}
}
}
}
/**
* Lower-case key comparator
* @author radek
*
*/
public class CaseInsensitiveComparator implements Comparator<String>
{
@Override
public int compare(String aK, String bK) {
return aK.toLowerCase().compareTo(bK.toLowerCase());
}
}
}
|
package org.intermine.web;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* Make some change to a user template.
*
* @author Thomas Riley
*/
public class UserTemplateAction extends DispatchAction
{
/**
* Delete a template query.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward delete(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
String queryName = request.getParameter("name");
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
TemplateQuery template = (TemplateQuery) profile.getSavedTemplates().get(queryName);
if (template != null) {
String msg = getResources(request).getMessage("templateList.deleted",
template.getName());
session.setAttribute(Constants.MESSAGE, msg);
// If superuser then rebuild shared templates
if (profile.getUsername() != null
&& profile.getUsername().equals
(servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT))) {
InitialiserPlugin.loadGlobalTemplateQueries(servletContext);
}
} else {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionError("errors.template.nosuchtemplate"));
saveErrors(request, errors);
}
return mapping.findForward("begin");
}
}
|
package wwwc.nees.joint.module.kao;
import wwwc.nees.joint.model.OWLUris;
import wwwc.nees.joint.model.RDFUris;
import wwwc.nees.joint.model.SWRLUris;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openrdf.model.Literal;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.query.Binding;
import org.openrdf.query.BindingSet;
import org.openrdf.query.BooleanQuery;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.Update;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
/**
* Class which implements QueryRunner Interface for performing SPARQL queries in
* the repository.
*
* @author Olavo Holanda
* @version 1.0 - 15/01/2012
*/
public class SPARQLQueryRunnerImpl implements QueryRunner {
// VARIABLES
// Variable to connect with the repository
private Repository repository;
private DatatypeManager datatypeManager;
private RetrieveOperations retrieveOp;
private static final String CALLRET = "callret-";
// Default namespaces to use in the SPARQL queries
public static final String DEFAULT_PREFIXES = "PREFIX rdf:<" + RDFUris.RDF
+ ">\n PREFIX owl:<" + OWLUris.OWL
+ ">\n PREFIX rdfs:<" + RDFUris.RDFS
+ ">\n PREFIX xsd:<" + RDFUris.XSD
+ ">\n PREFIX swrl:<" + SWRLUris.SWRL + ">\n";
// CONSTRUCTOR
/**
* Simple constructor that receives an object connection of the repository.
*
* @param connection the <code>ObjectConnection</code> with the repository.
*
*/
public SPARQLQueryRunnerImpl(Repository repo) {
this.repository = repo;
this.datatypeManager = DatatypeManager.getInstance();
}
// METHODS
/**
* Performs SPARQL queries in the repository, returning a single result.
*
* @param query the <code>String</code> with the query to be performed.
*
* @return object <code>Object</code> result.
*/
@Override
public Object executeQueryAsSingleResult(String query, URI... contexts) {
Object returnObject = null;
TupleQuery tupleQuery;
try {
RepositoryConnection conn = this.repository.getConnection();
conn.setAutoCommit(false);
try {
this.retrieveOp = new RetrieveOperations(conn);
// Creates the query based on the parameter
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
// Performs the query
TupleQueryResult result = tupleQuery.evaluate();
if (!result.hasNext()) {
return null;
}
if (result.getBindingNames().size() > 1) {
List<String> names = result.getBindingNames();
List<String> sortedNames = new ArrayList<>();
Map<Integer, String> positions = new HashMap<>();
String[] realPositions = new String[result.getBindingNames().size()];
for (String string : names) {
Integer index = query.indexOf("?" + string);
if (index == -1) {
realPositions[Integer.getInteger(string.replace(CALLRET, ""))] = string;
} else {
positions.put(index, string);
}
}
List<Integer> listaKeys = new ArrayList<>(positions.keySet());
Collections.sort(listaKeys);
for (Integer integer : listaKeys) {
String value = positions.get(integer);
sortedNames.add(value);
}
for (int i = 0; i < realPositions.length; i++) {
if (realPositions[i] != null) {
sortedNames.add(i, realPositions[i]);
}
}
BindingSet binSet = result.next();
Object[] retorno = new Object[binSet.size()];
int counter = 0;
for (String bName : sortedNames) {
Binding binding = binSet.getBinding(bName);
if (binding == null) {
retorno[counter] = null;
counter++;
continue;
}
Value re = binSet.getBinding(bName).getValue();
if (re instanceof Literal) {
retorno[counter] = datatypeManager.convertLiteralToDataype((Literal) re);
} else {
String className = this.retrieveOp.getClassFromBase(re.stringValue(), contexts);
retorno[counter] = this.retrieveOp.convertOriginalForImpl(re.stringValue(), Class.forName(className), contexts);
}
counter++;
}
System.out.println(retorno);
return retorno;
} else {
BindingSet binSet = result.next();
Value re = binSet.iterator().next().getValue();
if (re == null) {
return null;
} else if (re instanceof Literal) {
returnObject = datatypeManager.convertLiteralToDataype((Literal) re);
} else {
String className = this.retrieveOp.getClassFromBase(re.stringValue(), contexts);
if (className.equals("java.lang.Object")) {
returnObject = re.stringValue();
} else {
returnObject = this.retrieveOp.convertOriginalForImpl(re.stringValue(), Class.forName(className), contexts);
}
}
}
conn.commit();
} catch (Exception e) {
conn.rollback();
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, e);
} finally {
conn.close();
}
} catch (RepositoryException eR) {
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, eR);
}
// Gets the first and only index
return returnObject;
}
/**
* Performs SPARQL queries in the repository, returning a java.util.List of
* results.
*
* @param query the <code>String</code> with the query to be performed.
*
* @return <code>List<Object></code> a java.util.List with the results.
*/
@Override
public List<Object> executeQueryAsList(String query, URI... contexts) {
// Creates a java.util.List
List<Object> resultList = new ArrayList<>();
TupleQuery tupleQuery;
try {
// Gets a connection from repository
RepositoryConnection conn = this.repository.getConnection();
// initiates the transaction
conn.setAutoCommit(false);
// calls the manager from retrieve operations
this.retrieveOp = new RetrieveOperations(conn);
try {
// Creates the query based on the parameter
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
// Performs the query
TupleQueryResult result = tupleQuery.evaluate();
String className = "";
if (result.getBindingNames().size() > 1) {
List<String> names = result.getBindingNames();
List<String> sortedNames = new ArrayList<>();
Map<Integer, String> positions = new HashMap<>();
String[] realPositions = new String[result.getBindingNames().size()];
for (String string : names) {
Integer index = query.indexOf("?" + string);
if (index == -1) {
realPositions[Integer.parseInt(string.replace(CALLRET, ""))] = string;
} else {
positions.put(index, string);
}
}
List<Integer> listaKeys = new ArrayList<>(positions.keySet());
Collections.sort(listaKeys);
for (Integer integer : listaKeys) {
String value = positions.get(integer);
sortedNames.add(value);
}
for (int i = 0; i < realPositions.length; i++) {
if (realPositions[i] != null) {
sortedNames.add(i, realPositions[i]);
}
}
while (result.hasNext()) {
BindingSet binSet = result.next();
Object[] retorno = new Object[binSet.size()];
int counter = 0;
for (String bName : sortedNames) {
Binding binding = binSet.getBinding(bName);
if (binding == null) {
retorno[counter] = null;
counter++;
continue;
}
Value re = binSet.getBinding(bName).getValue();
if (re instanceof Literal) {
retorno[counter] = datatypeManager.convertLiteralToDataype((Literal) re);
} else {
className = this.retrieveOp.getClassFromBase(re.stringValue(), contexts);
retorno[counter] = this.retrieveOp.convertOriginalForImpl(re.stringValue(), Class.forName(className), contexts);
}
counter++;
}
resultList.add(retorno);
}
} else {
// boolean identified = false;
// boolean literal = false;
//checks if there is any result
if (result.hasNext()) {
//gets the first result for type checking
BindingSet binSet = result.next();
//gets the value of the first row
Value re = binSet.iterator().next().getValue();
//if the element is a Literal, else it is an instance
if (re instanceof Literal) {
//creates the collection of literal
List<Literal> literals = new ArrayList<>();
//adds the first element
literals.add((Literal) re);
while (result.hasNext()) {
//gets the element in the row and casts its value to Literal
BindingSet binding = result.next();
Literal lit = (Literal) binding.iterator().next().getValue();
//adds in the collection
literals.add(lit);
}
result.close();
//returns the collection already parsed
return this.datatypeManager.convertCollectionOfLiteralToDataypes(literals);
} else {
//checks which class type the element belongs
className = this.retrieveOp.getClassFromBase(re.stringValue(), contexts);
//creates the collection of objects
List<String> instancesURI = new ArrayList<>();
//adds the first element
instancesURI.add(re.stringValue());
while (result.hasNext()) {
//gets the element in the row and casts its value to Literal
BindingSet binding = result.next();
String uri = binding.iterator().next().getValue().stringValue();
//adds in the collection
instancesURI.add(uri);
}
result.close();
return this.retrieveOp.convertCollectionOriginalForImpl(instancesURI, Class.forName(className), contexts);
}
}
}
result.close();
conn.commit();
} catch (Exception e) {
conn.rollback();
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, e);
} finally {
conn.close();
}
} catch (RepositoryException eR) {
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, eR);
}
return resultList;
}
/**
* Performs SPARQL queries in the repository, returning a java.util.Iterator
* with the results.
*
* @param query the <code>String</code> with the query to be performed.
*
* @return <code>Iterator<Object></code> a java.util.List with the results.
*/
@Override
public Iterator<Object> executeQueryAsIterator(String query, URI... contexts) {
// Creates a java.util.List
List<Object> resultList = new ArrayList<>();
try {
// Changes the result to a java.util.List
resultList = (List<Object>) this.executeQueryAsList(query, contexts);
} catch (Exception e) {
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, e);
}
//Gets the iterator of the list
return resultList.iterator();
}
/**
* Performs SPARQL queries in the repository, returning a boolean with the
* result.
*
* @param query the <code>String</code> with the query to be performed.
*
* @return <code>boolean<Object></code> true or false.
*/
@Override
public boolean executeBooleanQuery(String query) {
boolean result = false;
BooleanQuery objectQuery;
try {
RepositoryConnection conn = this.repository.getConnection();
conn.setAutoCommit(false);
try {
// Creates the query based on the parameter
objectQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, query);
// Performs the query
result = objectQuery.evaluate();
conn.commit();
} catch (Exception e) {
conn.rollback();
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, e);
} finally {
conn.close();
}
} catch (RepositoryException eR) {
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, eR);
}
return result;
}
/**
* Performs SPARQL update queries in the repository, returning a boolean
* true if the query was performed with successful or false otherwise.
*
* @param query the <code>String</code> with the query to be performed.
* @return <code>boolean</code> true or false.
*/
@Override
public boolean executeUpdateQuery(String query) {
boolean result = false;
try {
RepositoryConnection conn = this.repository.getConnection();
conn.setAutoCommit(false);
try {
// Creates the update query based on the parameter
Update update = conn.prepareUpdate(QueryLanguage.SPARQL, query);
// Performs the query
update.execute();
conn.commit();
result = true;
} catch (Exception e) {
conn.rollback();
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, e);
} finally {
conn.close();
}
} catch (RepositoryException eR) {
Logger.getLogger(SPARQLQueryRunnerImpl.class.getName()).
log(Level.SEVERE, null, eR);
}
return result;
}
}
|
package jadx.core.xmlgen;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.xmlgen.entry.EntryConfig;
import jadx.core.xmlgen.entry.RawNamedValue;
import jadx.core.xmlgen.entry.RawValue;
import jadx.core.xmlgen.entry.ResourceEntry;
import jadx.core.xmlgen.entry.ValuesParser;
public class ResTableParser extends CommonBinaryParser {
private static final Logger LOG = LoggerFactory.getLogger(ResTableParser.class);
private static final Pattern VALID_RES_KEY_PATTERN = Pattern.compile("[\\w\\d_]+");
private static final class PackageChunk {
private final int id;
private final String name;
private final String[] typeStrings;
private final String[] keyStrings;
private PackageChunk(int id, String name, String[] typeStrings, String[] keyStrings) {
this.id = id;
this.name = name;
this.typeStrings = typeStrings;
this.keyStrings = keyStrings;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String[] getTypeStrings() {
return typeStrings;
}
public String[] getKeyStrings() {
return keyStrings;
}
}
/**
* No renaming, pattern checking or name generation. Required for res-map.txt building
*/
private final boolean useRawResName;
private final RootNode root;
private final ResourceStorage resStorage = new ResourceStorage();
private String[] strings;
public ResTableParser(RootNode root) {
this(root, false);
}
public ResTableParser(RootNode root, boolean useRawResNames) {
this.root = root;
this.useRawResName = useRawResNames;
}
public void decode(InputStream inputStream) throws IOException {
is = new ParserStream(inputStream);
decodeTableChunk();
resStorage.finish();
}
public ResContainer decodeFiles(InputStream inputStream) throws IOException {
decode(inputStream);
ValuesParser vp = new ValuesParser(strings, resStorage.getResourcesNames());
ResXmlGen resGen = new ResXmlGen(resStorage, vp);
ICodeInfo content = XmlGenUtils.makeXmlDump(root.makeCodeWriter(), resStorage);
List<ResContainer> xmlFiles = resGen.makeResourcesXml();
return ResContainer.resourceTable("res", xmlFiles, content);
}
public ResourceStorage getResStorage() {
return resStorage;
}
public String[] getStrings() {
return strings;
}
void decodeTableChunk() throws IOException {
is.checkInt16(RES_TABLE_TYPE, "Not a table chunk");
is.checkInt16(0x000c, "Unexpected table header size");
/* int size = */
is.readInt32();
int pkgCount = is.readInt32();
strings = parseStringPool();
for (int i = 0; i < pkgCount; i++) {
parsePackage();
}
}
private PackageChunk parsePackage() throws IOException {
long start = is.getPos();
is.checkInt16(RES_TABLE_PACKAGE_TYPE, "Not a table chunk");
int headerSize = is.readInt16();
if (headerSize != 0x011c && headerSize != 0x0120) {
die("Unexpected package header size");
}
long size = is.readUInt32();
long endPos = start + size;
int id = is.readInt32();
String name = is.readString16Fixed(128);
long typeStringsOffset = start + is.readInt32();
/* int lastPublicType = */
is.readInt32();
long keyStringsOffset = start + is.readInt32();
/* int lastPublicKey = */
is.readInt32();
if (headerSize == 0x0120) {
/* int typeIdOffset = */
is.readInt32();
}
String[] typeStrings = null;
if (typeStringsOffset != 0) {
is.skipToPos(typeStringsOffset, "Expected typeStrings string pool");
typeStrings = parseStringPool();
}
String[] keyStrings = null;
if (keyStringsOffset != 0) {
is.skipToPos(keyStringsOffset, "Expected keyStrings string pool");
keyStrings = parseStringPool();
deobfKeyStrings(keyStrings);
}
PackageChunk pkg = new PackageChunk(id, name, typeStrings, keyStrings);
resStorage.setAppPackage(name);
while (is.getPos() < endPos) {
long chunkStart = is.getPos();
int type = is.readInt16();
if (type == RES_NULL_TYPE) {
continue;
}
if (type == RES_TABLE_TYPE_SPEC_TYPE) {
parseTypeSpecChunk();
} else if (type == RES_TABLE_TYPE_TYPE) {
parseTypeChunk(chunkStart, pkg);
}
}
return pkg;
}
private void deobfKeyStrings(String[] keyStrings) {
int keysCount = keyStrings.length;
if (root.getArgs().isRenamePrintable()) {
for (int i = 0; i < keysCount; i++) {
String keyString = keyStrings[i];
if (!NameMapper.isAllCharsPrintable(keyString)) {
keyStrings[i] = makeNewKeyName(i);
}
}
}
if (root.getArgs().isRenameValid()) {
Set<String> keySet = new HashSet<>(keysCount);
for (int i = 0; i < keysCount; i++) {
String keyString = keyStrings[i];
boolean isNew = keySet.add(keyString);
if (!isNew) {
keyStrings[i] = makeNewKeyName(i);
}
}
}
}
private String makeNewKeyName(int idx) {
return String.format("jadx_deobf_0x%08x", idx);
}
@SuppressWarnings("unused")
private void parseTypeSpecChunk() throws IOException {
is.checkInt16(0x0010, "Unexpected type spec header size");
/* int size = */
is.readInt32();
int id = is.readInt8();
is.skip(3);
int entryCount = is.readInt32();
for (int i = 0; i < entryCount; i++) {
int entryFlag = is.readInt32();
}
}
private void parseTypeChunk(long start, PackageChunk pkg) throws IOException {
/* int headerSize = */
is.readInt16();
/* int size = */
long chunkSize = is.readUInt32();
long chunkEnd = start + chunkSize;
int id = is.readInt8();
is.checkInt8(0, "type chunk, res0");
is.checkInt16(0, "type chunk, res1");
int entryCount = is.readInt32();
long entriesStart = start + is.readInt32();
EntryConfig config = parseConfig();
if (config.isInvalid) {
String typeName = pkg.getTypeStrings()[id - 1];
LOG.warn("Invalid config flags detected: {}{}", typeName, config.getQualifiers());
}
int[] entryIndexes = new int[entryCount];
for (int i = 0; i < entryCount; i++) {
entryIndexes[i] = is.readInt32();
}
is.checkPos(entriesStart, "Expected entry start");
for (int i = 0; i < entryCount; i++) {
if (entryIndexes[i] != NO_ENTRY) {
if (is.getPos() >= chunkEnd) {
// Certain resource obfuscated apps like com.facebook.orca have more entries defined
// than actually fit into the chunk size -> ignore the remaining entries
LOG.warn("End of chunk reached - ignoring remaining {} entries", entryCount - i);
break;
}
parseEntry(pkg, id, i, config.getQualifiers());
}
}
}
private void parseEntry(PackageChunk pkg, int typeId, int entryId, String config) throws IOException {
int size = is.readInt16();
int flags = is.readInt16();
int key = is.readInt32();
if (key == -1) {
return;
}
int resRef = pkg.getId() << 24 | typeId << 16 | entryId;
String typeName = pkg.getTypeStrings()[typeId - 1];
String origKeyName = pkg.getKeyStrings()[key];
ResourceEntry newResEntry = new ResourceEntry(resRef, pkg.getName(), typeName, getResName(typeName, resRef, origKeyName), config);
ResourceEntry prevResEntry = resStorage.searchEntryWithSameName(newResEntry);
if (prevResEntry != null) {
newResEntry = newResEntry.copyWithId();
// rename also previous entry for consistency
ResourceEntry replaceForPrevEntry = prevResEntry.copyWithId();
resStorage.replace(prevResEntry, replaceForPrevEntry);
resStorage.addRename(replaceForPrevEntry);
}
if (!Objects.equals(origKeyName, newResEntry.getKeyName())) {
resStorage.addRename(newResEntry);
}
if ((flags & FLAG_COMPLEX) != 0 || size == 16) {
int parentRef = is.readInt32();
int count = is.readInt32();
newResEntry.setParentRef(parentRef);
List<RawNamedValue> values = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
values.add(parseValueMap());
}
newResEntry.setNamedValues(values);
} else {
newResEntry.setSimpleValue(parseValue());
}
resStorage.add(newResEntry);
}
private String getResName(String typeName, int resRef, String origKeyName) {
if (this.useRawResName) {
return origKeyName;
}
String renamedKey = resStorage.getRename(resRef);
if (renamedKey != null) {
return renamedKey;
}
FieldNode constField = root.getConstValues().getGlobalConstFields().get(resRef);
if (constField != null) {
constField.add(AFlag.DONT_RENAME);
return constField.getName();
}
// styles might contain dots in name, use VALID_RES_KEY_PATTERN only for resource file name
if (typeName.equals("style")) {
return origKeyName;
} else if (VALID_RES_KEY_PATTERN.matcher(origKeyName).matches()) {
return origKeyName;
}
// Making sure origKeyName compliant with resource file name rules
Matcher m = VALID_RES_KEY_PATTERN.matcher(origKeyName);
StringBuilder sb = new StringBuilder();
boolean first = true;
while (m.find()) {
if (!first) {
sb.append("_");
}
sb.append(m.group());
first = false;
}
// autogenerate key name, appended with cleaned origKeyName to be human-friendly
String newResName = String.format("res_0x%08x", resRef);
String cleanedResName = sb.toString();
if (!cleanedResName.isEmpty()) {
newResName += "_" + cleanedResName.toLowerCase();
}
return newResName;
}
private RawNamedValue parseValueMap() throws IOException {
int nameRef = is.readInt32();
return new RawNamedValue(nameRef, parseValue());
}
private RawValue parseValue() throws IOException {
is.checkInt16(8, "value size");
is.checkInt8(0, "value res0 not 0");
int dataType = is.readInt8();
int data = is.readInt32();
return new RawValue(dataType, data);
}
private EntryConfig parseConfig() throws IOException {
long start = is.getPos();
int size = is.readInt32();
if (size < 28) {
throw new IOException("Config size < 28");
}
short mcc = (short) is.readInt16();
short mnc = (short) is.readInt16();
char[] language = unpackLocaleOrRegion((byte) is.readInt8(), (byte) is.readInt8(), 'a');
char[] country = unpackLocaleOrRegion((byte) is.readInt8(), (byte) is.readInt8(), '0');
byte orientation = (byte) is.readInt8();
byte touchscreen = (byte) is.readInt8();
int density = is.readInt16();
byte keyboard = (byte) is.readInt8();
byte navigation = (byte) is.readInt8();
byte inputFlags = (byte) is.readInt8();
is.readInt8(); // inputPad0
short screenWidth = (short) is.readInt16();
short screenHeight = (short) is.readInt16();
short sdkVersion = (short) is.readInt16();
is.readInt16(); // minorVersion must always be 0
byte screenLayout = 0;
byte uiMode = 0;
short smallestScreenWidthDp = 0;
if (size >= 32) {
screenLayout = (byte) is.readInt8();
uiMode = (byte) is.readInt8();
smallestScreenWidthDp = (short) is.readInt16();
}
short screenWidthDp = 0;
short screenHeightDp = 0;
if (size >= 36) {
screenWidthDp = (short) is.readInt16();
screenHeightDp = (short) is.readInt16();
}
char[] localeScript = null;
char[] localeVariant = null;
if (size >= 48) {
localeScript = readScriptOrVariantChar(4).toCharArray();
localeVariant = readScriptOrVariantChar(8).toCharArray();
}
byte screenLayout2 = 0;
byte colorMode = 0;
if (size >= 52) {
screenLayout2 = (byte) is.readInt8();
colorMode = (byte) is.readInt8();
is.readInt16(); // reserved padding
}
is.skipToPos(start + size, "Config skip trailing bytes");
return new EntryConfig(mcc, mnc, language, country,
orientation, touchscreen, density, keyboard, navigation,
inputFlags, screenWidth, screenHeight, sdkVersion,
screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp,
screenHeightDp, localeScript, localeVariant, screenLayout2,
colorMode, false, size);
}
private char[] unpackLocaleOrRegion(byte in0, byte in1, char base) {
// check high bit, if so we have a packed 3 letter code
if (((in0 >> 7) & 1) == 1) {
int first = in1 & 0x1F;
int second = ((in1 & 0xE0) >> 5) + ((in0 & 0x03) << 3);
int third = (in0 & 0x7C) >> 2;
// since this function handles languages & regions, we add the value(s) to the base char
// which is usually 'a' or '0' depending on language or region.
return new char[] { (char) (first + base), (char) (second + base), (char) (third + base) };
}
return new char[] { (char) in0, (char) in1 };
}
private String readScriptOrVariantChar(int length) throws IOException {
long start = is.getPos();
StringBuilder sb = new StringBuilder(16);
for (int i = 0; i < length; i++) {
short ch = (short) is.readInt8();
if (ch == 0) {
break;
}
sb.append((char) ch);
}
is.skipToPos(start + length, "readScriptOrVariantChar");
return sb.toString();
}
}
|
package org.broadinstitute.sting.utils;
import edu.mit.broad.picard.directed.IntervalList;
import edu.mit.broad.picard.util.Interval;
import net.sf.picard.reference.ReferenceSequenceFile;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMSequenceDictionary;
import net.sf.samtools.SAMSequenceRecord;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GenomeLocParser {
private static Logger logger = Logger.getLogger(GenomeLocParser.class);
private static final Pattern regex1 = Pattern.compile("([\\w&&[^:]]+)$"); // matches case 1
private static final Pattern regex2 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)$"); // matches case 2
private static final Pattern regex3 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)-([\\d,]+)$"); // matches case 3
private static final Pattern regex4 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)\\+"); // matches case 4
// Ugly global variable defining the optional ordering of contig elements
//public static Map<String, Integer> refContigOrdering = null;
private static SAMSequenceDictionary contigInfo = null;
/**
* do we have a contig ordering setup?
*
* @return true if the contig order is setup
*/
public static boolean hasKnownContigOrdering() {
return contigInfo != null;
}
/**
* get the contig's SAMSequenceRecord
*
* @param contig the string name of the contig
*
* @return the sam sequence record
*/
public static SAMSequenceRecord getContigInfo(final String contig) {
return contigInfo.getSequence(contig);
}
/**
* Returns the contig index of a specified string version of the contig
*
* @param contig the contig string
*
* @return the contig index, -1 if not found
*/
public static int getContigIndex(final String contig) {
if (contigInfo.getSequenceIndex(contig) == -1)
Utils.scareUser(String.format("Contig %s given as location, but this contig isn't present in the Fasta sequence dictionary", contig));
return contigInfo.getSequenceIndex(contig);
}
/**
* set our internal reference contig order
*
* @param refFile the reference file
*
* @return true if we were successful
*/
public static boolean setupRefContigOrdering(final ReferenceSequenceFile refFile) {
return setupRefContigOrdering(refFile.getSequenceDictionary());
}
/**
* setup our internal reference contig order
*
* @param seqDict the sequence dictionary
*
* @return true if we were successful
*/
public static boolean setupRefContigOrdering(final SAMSequenceDictionary seqDict) {
if (seqDict == null) { // we couldn't load the reference dictionary
logger.info("Failed to load reference dictionary, falling back to lexicographic order for contigs");
Utils.scareUser("Failed to load reference dictionary");
return false;
} else if (contigInfo == null) {
contigInfo = seqDict;
logger.debug(String.format("Prepared reference sequence contig dictionary"));
for (SAMSequenceRecord contig : seqDict.getSequences()) {
logger.debug(String.format(" %s (%d bp)", contig.getSequenceName(), contig.getSequenceLength()));
}
}
return true;
}
/**
* parse a genome location, from a location string
*
* @param str the string to parse
*
* @return a GenomeLoc representing the String
*/
public static GenomeLoc parseGenomeLoc(final String str) {
// 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
//System.out.printf("Parsing location '%s'%n", str);
String contig = null;
long start = 1;
long stop = Integer.MAX_VALUE;
boolean bad = false;
Matcher match1 = regex1.matcher(str);
Matcher match2 = regex2.matcher(str);
Matcher match3 = regex3.matcher(str);
Matcher match4 = regex4.matcher(str);
try {
if (match1.matches()) {
contig = match1.group(1);
} else if (match2.matches()) {
contig = match2.group(1);
start = parsePosition(match2.group(2));
stop = start;
} else if (match4.matches()) {
contig = match4.group(1);
start = parsePosition(match4.group(2));
} else if (match3.matches()) {
contig = match3.group(1);
start = parsePosition(match3.group(2));
stop = parsePosition(match3.group(3));
if (start > stop)
bad = true;
} else {
bad = true;
}
} catch (Exception e) {
bad = true;
}
if (bad) {
throw new StingException("Invalid Genome Location string: " + str);
}
if (stop == Integer.MAX_VALUE && hasKnownContigOrdering()) {
// lookup the actually stop position!
stop = getContigInfo(contig).getSequenceLength();
}
if (!isContigValid(contig))
throw new MalformedGenomeLocException("Contig " + contig + " does not match any contig in the GATK sequence dictionary derived from the reference.");
GenomeLoc loc = parseGenomeLoc(contig, start, stop);
// System.out.printf(" => Parsed location '%s' into %s%n", str, loc);
return loc;
}
/**
* Useful utility function that parses a location string into a coordinate-order sorted
* array of GenomeLoc objects
*
* @param str String representation of genome locs. Null string corresponds to no filter.
*
* @return Array of GenomeLoc objects corresponding to the locations in the string, sorted by coordinate order
*/
public static List<GenomeLoc> parseGenomeLocs(final String str) {
// Null string means no filter.
if (str == null) return null;
// Of the form: loc1;loc2;...
// Where each locN can be:
// 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
try {
List<GenomeLoc> locs = new ArrayList<GenomeLoc>();
for (String loc : str.split(";"))
locs.add(parseGenomeLoc(loc.trim()));
Collections.sort(locs);
//logger.info(String.format("Going to process %d locations", locs.length));
locs = mergeOverlappingLocations(locs);
logger.debug("Locations are:" + Utils.join(", ", locs));
return locs;
} catch (Exception e) { // TODO: fix this so that it passes the message from the exception, and doesn't print it out
throw new StingException(String.format("Invalid locations string: %s, format is loc1;loc2; where each locN can be 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'", str), e);
}
}
// Parsing string representations
private static long parsePosition(final String pos) {
String x = pos.replaceAll(",", "");
return Long.parseLong(x);
}
/**
* merge a list of genome locs that may be overlapping, returning the list of unique genomic locations
*
* @param raw the unchecked genome loc list
*
* @return the list of merged locations
*/
public static List<GenomeLoc> mergeOverlappingLocations(final List<GenomeLoc> raw) {
logger.debug(" Raw locations are: " + Utils.join(", ", raw));
if (raw.size() <= 1)
return raw;
else {
ArrayList<GenomeLoc> merged = new ArrayList<GenomeLoc>();
Iterator<GenomeLoc> it = raw.iterator();
GenomeLoc prev = it.next();
while (it.hasNext()) {
GenomeLoc curr = it.next();
if (prev.contiguousP(curr)) {
prev = prev.merge(curr);
} else {
merged.add(prev);
prev = curr;
}
}
merged.add(prev);
return merged;
}
}
/**
* Determines whether the given contig is valid with respect to the sequence dictionary
* already installed in the GenomeLoc.
*
* @return True if the contig is valid. False otherwise.
*/
private static boolean isContigValid(String contig) {
int contigIndex = contigInfo.getSequenceIndex(contig);
return isSequenceIndexValid(contigIndex);
}
/**
* Determines whether the given sequence index is valid with respect to the sequence dictionary.
*
* @param sequenceIndex sequence index
*
* @return True if the sequence index is valid, false otherwise.
*/
private static boolean isSequenceIndexValid(int sequenceIndex) {
return sequenceIndex >= 0 && sequenceIndex < contigInfo.size();
}
/**
* Use this static constructor when the input data is under limited control (i.e. parsing user data).
*
* @param contig Contig to parse.
* @param start Starting point.
* @param stop Stop point.
*
* @return The genome location, or a MalformedGenomeLocException if unparseable.
*/
public static GenomeLoc parseGenomeLoc(final String contig, long start, long stop) {
if (!isContigValid(contig))
throw new MalformedGenomeLocException("Contig " + contig + " does not match any contig in the GATK sequence dictionary derived from the reference.");
return new GenomeLoc(contig, getContigIndex(contig), start, stop);
}
/**
* Read a file of genome locations to process.
* regions specified by the location string. The string is of the form:
* Of the form: loc1;loc2;...
* Where each locN can be:
* 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
*
* @param file_name
*/
public static List<GenomeLoc> intervalFileToList(final String file_name) {
/**
* first try to read it as an interval file since that's well structured
* we'll fail quickly if it's not a valid file. Then try to parse it as
* a location string file
*/
List<GenomeLoc> ret = null;
try {
IntervalList il = IntervalList.fromFile(new File(file_name));
// iterate through the list of merged intervals and add then as GenomeLocs
ret = new ArrayList<GenomeLoc>();
for (Interval interval : il.getUniqueIntervals()) {
ret.add(new GenomeLoc(interval.getSequence(), getContigIndex(interval.getSequence()), interval.getStart(), interval.getEnd()));
}
return ret;
} catch (Exception e) {
try {
xReadLines reader = new xReadLines(new File(file_name));
List<String> lines = reader.readLines();
reader.close();
String locStr = Utils.join(";", lines);
logger.debug("locStr: " + locStr);
ret = parseGenomeLocs(locStr);
return ret;
} catch (Exception e2) {
logger.error("Attempt to parse interval file in GATK format failed: " + e2.getMessage());
e2.printStackTrace();
throw new StingException("Unable to parse out interval file in either format", e);
}
}
}
/**
* get the sequence name from a sequence index
*
* @param contigIndex get the contig index
*
* @return the string that represents that contig name
*/
private static String getSequenceNameFromIndex(int contigIndex) {
return GenomeLocParser.contigInfo.getSequence(contigIndex).getSequenceName();
}
/**
* create a genome loc, given the contig name, start, and stop
*
* @param contig the contig name
* @param start the starting position
* @param stop the stop position
*
* @return a new genome loc
*/
public static GenomeLoc createGenomeLoc(String contig, final long start, final long stop) {
checkSetup();
return verifyGenomeLoc(new GenomeLoc(contig, GenomeLocParser.getContigIndex(contig), start, stop));
}
/**
* create a genome loc, given the contig index, start, and stop
*
* @param contigIndex the contig index
* @param start the start position
* @param stop the stop position
*
* @return a new genome loc
*/
public static GenomeLoc createGenomeLoc(int contigIndex, final long start, final long stop) {
checkSetup();
if (start < 0) {
throw new StingException("Bad start position " + start);
}
if (stop < -1) {
throw new StingException("Bad stop position " + stop);
} // a negative -1 indicates it's not a meaningful end position
return new GenomeLoc(getSequenceNameFromIndex(contigIndex), contigIndex, start, stop);
}
/**
* create a genome loc, given a read
*
* @param read
*
* @return
*/
public static GenomeLoc createGenomeLoc(final SAMRecord read) {
checkSetup();
return verifyGenomeLoc(new GenomeLoc(read.getReferenceName(), read.getReferenceIndex(), read.getAlignmentStart(), read.getAlignmentEnd()));
}
/**
* create a new genome loc, given the contig position, and a single position
*
* @param contig the contig name
* @param pos the postion
*
* @return a genome loc representing a single base at the specified postion on the contig
*/
public static GenomeLoc createGenomeLoc(final int contig, final long pos) {
checkSetup();
return verifyGenomeLoc(new GenomeLoc(getSequenceNameFromIndex(contig), contig, pos, pos));
}
/**
* create a new genome loc, given the contig name, and a single position
*
* @param contig the contig name
* @param pos the postion
*
* @return a genome loc representing a single base at the specified postion on the contig
*/
public static GenomeLoc createGenomeLoc(final String contig, final long pos) {
checkSetup();
return verifyGenomeLoc(new GenomeLoc(contig, GenomeLocParser.getContigIndex(contig), pos, pos));
}
public static GenomeLoc createGenomeLoc(final GenomeLoc toCopy) {
checkSetup();
return verifyGenomeLoc(new GenomeLoc(toCopy.getContig(), toCopy.getContigIndex(), toCopy.getStart(), toCopy.getStop()));
}
/**
* verify the specified genome loc is valid, if it's not, throw an exception
*
* @param toReturn teh genome loc we're about to return
*
* @return the genome loc if it's valid, otherwise we throw an exception
*/
private static GenomeLoc verifyGenomeLoc(GenomeLoc toReturn) {
if (toReturn.getStart() < 0) {
throw new StingException("Parameters to GenomeLocParser are incorrect: the start position is less than 0");
}
if ((toReturn.getStop() != -1) && (toReturn.getStop() < 0)) {
throw new StingException("Parameters to GenomeLocParser are incorrect: the stop position is less than 0");
}
if (toReturn.getContigIndex() < 0) {
throw new StingException("Parameters to GenomeLocParser are incorrect: the contig index is less than 0");
}
if (toReturn.getContigIndex() >= contigInfo.getSequences().size()) {
throw new StingException("Parameters to GenomeLocParser are incorrect: the contig index is greater then the stored sequence count");
}
return toReturn;
}
/**
* Move this Genome loc to the next contig, with a start
* and stop of 1.
*
* @return true if we are not out of contigs, otherwise false if we're
* at the end of the genome (no more contigs to jump to).
*/
public static GenomeLoc toNextContig(GenomeLoc current) {
if (current.getContigIndex() + 1 >= contigInfo.getSequences().size()) {
return null;
} else
return verifyGenomeLoc(new GenomeLoc(getSequenceNameFromIndex(current.getContigIndex() + 1), current.getContigIndex() + 1, 1, 1));
}
/**
* create a new genome loc, given an old location and a new contig
*
* @param loc the old location
* @param contig the new contig to set
*
* @return a new genome loc with an updated contig name and index
*/
public static GenomeLoc setContig(GenomeLoc loc, String contig) {
checkSetup();
int index = -1;
if ( ( index = contigInfo.getSequenceIndex(contig) ) < 0 ) {
throw new StingException("Contig name ( " + contig + " ) not in the set sequence dictionary.");
}
return verifyGenomeLoc(new GenomeLoc(contig, index, loc.start, loc.getStop()));
}
/** Sets contig index. UNSAFE since it 1) does NOT update contig name; 2) does not validate the index
*
* @param contig
*/
public static GenomeLoc setContigIndex(GenomeLoc loc, int contig) {
checkSetup();
if ((contig >= GenomeLocParser.contigInfo.getSequences().size()) || (contig < 0)) {
throw new StingException("Contig index ( " + contig + " ) is not in the sequence dictionary set.");
}
return verifyGenomeLoc(new GenomeLoc(GenomeLocParser.contigInfo.getSequence(contig).getSequenceName(), contig, loc.start, loc.getStop()));
}
/**
* create a new genome loc from an existing loc, with a new start position
*
* @param loc the old location
* @param start a new start position
*
* @return the newly created genome loc
*/
public static GenomeLoc setStart(GenomeLoc loc, long start) {
checkSetup();
if (loc.getContigIndex() < 0 || loc.getContigIndex() >= contigInfo.getSequences().size()) {
throw new StingException("Genome loc passed in to setStart has a contig index outside the range of our current sequence dictionary");
}
int length = GenomeLocParser.contigInfo.getSequences().get(loc.getContigIndex()).getSequenceLength();
if (start > length) {
throw new StingException("start value of " + start + " is greater than the contig length, and is not -1. (length = " + length + ").");
}
return verifyGenomeLoc(new GenomeLoc(loc.getContig(), loc.getContigIndex(), start, loc.getStop()));
}
/**
* create a new genome loc from an existing loc, with a new stop position
*
* @param loc the old location
* @param stop a new stop position
*
* @return
*/
public static GenomeLoc setStop(GenomeLoc loc, long stop) {
checkSetup();
if (loc.getContigIndex() < 0 || loc.getContigIndex() >= contigInfo.getSequences().size()) {
throw new StingException("Genome loc passed in to setStart has a contig index outside the range of our current sequence dictionary");
}
if ((stop != -1) && (stop > GenomeLocParser.contigInfo.getSequences().get(loc.getContigIndex()).getSequenceLength())) {
throw new StingException("stop value of " + stop + " is greater than the contig length, and is not -1.");
}
return verifyGenomeLoc(new GenomeLoc(loc.getContig(), loc.getContigIndex(), loc.start, stop));
}
/**
* return a new genome loc, with an incremented position
* @param loc the old location
* @return a new genome loc
*/
public static GenomeLoc incPos(GenomeLoc loc) {
return incPos(loc, 1);
}
/**
* return a new genome loc, with an incremented position
* @param loc the old location
* @param by how much to move the start and stop by
* @return a new genome loc
*/
public static GenomeLoc incPos(GenomeLoc loc, long by) {
return verifyGenomeLoc(new GenomeLoc(loc.getContig(), loc.getContigIndex(), loc.start + by, loc.stop + by));
}
/**
* create a new genome loc with an incremented position
* @param loc the location
* @return a new genome loc
*/
public static GenomeLoc nextLoc(GenomeLoc loc) {
return incPos(loc);
}
/** check to make sure that we've setup the contig information */
private static void checkSetup() {
if (contigInfo == null) {
throw new StingException("The GenomeLocParser hasn't been setup with a contig sequence yet");
}
}
/**
* compare two contig names, in the current context
*
* @param firstContig
* @param secondContig
*
* @return
*/
public static int compareContigs(String firstContig, String secondContig) {
checkSetup();
Integer ref1 = GenomeLocParser.getContigIndex(firstContig);
Integer ref2 = GenomeLocParser.getContigIndex(secondContig);
return ref1.compareTo(ref2);
}
}
|
package joliex.meta;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import jolie.CommandLineException;
import jolie.CommandLineParser;
import jolie.lang.NativeType;
import jolie.lang.parse.ParserException;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OperationDeclaration;
import jolie.lang.parse.ast.OutputPortInfo;
import jolie.lang.parse.ast.PortInfo;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.types.TypeDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.lang.parse.util.ParsingUtils;
import jolie.lang.parse.util.ProgramInspector;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.embedding.RequestResponse;
import jolie.util.Range;
/**
*
* @author claudio guidi
*/
public class MetaJolie extends JavaService {
private int MAX_CARD = 2147483647;
private boolean is_generalType(String type) {
// standard types are not inserted. TO BE IMPROVED
boolean response = false;
if (type.equals("Date")) {
response = true;
} else if (type.equals("String")) {
response = true;
} else if (type.equals("Integer")) {
response = true;
} else if (type.equals("Void")) {
response = true;
} else if (type.equals("__Role")) {
response = true;
}
return response;
}
private Value getNativeType(NativeType type) {
Value response = Value.create();
if (type == NativeType.ANY) {
response.getFirstChild("any_type").setValue(true);
} else if (type == NativeType.STRING) {
response.getFirstChild("string_type").setValue(true);
} else if (type == NativeType.DOUBLE) {
response.getFirstChild("double_type").setValue(true);
} else if (type == NativeType.INT) {
response.getFirstChild("int_type").setValue(true);
} else if (type == NativeType.VOID) {
response.getFirstChild("void_type").setValue(true);
} else if (type == NativeType.BOOL) {
response.getFirstChild("bool_type").setValue(true);
} else if (type == NativeType.LONG) {
response.getFirstChild("long_type").setValue(true);
}
// type undefined?
return response;
}
private boolean isNativeType(String type) {
if (type.equals("any") || type.equals("string") || type.equals("double") || type.equals("int") || type.equals("void")) {
return true;
} else {
return false;
}
}
private Value addCardinality(Range range) {
Value response = Value.create();
response.getFirstChild("min").setValue(range.min());
if (range.max() == MAX_CARD) {
response.getFirstChild("infinite").setValue(1);
} else {
response.getFirstChild("max").setValue(range.max());
}
return response;
}
private Value addTypeInLine(ArrayList<TypeDefinition> types, ValueVector types_vector, Value name, TypeDefinition typedef) {
Value response = Value.create();
response.getFirstChild("name").getFirstChild("name").setValue(typedef.id()); // not useful, inserted for respecting Type
if (typedef instanceof TypeDefinitionLink) {
response.getFirstChild("root_type").getFirstChild("link").setValue(((TypeDefinitionLink) typedef).linkedTypeName());
insertType(types, types_vector, name, ((TypeDefinitionLink) typedef).linkedType());
} else {
TypeInlineDefinition td = (TypeInlineDefinition) typedef;
response.getFirstChild("root_type").deepCopy(getNativeType(typedef.nativeType()));
if (td.hasSubTypes()) {
for (Entry<String, TypeDefinition> entry : td.subTypes()) {
response.getChildren("sub_type").add(addSubType(types, types_vector, name, entry.getValue()));
}
}
}
return response;
}
private Value addSubType(ArrayList<TypeDefinition> types, ValueVector types_vector, Value name, TypeDefinition type) {
Value response = Value.create();
response.getFirstChild("name").setValue(type.id());
response.getFirstChild("cardinality").deepCopy(addCardinality(type.cardinality()));
if (type instanceof TypeDefinitionLink) {
response.getFirstChild("type_link").deepCopy(setName(name));
response.getFirstChild("type_link").getFirstChild("name").setValue(((TypeDefinitionLink) type).linkedTypeName());
if (!is_generalType(((TypeDefinitionLink) type).linkedTypeName())) {
insertType(types, types_vector, name, ((TypeDefinitionLink) type).linkedType());
}
} else {
response.getFirstChild("type_inline").deepCopy(addTypeInLine(types, types_vector, name, type));
}
return response;
}
private void insertType(ArrayList<TypeDefinition> types, ValueVector types_vector, Value name, TypeDefinition typedef) {
if (!types.contains(typedef)) {
types.add( typedef );
Value type = Value.create();
if (typedef instanceof TypeDefinitionLink) {
if (!is_generalType(typedef.id())) {
type.getFirstChild("name").deepCopy(setName(name));
type.getFirstChild("name").getFirstChild("name").setValue(typedef.id());
type.getFirstChild("root_type").getFirstChild("link").getFirstChild("name").setValue(((TypeDefinitionLink) typedef).linkedTypeName());
insertType(types, types_vector, name, ((TypeDefinitionLink) typedef).linkedType());
}
} else {
if (!is_generalType(typedef.id())) {
TypeInlineDefinition td = (TypeInlineDefinition) typedef;
type.getFirstChild("name").deepCopy(setName(name));
type.getFirstChild("name").getFirstChild("name").setValue(td.id());
type.getFirstChild("root_type").deepCopy(getNativeType(td.nativeType()));
if (td.hasSubTypes()) {
int subtype_counter = 0;
for (Entry<String, TypeDefinition> entry : td.subTypes()) {
type.getChildren("sub_type").get(subtype_counter).deepCopy(addSubType(types, types_vector, name, entry.getValue()));
subtype_counter++;
}
}
}
}
types_vector.add( type );
}
}
private Value getSubType(TypeDefinition type, Value name) {
Value response = Value.create();
response.getFirstChild("name").setValue(type.id());
response.getFirstChild("cardinality").deepCopy(addCardinality(type.cardinality()));
if (type instanceof TypeDefinitionLink) {
response.getFirstChild("type_link").deepCopy(setName(name));
response.getFirstChild("type_link").getFirstChild("name").setValue(((TypeDefinitionLink) type).linkedTypeName());
} else {
response.getFirstChild("type_inline").deepCopy(getType(type, name));
}
return response;
}
private Value getType(TypeDefinition typedef, Value name) {
Value type = Value.create();
type.getFirstChild("name").deepCopy(setName(name));
type.getFirstChild("name").getFirstChild("name").setValue(typedef.id());
if (typedef instanceof TypeDefinitionLink) {
type.getFirstChild("root_type").getFirstChild("link").getFirstChild("name").setValue(((TypeDefinitionLink) typedef).linkedTypeName());
if (name.getFirstChild("domain").isDefined()) {
type.getFirstChild("root_type").getFirstChild("link").getFirstChild("domain").setValue(name.getFirstChild("domain").strValue());
}
} else {
TypeInlineDefinition td = (TypeInlineDefinition) typedef;
type.getFirstChild("root_type").deepCopy(getNativeType(td.nativeType()));
if (td.hasSubTypes()) {
int subtype_counter = 0;
for (Entry<String, TypeDefinition> entry : td.subTypes()) {
type.getChildren("sub_type").get(subtype_counter).deepCopy(getSubType(entry.getValue(), name));
subtype_counter++;
}
}
}
return type;
}
private List<TypeDefinition> addType(List<TypeDefinition> types, TypeDefinition typedef) {
if (!types.contains(typedef)) {
types.add(typedef);
if (typedef instanceof TypeDefinitionLink) {
addType(types, ((TypeDefinitionLink) typedef).linkedType());
} else {
TypeInlineDefinition td = (TypeInlineDefinition) typedef;
if (td.hasSubTypes()) {
for (Entry<String, TypeDefinition> entry : td.subTypes()) {
addType(types, entry.getValue());
}
}
}
}
return types;
}
private Value getInterface(InterfaceDefinition intf, Value name, List<TypeDefinition> types) {
Value response = Value.create();
// setting the name
response.getFirstChild("name").deepCopy(setName(name));
response.getFirstChild("name").getFirstChild("name").setValue(intf.name());
ValueVector operations = response.getChildren("operations");
// scans operations and types
Map< String, OperationDeclaration> operationMap = intf.operationsMap();
for (Entry< String, OperationDeclaration> operationEntry : operationMap.entrySet()) {
Value current_operation = Value.create();
if (operationEntry.getValue() instanceof OneWayOperationDeclaration) {
OneWayOperationDeclaration oneWayOperation = (OneWayOperationDeclaration) operationEntry.getValue();
current_operation.getFirstChild("operation_name").setValue(oneWayOperation.id());
current_operation.getFirstChild("input").deepCopy(setName(name));
current_operation.getFirstChild("input").getFirstChild("name").setValue(oneWayOperation.requestType().id());
if (!isNativeType(oneWayOperation.requestType().id())) {
addType(types, oneWayOperation.requestType());
}
} else {
RequestResponseOperationDeclaration requestResponseOperation = (RequestResponseOperationDeclaration) operationEntry.getValue();
current_operation.getFirstChild("operation_name").setValue(requestResponseOperation.id());
current_operation.getFirstChild("input").deepCopy(setName(name));
current_operation.getFirstChild("input").getFirstChild("name").setValue(requestResponseOperation.requestType().id());
current_operation.getFirstChild("output").deepCopy(setName(name));
current_operation.getFirstChild("output").getFirstChild("name").setValue(requestResponseOperation.responseType().id());
if (!isNativeType(requestResponseOperation.requestType().id())) {
addType(types, requestResponseOperation.requestType());
}
if (!isNativeType(requestResponseOperation.responseType().id())) {
addType(types, requestResponseOperation.responseType());
}
}
operations.add(current_operation);
}
return response;
}
private List<InterfaceDefinition> addInterfaceToList(List<InterfaceDefinition> list, InterfaceDefinition intf) {
if (!list.contains(intf)) {
list.add(intf);
}
return list;
}
private Value setName(String name) {
Value v = Value.create();
v.getFirstChild("name").setValue(name);
return v;
}
private Value setName(String name, String domain) {
Value v = setName(name);
v.getFirstChild("domain").setValue(domain);
return v;
}
private Value setName(String name, String domain, String registry) {
Value v = setName(name, domain);
v.getFirstChild("registry").setValue(registry);
return v;
}
private Value setName(Value name) {
Value v;
if (name.getFirstChild("domain").isDefined() && name.getFirstChild("registry").isDefined()) {
v = setName(name.getFirstChild("name").strValue(), name.getFirstChild("domain").strValue(), name.getFirstChild("registry").strValue());
} else if (name.getFirstChild("domain").isDefined() && !name.getFirstChild("registry").isDefined()) {
v = setName(name.getFirstChild("name").strValue(), name.getFirstChild("domain").strValue());
} else {
v = setName(name.getFirstChild("name").strValue());
}
return v;
}
private Value getPort(PortInfo portInfo, Value name) {
Value response = Value.create();
response.getFirstChild("name").deepCopy(setName(name));
// setting the name of the port
response.getFirstChild("name").getFirstChild("name").setValue(portInfo.id());
if (portInfo instanceof InputPortInfo) {
InputPortInfo port = (InputPortInfo) portInfo;
response.getFirstChild("location").setValue(port.location().toString());
if (port.protocolId() != null) {
response.getFirstChild("protocol").setValue(port.protocolId());
} else {
response.getFirstChild("protocol").setValue("");
}
} else if (portInfo instanceof OutputPortInfo) {
OutputPortInfo port = (OutputPortInfo) portInfo;
response.getFirstChild("location").setValue(port.location().toString());
if (port.protocolId() != null) {
response.getFirstChild("protocol").setValue(port.protocolId());
} else {
response.getFirstChild("protocol").setValue("");
}
}
ArrayList<TypeDefinition> types = new ArrayList<TypeDefinition>();
// scan all the interfaces first interface
for (int intf_index = 0; intf_index < portInfo.getInterfaceList().size(); intf_index++) {
InterfaceDefinition interfaceDefinition = portInfo.getInterfaceList().get(intf_index);
Value input_interface = response.getFirstChild("interfaces");
input_interface.getFirstChild("name").deepCopy(setName(name));
input_interface.getFirstChild("name").getFirstChild("name").setValue(interfaceDefinition.name());
ValueVector operations = input_interface.getChildren("operations");
ValueVector interface_types = input_interface.getChildren("types");
// scans operations and types
Map< String, OperationDeclaration> operationMap = interfaceDefinition.operationsMap();
for (Entry< String, OperationDeclaration> operationEntry : operationMap.entrySet()) {
Value current_operation = Value.create();;
if (operationEntry.getValue() instanceof OneWayOperationDeclaration) {
OneWayOperationDeclaration oneWayOperation = (OneWayOperationDeclaration) operationEntry.getValue();
current_operation.getFirstChild("operation_name").setValue(oneWayOperation.id());
current_operation.getFirstChild("input").deepCopy(setName(name));
current_operation.getFirstChild("input").getFirstChild("name").setValue(oneWayOperation.requestType().id());
if (!isNativeType(oneWayOperation.requestType().id())) {
insertType(types, interface_types, name, oneWayOperation.requestType());
}
} else {
RequestResponseOperationDeclaration requestResponseOperation = (RequestResponseOperationDeclaration) operationEntry.getValue();
current_operation.getFirstChild("operation_name").setValue(requestResponseOperation.id());
current_operation.getFirstChild("input").deepCopy(setName(name));
current_operation.getFirstChild("input").getFirstChild("name").setValue(requestResponseOperation.requestType().id());
current_operation.getFirstChild("output").deepCopy(setName(name));
current_operation.getFirstChild("output").getFirstChild("name").setValue(requestResponseOperation.responseType().id());
if (!isNativeType(requestResponseOperation.requestType().id())) {
insertType(types, interface_types, name, requestResponseOperation.requestType());
}
if (!isNativeType(requestResponseOperation.responseType().id())) {
insertType(types, interface_types, name, requestResponseOperation.responseType());
}
}
operations.add(current_operation);
}
}
return response;
}
private Value getPort(PortInfo portInfo, Value name, List<InterfaceDefinition> interfaces) {
Value response = Value.create();
// setting domain and registry from request
response.getFirstChild("name").deepCopy(setName(name));
// setting the name of the port
response.getFirstChild("name").getFirstChild("name").setValue(portInfo.id());
if (portInfo instanceof InputPortInfo) {
InputPortInfo port = (InputPortInfo) portInfo;
if (port.location() != null) {
response.getFirstChild("location").setValue(port.location().toString());
} else {
response.getFirstChild("location").setValue("local");
}
if (port.protocolId() != null) {
response.getFirstChild("protocol").setValue(port.protocolId());
} else {
response.getFirstChild("protocol").setValue("");
}
} else if (portInfo instanceof OutputPortInfo) {
OutputPortInfo port = (OutputPortInfo) portInfo;
if (port.location() != null) {
response.getFirstChild("location").setValue(port.location().toString());
} else {
response.getFirstChild("location").setValue("local");
}
if (port.protocolId() != null) {
response.getFirstChild("protocol").setValue(port.protocolId());
} else {
response.getFirstChild("protocol").setValue("");
}
}
// scans interfaces
List<InterfaceDefinition> interfaceList = portInfo.getInterfaceList();
for (int intf = 0; intf < interfaceList.size(); intf++) {
InterfaceDefinition interfaceDefinition = portInfo.getInterfaceList().get(intf);
// setting the name of the interface within the port response
response.getChildren("interfaces").get(intf).getFirstChild("name").deepCopy(setName(name));
response.getChildren("interfaces").get(intf).getFirstChild("name").getFirstChild("name").setValue(interfaceDefinition.name());
interfaces = addInterfaceToList(interfaces, interfaceDefinition);
}
return response;
}
@RequestResponse
public Value parseRoles(Value request) {
Value response = Value.create();
try {
response.getFirstChild("name").deepCopy(setName(request.getFirstChild("rolename")));
String[] args = new String[]{request.getFirstChild("filename").strValue(), "-i", "/opt/jolie/include"};
CommandLineParser cmdParser = new CommandLineParser(args, MetaJolie.class.getClassLoader());
args = cmdParser.arguments();
Program program = ParsingUtils.parseProgram(
cmdParser.programStream(),
URI.create("file:" + cmdParser.programFilepath()),
cmdParser.includePaths(), MetaJolie.class.getClassLoader(), cmdParser.definedConstants());
ProgramInspector inspector = ParsingUtils.createInspector(program);
URI originalFile = program.context().source();
// scanning first inputport
InputPortInfo[] inputPortList = inspector.getInputPorts(originalFile);
Value input = response.getFirstChild("input");
if (inputPortList.length > 0) {
InputPortInfo inputPort = inputPortList[0];
input.deepCopy(getPort(inputPort, request.getFirstChild("name")));
}
// scanning first outputPort if it exists
OutputPortInfo[] outputPortList = inspector.getOutputPorts();
if (outputPortList.length > 0) {
Value output = response.getFirstChild("output");
output.deepCopy(getPort(outputPortList[0], request.getFirstChild("name")));
}
} catch (CommandLineException e) {
// TO DO
e.printStackTrace();
} catch (IOException e) {
// TO DO
e.printStackTrace();
} catch (ParserException e) {
// TO DO
e.printStackTrace();
}
return response;
}
@RequestResponse
public Value getMetaData(Value request) {
String domain = "";
List<TypeDefinition> types = new ArrayList<TypeDefinition>();
List<InterfaceDefinition> interfaces = new ArrayList<InterfaceDefinition>();
Value response = Value.create();
try {
String[] args = new String[]{request.getFirstChild("filename").strValue(), "-i", "/opt/jolie/include"};
if (request.getFirstChild("name").getFirstChild("domain").isDefined()) {
domain = request.getFirstChild("name").getFirstChild("domain").strValue();
}
CommandLineParser cmdParser = new CommandLineParser(args, MetaJolie.class.getClassLoader());
args = cmdParser.arguments();
Program program = ParsingUtils.parseProgram(
cmdParser.programStream(),
URI.create("file:" + cmdParser.programFilepath()),
cmdParser.includePaths(), MetaJolie.class.getClassLoader(), cmdParser.definedConstants());
ProgramInspector inspector = ParsingUtils.createInspector(program);
URI originalFile = program.context().source();
response.getFirstChild("service").getFirstChild("name").deepCopy(setName(request.getFirstChild("name")));
InputPortInfo[] inputPortList = inspector.getInputPorts(originalFile);
ValueVector input = response.getChildren("input");
if (inputPortList.length > 0) {
for (int ip = 0; ip < inputPortList.length; ip++) {
InputPortInfo inputPort = inputPortList[ ip];
input.get(ip).deepCopy(getPort(inputPort, request.getFirstChild("name"), interfaces));
response.getFirstChild("service").getChildren("input").get(ip).getFirstChild("name").setValue(inputPort.id());
response.getFirstChild("service").getChildren("input").get(ip).getFirstChild("domain").setValue(domain);
}
}
OutputPortInfo[] outputPortList = inspector.getOutputPorts();
if (outputPortList.length > 0) {
ValueVector output = response.getChildren("output");
for (int op = 0; op < outputPortList.length; op++) {
OutputPortInfo outputPort = outputPortList[ op];
output.get(op).deepCopy(getPort(outputPort, request.getFirstChild("name"), interfaces));
response.getFirstChild("service").getChildren("output").get(op).getFirstChild("name").setValue(outputPort.id());
response.getFirstChild("service").getChildren("output").get(op).getFirstChild("domain").setValue(domain);
}
}
// adding interfaces
for (int intf = 0; intf < interfaces.size(); intf++) {
InterfaceDefinition interfaceDefinition = interfaces.get(intf);
response.getChildren("interfaces").get(intf).deepCopy(getInterface(interfaceDefinition, request.getFirstChild("name"), types));
}
// adding types
for (int tp = 0; tp < types.size(); tp++) {
TypeDefinition typeDefinition = types.get(tp);
response.getChildren("types").get(tp).deepCopy(getType(typeDefinition, request.getFirstChild("name")));
}
} catch (CommandLineException e) {
// TO DO
e.printStackTrace();
} catch (IOException e) {
// TO DO
e.printStackTrace();
} catch (ParserException e) {
// TO DO
e.printStackTrace();
}
return response;
}
@RequestResponse
public Value getInputPortMetaData(Value request) {
String domain = "";
List<TypeDefinition> types = new ArrayList<TypeDefinition>();
List<InterfaceDefinition> interfaces = new ArrayList<InterfaceDefinition>();
Value response = Value.create();
try {
String[] args = new String[]{request.getFirstChild("filename").strValue(), "-i", "/opt/jolie/include"};
if (request.getFirstChild("domain").isDefined()) {
domain = request.getFirstChild("domain").strValue();
}
CommandLineParser cmdParser = new CommandLineParser(args, MetaJolie.class.getClassLoader());
args = cmdParser.arguments();
Program program = ParsingUtils.parseProgram(
cmdParser.programStream(),
URI.create("file:" + cmdParser.programFilepath()),
cmdParser.includePaths(), MetaJolie.class.getClassLoader(), cmdParser.definedConstants());
ProgramInspector inspector = ParsingUtils.createInspector(program);
URI originalFile = program.context().source();
InputPortInfo[] inputPortList = inspector.getInputPorts(originalFile);
ValueVector input = response.getChildren("input");
if (inputPortList.length > 0) {
for (int ip = 0; ip < inputPortList.length; ip++) {
InputPortInfo inputPort = inputPortList[ ip];
input.get(ip).deepCopy(getPort(inputPort, request.getFirstChild("name")));
}
}
} catch (CommandLineException e) {
// TO DO
e.printStackTrace();
} catch (IOException e) {
// TO DO
e.printStackTrace();
} catch (ParserException e) {
// TO DO
e.printStackTrace();
}
return response;
}
@RequestResponse
public Value checkNativeType( Value request ) {
Value response = Value.create();
response.getFirstChild("result").setValue( isNativeType( request.getFirstChild("type_name").strValue()));
return response;
}
}
|
package com.swara.music.data;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Preconditions;
import org.apache.commons.math3.fraction.Fraction;
/**
* A set of notes played simultaneously for a period of time. Chords are combined together to form a
* {@link Phrase}. Chords are built using a {@link Chord.Builder} and are immutable, and, therefore,
* thread-safe.
*/
@JsonDeserialize(builder = Chord.Builder.class)
public class Chord {
private final Set<Note> notes;
private final Fraction duration;
private final int volume;
private Chord(Builder builder) {
this.notes = builder.notes;
this.duration = builder.duration;
this.volume = builder.volume;
}
/**
* Returns the notes that comprise the chord. An empty set indicates a musical rest.
*/
@JsonGetter
public Set<Note> notes() {
return this.notes;
}
/**
* Returns the duration of the chord. Like a time signature, the duration is a fraction in which
* the denominator is a type of note and the numerator is the number of that type of note that
* the chord takes up. For example, a duration of 3/8 indicates that the chord takes up the time
* of 3 eighth-notes.
*/
@JsonGetter
public Fraction duration() {
return this.duration;
}
/**
* Returns the volume of the chord. Volume is synonymous with MIDI velocity. The volume is
* encoded as a number on the interval [0, 128), in which 0 represents silence.
*/
@JsonGetter
public int volume() {
return this.volume;
}
/**
* Constructs a {@link Chord} using a Fluent-style builder pattern. By default, the builder will
* construct a quarter-rest.
*/
public static final class Builder {
private Set<Note> notes;
private Fraction duration;
private int volume;
public Builder() {
this.notes = new HashSet<>();
this.duration = Fraction.ONE_QUARTER;
this.volume = 64;
}
public Builder withNote(Note note) {
// The note must not be null.
Preconditions.checkNotNull(note);
this.notes.add(note);
return this;
}
public Builder withNotes(Collection<? extends Note> notes) {
// The notes may not be null.
Preconditions.checkNotNull(notes);
this.notes.addAll(notes);
return this;
}
public Builder withDuration(Fraction duration) {
// The duration must be positive and non-null.
Preconditions.checkNotNull(duration);
Preconditions.checkArgument(duration.compareTo(Fraction.ZERO) > 0);
this.duration = duration;
return this;
}
public Builder withVolume(int volume) {
// The volume must be on the interval [0, 128).
Preconditions.checkArgument(volume >= 0 && volume < 128);
this.volume = volume;
return this;
}
public Chord build() {
return new Chord(this);
}
}
}
|
package org.akvo.flow.api.app;
import com.gallatinsystems.device.dao.DeviceDAO;
import com.gallatinsystems.device.domain.Device;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.surveyal.dao.SurveyedLocaleDao;
import com.gallatinsystems.surveyal.domain.SurveyedLocale;
import org.akvo.flow.dao.DataPointAssignmentDao;
import org.akvo.flow.domain.DataUtils;
import org.akvo.flow.domain.persistent.DataPointAssignment;
import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto;
import org.waterforpeople.mapping.app.web.dto.SurveyedLocaleDto;
import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyInstance;
import org.waterforpeople.mapping.serialization.response.MediaResponse;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.gallatinsystems.common.Constants.ALL_DATAPOINTS;
public class DataPointUtil {
private static final Logger log = Logger.getLogger(DataPointUtil.class.getName());
SurveyedLocaleDao surveyedLocaleDao = new SurveyedLocaleDao();
DataPointAssignmentDao dataPointAssignmentDao = new DataPointAssignmentDao();
public List<SurveyedLocaleDto> getSimpleSurveyedLocaleDtosList(List<SurveyedLocale> slList) {
List<SurveyedLocaleDto> dtoList = new ArrayList<>();
for (SurveyedLocale surveyedLocale : slList) {
SurveyedLocaleDto dto = createSimpleSurveyedLocaleDto(surveyedLocale);
dtoList.add(dto);
}
return dtoList;
}
public List<SurveyedLocaleDto> getSurveyedLocaleDtosList(List<SurveyedLocale> slList, Long surveyId) {
List<SurveyedLocaleDto> dtoList = new ArrayList<>();
HashMap<Long, String> questionTypeMap = new HashMap<>();
QuestionDao questionDao = new QuestionDao();
Map<Long, List<SurveyInstance>> surveyInstancesMap = getSurveyInstances(slList);
Map<Long, List<QuestionAnswerStore>> questionAnswerStore = getQuestionAnswerStoreMap(
surveyInstancesMap);
for (SurveyedLocale surveyedLocale : slList) {
long surveyedLocaleId = surveyedLocale.getKey().getId();
SurveyedLocaleDto dto = createSurveyedLocaleDto(surveyId, questionDao,
questionTypeMap, surveyedLocale, questionAnswerStore,
surveyInstancesMap.get(surveyedLocaleId));
dtoList.add(dto);
}
return dtoList;
}
public List<SurveyedLocale> getAssignedDataPoints(String androidId, Long surveyId, String cursor, int limit) throws Exception {
//Find the device (if any)
DeviceDAO deviceDao = new DeviceDAO();
Device device = deviceDao.getDevice(androidId, null, null);
if (device == null) {
throw new Exception("Device not found");
}
log.fine("Found device: " + device);
// verify assignments exist
long deviceId = device.getKey().getId();
List<DataPointAssignment> dataPointAssignments =
dataPointAssignmentDao.listByDeviceAndSurvey(deviceId, surveyId);
if (dataPointAssignments.isEmpty()) {
log.log(Level.WARNING, "No assignments found for surveyId: " + surveyId + " - deviceId: " + deviceId);
throw new NoDataPointsAssignedException("No datapoints assigned found");
}
return getDataPointList(dataPointAssignments.get(0), surveyId, cursor, limit);
}
private List<SurveyedLocale> getDataPointList(DataPointAssignment assignment, Long surveyId, String cursor, int limit) {
if (assignment == null || allDataPointsAreAssigned(assignment)) {
return getAllDataPoints(surveyId, cursor, limit);
} else {
return getAssignedDataPoints(assignment);
}
}
private boolean allDataPointsAreAssigned(DataPointAssignment assignment) {
if (assignment == null) {
return false;
}
Set<Long> assignedDataPoints = new HashSet<>(assignment.getDataPointIds());
return ALL_DATAPOINTS.equals(assignedDataPoints);
}
private List<SurveyedLocale> getAllDataPoints(Long surveyId, String cursor, int limit) {
return surveyedLocaleDao.listLocalesBySurveyGroupAndUpdateDate(surveyId, null, cursor, limit);
}
/*
* Return only datapoints that have been explicitly assigned to a device
*/
private List<SurveyedLocale> getAssignedDataPoints(DataPointAssignment assignment) {
Set<Long> assignedDataPointIds = new HashSet<>();
assignedDataPointIds.addAll(assignment.getDataPointIds());
return surveyedLocaleDao.listByKeys(new ArrayList<>(assignedDataPointIds));
}
private SurveyedLocaleDto createSimpleSurveyedLocaleDto(SurveyedLocale surveyedLocale) {
SurveyedLocaleDto dto = new SurveyedLocaleDto();
dto.setId(surveyedLocale.getIdentifier());
dto.setSurveyGroupId(surveyedLocale.getSurveyGroupId());
dto.setDisplayName(surveyedLocale.getDisplayName());
dto.setLat(surveyedLocale.getLatitude());
dto.setLon(surveyedLocale.getLongitude());
dto.setLastUpdateDateTime(surveyedLocale.getLastUpdateDateTime());
return dto;
}
private SurveyedLocaleDto createSurveyedLocaleDto(Long surveyGroupId, QuestionDao questionDao,
HashMap<Long, String> questionTypeMap, SurveyedLocale surveyedLocale,
Map<Long, List<QuestionAnswerStore>> questionAnswerStoreMap,
@Nullable List<SurveyInstance> surveyInstances) {
SurveyedLocaleDto dto = new SurveyedLocaleDto();
dto.setId(surveyedLocale.getIdentifier());
dto.setSurveyGroupId(surveyGroupId);
dto.setDisplayName(surveyedLocale.getDisplayName());
dto.setLat(surveyedLocale.getLatitude());
dto.setLon(surveyedLocale.getLongitude());
dto.setLastUpdateDateTime(surveyedLocale.getLastUpdateDateTime());
if (surveyInstances != null) {
for (SurveyInstance surveyInstance : surveyInstances) {
Long surveyInstanceId = surveyInstance.getObjectId();
List<QuestionAnswerStore> answerStores = questionAnswerStoreMap
.get(surveyInstanceId);
SurveyInstanceDto siDto = createSurveyInstanceDto(questionDao, questionTypeMap,
answerStores, surveyInstance);
dto.getSurveyInstances().add(siDto);
}
}
return dto;
}
/**
* Returns a map of QuestionAnswerStore lists,
* keys: surveyInstanceId, value: list of QuestionAnswerStore for that surveyInstance
*/
private Map<Long, List<QuestionAnswerStore>> getQuestionAnswerStoreMap(
Map<Long, List<SurveyInstance>> surveyInstanceMap) {
QuestionAnswerStoreDao questionAnswerStoreDao = new QuestionAnswerStoreDao();
List<Long> surveyInstancesIds = getSurveyInstancesIds(surveyInstanceMap);
List<QuestionAnswerStore> questionAnswerList = questionAnswerStoreDao
.fetchItemsByIdBatches(surveyInstancesIds, "surveyInstanceId");
Map<Long, List<QuestionAnswerStore>> questionAnswerStoreMap = new HashMap<>();
if (questionAnswerList != null && questionAnswerList.size() > 0) {
for (QuestionAnswerStore questionAnswerStore : questionAnswerList) {
// put them in a map with the surveyInstanceId as key
Long surveyInstanceId = questionAnswerStore.getSurveyInstanceId();
if (questionAnswerStoreMap.containsKey(surveyInstanceId)) {
questionAnswerStoreMap.get(surveyInstanceId).add(questionAnswerStore);
} else {
ArrayList<QuestionAnswerStore> questionAnswerStores = new ArrayList<>();
questionAnswerStores.add(questionAnswerStore);
questionAnswerStoreMap.put(surveyInstanceId, questionAnswerStores);
}
}
}
return questionAnswerStoreMap;
}
private List<Long> getSurveyInstancesIds(Map<Long, List<SurveyInstance>> surveyInstanceMap) {
List<Long> surveyInstancesIds = new ArrayList<>();
Collection<List<SurveyInstance>> values = surveyInstanceMap.values();
for (List<SurveyInstance> surveyInstances : values) {
for (SurveyInstance surveyInstance: surveyInstances) {
surveyInstancesIds.add(surveyInstance.getObjectId());
}
}
return surveyInstancesIds;
}
/**
* Fetches SurveyInstances using the surveyedLocalesIds and puts them in a map:
* key: SurveyedLocalesId, value: list of SurveyInstances
* @param dataPointList
*/
private Map<Long, List<SurveyInstance>> getSurveyInstances(List<SurveyedLocale> dataPointList) {
SurveyInstanceDAO surveyInstanceDAO = new SurveyInstanceDAO();
SurveyedLocaleDao surveyedLocaleDao = new SurveyedLocaleDao();
List<SurveyInstance> values = surveyInstanceDAO.getMonitoringData(dataPointList);
return values.stream().collect(Collectors.groupingBy(SurveyInstance::getSurveyedLocaleId));
}
private SurveyInstanceDto createSurveyInstanceDto(QuestionDao qDao,
HashMap<Long, String> questionTypeMap,
@Nullable List<QuestionAnswerStore> questionAnswerStores,
@Nullable SurveyInstance surveyInstance) {
SurveyInstanceDto surveyInstanceDto = new SurveyInstanceDto();
if (surveyInstance != null) {
surveyInstanceDto.setUuid(surveyInstance.getUuid());
surveyInstanceDto.setSubmitter(surveyInstance.getSubmitterName());
surveyInstanceDto.setSurveyId(surveyInstance.getSurveyId());
surveyInstanceDto.setCollectionDate(surveyInstance.getCollectionDate());
}
if (questionAnswerStores != null) {
for (QuestionAnswerStore questionAnswerStore : questionAnswerStores) {
Long questionId = questionAnswerStore.getQuestionIDLong();
if (questionId == null) {
continue;// The question was deleted before storing the response.
}
String type = getQuestionType(qDao, questionTypeMap, questionAnswerStore);
String value = getAnswerValue(questionAnswerStore, type);
surveyInstanceDto.addProperty(questionId, value, type);
}
}
return surveyInstanceDto;
}
private String getAnswerValue(QuestionAnswerStore questionAnswerStore, String type) {
// Make all responses backwards compatible
String answerValue = questionAnswerStore.getValue();
String value = answerValue != null ? answerValue : "";
switch (type) {
case "OPTION":
case "OTHER":
if (value.startsWith("[")) {
value = DataUtils.jsonResponsesToPipeSeparated(value);
}
break;
case "IMAGE":
case "VIDEO":
value = MediaResponse.format(value, MediaResponse.VERSION_STRING);
break;
default:
break;
}
return value;
}
private String getQuestionType(QuestionDao questionDao, HashMap<Long, String> questionTypeMap,
QuestionAnswerStore questionAnswerStore) {
String type = questionAnswerStore.getType();
if (type == null || "".equals(type)) {
type = "VALUE";
} else if ("PHOTO".equals(type)) {
type = "IMAGE";
} else if ("OPTION".equals(type)) {
// first see if we have the question in the map already
Long questionId = questionAnswerStore.getQuestionIDLong();
if (questionTypeMap.containsKey(questionId)) {
type = questionTypeMap.get(questionId);
} else {
// find question by id
Question question = questionDao.getByKey(questionId);
if (question != null) {
// if the question has the allowOtherFlag set,
// use OTHER as the device question type
if (question.getAllowOtherFlag()) {
type = "OTHER";
}
questionTypeMap.put(questionId, type);
}
}
}
return type;
}
}
|
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.netmgt.capsd;
import java.lang.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import java.util.Iterator;
import java.util.Date;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.eventd.EventIpcManagerFactory;
import org.opennms.netmgt.capsd.snmp.*;
import org.opennms.protocols.snmp.*;
import org.opennms.netmgt.config.DatabaseConnectionFactory;
import org.opennms.netmgt.config.CapsdConfigFactory;
import org.opennms.netmgt.config.PollerConfigFactory;
import org.opennms.netmgt.config.CollectdConfigFactory;
// These generated by castor
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Parm;
import org.opennms.netmgt.xml.event.Value;
import org.opennms.netmgt.xml.event.Parms;
// castor classes generated from the discovery-configuration.xsd
import org.opennms.netmgt.config.capsd.*;
final class RescanProcessor
implements Runnable
{
/**
* SQL statement for retrieving the 'nodetype' field of the node table
* for the specified nodeid. Used to determine if the node is active ('A')
* or been marked as deleted ('D')..
*/
final static String SQL_DB_RETRIEVE_NODE_TYPE = "SELECT nodetype FROM node WHERE nodeID=?";
/**
* SQL statement used to retrieve other nodeIds that have the same ipinterface
* as the updating node.
*/
final static String SQL_DB_RETRIEVE_OTHER_NODES = "SELECT nodeid FROM ipinterface"
+ "WHERE ipaddr = ? AND ifindex = ? AND nodeid !=? ";
/**
* SQL statement for retrieving the nodeids that have the same ipaddr as the updating node
* no matter what ifindex they have.
*/
final static String SQL_DB_RETRIEVE_DUPLICATE_NODEIDS = "SELECT nodeid FROM ipinterface WHERE ipaddr = ? AND nodeid !=? ";
/**
* SQL statements used to reparent an interface and its associated
* services under a new parent nodeid
*/
final static String SQL_DB_REPARENT_IP_INTERFACE = "UPDATE ipinterface SET nodeID=? WHERE nodeID=? AND ipaddr=? AND isManaged!='D'";
final static String SQL_DB_REPARENT_SNMP_IF_LOOKUP = "SELECT ipaddr FROM snmpinterface WHERE nodeID=? AND snmpifindex=?";
final static String SQL_DB_REPARENT_SNMP_IF_DELETE = "DELETE FROM snmpinterface WHERE nodeID=? AND snmpifindex=?";
final static String SQL_DB_REPARENT_SNMP_INTERFACE = "UPDATE snmpinterface SET nodeID=? WHERE nodeID=? AND snmpifindex=?";
final static String SQL_DB_REPARENT_IF_SERVICES = "UPDATE ifservices SET nodeID=? WHERE nodeID=? AND ipaddr=? AND status!='D'";
/**
* SQL statements used to clear up ipinterface table, ifservices table and snmpinterface
* table when delete a duplicate node.
*/
final static String SQL_DB_DELETE_DUP_INTERFACE = "DELETE FROM ipinterface WHERE nodeID=?";
final static String SQL_DB_DELETE_DUP_SERVICES = "DELETE FROM ifservices WHERE nodeid=?";
final static String SQL_DB_DELETE_DUP_SNMPINTERFACE = "DELETE FROM snmpinterface WHERE nodeid =?";
private final static String SELECT_METHOD_MIN = "min";
private final static String SELECT_METHOD_MAX = "max";
/**
* Information necessary to schedule the node.
*/
private Scheduler.NodeInfo m_scheduledNode;
/**
* Indicates if the rescan is in response to a forceRescan event.
*/
private boolean m_forceRescan;
/**
* Event list...during the rescan significant database changes
* cause events (interfaceReparented, nodeGainedService, etc...)
* to be created and added to the event list. The last thing
* the rescan process does is send the events out.
*/
private List m_eventList;
/**
* Capsd configuration factory
*/
private CapsdConfigFactory m_cFactory;
/**
* Set during the rescan to true if any of the ifIndex values
* associated with a node's interface's were modified as a
* result of the scan.
*/
private boolean m_ifIndexOnNodeChangedFlag;
/**
* Set during the rescan to true if a new interface is added
* to the snmpInterfaces table or if any key fields of the node's
* snmpIntefaces table were modified (such as ifIndex or ifType)
*/
private boolean m_snmpIfTableChangedFlag;
/**
* Constructor.
*
* @param nodeInfo Scheduler.NodeInfo object containing the nodeid of
* the node to be rescanned.
* @param forceRescan True if a forced rescan is to be performed (all interfaces
* not just managed interfaces scanned), false otherwise.
*/
RescanProcessor(Scheduler.NodeInfo nodeInfo, boolean forceRescan)
{
// Check the arguments
if(nodeInfo == null)
throw new IllegalArgumentException("The nodeInfo parm cannot be null!");
m_scheduledNode = nodeInfo;
m_forceRescan = forceRescan;
m_eventList = new ArrayList();
}
/**
* This method is responsible for updating the node table using the most
* recent data collected from the node's managed interfaces.
*
* @param dbc Database connection
* @param now Date object representing the time of the rescan.
* @param dbNodeEntry DbNodeEntry object representing existing values in the database
* @param currPrimarySnmpIf Primary SNMP interface address based on latest collection
* @param dbIpInterfaces Array of DbIpInterfaceEntry objects representing all the
* interfaces retrieved from the database for this node.
* @param collectorMap Map of IfCollector objects...one per managed interface.
*
* @return DbNodeEntry object representing the updated values from the node table in the
* database.
*
* @throws SQLException if there is a problem updating the node table.
*/
private DbNodeEntry updateNode(Connection dbc,
Date now,
DbNodeEntry dbNodeEntry,
InetAddress currPrimarySnmpIf,
DbIpInterfaceEntry[] dbIpInterfaces,
Map collectorMap)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("updateNode: updating node id " + dbNodeEntry.getNodeId());
// Clone the existing dbNodeEntry so we have all the original
// values of the 'node' table fields in case we need to generate
DbNodeEntry originalDbNodeEntry = DbNodeEntry.clone(dbNodeEntry);
// Create node which represents the most recently retrieved
// information in the collector for this node
DbNodeEntry currNodeEntry = DbNodeEntry.create();
currNodeEntry.setNodeType(DbNodeEntry.NODE_TYPE_ACTIVE);
// Set node label and SMB info based on latest collection
setNodeLabelAndSmbInfo(collectorMap, dbNodeEntry, currNodeEntry, currPrimarySnmpIf);
// Set SNMP info
if (currPrimarySnmpIf != null)
{
// We prefer to use the collector for the primary SNMP interface
// to update SNMP data in the node table. However a collector
// for the primary SNMP interface may not exist in the map if
// a node has only recently had SNMP support enabled or if the
// new primary SNMP interface was only recently added to the
// node. At any rate if it exists use it, if not use the
// first collector which supports SNMP.
IfCollector primaryIfc = (IfCollector)collectorMap.get(currPrimarySnmpIf.getHostAddress());
if (primaryIfc == null)
{
Collection collectors = collectorMap.values();
Iterator iter = collectors.iterator();
while (iter.hasNext())
{
primaryIfc = (IfCollector)iter.next();
if (primaryIfc.getSnmpCollector() != null)
break;
}
}
// Sanity check...should always have a primary interface
// collector at this point
if (primaryIfc == null)
{
log.error("updateNode: failed to determine primary interface collector for node " + dbNodeEntry.getNodeId());
throw new RuntimeException("Update node failed for node " + dbNodeEntry.getNodeId() + ", unable to determine primary interface collector.");
}
IfSnmpCollector snmpc = primaryIfc.getSnmpCollector();
if (snmpc != null && snmpc.hasSystemGroup())
{
SystemGroup sysgrp = snmpc.getSystemGroup();
// sysObjectId
currNodeEntry.setSystemOID(sysgrp.get(SystemGroup.SYS_OBJECTID).toString());
// sysName
String str = SystemGroup.getPrintableString((SnmpOctetString)sysgrp.get(SystemGroup.SYS_NAME));
if(str != null && str.length() > 0)
currNodeEntry.setSystemName(str);
// sysDescription
str = SystemGroup.getPrintableString((SnmpOctetString) sysgrp.get(SystemGroup.SYS_DESCR));
if (str!= null && str.length() > 0)
currNodeEntry.setSystemDescription(str);
// sysLocation
str = SystemGroup.getPrintableString((SnmpOctetString) sysgrp.get(SystemGroup.SYS_LOCATION));
if(str != null && str.length() > 0)
currNodeEntry.setSystemLocation(str);
// sysContact
str = SystemGroup.getPrintableString((SnmpOctetString) sysgrp.get(SystemGroup.SYS_CONTACT));
if(str != null && str.length() > 0)
currNodeEntry.setSystemContact(str);
}
}
// Currently, we do not use the ParentId except in mapping. Unforunately, this is never
// set in the currNodeEntry so it gets reset here. As a workaround, setting it to the old value.
currNodeEntry.updateParentId(dbNodeEntry.getParentId());
// Update any fields which have changed
if (log.isDebugEnabled())
{
log.debug("updateNode:
log.debug("updateNode:
}
dbNodeEntry.updateParentId(currNodeEntry.getParentId());
dbNodeEntry.updateNodeType(currNodeEntry.getNodeType());
dbNodeEntry.updateSystemOID(currNodeEntry.getSystemOID());
dbNodeEntry.updateSystemName(currNodeEntry.getSystemName());
dbNodeEntry.updateSystemDescription(currNodeEntry.getSystemDescription());
dbNodeEntry.updateSystemLocation(currNodeEntry.getSystemLocation());
dbNodeEntry.updateSystemContact(currNodeEntry.getSystemContact());
dbNodeEntry.updateNetBIOSName(currNodeEntry.getNetBIOSName());
dbNodeEntry.updateDomainName(currNodeEntry.getDomainName());
dbNodeEntry.updateOS(currNodeEntry.getOS());
dbNodeEntry.setLastPoll(now);
// Only update node label/source if original node entry is
// not set to user-defined.
if (dbNodeEntry.getLabelSource() != dbNodeEntry.LABEL_SOURCE_USER)
{
dbNodeEntry.updateLabel(currNodeEntry.getLabel());
dbNodeEntry.updateLabelSource(currNodeEntry.getLabelSource());
}
// Set event flags
boolean nodeLabelChangedFlag = false;
boolean nodeInfoChangedFlag = false;
if (dbNodeEntry.hasLabelChanged() ||
dbNodeEntry.hasLabelSourceChanged())
{
nodeLabelChangedFlag = true;
}
if (dbNodeEntry.hasSystemOIDChanged() ||
dbNodeEntry.hasSystemNameChanged() ||
dbNodeEntry.hasSystemDescriptionChanged() ||
dbNodeEntry.hasSystemLocationChanged() ||
dbNodeEntry.hasSystemContactChanged() ||
dbNodeEntry.hasNetBIOSNameChanged() ||
dbNodeEntry.hasDomainNameChanged() ||
dbNodeEntry.hasOSChanged())
{
nodeInfoChangedFlag = true;
}
// Call store to update the database
dbNodeEntry.store(dbc);
// Create nodeLabelChanged event if necessary
if (nodeLabelChangedFlag)
{
createNodeLabelChangedEvent(dbNodeEntry, originalDbNodeEntry);
}
// Create nodeInfoChangedEvent if necessary
if (nodeInfoChangedFlag)
{
createNodeInfoChangedEvent(dbNodeEntry, originalDbNodeEntry);
}
return dbNodeEntry;
}
/**
* This method is responsible for updating all of the interface's associated
* with a node.
*
* @param dbc Database connection.
* @param now Date/time to be associated with the update.
* @param node Node entry for the node being rescanned
* @param collectorMap Map of IfCollector objects associated with the node.
*
* @throws SQLException if there is a problem updating the ipInterface table.
*/
private void updateInterfaces(Connection dbc,
Date now,
DbNodeEntry node,
Map collectorMap)
throws SQLException
{
// Reset modification flags. These flags are set by
// the updateInterface() method when changes have been
// detected which warrant further action (such as
// generating an event).
m_ifIndexOnNodeChangedFlag = false;
m_snmpIfTableChangedFlag = false;
// List of update interfaces
// This list is maintained so that for nodes with multiple
// interfaces which support SNMP, interfaces are not updated
// more than once.
List updatedIfList = new ArrayList();
// Determine if any of the interface collector objects have
// an SNMP collector associated with them. If so, use the first
// interface with SNMP data collected to update all SNMP-found
// interfaces.
Iterator iter = collectorMap.values().iterator();
IfCollector collectorWithSnmp = null;
while (iter.hasNext())
{
IfCollector tmp = (IfCollector)iter.next();
if (tmp.getSnmpCollector() != null)
{
collectorWithSnmp = tmp;
break;
}
}
IfSnmpCollector snmpCollector = null;
if (collectorWithSnmp != null)
{
snmpCollector = collectorWithSnmp.getSnmpCollector();
updateInterface(dbc,
now,
node,
collectorWithSnmp.getTarget(),
collectorWithSnmp.getTarget(),
collectorWithSnmp.getSupportedProtocols(),
snmpCollector);
updatedIfList.add(collectorWithSnmp.getTarget());
// Update subtargets
if (collectorWithSnmp.hasAdditionalTargets())
{
Map subTargets = collectorWithSnmp.getAdditionalTargets();
Iterator xiter = subTargets.keySet().iterator();
while (xiter.hasNext())
{
InetAddress subIf = (InetAddress)xiter.next();
updateInterface(dbc,
now,
node,
collectorWithSnmp.getTarget(),
subIf,
(List)subTargets.get(subIf),
snmpCollector);
updatedIfList.add(subIf);
}
}
// Add any new non-IP interfaces
if (collectorWithSnmp.hasNonIpInterfaces())
{
iter = ((List)collectorWithSnmp.getNonIpInterfaces()).iterator();
while(iter.hasNext())
{
SnmpInt32 ifIndex = (SnmpInt32)iter.next();
updateNonIpInterface(dbc, now, node, ifIndex.getValue(), snmpCollector);
}
}
}
// Majority of interfaces should have been updated by this
// point (provided the node supports SNMP). Only non-SNMP
// interfaces and those associated with the node via
// SMB (NetBIOS name) should remain. Loop through collector
// map and update any remaining interfaces. Use the
// updatedIfList object to filter out any interfaces which
// have already been updated
// Iterate over interfaces from collection map
iter = collectorMap.values().iterator();
while (iter.hasNext())
{
IfCollector ifc = (IfCollector)iter.next();
// Update target
InetAddress ifaddr = ifc.getTarget();
if (!updatedIfList.contains(ifaddr))
{
updateInterface(dbc,
now,
node,
ifc.getTarget(),
ifaddr,
ifc.getSupportedProtocols(),
snmpCollector);
updatedIfList.add(ifaddr);
}
// Update subtargets
if (ifc.hasAdditionalTargets())
{
Map subTargets = ifc.getAdditionalTargets();
Set keys = subTargets.keySet();
Iterator xiter = keys.iterator();
while (xiter.hasNext())
{
InetAddress subIf = (InetAddress)xiter.next();
if (!updatedIfList.contains(subIf))
{
updateInterface(dbc,
now,
node,
ifc.getTarget(),
subIf,
(List)subTargets.get(subIf),
snmpCollector);
updatedIfList.add(subIf);
}
}
}
} // end while(more interfaces)
}
/**
* This method is responsible for updating the ipInterface table entry
* for a specific interface.
*
* @param dbc Database Connection
* @param now Date/time to be associated with the update.
* @param node Node entry for the node being rescanned
* @param ifIndex Interface index of non-IP interface to update
* @param snmpc SNMP collector or null if SNMP not supported.
*
* @throws SQLException if there is a problem updating the ipInterface table.
*/
private void updateNonIpInterface(Connection dbc,
Date now,
DbNodeEntry node,
int ifIndex,
IfSnmpCollector snmpc)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("updateNonIpInterface: node= " + node.getNodeId() + " ifIndex= " + ifIndex);
// Sanity Check
if (snmpc == null || snmpc.failed())
return;
// Construct InetAddress object for "0.0.0.0" address
InetAddress ifAddr = null;
try
{
ifAddr = InetAddress.getByName("0.0.0.0");
}
catch (UnknownHostException uhE)
{
log.error("Failed to update non-IP interfaces, unable to construct '0.0.0.0' InetAddress", uhE);
return;
}
// IpInterface table updates
// Attempt to load IP Interface entry from the database
DbIpInterfaceEntry dbIpIfEntry = DbIpInterfaceEntry.get(dbc, node.getNodeId(), ifAddr, ifIndex);
if (dbIpIfEntry == null)
{
// Create a new entry
if (log.isDebugEnabled())
log.debug("updateNonIpInterface: non-IP interface with ifIndex " + ifIndex + " not in database, creating new interface object.");
dbIpIfEntry = DbIpInterfaceEntry.create(node.getNodeId(), ifAddr);
}
// Update any IpInterface table fields which have changed
dbIpIfEntry.setLastPoll(now);
dbIpIfEntry.setIfIndex(ifIndex);
dbIpIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED);
int status = snmpc.getAdminStatus(ifIndex);
if(status != -1)
dbIpIfEntry.setStatus(status);
// Removed the following update to insure that the issnmpprimary field was not
// over-written during a rescan. Since it should already be set, there is no
// need to re-set it.
// dbIpIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
// Update the database
dbIpIfEntry.store(dbc);
// SnmpInterface table updates
if (log.isDebugEnabled())
log.debug("updateNonIpInterface: updating non-IP snmp interface with nodeId=" + node.getNodeId() + " and ifIndex=" + ifIndex);
// Create and load SNMP Interface entry from the database
boolean newSnmpIfTableEntry = false;
DbSnmpInterfaceEntry dbSnmpIfEntry = DbSnmpInterfaceEntry.get(dbc, node.getNodeId(), ifIndex);
if (dbSnmpIfEntry == null)
{
// SNMP Interface not found with this nodeId & ifIndex, create new interface
if (log.isDebugEnabled())
log.debug("updateNonIpInterface: non-IP SNMP interface with ifIndex " + ifIndex + " not in database, creating new snmpInterface object.");
dbSnmpIfEntry = DbSnmpInterfaceEntry.create(node.getNodeId(), ifIndex);
newSnmpIfTableEntry = true;
}
// Find the ifTable entry for this interface
IfTable ift = snmpc.getIfTable();
Iterator ifiter = ift.getEntries().iterator();
IfTableEntry ifte = null;
boolean match = false;
while(ifiter.hasNext())
{
ifte = (IfTableEntry)ifiter.next();
// index
SnmpInt32 sint = (SnmpInt32)ifte.get(IfTableEntry.IF_INDEX);
if(sint != null)
{
if (ifIndex == sint.getValue())
{
if (log.isDebugEnabled())
log.debug("updateNonIpInterface: found match for ifIndex: " + ifIndex);
match = true;
break;
}
}
}
// Make sure we have a valid IfTableEntry object and update
// any values which have changed
if (match && ifte != null)
{
// index
//dbSnmpIfEntry.updateIfIndex(ifIndex);
// ipAddress
dbSnmpIfEntry.updateIfAddress(ifAddr);
// netmask
// NOTE: non-IP interfaces don't have netmasks so skip
// type
SnmpInt32 sint = (SnmpInt32)ifte.get(IfTableEntry.IF_TYPE);
dbSnmpIfEntry.updateType(sint.getValue());
// description
String str = SystemGroup.getPrintableString((SnmpOctetString)ifte.get(IfTableEntry.IF_DESCR));
if (log.isDebugEnabled())
log.debug("updateNonIpInterface: ifIndex: " + ifIndex + " has ifDescription: " + str);
if(str != null && str.length() > 0)
dbSnmpIfEntry.updateDescription(str);
// physical address
StringBuffer sbuf = new StringBuffer();
SnmpOctetString ostr = (SnmpOctetString)ifte.get(IfTableEntry.IF_PHYS_ADDR);
if ( ostr != null && ostr.getLength() > 0)
{
byte[] bytes = ostr.getString();
for(int i = 0; i < bytes.length; i++)
{
sbuf.append(Integer.toHexString(((int)bytes[i] >> 4) & 0xf));
sbuf.append(Integer.toHexString((int)bytes[i] & 0xf));
}
}
String physAddr = sbuf.toString().trim();
if (log.isDebugEnabled())
log.debug("updateNonIpInterface: ifIndex: " + ifIndex + " has physical address: -" + physAddr + "-");
if (physAddr.length() == 12)
{
dbSnmpIfEntry.updatePhysicalAddress(physAddr);
}
// speed
SnmpUInt32 uint = (SnmpUInt32)ifte.get(IfTableEntry.IF_SPEED);
if (uint == null)
{
dbSnmpIfEntry.updateSpeed(0);
}
else
{
dbSnmpIfEntry.updateSpeed((int)uint.getValue());
}
// admin status
sint = (SnmpInt32)ifte.get(IfTableEntry.IF_ADMIN_STATUS);
if (sint == null)
{
dbSnmpIfEntry.updateAdminStatus(0);
}
else
{
dbSnmpIfEntry.updateAdminStatus(sint.getValue());
}
// oper status
sint = (SnmpInt32)ifte.get(IfTableEntry.IF_OPER_STATUS);
if (sint == null)
{
dbSnmpIfEntry.updateOperationalStatus(0);
}
else
{
dbSnmpIfEntry.updateOperationalStatus(sint.getValue());
}
// name (from interface extensions table)
SnmpOctetString snmpIfName = snmpc.getIfName(ifIndex);
if (snmpIfName != null)
{
String ifName = SystemGroup.getPrintableString(snmpIfName);
if (ifName!= null && ifName.length() > 0)
dbSnmpIfEntry.updateName(ifName);
}
} // end if valid ifTable entry
// If this is a new interface or if any of the following
// key fields have changed set the m_snmpIfTableChangedFlag
// variable to TRUE. This will potentially trigger an event
// which will cause the poller to reinitialize the primary
// SNMP interface for the node.
if (!m_snmpIfTableChangedFlag &&
newSnmpIfTableEntry ||
//dbSnmpIfEntry.hasIfIndexChanged() ||
dbSnmpIfEntry.hasIfAddressChanged() ||
dbSnmpIfEntry.hasTypeChanged() ||
dbSnmpIfEntry.hasNameChanged() ||
dbSnmpIfEntry.hasDescriptionChanged() ||
dbSnmpIfEntry.hasPhysicalAddressChanged())
{
m_snmpIfTableChangedFlag = true;
}
// Update the database
dbSnmpIfEntry.store(dbc);
}
/**
* This method is responsible for updating the ipInterface table entry
* for a specific interface.
*
* @param dbc Database Connection
* @param now Date/time to be associated with the update.
* @param node Node entry for the node being rescanned
* @param target Target interface (from IfCollector.getTarget())
* @param ifaddr Interface being updated.
* @param protocols Protocols supported by the interface.
* @param snmpc SNMP collector or null if SNMP not supported.
*
* @throws SQLException if there is a problem updating the ipInterface table.
*/
private void updateInterface(Connection dbc,
Date now,
DbNodeEntry node,
InetAddress target,
InetAddress ifaddr,
List protocols,
IfSnmpCollector snmpc)
throws SQLException
{
// Reparenting
// This sub-interface was not previously associated with this node. If
// the sub-interface is already associated with another node we must do
// one of the following:
// 1. If the target interface (the one being rescanned) appears to be an
// interface alias all of the interfaces under the sub-interface's node
// will be reparented under the nodeid of the target interface.
// 2. If however the interface is not an alias, only the sub-interface will
// be reparented under the nodeid of the interface being rescanned.
// In the reparenting p/ocess, the database ipinterface, snmpinterface
// and ifservices table entries associated with the reparented interface
// will be "updated" to reflect the new nodeid. If the old node has
// no remaining interfaces following the reparenting it will be marked
// as deleted.
// Special case: Need to skip interface reparenting for '0.0.0.0'
// interfaces as well as loopback interfaces ('127.*.*.*').
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
{
log.debug("updateInterface: updating interface " + ifaddr.getHostAddress() + "(targetIf="
+ target.getHostAddress() + ")");
log.debug("updateInterface: the snmp collection passed in is collected via"
+ snmpc.getTarget().getHostAddress());
}
boolean reparentFlag = false;
boolean newIpIfEntry = false;
// Attempt to load IP Interface entry from the database
int ifIndex = snmpc.getIfIndex(ifaddr);
if (log.isDebugEnabled())
log.debug("updateInterface: interface =" + ifaddr.getHostAddress() + " ifIndex = " + ifIndex);
DbIpInterfaceEntry dbIpIfEntry = DbIpInterfaceEntry.get(dbc, node.getNodeId(), ifaddr);
// the updating interface may have already existed in the ipinterface table with different
// nodeIds. If it exist in a different node, verify if all the interfaces on that node
// are contained in the snmpc of the updating interface. If they are, reparent all
// the interfaces on that node to the node of the updating interface, otherwise, just add
// the interface to the updating node.
PreparedStatement stmt = null;
try
{
stmt = dbc.prepareStatement(SQL_DB_RETRIEVE_OTHER_NODES);
stmt.setString(1, ifaddr.getHostAddress());
stmt.setInt(2, ifIndex);
stmt.setInt(3, node.getNodeId());
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
int existingNodeId = rs.getInt(1);
DbNodeEntry suspectNodeEntry = DbNodeEntry.get(dbc, existingNodeId);
// Verify if the suspectNodeEntry is a duplicate node
if (isDuplicateNode(dbc, suspectNodeEntry, snmpc))
{
// Retrieve list of interfaces associated with the old node
DbIpInterfaceEntry[] tmpIfArray = suspectNodeEntry.getInterfaces(dbc);
// Reparent each interface under the targets' nodeid
for (int i=0; i<tmpIfArray.length; i++)
{
InetAddress addr = tmpIfArray[i].getIfAddress();
int index = tmpIfArray[i].getIfIndex();
// Skip non-IP or loopback interfaces
if (addr.getHostAddress().equals("0.0.0.0") &&
addr.getHostAddress().startsWith("127."))
{
continue;
}
if (log.isDebugEnabled())
log.debug("updateInterface: reparenting interface "
+ addr.getHostAddress()
+ " under node: " + node.getNodeId()
+ " from existing node: " + existingNodeId);
reparentInterface(dbc, addr, index, node.getNodeId(), existingNodeId);
if (ifaddr.getHostAddress().equals(addr.getHostAddress()))
{
if (log.isDebugEnabled())
log.debug("updateInterface: interface "
+ ifaddr.getHostAddress()
+ " is added to node: " + node.getNodeId()
+ " by reparenting from existing node: " + existingNodeId);
dbIpIfEntry = DbIpInterfaceEntry.get(dbc, node.getNodeId(), ifaddr);
reparentFlag = true;
}
// Create interfaceReparented event
createInterfaceReparentedEvent(node, existingNodeId, addr);
}
// delete duplicate node after reparenting.
deleteDuplicateNode(dbc, suspectNodeEntry);
createDuplicateNodeDeletedEvent(suspectNodeEntry);
}
}
}
catch(SQLException sqlE)
{
log.error("SQLException while updating interface: " + ifaddr.getHostAddress()
+ " on nodeid: " + node.getNodeId());
throw sqlE;
}
finally
{
try
{
stmt.close();
}
catch (SQLException e) {}
}
// if no reparenting occured on the updating interface, add it to the
// updating node.
if (dbIpIfEntry == null)
{
// Interface not found with this nodeId so create new interface entry
if (log.isDebugEnabled())
log.debug("updateInterface: interface " + ifaddr
+ " not in database under nodeid " + node.getNodeId()
+ ", creating new interface object.");
dbIpIfEntry = DbIpInterfaceEntry.create(node.getNodeId(), ifaddr, ifIndex);
if ( isDuplicateInterface(dbc, ifaddr, node.getNodeId()))
{
createDuplicateIpAddressEvent(dbIpIfEntry);
}
newIpIfEntry = true;
}
// update ipinterface for the updating interface
updateInterfaceInfo(dbc, now, node, dbIpIfEntry, snmpc, newIpIfEntry, reparentFlag);
// update IfServices for the updating interface
updateServiceInfo(dbc, node, dbIpIfEntry, newIpIfEntry, protocols);
// update SNMP info if available
updateSnmpInfo(dbc, node, dbIpIfEntry, snmpc);
}
/**
* This method is responsible to delete any interface associated with the duplicate node,
* delete any entry left in ifservices table and snmpinterface table for the duplicate node,
* and make the node as 'deleted'.
*
* @param dbc Database Connection
* @param duplicateNode Duplicate node to delete.
*
*/
private void deleteDuplicateNode( Connection dbc,
DbNodeEntry duplicateNode)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
boolean duplicate = false;
PreparedStatement ifStmt = dbc.prepareStatement(SQL_DB_DELETE_DUP_INTERFACE);
PreparedStatement svcStmt = dbc.prepareStatement(SQL_DB_DELETE_DUP_SERVICES);
PreparedStatement snmpStmt = dbc.prepareStatement(SQL_DB_DELETE_DUP_SNMPINTERFACE);
try
{
ifStmt.setInt(1, duplicateNode.getNodeId());
svcStmt.setInt(1, duplicateNode.getNodeId());
snmpStmt.setInt(1, duplicateNode.getNodeId());
ifStmt.executeUpdate();
svcStmt.executeUpdate();
snmpStmt.executeUpdate();
duplicateNode.setNodeType(DbNodeEntry.NODE_TYPE_DELETED);
duplicateNode.store(dbc);
}
catch(SQLException sqlE)
{
log.error("deleteDuplicateNode SQLException while deleting duplicate node: " + duplicateNode.getNodeId());
throw sqlE;
}
finally
{
try
{
ifStmt.close();
svcStmt.close();
snmpStmt.close();
}
catch (SQLException e) {}
}
}
/**
* This method verify if an ipaddress is existing in other node except
* in the updating node.
*
* @param dbc Database Connection
* @param ifaddr Ip address being verified.
* @param nodeId Node Id of the node being rescanned
*
*/
private boolean isDuplicateInterface( Connection dbc,
InetAddress ifaddr,
int nodeId)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
boolean duplicate = false;
PreparedStatement stmt = null;
try
{
stmt = dbc.prepareStatement(SQL_DB_RETRIEVE_DUPLICATE_NODEIDS);
stmt.setString(1, ifaddr.getHostAddress());
stmt.setInt(2, nodeId);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
duplicate = true;
}
}
catch(SQLException sqlE)
{
log.error("isDuplicateInterface: SQLException while updating interface: " + ifaddr.getHostAddress()
+ " on nodeid: " + nodeId);
throw sqlE;
}
finally
{
try
{
stmt.close();
}
catch (SQLException e) {}
return duplicate;
}
}
/**
* This method is responsible for updating the ipinterface table entry
* for a specific interface.
*
* @param dbc Database Connection.
* @param now Date/time to be associated with the update.
* @param node Node entry for the node being rescanned.
* @param dbIpIfEntry interface entry of the updating interface.
* @param snmpc SNMP collector or null if SNMP not supported.
* @param isNewIpEntry if dbIpIfEntry is a new entry.
* @param isReparented if dbIpIfentry is reparented.
*
* @throws SQLException if there is a problem updating the ipinterface table.
*/
private void updateInterfaceInfo( Connection dbc,
Date now,
DbNodeEntry node,
DbIpInterfaceEntry dbIpIfEntry,
IfSnmpCollector snmpc,
boolean isNewIpEntry,
boolean isReparented )
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
CapsdConfigFactory cFactory = CapsdConfigFactory.getInstance();
PollerConfigFactory pollerCfgFactory = PollerConfigFactory.getInstance();
InetAddress ifaddr = dbIpIfEntry.getIfAddress();
int ifIndex = snmpc.getIfIndex(ifaddr);
// Clone the existing database entry so we have access to the values
// of the database fields associated with the interface in the event
// that something has changed.
DbIpInterfaceEntry originalIpIfEntry = DbIpInterfaceEntry.clone(dbIpIfEntry);
// Create IP interface entry representing latest information
// retrieved for the interface via the collector
DbIpInterfaceEntry currIpIfEntry = DbIpInterfaceEntry.create(node.getNodeId(), ifaddr, ifIndex);
// Hostname
currIpIfEntry.setHostname(ifaddr.getHostName());
// Managed state
// NOTE: (reference internal bug# 201)
// If the ip is 'managed', it might still be 'not polled' based
// on the poller configuration.
// Try to avoid re-evaluating the ip against filters for
// each service, try to get the first package here and use
// that for service evaluation
// At this point the ip is already/ in the database, so package filter
// evaluation should go through OK
org.opennms.netmgt.config.poller.Package ipPkg = null;
if(cFactory.isAddressUnmanaged(ifaddr))
currIpIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED);
else
{
boolean ipToBePolled = false;
ipPkg = pollerCfgFactory.getFirstPackageMatch(ifaddr.getHostAddress());
if (ipPkg != null)
ipToBePolled = true;
if (ipToBePolled)
currIpIfEntry.setManagedState(DbIpInterfaceEntry.STATE_MANAGED);
else
currIpIfEntry.setManagedState(DbIpInterfaceEntry.STATE_NOT_POLLED);
}
// If SNMP data collection is available set SNMP Primary state
// as well as ifIndex and ifStatus. Also retrieve ifType (loopback
// interfaces will be skipped).
int ifType = -1;
if (snmpc != null && !snmpc.failed())
{
if(ifIndex != -1)
{
int status = snmpc.getAdminStatus(ifIndex);
currIpIfEntry.setStatus(status);
ifType = snmpc.getIfType(ifIndex);
// For new interfaces simply set 'isSnmpPrimary' field to secondary for now.
// Following the interface updates the primary SNMP interface will be determined
// and the value of the 'isSnmpPrimary' field set to 'P' (primary) for that
// interface.
if (isNewIpEntry)
currIpIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_SECONDARY);
else
currIpIfEntry.setPrimaryState(originalIpIfEntry.getPrimaryState());
}
else
{
// No ifIndex found so set primary state to NOT_ELIGIBLE
currIpIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
}
}
// Update any fields which have changed
dbIpIfEntry.setLastPoll(now);
dbIpIfEntry.updateHostname(currIpIfEntry.getHostname());
dbIpIfEntry.updateManagedState(currIpIfEntry.getManagedState());
dbIpIfEntry.updateStatus(currIpIfEntry.getStatus());
dbIpIfEntry.updatePrimaryState(currIpIfEntry.getPrimaryState());
dbIpIfEntry.updateIfIndex(currIpIfEntry.getIfIndex());
// Set event flags
// NOTE: Must set these flags prior to call to DbIpInterfaceEntry.store()
// method which will cause the change map to be cleared.
boolean ifIndexChangedFlag = false;
boolean ipHostnameChangedFlag = false;
if (dbIpIfEntry.hasIfIndexChanged())
ifIndexChangedFlag = true;
if (dbIpIfEntry.hasHostnameChanged())
ipHostnameChangedFlag = true;
// Update the database
dbIpIfEntry.store(dbc);
// If the interface was not already in the database under
// the node being rescanned or some other node send a
// nodeGainedInterface event.
if (isNewIpEntry && !isReparented)
{
createNodeGainedInterfaceEvent(dbIpIfEntry);
}
// If an interface has been reparented send associated events
else if (isReparented)
{
// InterfaceIndexChanged event
if (log.isDebugEnabled())
log.debug("updateInterfaceInfo: ifIndex changed: " + ifIndexChangedFlag);
if (ifIndexChangedFlag)
{
createInterfaceIndexChangedEvent(dbIpIfEntry, originalIpIfEntry);
m_ifIndexOnNodeChangedFlag = true;
}
// IPHostNameChanged event
if (log.isDebugEnabled())
log.debug("updateInterfaceInfo: hostname changed: " + ipHostnameChangedFlag);
if (ipHostnameChangedFlag)
{
createIpHostNameChangedEvent(dbIpIfEntry, originalIpIfEntry);
}
}
// If the interface is not new check to see if the interface's
// ifIndex or ipHostname have changed.
else
{
// InterfaceIndexChanged event
if (log.isDebugEnabled())
log.debug("updateInterfaceInfo: ifIndex changed: " + ifIndexChangedFlag);
if (ifIndexChangedFlag)
{
createInterfaceIndexChangedEvent(dbIpIfEntry, originalIpIfEntry);
m_ifIndexOnNodeChangedFlag = true;
}
// IPHostNameChanged event
if (log.isDebugEnabled())
log.debug("updateInterfaceInfo: hostname changed: " + ipHostnameChangedFlag);
if (ipHostnameChangedFlag)
{
createIpHostNameChangedEvent(dbIpIfEntry, originalIpIfEntry);
}
}
}
/**
* This method is responsible for updating the ifservices table entry
* for a specific interface.
*
* @param dbc Database Connection.
* @param node Node entry for the node being rescanned.
* @param dbIpIfEntry interface entry of the updating interface.
* @param isNewIpEntry if the dbIpIfEntry is a new entry.
* @param protocols Protocols supported by the interface.
*
* @throws SQLException if there is a problem updating the ifservices table.
*/
private void updateServiceInfo( Connection dbc,
DbNodeEntry node,
DbIpInterfaceEntry dbIpIfEntry,
boolean isNewIpEntry,
List protocols )
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
CapsdConfigFactory cFactory = CapsdConfigFactory.getInstance();
PollerConfigFactory pollerCfgFactory = PollerConfigFactory.getInstance();
org.opennms.netmgt.config.poller.Package ipPkg = null;
InetAddress ifaddr = dbIpIfEntry.getIfAddress();
// Retrieve from the database the interface's service list
DbIfServiceEntry[] dbSupportedServices = dbIpIfEntry.getServices(dbc);
// add newly supported protocols
// NOTE!!!!!: (reference internal bug# 201)
// If the ip is 'managed', the service can still be 'not polled'
// based on the poller configuration - at this point the ip is already
// in the database, so package filter evaluation should go through OK
Iterator iproto = protocols.iterator();
while(iproto.hasNext())
{
IfCollector.SupportedProtocol p = (IfCollector.SupportedProtocol)iproto.next();
Number sid = (Number)cFactory.getServiceIdentifier(p.getProtocolName());
// Only adding newly supported services so check against the service
// list retrieved from the database
boolean found = false;
for (int i=0; i<dbSupportedServices.length && !found; i++)
{
if (dbSupportedServices[i].getServiceId() == sid.intValue())
found = true;
}
if (!found)
{
DbIfServiceEntry ifSvcEntry = DbIfServiceEntry.create(node.getNodeId(), ifaddr, sid.intValue());
// now fill in the entry
if(cFactory.isAddressUnmanaged(ifaddr))
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_UNMANAGED);
else
{
boolean svcToBePolled = false;
if (ipPkg != null)
{
ipPkg = pollerCfgFactory.getFirstPackageMatch(ifaddr.getHostAddress());
svcToBePolled = pollerCfgFactory.isPolled(p.getProtocolName(), ipPkg);
if (!svcToBePolled)
svcToBePolled = pollerCfgFactory.isPolled(ifaddr.getHostAddress(),
p.getProtocolName());
}
if (svcToBePolled)
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_ACTIVE);
else
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_NOT_POLLED);
}
// Set qualifier if available. Currently the qualifier field
// is used to store the port at which the protocol was found.
if (p.getQualifiers() != null && p.getQualifiers().get("port") != null)
{
try
{
Integer port = (Integer)p.getQualifiers().get("port");
if (log.isDebugEnabled())
log.debug("updateIfServices: got a port qualifier: " + port
+ " for service: " + p.getProtocolName());
ifSvcEntry.setQualifier(port.toString());
}
catch (ClassCastException ccE)
{
// Do nothing
}
}
ifSvcEntry.setSource(DbIfServiceEntry.SOURCE_PLUGIN);
ifSvcEntry.setNotify(DbIfServiceEntry.NOTIFY_ON);
int index = dbIpIfEntry.getIfIndex();
if (index > 0)
ifSvcEntry.setIfIndex(index);
ifSvcEntry.store();
if (log.isDebugEnabled())
log.debug("updateIfServices: update service: " + p.getProtocolName()
+ " for interface:" + ifaddr.getHostAddress()
+ " on node:" + node.getNodeId());
// Generate nodeGainedService event
createNodeGainedServiceEvent(node, dbIpIfEntry, p.getProtocolName());
// If this interface already existed in the database and SNMP
// service has been gained then create interfaceSupportsSNMP event
if (!isNewIpEntry && p.getProtocolName().equalsIgnoreCase("SNMP"))
{
createInterfaceSupportsSNMPEvent(dbIpIfEntry);
}
}
} // end while(more protocols)
}
/**
* This method is responsible for updating the snmpInterface table entry
* for a specific interface.
*
* @param dbc Database Connection
* @param node Node entry for the node being rescanned
* @param dbIpIfEntry interface entry of the updating interface
* @param snmpc SNMP collector or null if SNMP not supported.
*
* @throws SQLException if there is a problem updating the snmpInterface table.
*/
private void updateSnmpInfo( Connection dbc,
DbNodeEntry node,
DbIpInterfaceEntry dbIpIfEntry,
IfSnmpCollector snmpc)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
InetAddress ifaddr = dbIpIfEntry.getIfAddress();
// If SNMP info is available update the snmpInterface table entry with
// anything that has changed.
if (snmpc != null && !snmpc.failed() && dbIpIfEntry.getIfIndex() != -1)
{
if (log.isDebugEnabled())
log.debug("updateSnmpInfo: updating snmp interface for nodeId/ifIndex=" +
+ node.getNodeId() + "/" + dbIpIfEntry.getIfIndex());
// Create and load SNMP Interface entry from the database
boolean newSnmpIfTableEntry = false;
DbSnmpInterfaceEntry dbSnmpIfEntry = DbSnmpInterfaceEntry.get(dbc, node.getNodeId(), dbIpIfEntry.getIfIndex());
if (dbSnmpIfEntry == null)
{
// SNMP Interface not found with this nodeId, create new interface
if (log.isDebugEnabled())
log.debug("updateSnmpInfo: SNMP interface index " + dbIpIfEntry.getIfIndex()
+ " not in database, creating new interface object.");
dbSnmpIfEntry = DbSnmpInterfaceEntry.create(node.getNodeId(), dbIpIfEntry.getIfIndex());
newSnmpIfTableEntry = true;
}
// Create SNMP interface entry representing latest information
// retrieved for the interface via the collector
DbSnmpInterfaceEntry currSnmpIfEntry = DbSnmpInterfaceEntry.create(node.getNodeId(), dbIpIfEntry.getIfIndex());
// Find the ifTable entry for this interface
IfTable ift = snmpc.getIfTable();
Iterator ifiter = ift.getEntries().iterator();
IfTableEntry ifte = null;
while(ifiter.hasNext())
{
ifte = (IfTableEntry)ifiter.next();
// index
SnmpInt32 sint = (SnmpInt32)ifte.get(IfTableEntry.IF_INDEX);
if(sint != null)
{
if (dbIpIfEntry.getIfIndex() == sint.getValue())
break;
}
}
// Make sure we have a valid IfTableEntry object
if (ifte != null)
{
// IP address and netmask
// WARNING: IfSnmpCollector.getIfAddressAndMask() ONLY returns
// the FIRST IP address and mask for a given interface as specified
// in the ipAddrTable.
InetAddress[] aaddrs = snmpc.getIfAddressAndMask(dbIpIfEntry.getIfIndex());
// Address array should NEVER be null but just in case..
if(aaddrs == null)
{
log.warn("updateSnmpInfo: unable to retrieve address and netmask for nodeId/ifIndex: " +
node.getNodeId() + "/" + dbIpIfEntry.getIfIndex());
aaddrs = new InetAddress[2];
// Set interface address to current interface
aaddrs[0] = ifaddr;
// Set netmask to NULL
aaddrs[1] = null;
}
// IP address
currSnmpIfEntry.setIfAddress(aaddrs[0]);
// netmask
if (aaddrs[1] != null)
{
if (log.isDebugEnabled())
log.debug("updateSnmpInfo: interface " + aaddrs[0].getHostAddress()
+ " has netmask: " + aaddrs[1].getHostAddress());
currSnmpIfEntry.setNetmask(aaddrs[1]);
}
// type
SnmpInt32 sint = (SnmpInt32)ifte.get(IfTableEntry.IF_TYPE);
currSnmpIfEntry.setType(sint.getValue());
// description
String str = SystemGroup.getPrintableString((SnmpOctetString)ifte.get(IfTableEntry.IF_DESCR));
if (log.isDebugEnabled())
log.debug("updateSnmpInfo: " + ifaddr + " has ifDescription: " + str);
if(str != null && str.length() > 0)
currSnmpIfEntry.setDescription(str);
// physical address
StringBuffer sbuf = new StringBuffer();
SnmpOctetString ostr = (SnmpOctetString)ifte.get(IfTableEntry.IF_PHYS_ADDR);
if ( ostr != null && ostr.getLength() > 0)
{
byte[] bytes = ostr.getString();
for(int i = 0; i < bytes.length; i++)
{
sbuf.append(Integer.toHexString(((int)bytes[i] >> 4) & 0xf));
sbuf.append(Integer.toHexString((int)bytes[i] & 0xf));
}
}
String physAddr = sbuf.toString().trim();
if (log.isDebugEnabled())
log.debug("updateSnmpInfo: " + ifaddr + " has phys address: -" + physAddr + "-");
if (physAddr.length() == 12)
{
currSnmpIfEntry.setPhysicalAddress(physAddr);
}
// speed
SnmpUInt32 uint = (SnmpUInt32)ifte.get(IfTableEntry.IF_SPEED);
currSnmpIfEntry.setSpeed((int)uint.getValue());
// admin status
sint = (SnmpInt32)ifte.get(IfTableEntry.IF_ADMIN_STATUS);
currSnmpIfEntry.setAdminStatus(sint.getValue());
// oper status
sint = (SnmpInt32)ifte.get(IfTableEntry.IF_OPER_STATUS);
currSnmpIfEntry.setOperationalStatus(sint.getValue());
// name (from interface extensions table)
SnmpOctetString snmpIfName = snmpc.getIfName(dbIpIfEntry.getIfIndex());
if (snmpIfName != null)
{
String ifName = SystemGroup.getPrintableString(snmpIfName);
if (ifName!= null && ifName.length() > 0)
currSnmpIfEntry.setName(ifName);
}
} // end if valid ifTable entry
// Update any fields which have changed
//dbSnmpIfEntry.updateIfIndex(currSnmpIfEntry.getIfIndex());
dbSnmpIfEntry.updateIfAddress(currSnmpIfEntry.getIfAddress());
dbSnmpIfEntry.updateNetmask(currSnmpIfEntry.getNetmask());
dbSnmpIfEntry.updatePhysicalAddress(currSnmpIfEntry.getPhysicalAddress());
dbSnmpIfEntry.updateDescription(currSnmpIfEntry.getDescription());
dbSnmpIfEntry.updateName(currSnmpIfEntry.getName());
dbSnmpIfEntry.updateType(currSnmpIfEntry.getType());
dbSnmpIfEntry.updateSpeed(currSnmpIfEntry.getSpeed());
dbSnmpIfEntry.updateAdminStatus(currSnmpIfEntry.getAdminStatus());
dbSnmpIfEntry.updateOperationalStatus(currSnmpIfEntry.getOperationalStatus());
// If this is a new interface or if any of the following
// key fields have changed set the m_snmpIfTableChangedFlag
// variable to TRUE. This will potentially trigger an event
// which will cause the poller to reinitialize the primary
// SNMP interface for the node.
if (!m_snmpIfTableChangedFlag &&
newSnmpIfTableEntry ||
//dbSnmpIfEntry.hasIfIndexChanged() ||
dbSnmpIfEntry.hasIfAddressChanged() ||
dbSnmpIfEntry.hasTypeChanged() ||
dbSnmpIfEntry.hasNameChanged() ||
dbSnmpIfEntry.hasDescriptionChanged() ||
dbSnmpIfEntry.hasPhysicalAddressChanged())
{
m_snmpIfTableChangedFlag = true;
}
// Update the database
dbSnmpIfEntry.store(dbc);
} // end if snmp info available
}
/**
* This method checks if a suspect node entry is a duplicate node to the
* updating node by verify if each interface in the suspect node is
* contained in the ipAddrTable of the updating node.
*
* @param dbc Database connection
* @param suspectNode the suspect node to verify duplication.
* @param snmpc the SNMP collection of the updating node.
*/
private boolean isDuplicateNode(Connection dbc, DbNodeEntry suspectNode, IfSnmpCollector snmpc)
{
Category log = ThreadCategory.getInstance(getClass());
if (suspectNode == null)
{
if (log.isDebugEnabled())
log.debug("isDuplicateNode: null node.");
return false;
}
// Retrieve list of interfaces associated with the suspect node
try
{
DbIpInterfaceEntry[] tmpIfArray = suspectNode.getInterfaces(dbc);
for (int i = 0; i < tmpIfArray.length; i++)
{
InetAddress addr = tmpIfArray[i].getIfAddress();
int index = tmpIfArray[i].getIfIndex();
InetAddress[] updateIfs = snmpc.getIfAddressAndMask(index);
if (updateIfs == null)
{
if (log.isDebugEnabled())
log.debug("isDuplicateNode: Interface: " + addr.getHostAddress()
+ " is not in the ipAddrTable of the updating node.");
return false;
}
else
{
boolean match = false;
for (int inx = 0; inx < updateIfs.length; inx ++)
{
if (updateIfs[inx].getHostAddress().equals(addr.getHostAddress()))
{
if (log.isDebugEnabled())
log.debug("isDuplicateNode: Interface: " + addr.getHostAddress()
+ " found a match in the ipAddrTable of the updating node.");
match = true;
break;
}
}
if (!match)
{
if (log.isDebugEnabled())
log.debug("isDuplicateNode: Interface: " + addr.getHostAddress()
+ " is not in the ipAddrTable of the updating node.");
return false;
}
}
}
return true;
}
catch (SQLException sqlE)
{
log.error("isDuplicateNode: failed to retrieve all interfaces for the supect node"
+ suspectNode.getNodeId(), sqlE);
return false;
}
}
/**
* Responsible for iterating inserting an entry into the ifServices
* table for each protocol supported by the interface.
*
* @param node Node entry
* @param ipIfEntry DbIpInterfaceEntry object
* @param protocols List of supported protocols
* @param addrUnmanaged Boolean flag indicating if interface is managed or
* unmanaged according to the Capsd configuration.
* @param ifIndex Interface index or -1 if index is not known
* @param ipPkg Poller package to which the interface belongs
*
* @throws SQLException if an error occurs adding interfaces to the ipInterface
* table.
*/
private void addSupportedProtocols(DbNodeEntry node,
DbIpInterfaceEntry ipIfEntry,
List protocols,
boolean addrUnmanaged,
int ifIndex,
org.opennms.netmgt.config.poller.Package ipPkg)
throws SQLException
{
InetAddress ifaddr = ipIfEntry.getIfAddress();
// add the supported protocols
Iterator iproto = protocols.iterator();
while(iproto.hasNext())
{
IfCollector.SupportedProtocol p = (IfCollector.SupportedProtocol)iproto.next();
Number sid = (Number)CapsdConfigFactory.getInstance().getServiceIdentifier(p.getProtocolName());
DbIfServiceEntry ifSvcEntry = DbIfServiceEntry.create(node.getNodeId(),
ifaddr, sid.intValue());
// now fill in the entry
if(addrUnmanaged)
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_UNMANAGED);
else
{
boolean svcToBePolled = false;
if (ipPkg != null)
{
svcToBePolled = PollerConfigFactory.getInstance().isPolled(p.getProtocolName(), ipPkg);
if (!svcToBePolled)
svcToBePolled = PollerConfigFactory.getInstance().isPolled(ifaddr.getHostAddress(),
p.getProtocolName());
}
if (svcToBePolled)
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_ACTIVE);
else
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_NOT_POLLED);
}
// Set qualifier if available. Currently the qualifier field
// is used to store the port at which the protocol was found.
if (p.getQualifiers() != null && p.getQualifiers().get("port") != null)
{
try
{
Integer port = (Integer)p.getQualifiers().get("port");
ifSvcEntry.setQualifier(port.toString());
}
catch (ClassCastException ccE)
{
// Do nothing
}
}
ifSvcEntry.setSource(DbIfServiceEntry.SOURCE_PLUGIN);
ifSvcEntry.setNotify(DbIfServiceEntry.NOTIFY_ON);
if(ifIndex != -1)
ifSvcEntry.setIfIndex(ifIndex);
ifSvcEntry.store();
}
}
/**
* This method is responsible for reparenting an interface's database
* table entries under its new node identifier. The following tables
* are updated:
*
* ipInterface
* snmpInterface
* ifServices
*
* @param dbc Database connection
* @param ifAddr Interface to be reparented.
* @param newNodeId Interface's new node identifier
* @param oldNodeId Interfaces' old node identifier
*
* @throws SQLException if a database error occurs during reparenting.
*/
private void reparentInterface(Connection dbc,
InetAddress ifAddr,
int ifIndex,
int newNodeId,
int oldNodeId)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
// Reparent the interface
PreparedStatement ipInterfaceStmt = dbc.prepareStatement(SQL_DB_REPARENT_IP_INTERFACE);
PreparedStatement snmpIfLookupStmt = dbc.prepareStatement(SQL_DB_REPARENT_SNMP_IF_LOOKUP);
PreparedStatement snmpIfDeleteStmt = dbc.prepareStatement(SQL_DB_REPARENT_SNMP_IF_DELETE);
PreparedStatement snmpInterfaceStmt = dbc.prepareStatement(SQL_DB_REPARENT_SNMP_INTERFACE);
PreparedStatement ifServicesStmt = dbc.prepareStatement(SQL_DB_REPARENT_IF_SERVICES);
try
{
log.debug("reparentInterfaces: reparenting address/ifIndex/nodeID: " + ifAddr.getHostAddress() + "/" + ifIndex + "/" + newNodeId);
// Update the 'ipInterface' table entry so that this
// interface's nodeID is set to the value of reparentNodeID
ipInterfaceStmt.setInt(1, newNodeId);
ipInterfaceStmt.setInt(2, oldNodeId);
ipInterfaceStmt.setString(3, ifAddr.getHostAddress());
// execute and log
ipInterfaceStmt.executeUpdate();
// SNMP interface
// NOTE: Only reparent SNMP interfaces if we have valid ifIndex
if (ifIndex < 1)
{
log.debug("reparentInterfaces: don't have a valid ifIndex, skipping snmpInterface table reparenting.");
}
else
{
// NOTE: Now that the snmpInterface table is uniquely keyed
// by nodeId and ifIndex we must only reparent the
// old entry if there isn't already an entry with
// the same nodeid/ifindex pairing. If it can't
// be reparented it will be deleted.
// Look for matching nodeid/ifindex for the entry to be reparented
boolean alreadyExists = false;
snmpIfLookupStmt.setInt(1, newNodeId);
snmpIfLookupStmt.setInt(2, ifIndex);
ResultSet rs = snmpIfLookupStmt.executeQuery();
if (rs.next())
{
// Looks like we got a match so just delete
// the entry from the old node
log.debug("interface with ifindex " + ifIndex + " already exists under new node " + newNodeId + ", deleting from under old node " + oldNodeId);
alreadyExists = true;
snmpIfDeleteStmt.setInt(1, oldNodeId);
snmpIfDeleteStmt.setInt(2, ifIndex);
snmpIfDeleteStmt.executeUpdate();
}
if (alreadyExists == false)
{
// Update the 'snmpinterface' table entry so that this
// interface's nodeID is set to the value of reparentNodeID
log.debug("interface with ifindex " + ifIndex + " does not yet exist under new node " + newNodeId + ", reparenting.");
snmpInterfaceStmt.setInt(1, newNodeId);
snmpInterfaceStmt.setInt(2, oldNodeId);
snmpInterfaceStmt.setInt(3, ifIndex);
// execute and log
snmpInterfaceStmt.executeUpdate();
}
}
// Update the 'nodeID' field of all 'ifservices' table entries for
// the reparented interfaces.
ifServicesStmt.setInt(1, newNodeId);
ifServicesStmt.setInt(2, oldNodeId);
ifServicesStmt.setString(3, ifAddr.getHostAddress());
// execute and log
ifServicesStmt.executeUpdate();
log.debug("reparentInterface: reparented " + ifAddr.getHostAddress() +
" : ifIndex: " + ifIndex +
" : oldNodeID: " + oldNodeId +
" newNodeID: " + newNodeId);
}
catch(SQLException sqlE)
{
log.error("SQLException while reparenting addr/ifindex/nodeid " + ifAddr.getHostAddress() + "/" + ifIndex + "/" + oldNodeId);
throw sqlE;
}
finally
{
ipInterfaceStmt.close();
snmpIfLookupStmt.close();
snmpIfDeleteStmt.close();
snmpInterfaceStmt.close();
ifServicesStmt.close();
}
}
/**
* Builds a list of InetAddress objects representing each of
* the interfaces from the collector map object which support SNMP
* and have a valid ifIndex and have an IfType of loopback.
*
* This is part of a feature to choose a non 127.*.*.* loopback
* address as the primary SNMP interface.
*
* @param collectorMap Map of IfCollector objects containing data collected
* from all of the node's interfaces.
* @param snmpc Reference to SNMP collection object
*
* @return List of InetAddress objects.
*/
private static List buildLBSnmpAddressList(Map collectorMap, IfSnmpCollector snmpc)
{
Category log = ThreadCategory.getInstance(RescanProcessor.class);
List addresses = new ArrayList();
// Verify that we have SNMP info
if (snmpc == null)
{
if (log.isDebugEnabled())
log.debug("buildLBSnmpAddressList: no SNMP info available...");
return addresses;
}
// To be eligible to be the primary SNMP interface for a node:
// 1. The interface must support SNMP
// 2. The interface must have a valid ifIndex.
Collection values = collectorMap.values();
Iterator iter = values.iterator();
while(iter.hasNext())
{
IfCollector ifc = (IfCollector)iter.next();
// Add eligible target.
InetAddress ifaddr = ifc.getTarget();
if (addresses.contains(ifaddr) == false)
{
if ( SuspectEventProcessor.supportsSnmp(ifc.getSupportedProtocols()) &&
SuspectEventProcessor.hasIfIndex(ifaddr, snmpc) && SuspectEventProcessor.getIfType(ifaddr, snmpc) == 24)
{
if (log.isDebugEnabled())
log.debug("buildLBSnmpAddressList: adding target interface " + ifaddr.getHostAddress() + " temporarily marked as primary!");
addresses.add(ifaddr);
}
}
// Now go through list of sub-targets
if (ifc.hasAdditionalTargets())
{
Map subTargets = ifc.getAdditionalTargets();
Set keys = subTargets.keySet();
Iterator siter = keys.iterator();
while(siter.hasNext())
{
// Add eligible subtargets.
InetAddress xifaddr = (InetAddress)siter.next();
if (addresses.contains(xifaddr) == false)
{
if (SuspectEventProcessor.supportsSnmp((List)subTargets.get(xifaddr)) &&
SuspectEventProcessor.hasIfIndex(xifaddr, snmpc) && SuspectEventProcessor.getIfType(xifaddr, snmpc) == 24)
{
if (log.isDebugEnabled())
log.debug("buildLBSnmpAddressList: adding subtarget interface " + xifaddr.getHostAddress() + " temporarily marked as primary!");
addresses.add(xifaddr);
}
}
}
}
}
return addresses;
}
/**
* Builds a list of InetAddress objects representing each of
* the interfaces from the collector map object which support SNMP
* and have a valid ifIndex.
*
* @param collectorMap Map of IfCollector objects containing data collected
* from all of the node's interfaces.
* @param snmpc Reference to SNMP collection object
*
* @return List of InetAddress objects.
*/
private static List buildSnmpAddressList(Map collectorMap, IfSnmpCollector snmpc)
{
Category log = ThreadCategory.getInstance(RescanProcessor.class);
List addresses = new ArrayList();
// Verify that we have SNMP info
if (snmpc == null)
{
if (log.isDebugEnabled())
log.debug("buildSnmpAddressList: no SNMP info available...");
return addresses;
}
// To be eligible to be the primary SNMP interface for a node:
// 1. The interface must support SNMP
// 2. The interface must have a valid ifIndex.
Collection values = collectorMap.values();
Iterator iter = values.iterator();
while(iter.hasNext())
{
IfCollector ifc = (IfCollector)iter.next();
// Add eligible target.
InetAddress ifaddr = ifc.getTarget();
if (addresses.contains(ifaddr) == false)
{
if ( SuspectEventProcessor.supportsSnmp(ifc.getSupportedProtocols()) &&
SuspectEventProcessor.hasIfIndex(ifaddr, snmpc) )
{
if (log.isDebugEnabled())
log.debug("buildSnmpAddressList: adding target interface " + ifaddr.getHostAddress() + " temporarily marked as primary!");
addresses.add(ifaddr);
}
}
// Now go through list of sub-targets
if (ifc.hasAdditionalTargets())
{
Map subTargets = ifc.getAdditionalTargets();
Set keys = subTargets.keySet();
Iterator siter = keys.iterator();
while(siter.hasNext())
{
// Add eligible subtargets.
InetAddress xifaddr = (InetAddress)siter.next();
if (addresses.contains(xifaddr) == false)
{
if (SuspectEventProcessor.supportsSnmp((List)subTargets.get(xifaddr)) &&
SuspectEventProcessor.hasIfIndex(xifaddr, snmpc) )
{
if (log.isDebugEnabled())
log.debug("buildSnmpAddressList: adding subtarget interface " + xifaddr.getHostAddress() + " temporarily marked as primary!");
addresses.add(xifaddr);
}
}
}
}
}
return addresses;
}
/**
* This method is responsible for determining the primary IP interface
* for the node being rescanned.
*
* @param collectorMap Map of IfCollector objects containing data collected
* from all of the node's interfaces.
*
* @return InetAddress The primary IP interface for the node or null if
* a primary interface for the node could not be determined.
*/
private InetAddress determinePrimaryIpInterface(Map collectorMap)
{
Category log = ThreadCategory.getInstance(getClass());
// For now hard-coding primary interface address selection method to MIN
String method = SELECT_METHOD_MIN;
Collection values = collectorMap.values();
Iterator iter = values.iterator();
InetAddress primaryIf = null;
while(iter.hasNext())
{
IfCollector ifc = (IfCollector)iter.next();
InetAddress currIf = ifc.getTarget();
if (primaryIf == null)
{
primaryIf = currIf;
continue;
}
else
{
// Test the target interface of the collector first.
primaryIf = SuspectEventProcessor.compareAndSelectPrimary(currIf, primaryIf, method);
// Now test each of the collected subtargets
if (ifc.hasAdditionalTargets())
{
Map subTargets = ifc.getAdditionalTargets();
Set keys = subTargets.keySet();
Iterator siter = keys.iterator();
while(siter.hasNext())
{
currIf = (InetAddress)siter.next();
primaryIf = SuspectEventProcessor.compareAndSelectPrimary(currIf, primaryIf, method);
}
}
}
}
if (log.isDebugEnabled())
if (primaryIf != null)
log.debug("determinePrimaryIpInterface: selected primary interface: " + primaryIf.getHostAddress());
else
log.debug("determinePrimaryIpInterface: no primary interface found");
return primaryIf;
}
/**
* Primarily, this method is responsible for assigning the node's nodeLabel
* value using information collected from the node's various interfaces.
* Additionally, if the node talks NetBIOS/SMB, then the node's NetBIOS name
* and operating system fields are assigned.
*
* @param collectorMap Map of IfCollector objects, one per interface.
* @param dbNodeEntry Node entry, as it exists in the database.
* @param currNodeEntry Current node entry, as collected during the
* current rescan.
* @param currPrimarySnmpIf Primary SNMP interface, as determined from the
* collection retrieved during the current rescan.
*/
private void setNodeLabelAndSmbInfo(Map collectorMap,
DbNodeEntry dbNodeEntry,
DbNodeEntry currNodeEntry,
InetAddress currPrimarySnmpIf)
{
Category log = ThreadCategory.getInstance(getClass());
boolean labelSet = false;
// We are going to change the order in which labels are assigned.
// First, we check DNS - the hostname of the primary interface.
// Then we check SMB - next SNMP sysName - and finally IP address
// This is different then in 1.0 - when SMB came first.
InetAddress primaryIf = null;
if (!labelSet)
{
// If no label is set, attempt to get the hostname for the primary SNMP interface.
// Note: this was wrong prior to 1.0.1 - the method determinePrimaryIpInterface
// would return the lowest numbered interface, not necessarily the primary
// SNMP interface.
if (currPrimarySnmpIf != null)
{
primaryIf = currPrimarySnmpIf;
}
else
{
primaryIf = determinePrimaryIpInterface(collectorMap);
}
if (primaryIf == null)
{
log.error("setNodeLabelAndSmbInfo: failed to find primary interface...");
}
else
{
String hostName = primaryIf.getHostName();
if (!hostName.equals(primaryIf.getHostAddress()))
{
labelSet = true;
currNodeEntry.setLabel(hostName);
currNodeEntry.setLabelSource(DbNodeEntry.LABEL_SOURCE_HOSTNAME);
}
}
}
IfSmbCollector savedSmbcRef = null;
// Does the node entry in database have a NetBIOS name?
if (dbNodeEntry.getNetBIOSName() != null)
{
// Yes it does, so search through collected info for all
// interfaces and see if any have a NetBIOS name
// which matches the existing one in the database
Collection values = collectorMap.values();
Iterator iter = values.iterator();
while(iter.hasNext() && !labelSet)
{
IfCollector ifc = (IfCollector)iter.next();
IfSmbCollector smbc = ifc.getSmbCollector();
if (smbc != null)
{
if(smbc.getNbtName() != null)
{
// Save reference to first IfSmbCollector object
// for future use.
savedSmbcRef = smbc;
String netbiosName = smbc.getNbtName().toUpperCase();
if (netbiosName.equals(dbNodeEntry.getNetBIOSName()))
{
// Found a match.
labelSet = true;
currNodeEntry.setLabel(netbiosName);
currNodeEntry.setLabelSource(DbNodeEntry.LABEL_SOURCE_NETBIOS);
currNodeEntry.setNetBIOSName(netbiosName);
if(smbc.getDomainName() != null)
currNodeEntry.setDomainName(smbc.getDomainName());
if(smbc.getOS() != null)
currNodeEntry.setOS(smbc.getOS());
}
}
}
}
}
else
{
// No it does not, attempt to find an interface
// collector that does have a NetBIOS name and
// save a reference to that collector
Collection values = collectorMap.values();
Iterator iter = values.iterator();
while(iter.hasNext())
{
IfCollector ifc = (IfCollector)iter.next();
IfSmbCollector smbc = ifc.getSmbCollector();
if (smbc != null && smbc.getNbtName() != null)
{
savedSmbcRef = smbc;
}
}
}
// If node label has not yet been set and SMB info is available
// use that info to set the node label and NetBIOS name
if (!labelSet && savedSmbcRef != null)
{
labelSet = true;
currNodeEntry.setLabel(savedSmbcRef.getNbtName());
currNodeEntry.setLabelSource(DbNodeEntry.LABEL_SOURCE_NETBIOS);
currNodeEntry.setNetBIOSName(currNodeEntry.getLabel());
if(savedSmbcRef.getDomainName() != null)
currNodeEntry.setDomainName(savedSmbcRef.getDomainName());
if(savedSmbcRef.getOS() != null)
currNodeEntry.setOS(savedSmbcRef.getOS());
}
// If we get this far no IP hostname or SMB info was available. Next we want
// to use MIB-II sysName for the node label. The primary SNMP interface
// has already been determined so use it if available.
if (!labelSet && currPrimarySnmpIf != null)
{
// We prefer to use the collector for the primary SNMP interface
// however a collector for the primary SNMP interface may not exist
// in the map if a node has only recently had SNMP support enabled
// or if the new primary SNMP interface was only recently added to the
// node. At any rate if it exists use it, if not use the
// first collector which supports SNMP.
IfCollector ifc = (IfCollector)collectorMap.get(currPrimarySnmpIf.getHostAddress());
if (ifc == null)
{
Collection collectors = collectorMap.values();
Iterator iter = collectors.iterator();
while (iter.hasNext())
{
ifc = (IfCollector)iter.next();
if (ifc.getSnmpCollector() != null)
break;
}
}
// Sanity check
if (ifc == null || ifc.getSnmpCollector() == null)
{
log.warn("setNodeLabelAndSmbInfo: primary SNMP interface set to " + currPrimarySnmpIf.getHostAddress() + " but no SNMP collector found.");
}
else
{
IfSnmpCollector snmpc = ifc.getSnmpCollector();
SystemGroup sysgrp = snmpc.getSystemGroup();
String str = SystemGroup.getPrintableString((SnmpOctetString)sysgrp.get(SystemGroup.SYS_NAME));
if(str != null && str.length() > 0)
{
labelSet = true;
currNodeEntry.setLabel(str);
currNodeEntry.setLabelSource(DbNodeEntry.LABEL_SOURCE_SYSNAME);
}
}
}
if (!labelSet)
{
// If we get this far no SNMP info was available so we will default
// to the IP address of the primary interface.
if (primaryIf != null)
{
currNodeEntry.setLabel(primaryIf.getHostAddress());
currNodeEntry.setLabelSource(DbNodeEntry.LABEL_SOURCE_ADDRESS);
}
else
{
// If all else fails, just use the current values from
// the database.
currNodeEntry.setLabel(dbNodeEntry.getLabel());
currNodeEntry.setLabelSource(dbNodeEntry.getLabelSource());
}
}
}
/**
* Utility method used to determine if the specified node has been
* marked as deleted in the node table.
*
* @param dbc Database connection.
* @param nodeId Node identifier to check
*
* @return TRUE if node has been marked as deleted, FALSE otherwise.
*/
private boolean isNodeDeleted(Connection dbc, int nodeId)
throws SQLException
{
boolean nodeDeleted = false;
// Prepare & execute the SQL statement to retrieve the 'nodetype' field
// from the node table for the specified nodeid.
PreparedStatement stmt = null;
try
{
stmt = dbc.prepareStatement(SQL_DB_RETRIEVE_NODE_TYPE);
stmt.setInt(1, nodeId);
ResultSet rs = stmt.executeQuery();
rs.next();
String nodeTypeStr = rs.getString(1);
if(!rs.wasNull())
{
char nodeType = nodeTypeStr.charAt(0);
if (nodeType == DbNodeEntry.NODE_TYPE_DELETED)
nodeDeleted = true;
}
rs.close();
}
finally
{
try
{
stmt.close();
}
catch (Exception e)
{
}
}
return nodeDeleted;
}
/**
* Determines if the passed InetAddress object represents an interface alias.
* The interface is an alias if the IpAddrTable collected from it via SNMP
* does not contain itself.
*
* @param ipAddr Address of interface to be tested
* @param snmpc IfSnmpCollector object containing SNMP collected
* ifTable and ipAddrTable information.
*
* @return TRUE if the provided IP address is an alias, FALSE otherwise.
*/
private boolean isInterfaceAlias(InetAddress ipAddr, IfSnmpCollector snmpc)
{
Category log = ThreadCategory.getInstance(getClass());
// Sanity check...null parms?
if (ipAddr == null || snmpc == null)
throw new IllegalArgumentException("ipAddr and snmpc parms cannot be null.");
// SNMP collection successful?
if (snmpc.failed())
return false;
// Verify that SNMP collection contains ifTable and ipAddrTable entries
IfTable ifTable = null;
IpAddrTable ipAddrTable = null;
if(snmpc.hasIfTable())
ifTable = snmpc.getIfTable();
if (snmpc.hasIpAddrTable())
ipAddrTable = snmpc.getIpAddrTable();
if (ifTable == null || ipAddrTable == null)
return false;
// Loop through the interface table entries until there are no more
// entries or we've found a match
boolean isAlias = true;
Iterator iter = ifTable.getEntries().iterator();
while(iter.hasNext())
{
IfTableEntry ifEntry = (IfTableEntry)iter.next();
if (ifEntry.containsKey("ifIndex") != true) {
log.debug("isInterfaceAlias: Breaking from loop");
break;
}
// Get the list of IP addresses for the current index and
// determine if the provided address is present.
int ifIndex = -1;
SnmpInt32 snmpIfIndex = (SnmpInt32)ifEntry.get(IfTableEntry.IF_INDEX);
if(snmpIfIndex != null)
ifIndex = snmpIfIndex.getValue();
List addrList = IpAddrTable.getIpAddresses(ipAddrTable.getEntries(), ifIndex);
Iterator addrIter = addrList.iterator();
while(addrIter.hasNext())
{
InetAddress tmpAddr = (InetAddress)addrIter.next();
// Compare temp address to the provided IP address...as soon as we find
// a match we're done.
if (tmpAddr != null && tmpAddr.getHostAddress().equals(ipAddr.getHostAddress()))
{
// Match found, break out of inner while loop
isAlias = false;
break;
}
}
// If match found break out of outer while loop
if (isAlias == false)
break;
} // end while
return isAlias;
}
/**
* This method is used to verify if each interface on a node stored in the database is in the specified
* SNMP data collection.
*
* @param ipInterfaces the ipInterfaces on a node stored in the database
* @param snmpc IfSnmpCollector object containing SNMP collected
* ipAddrTable information.
*
* @return TRUE if each ipInterface is contained in the ipAddrTable of the specified SNMP collection.
*
*/
private boolean areDbInterfacesInSnmpCollection(DbIpInterfaceEntry[] dbInterfaces, IfSnmpCollector snmpc)
{
Category log = ThreadCategory.getInstance(getClass());
// Sanity check...null parms?
if (dbInterfaces == null || snmpc == null)
{
log.error("areDbInterfacesInSnmpCollection: empty dbInterfaces or IfSnmpCollector.");
return false;
}
// SNMP collection successful?
if (snmpc.failed())
{
log.error("areDbInterfacesInSnmpCollection: Snmp Collector failed.");
return false;
}
// Verify that SNMP collection contains ipAddrTable entries
IpAddrTable ipAddrTable = null;
if (snmpc.hasIpAddrTable())
ipAddrTable = snmpc.getIpAddrTable();
if ( ipAddrTable == null)
{
log.error("areDbInterfacesInSnmpCollection: null ipAddrTable in the snmp collection");
return false;
}
List ipAddrList = ipAddrTable.getIpAddresses(ipAddrTable.getEntries());
// Loop through the interface table entries until there are no more
// entries or we've found a match
boolean isAlias = true;
for (int i=0; i < dbInterfaces.length; i++)
{
InetAddress ipaddr = dbInterfaces[i].getIfAddress();
Iterator iter = ipAddrList.iterator();
boolean found = false;
while (iter.hasNext())
{
InetAddress addr = (InetAddress)iter.next();
if (log.isDebugEnabled())
log.debug("areDbInterfacesInSnmpCollection: ipaddress in db: " + ipaddr.getHostAddress()
+ " ipaddress in ipAddrTable: " + addr.getHostAddress());
if (ipaddr.getHostAddress().equals(addr.getHostAddress()))
{
found = true;
if (log.isDebugEnabled())
log.debug("areDbInterfacesInSnmpCollection: found match for ipaddress: "
+ ipaddr.getHostAddress());
break;
}
}
if (!found)
{
if (log.isDebugEnabled())
log.debug("areDbInterfacesInSnmpCollection: ipaddress : " + ipaddr.getHostAddress()
+ " not in the snmp collection. Snmp collection is not usable.");
return false;
}
}
return true;
}
/**
* This is where all the work of the class is done.
*/
public void run()
{
Category log = ThreadCategory.getInstance(getClass());
// perform rescan of the node
DbNodeEntry dbNodeEntry = null;
// Get DbNodeEntry object which represents this node and
// load it from the database
try
{
dbNodeEntry = DbNodeEntry.get(m_scheduledNode.getNodeId());
if (log.isDebugEnabled())
log.debug("RescanProcessor: start rescaning node: " + m_scheduledNode.getNodeId());
}
catch (SQLException sqlE)
{
log.error("RescanProcessor: unable to load node info for nodeId " + m_scheduledNode.getNodeId()
+ " from the database.", sqlE);
log.error("Rescan failed for node w/ nodeid " + m_scheduledNode.getNodeId());
return;
}
// If this is a forced rescan then retrieve all the interfaces
// associated with this node and perform collections against them.
// Otherwise, this is a regularly scheduled rescan, only the
// node's managed interfaces are to be retrieved and collected.
DbIpInterfaceEntry[] dbInterfaces = null;
if (m_forceRescan)
{
// Retrieve list of interfaces associated with this nodeID
// from the database
log.debug("retrieving all interfaces for node: " + m_scheduledNode.getNodeId());
try
{
dbInterfaces = dbNodeEntry.getInterfaces();
}
catch (NullPointerException npE)
{
log.error("RescanProcessor: Null pointer when retrieving interfaces for node "
+ m_scheduledNode.getNodeId(), npE);
log.error("Forced rescan failed for node w/ nodeid " + m_scheduledNode.getNodeId());
return;
}
catch (SQLException sqlE)
{
log.error("RescanProcessor: unable to load interface info for nodeId " + m_scheduledNode.getNodeId()
+ " from the database.", sqlE);
log.error("Forced rescan failed for node w/ nodeid " + m_scheduledNode.getNodeId());
return;
}
}
else
{
// Retrieve list of managed interfaces associated with this nodeID
// from the database
log.debug("retrieving managed interfaces for node: " + m_scheduledNode.getNodeId());
try
{
dbInterfaces = dbNodeEntry.getManagedInterfaces();
}
catch (NullPointerException npE)
{
log.error("RescanProcessor: Null pointer when retrieving managed interfaces for node "
+ m_scheduledNode.getNodeId(), npE);
log.error("Rescan failed for node w/ nodeid " + m_scheduledNode.getNodeId());
return;
}
catch (SQLException sqlE)
{
log.error("RescanProcessor: unable to load interface info for nodeId "
+ m_scheduledNode.getNodeId() + " from the database.", sqlE);
log.error("Rescan failed for node w/ nodeid " + m_scheduledNode.getNodeId());
return;
}
}
// Run collector for each retrieved interface and add result
// to a collector map.
Map collectorMap = new HashMap();
IfSnmpCollector snmpc = null;
boolean doSnmpCollection = true;
Map snmpTargets = null;
for (int i=0; i<dbInterfaces.length; i++)
{
InetAddress ifaddr = dbInterfaces[i].getIfAddress();
// collect the information from the interface.
// NOTE: skip '127.*.*.*' and '0.0.0.0' addresses.
if(ifaddr.getHostAddress().startsWith("127") ||
ifaddr.getHostAddress().equals("0.0.0.0"))
{
continue;
}
// Any targets/interfaces found via SNMP have already
// been probed so skip them.
if (snmpTargets != null)
{
log.debug("checking snmp target map for interface " + ifaddr.getHostAddress());
if (snmpTargets.get(ifaddr) != null)
{
if (log.isDebugEnabled())
log.debug("skipping collection for " + ifaddr.getHostAddress() + " found via SNMP.");
continue;
}
else
log.debug("snmp target map does not contain interface " + ifaddr.getHostAddress());
}
if (log.isDebugEnabled())
log.debug("running collection for " + ifaddr.getHostAddress());
IfCollector collector = new IfCollector(ifaddr, doSnmpCollection);
collector.run();
// Only need to collect SNMP data from one of the
// node's interfaces.
if (doSnmpCollection)
{
snmpc = collector.getSnmpCollector();
if (snmpc != null && !snmpc.failed())
{
// Got a successful SNMP collection from the node
if (areDbInterfacesInSnmpCollection(dbInterfaces, snmpc))
{
doSnmpCollection = false;
if (collector.hasAdditionalTargets())
snmpTargets = collector.getAdditionalTargets();
if (log.isDebugEnabled())
log.debug("SNMP data collected via " + ifaddr.getHostAddress());
}
else
{
if (log.isDebugEnabled())
log.debug("SNMP data collected via " + ifaddr.getHostAddress()
+ " is not right.");
// this interface must included in the subtargets of other interfaces,
// give up the IfCollector for this one.
continue;
}
}
}
if (log.isDebugEnabled())
log.debug("collection completed for " + ifaddr.getHostAddress());
collectorMap.put(ifaddr.getHostAddress(), collector);
}
// Update the database
Date now = null;
Connection dbc = null;
boolean updateCompleted = false;
try
{
// Synchronize on the Capsd sync lock so we can check if
// the interface is already in the database and perform
// the necessary inserts in one atomic operation
// The SuspectEventProcessor class is also synchronizing on this
// lock prior to performing database inserts or updates.
synchronized(Capsd.getDbSyncLock())
{
// Get database connection
dbc = DatabaseConnectionFactory.getInstance().getConnection();
// There is a slight possibility that the node being rescanned has
// been deleted (due to reparenting) by another thread between the
// time this rescan was started and the database sync lock was
// grabbed. Verify that the current nodeid is still valid (ie, not
// deleted) before continuing.
if (!isNodeDeleted(dbc, m_scheduledNode.getNodeId()))
{
// Get old primary SNMP interface (if one exists)
InetAddress oldPrimarySnmpIf = SuspectEventProcessor.getPrimarySnmpInterfaceFromDb(dbc, dbNodeEntry);
// Update interface information
now = new Date();
updateInterfaces(dbc, now, dbNodeEntry, collectorMap);
// Now that all interfaces have been added to the database we
// can update the 'primarySnmpInterface' field of the ipInterface
// table. Necessary because the IP address must already be in
// the database to evaluate against a filter rule.
// First create a list of eligible loopback interfaces.
List snmpLBAddresses = buildLBSnmpAddressList(collectorMap, snmpc);
InetAddress newLBSnmpPrimaryIf = CollectdConfigFactory.getInstance().determinePrimarySnmpInterface(snmpLBAddresses);
// Now create a list of all eligible interfaces. Choose loopback
// if exists.
List snmpAddresses = buildSnmpAddressList(collectorMap, snmpc);
InetAddress newSnmpPrimaryIf = CollectdConfigFactory.getInstance().determinePrimarySnmpInterface(snmpAddresses);
if (newLBSnmpPrimaryIf == null)
{
SuspectEventProcessor.setPrimarySnmpInterface(dbc, dbNodeEntry, newSnmpPrimaryIf, oldPrimarySnmpIf);
}
else
{
newSnmpPrimaryIf = newLBSnmpPrimaryIf;
if(log.isDebugEnabled())
log.debug("SuspectEventProcessor: Loopback Address set as primary: " + newLBSnmpPrimaryIf);
SuspectEventProcessor.setPrimarySnmpInterface(dbc, dbNodeEntry, newLBSnmpPrimaryIf, oldPrimarySnmpIf);
}
// Now that we've identified the new primary SNMP interface
// we can determine if it is necessary to generate certain
// SNMP data collection related events
generateSnmpDataCollectionEvents(dbNodeEntry, oldPrimarySnmpIf, newSnmpPrimaryIf);
// Update the node table entry
DbNodeEntry updatedNodeEntry = updateNode(dbc, now, dbNodeEntry, newSnmpPrimaryIf, dbInterfaces, collectorMap);
updateCompleted = true;
}
}
} // end try
catch(Throwable t)
{
log.error("Error updating records", t);
}
finally
{
// Finished with the database connection, close it.
try
{
if (dbc != null)
dbc.close();
}
catch(SQLException e)
{
log.error("Error closing connection", e);
}
}
// Send events associcatd with the rescan
if (updateCompleted)
{
// Send all events created during rescan process to eventd
Iterator iter = m_eventList.iterator();
while (iter.hasNext())
{
try
{
EventIpcManagerFactory.getInstance().getManager().sendNow((Event)iter.next());
}
catch(Throwable t)
{
log.warn("run: unexpected throwable exception caught during send to middleware", t);
}
}
}
// Update the schedule information for the rescanned node
m_scheduledNode.setLastScanned(now);
m_scheduledNode.setScheduled(false);
log.debug("RescanProcessor for node w/ nodeid " + m_scheduledNode.getNodeId() + " completed.");
} // end run
/**
* Determines if any SNMP data collection related events need to
* be generated based upon the results of the current rescan. If
* necessary will generate one of the following events:
* 'reinitializePrimarySnmpInterface'
* 'primarySnmpInterfaceChanged'
*
* @param nodeEntry DbNodeEntry object of the node being rescanned.
* @param oldPrimarySnmpIf Previous primary SNMP interface (from the DB).
* @param primarySnmpIf Primary SNMP interface as determined by the
* current rescan.
*/
private void generateSnmpDataCollectionEvents(DbNodeEntry nodeEntry, InetAddress oldPrimarySnmpIf, InetAddress primarySnmpIf)
{
Category log = ThreadCategory.getInstance(getClass());
// NOTE: If SNMP service was not previously supported on this node
// then the 'oldPrimarySnmpIf' variable will be null.
// If this is the case then no need to generate primarySnmpInterfaceChanged
// event, the nodeGainedService event generated due to the addition
// of SNMP is sufficient.
if (oldPrimarySnmpIf == null && primarySnmpIf != null)
{
if (log.isDebugEnabled())
log.debug("generateSnmpDataCollectionEvents: looks like SNMP support was recently enabled on this node...");
}
// A PrimarySnmpInterfaceChanged event is generated if the scan
// found a different primary SNMP interface than what is stored
// in the database.
else if ( oldPrimarySnmpIf != null && primarySnmpIf != null &&
!oldPrimarySnmpIf.equals(primarySnmpIf) )
{
if (log.isDebugEnabled())
{
log.debug("generateSnmpDataCollectionEvents: primary SNMP interface has changed. Was: " +
oldPrimarySnmpIf.getHostAddress() + " Is: " +
primarySnmpIf.getHostAddress());
}
createPrimarySnmpInterfaceChangedEvent(nodeEntry.getNodeId(), primarySnmpIf, oldPrimarySnmpIf);
}
// An interface map is built by the SNMP poller when the primary
// SNMP interface is initialized by the service monitor. This map
// is used to associate each interface on the node with its
// ifIndex and ifLabel for purposes of performing data collection
// and storage. If an ifIndex has changed for one or more
// interfaces or if a new interface was added to the node then
// the primary SNMP interface must be reinitialized so that this
// interface map can be rebuilt with the new information.
else if (m_ifIndexOnNodeChangedFlag || m_snmpIfTableChangedFlag)
{
if (log.isDebugEnabled())
log.debug("generateSnmpDataCollectionEvents: Generating reinitializeSnmpInterface event for interface " + primarySnmpIf.getHostAddress());
createReinitializePrimarySnmpInterfaceEvent(nodeEntry.getNodeId(), primarySnmpIf);
}
}
/**
* This method is responsible for generating a nodeLabelChanged event and
* adding it to the event list.
*
* @param updatedEntry Updated node entry object
* @param originalEntry Original node entry object
*/
private void createNodeLabelChangedEvent(DbNodeEntry updatedEntry, DbNodeEntry originalEntry)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createNodeLabelChangedEvent: nodeId: " + updatedEntry.getNodeId() +
" oldLabel: '" + originalEntry.getLabel() +
"' oldSource: '" + originalEntry.getLabelSource() +
"' newLabel: '" + updatedEntry.getLabel() +
"' newLabelSource: '" + updatedEntry.getLabelSource() + "'");
Event newEvent = new Event();
newEvent.setUei(EventConstants.NODE_LABEL_CHANGED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(updatedEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
if (originalEntry.getLabel() != null)
{
// Add old node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_OLD_NODE_LABEL);
parmValue = new Value();
parmValue.setContent(originalEntry.getLabel());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add old node label source
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_OLD_NODE_LABEL_SOURCE);
parmValue = new Value();
parmValue.setContent(String.valueOf(originalEntry.getLabelSource()));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
if (updatedEntry.getLabel() != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NEW_NODE_LABEL);
parmValue = new Value();
parmValue.setContent(updatedEntry.getLabel());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add new node label source
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NEW_NODE_LABEL_SOURCE);
parmValue = new Value();
parmValue.setContent(String.valueOf(updatedEntry.getLabelSource()));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createNodeLabelChangedEvent: successfully created nodeLabelChanged event for nodeid: " + updatedEntry.getNodeId());
}
/**
* This method is responsible for generating a nodeInfoChanged event and
* adding it to the event list.
*
* @param updatedEntry Updated node entry object
* @param originalEntry Original node entry object
*/
private void createNodeInfoChangedEvent(DbNodeEntry updatedEntry, DbNodeEntry originalEntry)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createNodeInfoChangedEvent: nodeId: " + updatedEntry.getNodeId());
Event newEvent = new Event();
newEvent.setUei(EventConstants.NODE_INFO_CHANGED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(updatedEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// SysOID
if (updatedEntry.getSystemOID() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSOID);
parmValue = new Value();
parmValue.setContent(updatedEntry.getSystemOID());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// SysName
if (updatedEntry.getSystemName() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSNAME);
parmValue = new Value();
parmValue.setContent(updatedEntry.getSystemName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// SysDescription
if (updatedEntry.getSystemDescription() != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSDESCRIPTION);
parmValue = new Value();
parmValue.setContent(updatedEntry.getSystemDescription());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// SysLocation
if (updatedEntry.getSystemLocation() != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSLOCATION);
parmValue = new Value();
parmValue.setContent(updatedEntry.getSystemLocation());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// SysContact
if (updatedEntry.getSystemContact() != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSCONTACT);
parmValue = new Value();
parmValue.setContent(updatedEntry.getSystemContact());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// NetBIOS name
if (updatedEntry.getNetBIOSName() != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_NETBIOS_NAME);
parmValue = new Value();
parmValue.setContent(updatedEntry.getNetBIOSName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Domain name
if (updatedEntry.getDomainName() != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_DOMAIN_NAME);
parmValue = new Value();
parmValue.setContent(updatedEntry.getDomainName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Operating System
if (updatedEntry.getOS() != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_OPERATING_SYSTEM);
parmValue = new Value();
parmValue.setContent(updatedEntry.getOS());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
/// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createNodeInfoChangedEvent: successfully created nodeInfoChanged event for nodeid: " + updatedEntry.getNodeId());
}
/**
* This method is responsible for generating a primarySnmpInterfaceChanged event and
* adding it to the event list.
*
* @param nodeId Nodeid of node being rescanned.
* @param newPrimaryIf new primary SNMP interface address
* @param oldPrimaryIf old primary SNMP interface address
*/
private void createPrimarySnmpInterfaceChangedEvent(int nodeId,
InetAddress newPrimaryIf,
InetAddress oldPrimaryIf)
{
Category log = ThreadCategory.getInstance(getClass());
String oldPrimaryAddr = null;
if (oldPrimaryIf != null)
oldPrimaryAddr = oldPrimaryIf.getHostAddress();
String newPrimaryAddr = null;
if (newPrimaryIf != null)
newPrimaryAddr = newPrimaryIf.getHostAddress();
if (log.isDebugEnabled())
log.debug("createPrimarySnmpInterfaceChangedEvent: nodeId: " + nodeId +
"oldPrimarySnmpIf: '" + oldPrimaryAddr +
"' newPrimarySnmpIf: '" + newPrimaryAddr + "'");
Event newEvent = new Event();
newEvent.setUei(EventConstants.PRIMARY_SNMP_INTERFACE_CHANGED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeId);
newEvent.setInterface(newPrimaryAddr);
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setService("SNMP");
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
if (oldPrimaryAddr != null)
{
// Add old node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_OLD_PRIMARY_SNMP_ADDRESS);
parmValue = new Value();
parmValue.setContent(oldPrimaryAddr);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
if (newPrimaryAddr != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NEW_PRIMARY_SNMP_ADDRESS);
parmValue = new Value();
parmValue.setContent(newPrimaryAddr);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createPrimarySnmpInterfaceChangedEvent: successfully created primarySnmpInterfaceChanged event for nodeid: " + nodeId);
}
/**
* This method is responsible for generating a interfaceIndexChanged event and
* adding it to the event list.
*
* @param updatedEntry updated IP interface database entry
* @param originalEntry original IP interface database entry
*/
private void createInterfaceIndexChangedEvent(DbIpInterfaceEntry updatedEntry, DbIpInterfaceEntry originalEntry)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createInterfaceIndexChangedEvent: nodeId: " + updatedEntry.getNodeId() +
" oldIfIndex: " + originalEntry.getIfIndex() +
" newIfIndex: " + updatedEntry.getIfIndex());
Event newEvent = new Event();
newEvent.setUei(EventConstants.INTERFACE_INDEX_CHANGED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(updatedEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(updatedEntry.getIfAddress().getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add old interface index
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_OLD_IFINDEX);
parmValue = new Value();
parmValue.setContent(String.valueOf(originalEntry.getIfIndex()));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add new interface index
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NEW_IFINDEX);
parmValue = new Value();
parmValue.setContent(String.valueOf(updatedEntry.getIfIndex()));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createInterfaceIndexChangedEvent: successfully created interfaceIndexChanged event for nodeid: " + updatedEntry.getNodeId());
}
/**
* This method is responsible for generating an ipHostNameChanged event and
* adding it to the event list.
*
* @param updatedEntry updated IP interface database entry
* @param originalEntry original IP interface database entry
*/
private void createIpHostNameChangedEvent(DbIpInterfaceEntry updatedEntry, DbIpInterfaceEntry originalEntry)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createIpHostNameChangedEvent: nodeId: " + updatedEntry.getNodeId() +
" oldHostName: " + originalEntry.getHostname() +
" newHostName: " + updatedEntry.getHostname());
Event newEvent = new Event();
newEvent.setUei(EventConstants.INTERFACE_IP_HOSTNAME_CHANGED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(updatedEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(updatedEntry.getIfAddress().getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add old IP Hostname
if (originalEntry.getHostname() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_OLD_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(originalEntry.getHostname());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add new IP Hostname
if (updatedEntry.getHostname() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(updatedEntry.getHostname());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createIpHostNameChangedEvent: successfully created ipHostNameChanged event for nodeid: " + updatedEntry.getNodeId());
}
/**
* This method is responsible for generating a interfaceReparented event and
* adding it to the event list.
*
* @param newNode Entry of node under which the interface was added.
* @param oldNodeId Node identifier of node from which the interface was removed.
* @param reparentedIf Reparented interface
*/
private void createInterfaceReparentedEvent(DbNodeEntry newNode,
int oldNodeId,
InetAddress reparentedIf)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createInterfaceReparentedEvent: ifAddr: " + reparentedIf.getHostAddress() +
" oldNodeId: " + oldNodeId + " newNodeId: " + newNode.getNodeId());
Event newEvent = new Event();
newEvent.setUei(EventConstants.INTERFACE_REPARENTED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(newNode.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(reparentedIf.getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add old node id
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_OLD_NODEID);
parmValue = new Value();
parmValue.setContent(String.valueOf(oldNodeId));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add new node id
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NEW_NODEID);
parmValue = new Value();
parmValue.setContent(String.valueOf(newNode.getNodeId()));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add ip host name
String hostname = reparentedIf.getHostName();
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(hostname);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add node label and node label source
if (newNode.getLabel() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_LABEL);
parmValue = new Value();
parmValue.setContent(newNode.getLabel());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_LABEL_SOURCE);
parmValue = new Value();
parmValue.setContent(String.valueOf(newNode.getLabelSource()));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add nodeSysName
if (newNode.getSystemName() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSNAME);
parmValue = new Value();
parmValue.setContent(newNode.getSystemName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add nodeSysDescription
if (newNode.getSystemDescription() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSDESCRIPTION);
parmValue = new Value();
parmValue.setContent(newNode.getSystemDescription());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createInterfaceReparentedEvent: successfully created interfaceReparented event for nodeid/interface: " +
newNode.getNodeId() + "/" + reparentedIf.getHostAddress());
}
/**
* This method is responsible for generating a duplicateNodeDeleted event and
* adding it to the event list.
*
* @param deletedNode Entry of duplciate node which was deleted.
*/
private void createDuplicateNodeDeletedEvent(DbNodeEntry deletedNode)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createDuplicateNodeDeletedEvent: delete nodeid: " + deletedNode.getNodeId());
Event newEvent = new Event();
newEvent.setUei(EventConstants.DUP_NODE_DELETED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(deletedNode.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createDuplicateNodeDeletedEvent: successfully created duplicateNodeDeleted event for nodeid: " + deletedNode.getNodeId());
}
/**
* This method is responsible for generating a nodeGainedInterface event and
* adding it to the event list.
*
* @param ifEntry Entry of new interface.
*/
private void createNodeGainedInterfaceEvent(DbIpInterfaceEntry ifEntry)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createNodeGainedInterfaceEvent: nodeId: " + ifEntry.getNodeId() +
" interface: " + ifEntry.getIfAddress().getHostAddress());
Event newEvent = new Event();
newEvent.setUei(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(ifEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(ifEntry.getIfAddress().getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add ip host name
String hostname = null;
if (ifEntry.getHostname() == null)
hostname = "";
else
hostname = ifEntry.getHostname();
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(hostname);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add discovery method
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_METHOD);
parmValue = new Value();
parmValue.setContent("icmp");
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createNodeGainedInterfaceEvent: successfully created nodeGainedInterface event for nodeid: " + ifEntry.getNodeId());
}
/**
* This method is responsible for generating a duplicateIpAddress event and
* adding it to the event list.
*
* @param ifEntry Entry of new interface.
*/
private void createDuplicateIpAddressEvent(DbIpInterfaceEntry ifEntry)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createDuplicateIpAddressEvent: nodeId: " + ifEntry.getNodeId() +
" interface: " + ifEntry.getIfAddress().getHostAddress());
Event newEvent = new Event();
newEvent.setUei(EventConstants.DUPLICATE_IPINTERFACE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(ifEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(ifEntry.getIfAddress().getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add ip host name
String hostname = null;
if (ifEntry.getHostname() == null)
hostname = "";
else
hostname = ifEntry.getHostname();
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(hostname);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add discovery method
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_METHOD);
parmValue = new Value();
parmValue.setContent("icmp");
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createDuplicateIpAddressEvent: successfully created duplicateIpAddress event for nodeid: "
+ ifEntry.getNodeId());
}
/**
* This method is responsible for generating a nodeGainedService event and
* adding it to the event list.
*
* @param nodeEntry Entry of node which has gained a service
* @param ifEntry Entry of interface which has gained a service
* @param svcName Service name
*/
private void createNodeGainedServiceEvent(DbNodeEntry nodeEntry, DbIpInterfaceEntry ifEntry, String svcName)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createNodeGainedServiceEvent: nodeId: " + ifEntry.getNodeId() +
" interface: " + ifEntry.getIfAddress().getHostAddress() +
" service: " + svcName);
Event newEvent = new Event();
newEvent.setUei(EventConstants.NODE_GAINED_SERVICE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(ifEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(ifEntry.getIfAddress().getHostAddress());
newEvent.setService(svcName);
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add ip host name
String hostname = null;
if (ifEntry.getHostname() == null)
hostname = "";
else
hostname = ifEntry.getHostname();
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(hostname);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add nodeSysName
if (nodeEntry.getSystemName() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSNAME);
parmValue = new Value();
parmValue.setContent(nodeEntry.getSystemName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add nodeSysDescription
if (nodeEntry.getSystemDescription() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSDESCRIPTION);
parmValue = new Value();
parmValue.setContent(nodeEntry.getSystemDescription());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createNodeGainedServiceEvent: successfully created nodeGainedService event for nodeid: " + ifEntry.getNodeId());
}
/**
* This method is responsible for generating a interfaceSupportsSNMPEvent event and
* adding it to the event list.
*
* @param ifEntry Entry of interface which has gained a service
*/
private void createInterfaceSupportsSNMPEvent(DbIpInterfaceEntry ifEntry)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("createInterfaceSupportsSNMPEvent: nodeId: " + ifEntry.getNodeId() +
" interface: " + ifEntry.getIfAddress().getHostAddress());
Event newEvent = new Event();
newEvent.setUei(EventConstants.INTERFACE_SUPPORTS_SNMP_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(ifEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(ifEntry.getIfAddress().getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("interfaceSupportsSNMPEvent: successfully created interfaceSupportsSNMPEvent event for nodeid: " + ifEntry.getNodeId());
}
/**
* This method is responsible for generating a reinitializePrimarySnmpInterface
* event and adding it to the event list.
*
* @param nodeId Nodeid of node being rescanned.
* @param InetAddress Primary SNMP interface address.
*/
private void createReinitializePrimarySnmpInterfaceEvent(int nodeId, InetAddress primarySnmpIf)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("reinitializePrimarySnmpInterface: nodeId: " + nodeId +
" interface: " + primarySnmpIf.getHostAddress());
Event newEvent = new Event();
newEvent.setUei(EventConstants.REINITIALIZE_PRIMARY_SNMP_INTERFACE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeId);
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(primarySnmpIf.getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add event to the list of events to be sent out.
m_eventList.add(newEvent);
if (log.isDebugEnabled())
log.debug("createReinitializePrimarySnmpInterfaceEvent: successfully created reinitializePrimarySnmpInterface event for interface: " + primarySnmpIf.getHostAddress());
}
} // end class
|
//This file is part of the OpenNMS(R) Application.
//OpenNMS(R) is a derivative work, containing both original code, included code and modified
//and included code are below.
//OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//This program is free software; you can redistribute it and/or modify
//(at your option) any later version.
//This program is distributed in the hope that it will be useful,
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//For more information contact:
package org.opennms.netmgt.collectd;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.BeanInfo;
import org.opennms.netmgt.config.DatabaseConnectionFactory;
import org.opennms.netmgt.config.JMXDataCollectionConfigFactory;
import org.opennms.netmgt.config.collectd.Attrib;
import org.opennms.netmgt.poller.monitors.NetworkInterface;
import org.opennms.netmgt.rrd.RRDDataSource;
import org.opennms.netmgt.rrd.RrdException;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.utils.EventProxy;
import org.opennms.netmgt.utils.ParameterMap;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.protocols.jmx.connectors.ConnectionWrapper;
public abstract class JMXCollector implements ServiceCollector {
/**
* SQL statement to retrieve interface's 'ipinterface' table information.
*/
private static final String SQL_GET_NODEID = "SELECT nodeid FROM ipinterface WHERE ipaddr=? AND ismanaged!='D'";
/**
* Interface attribute key used to store the map of IfInfo objects which
* hold data about each interface on a particular node.
*/
static String IF_MAP_KEY = "org.opennms.netmgt.collectd.JBossCollector.ifMap";
/**
* RRD data source name max length.
*/
private static final int MAX_DS_NAME_LENGTH = 19;
/**
* Path to JMX RRD file repository.
*/
private String m_rrdPath = null;
/**
* Local host name
*/
private String m_host;
/*
* In some circumstances there may be many instances of a given service but running on
* different ports. Rather than using the port as the identfier users may define a more
* meaninful name.
*/
private boolean useFriendlyName = false;
/* Attr key names */
/**
* Interface attribute key used to store a JMXNodeInfo object which holds
* data about the node being polled.
*/
static String NODE_INFO_KEY = "org.opennms.netmgt.collectd.JMXCollector.nodeInfo";
static String MAX_VARS_PER_PDU_STORAGE_KEY = "org.opennms.netmgt.collectd.JMXCollector.maxVarsPerPdu";
/*
* The service name is provided by the derived class
*/
private String serviceName = null;
/**
* <P>
* Returns the name of the service that the plug-in collects ("JMX").
* </P>
*
* @return The service that the plug-in collects.
*/
public String serviceName() {
return serviceName.toUpperCase();
}
public void setServiceName(String name) {
serviceName = name;
}
/**
* <P>
* Initialize the service collector.
* </P>
*
* <P>
* During initialization the JMX collector: - Initializes various
* configuration factories. - Verifies access to the database - Verifies
* access to RRD file repository - Verifies access to JNI RRD shared library -
* Determines if JMX to be stored for only the node'sprimary interface or
* for all interfaces.
* </P>
*
* @param parameters
* Not currently used.
*
* @exception RuntimeException
* Thrown if an unrecoverable error occurs that prevents the
* plug-in from functioning.
*
*/
public void initialize(Map parameters) {
// Log4j category
Category log = ThreadCategory.getInstance(getClass());
// Get local host name (used when generating threshold events)
try {
m_host = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
if (log.isEnabledFor(Priority.WARN))
log.warn("initialize: Unable to resolve local host name.", e);
m_host = "unresolved.host";
}
// Initialize the JMXDataCollectionConfigFactory
try {
JMXDataCollectionConfigFactory.reload();
} catch (MarshalException ex) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: Failed to load data collection configuration",ex);
throw new UndeclaredThrowableException(ex);
} catch (ValidationException ex) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: Failed to load data collection configuration",ex);
throw new UndeclaredThrowableException(ex);
} catch (IOException ex) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: Failed to load data collection configuration",ex);
throw new UndeclaredThrowableException(ex);
}
// Make sure we can connect to the database
java.sql.Connection ctest = null;
try {
DatabaseConnectionFactory.init();
ctest = DatabaseConnectionFactory.getInstance().getConnection();
} catch (IOException ie) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: IOException getting database connection", ie);
throw new UndeclaredThrowableException(ie);
} catch (MarshalException me) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: Marshall Exception getting database connection",me);
throw new UndeclaredThrowableException(me);
} catch (ValidationException ve) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: Validation Exception getting database connection",ve);
throw new UndeclaredThrowableException(ve);
} catch (SQLException sqlE) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: Failed getting connection to the database.",sqlE);
throw new UndeclaredThrowableException(sqlE);
} catch (ClassNotFoundException cnfE) {
if (log.isEnabledFor(Priority.FATAL))
log.fatal("initialize: Failed loading database driver.", cnfE);
throw new UndeclaredThrowableException(cnfE);
} finally {
if (ctest != null) {
try {
ctest.close();
} catch (Throwable t) {
if (log.isEnabledFor(Priority.WARN))
log.warn("initialize: an exception occured while closing the JDBC connection",t);
}
}
}
// Save local reference to singleton instance
// m_rrdInterface = org.opennms.netmgt.rrd.Interface.getInstance();
if (log.isDebugEnabled())
log.debug("initialize: successfully instantiated JNI interface to RRD...");
return;
}
private void initRRD() {
Category log = ThreadCategory.getInstance(getClass());
// Get path to RRD repository
m_rrdPath = JMXDataCollectionConfigFactory.getInstance().getRrdRepository();
if (m_rrdPath == null)
throw new RuntimeException(
"Configuration error, failed to retrieve path to RRD repository.");
// Strip the File.separator char off of the end of the path
if (m_rrdPath.endsWith(File.separator)) {
m_rrdPath = m_rrdPath.substring(0,(m_rrdPath.length() - File.separator.length()));
}
if (log.isDebugEnabled())
log.debug("initialize: " + serviceName + " RRD file repository path: " + m_rrdPath);
// If the RRD file repository directory does NOT already exist, create
File f = new File(m_rrdPath);
if (!f.isDirectory())
if (!f.mkdirs())
throw new RuntimeException("Unable to create RRD file repository, path: " + m_rrdPath);
try {
RrdUtils.initialize();
} catch (RrdException e) {
if (log.isEnabledFor(Priority.ERROR))
log.error("initialize: Unable to initialize RrdUtils", e);
throw new RuntimeException("Unable to initialize RrdUtils", e);
}
}
/**
*
* Responsible for freeing up any resources held by the collector.
*/
public void release() {
// Nothing to release...
}
/**
* Responsible for performing all necessary initialization for the specified
* interface in preparation for data collection.
*
* @param iface
* Network interface to be prepped for collection.
* @param parameters
* Key/value pairs associated with the package to which the
* interface belongs..
*
*/
public void initialize(NetworkInterface iface, Map parameters) {
Category log = ThreadCategory.getInstance(getClass());
InetAddress ipAddr = (InetAddress) iface.getAddress();
log.debug("initialize: " + m_rrdPath);
if (m_rrdPath == null) {
initRRD();
}
if (log.isDebugEnabled())
log.debug("initialize: InetAddress=" + ipAddr.getHostAddress());
// Retrieve the name of the JMX data collector
String collectionName = ParameterMap.getKeyedString(parameters,"collection", serviceName);
if (log.isDebugEnabled())
log.debug("initialize: collectionName=" + collectionName);
java.sql.Connection dbConn = null;
try {
dbConn = DatabaseConnectionFactory.getInstance().getConnection();
} catch (SQLException sqlE) {
if (log.isEnabledFor(Priority.ERROR))
log.error("initialize: Failed getting connection to the database.",sqlE);
throw new UndeclaredThrowableException(sqlE);
}
int nodeID = -1;
// Prepare & execute the SQL statement to get the 'nodeid' from the
// ipInterface table 'nodeid' will be used to retrieve the node's
// system object id from the node table.
// In addition to nodeid, the interface's ifIndex
// fields are also retrieved.
PreparedStatement stmt = null;
try {
stmt = dbConn.prepareStatement(SQL_GET_NODEID);
stmt.setString(1, ipAddr.getHostAddress()); // interface address
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
nodeID = rs.getInt(1);
if (rs.wasNull())
nodeID = -1;
} else {
nodeID = -1;
}
rs.close();
} catch (SQLException sqle) {
if (log.isDebugEnabled())
log.debug("initialize: SQL exception!!", sqle);
throw new RuntimeException(
"SQL exception while attempting to retrieve node id for interface "
+ ipAddr.getHostAddress());
} finally {
try {
stmt.close();
dbConn.close();
} catch (Exception e) {
// Ignore
}
}
JMXNodeInfo nodeInfo = new JMXNodeInfo(nodeID);
log.debug("nodeInfo: " + ipAddr.getHostAddress() + " " + nodeID + " " + iface);
// Retrieve list of MBean objects to be collected from the
// remote agent which are to be stored in the node-level RRD file.
// These objects pertain to the node itself not any individual
// interfaces.
List attrList = JMXDataCollectionConfigFactory.getInstance().getAttributeList(collectionName, serviceName, ipAddr.getHostAddress());
nodeInfo.setAttributeList(attrList);
HashMap dsList = buildDataSourceList(collectionName, attrList);
nodeInfo.setDsMap(dsList);
nodeInfo.setMBeans(JMXDataCollectionConfigFactory.getInstance().getMBeanInfo(collectionName));
// Add the JMXNodeInfo object as an attribute of the interface
iface.setAttribute(NODE_INFO_KEY, nodeInfo);
iface.setAttribute("collectionName", collectionName);
File repos = new File(m_rrdPath + "/" + nodeID + "/" + collectionName);
if (!repos.exists()) {
repos.mkdir();
}
}
/**
*
* Responsible for releasing any resources associated with the specified
* interface.
*
* @param iface
* Network interface to be released.
*/
public void release(NetworkInterface iface) {
// Nothing to release...
}
public abstract ConnectionWrapper getMBeanServerConnection(Map parameterMap, InetAddress address);
/**
* Perform data collection.
*
* @param iface
* Network interface to be data collected
* @param eproxy
* Eventy proxy for sending events.
* @param parameters
* Key/value pairs from the package to which the interface
* belongs.
*/
public int collect(NetworkInterface iface, EventProxy eproxy, Map map) {
Category log = ThreadCategory.getInstance(getClass());
InetAddress ipaddr = (InetAddress) iface.getAddress();
String collectionName = (String) iface.getAttribute("collectionName");
JMXNodeInfo nodeInfo = (JMXNodeInfo) iface.getAttribute(NODE_INFO_KEY);
HashMap list = nodeInfo.getDsMap();
HashMap mbeans = nodeInfo.getMBeans();
String collDir = serviceName;
ConnectionWrapper connection = null;
log.debug("collect " + ipaddr.getHostAddress() + " " + nodeInfo.getNodeId() + " " + m_rrdPath);
try {
String rrdPath = ParameterMap.getKeyedString( map, "rrdRepository", null);
int retry = ParameterMap.getKeyedInteger(map, "retry", 3);
String port = ParameterMap.getKeyedString( map, "port", null);
String friendlyName = ParameterMap.getKeyedString( map, "friendly-name", port);
InetAddress ipv4Addr = (InetAddress)iface.getAddress();
connection = getMBeanServerConnection(map, ipaddr);
if (connection == null) {
return COLLECTION_FAILED;
}
MBeanServerConnection mbeanServer = connection.getMBeanServer();
int serviceStatus = COLLECTION_FAILED;
if (useFriendlyName) {
collDir = friendlyName;
}
for (int attempts = 0; attempts <= retry; attempts++) {
try {
/*
* Iterate over the mbeans, for each object name perform a
* getAttributes, the update the RRD.
*/
for (Iterator iter = mbeans.values().iterator(); iter.hasNext();) {
BeanInfo beanInfo = (BeanInfo) iter.next();
String objectName = beanInfo.getObjectName();
String excludeList = beanInfo.getExcludes();
String[] attrNames = beanInfo.getAttributeNames();
if (objectName.indexOf("*") == -1) {
log.debug(serviceName + " Collector - getAttributes: " + objectName + " #attributes: " + attrNames.length);
try {
ObjectName oName = new ObjectName(objectName);
if (mbeanServer.isRegistered(oName)) {
AttributeList attrList = (AttributeList) mbeanServer.getAttributes(oName,attrNames);
updateRRDs(collectionName, iface, attrList, collDir, null, null);
}
} catch (InstanceNotFoundException e2) {
log.error("Unable to retrieve attributes from " + objectName);
}
}
else {
Set mbeanSet = mbeanServer.queryNames(new ObjectName(objectName),null);
for (Iterator objectNameIter = mbeanSet.iterator(); objectNameIter.hasNext();) {
ObjectName oName = (ObjectName)objectNameIter.next();
log.debug(serviceName + " Collector - getAttributesWC: " + oName + " #attributes: " + attrNames.length + " " + beanInfo.getKeyAlias());
try {
if (excludeList == null) {
/*
* the exclude list doesn't apply
*/
if (mbeanServer.isRegistered(oName)) {
AttributeList attrList = (AttributeList) mbeanServer.getAttributes(oName, attrNames);
updateRRDs(collectionName,
iface,
attrList,
collDir,
oName.getKeyProperty(beanInfo.getKeyField()),
beanInfo.getKeyAlias());
}
}
else {
/*
* filter out calls if the key field matches an entry in the exclude list
*/
String keyName = oName.getKeyProperty(beanInfo.getKeyField());
boolean found = false;
StringTokenizer st = new StringTokenizer(excludeList, ",");
while (st.hasMoreTokens()) {
if (keyName.equals(st.nextToken())) {
found = true;
break;
}
}
if (!found) {
if (mbeanServer.isRegistered(oName)) {
AttributeList attrList = (AttributeList) mbeanServer.getAttributes(oName, attrNames);
updateRRDs(collectionName,
iface,
attrList,
collDir,
oName.getKeyProperty(beanInfo.getKeyField()),
beanInfo.getKeyAlias());
}
}
}
} catch (InstanceNotFoundException e2) {
log.error("Error retrieving attributes for " + oName);
}
}
}
serviceStatus = COLLECTION_SUCCEEDED;
}
break;
}
catch (Exception e) {
e.fillInStackTrace();
log.debug(serviceName + " Collector.collect: IOException while collect address: " + iface.getAddress(), e);
}
} // of for
} catch (Exception e1) {
log.error("Error getting MBeanServer");
} finally {
if (connection != null) {
connection.close();
}
}
// return the status of the collection
return COLLECTION_SUCCEEDED;
}
public boolean createRRD(String collectionName,
InetAddress ipaddr,
String directory,
RRDDataSource ds,
String collectionDir,
String keyField)
throws RrdException {
String creator = "primary " + serviceName + " interface " + ipaddr.getHostAddress();
int step = JMXDataCollectionConfigFactory.getInstance().getStep(collectionName);
List rraList = JMXDataCollectionConfigFactory.getInstance().getRRAList(collectionName);
File repos = new File(directory + "/" + collectionDir);
if (!repos.exists()) {
repos.mkdir();
}
if (keyField == null) {
return RrdUtils.createRRD(creator,
directory + "/" + collectionDir,
ds.getName(),
step,
ds.getType(),
ds.getHeartbeat(),
ds.getMin(),
ds.getMax(),
rraList);
}
else {
if (keyField.equals("")) {
return RrdUtils.createRRD(creator,
directory + "/" + collectionDir,
ds.getName(),
step,
ds.getType(),
ds.getHeartbeat(),
ds.getMin(),
ds.getMax(),
rraList);
}
else {
return RrdUtils.createRRD(creator,
directory + "/" + collectionDir,
keyField + "_" + ds.getName(),
step,
ds.getType(),
ds.getHeartbeat(),
ds.getMin(),
ds.getMax(),
rraList);
}
}
}
/**
* This method is responsible for building an RRDTool style 'update' command
* which is issued via the RRD JNI interface in order to push the latest
* JMX-collected values into the interface's RRD database.
*
* @param collectionName
* JMX data Collection name from 'jmx-datacollection-config.xml'
* @param iface
* NetworkInterface object of the interface currently being
* polled
* @param nodeCollector
* Node level MBean data collected via JMX for the polled
* interface
* @param ifCollector
* Interface level MBean data collected via JMX for the polled
* interface
*
* @exception RuntimeException
* Thrown if the data source list for the interface is null.
*/
private boolean updateRRDs(String collectionName,
NetworkInterface iface,
AttributeList attributeList,
String collectionDir,
String keyField,
String substitutions) {
Category log = ThreadCategory.getInstance(getClass());
InetAddress ipaddr = (InetAddress) iface.getAddress();
JMXNodeInfo nodeInfo = (JMXNodeInfo) iface.getAttribute(NODE_INFO_KEY);
boolean rrdError = false;
// Node data
log.debug("updateRRDs: processing node-level collection...");
// Build path to node RRD repository. createRRD() will make the
// appropriate directories if they do not already exist.
String nodeRepository = m_rrdPath + File.separator + String.valueOf(nodeInfo.getNodeId());
// Iterate over the node datasource list and issue RRD update
// commands to update each datasource which has a corresponding
// value in the collected JMX data
HashMap dsMap = nodeInfo.getDsMap();
try {
for (int i = 0; i < attributeList.size(); i++) {
Attribute attribute = (Attribute) attributeList.get(i);
RRDDataSource ds = (RRDDataSource) dsMap.get(attribute.getName());
if (keyField == null) {
try {
createRRD(collectionName, ipaddr, nodeRepository, ds, collectionDir, null);
RrdUtils.updateRRD(ipaddr.getHostAddress(),
nodeRepository + "/" + collectionDir,
ds.getName(),
"" + attribute.getValue());
} catch (Throwable e1) {
}
}
else {
try {
String key = fixKey(keyField, ds.getName(), substitutions);
createRRD(collectionName, ipaddr, nodeRepository, ds, collectionDir, key);
if (key.equals("")) {
RrdUtils.updateRRD(ipaddr.getHostAddress(),
nodeRepository + "/" + collectionDir,
ds.getName(),
"" + attribute.getValue());
}
else {
RrdUtils.updateRRD(ipaddr.getHostAddress(),
nodeRepository + "/" + collectionDir,
key + "_" + ds.getName(),
"" + attribute.getValue());
}
} catch (Throwable e1) {
//log.debug("Error updating: " ds.getName());
}
}
try {
Thread.sleep(1100);
}catch (Exception te) {
}
}
} catch (Throwable e) {
//log.error("RRD Error", e);
rrdError = true;
}
return rrdError;
}
private String fixKey(String key, String attrName, String substitutions) {
String newKey = key;
if (key.startsWith("/")) {
newKey = key.substring(1);
}
if (substitutions != null && substitutions.length() > 0) {
StringTokenizer st = new StringTokenizer(substitutions, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken();
int index = token.indexOf("|");
if (newKey.equals(token.substring(0,index))) {
newKey = token.substring(index+1);
}
}
}
return newKey;
}
/**
* @param ds
* @param collectorEntry
* @param
* @param dsVal
* @return
* @throws Exception
*/
public String getRRDValue(RRDDataSource ds, JMXCollectorEntry collectorEntry)
throws IllegalArgumentException {
Category log = ThreadCategory.getInstance(getClass());
String dsVal = null;
// Make sure we have an actual object id value.
if (ds.getOid() == null)
return null;
return (String) collectorEntry.get(ds.getOid());
}
/**
* This method is responsible for building a list of RRDDataSource objects
* from the provided list of MBeanObject objects.
*
* @param collectionName
* Collection name
* @param oidList
* List of MBeanObject objects defining the oid's to be collected
* via JMX.
*
* @return list of RRDDataSource objects
*/
private HashMap buildDataSourceList(String collectionName, List attributeList) {
// Log4j category
Category log = ThreadCategory.getInstance(getClass());
// Retrieve the RRD expansion data source list which contains all
// the expansion data source's. Use this list as a basis
// for building a data source list for the current interface.
HashMap dsList = new HashMap();
// Loop through the MBean object list to be collected for this interface
// and add a corresponding RRD data source object. In this manner
// each interface will have RRD files create which reflect only the data
// sources pertinent to it.
Iterator o = attributeList.iterator();
while (o.hasNext()) {
Attrib attr = (Attrib) o.next();
RRDDataSource ds = null;
// Verify that this object has an appropriate "integer" data type
// which can be stored in an RRD database file (must map to one of
// the supported RRD data source types: COUNTER or GAUGE).
String ds_type = RRDDataSource.mapType(attr.getType());
if (ds_type != null) {
// Passed!! Create new data source instance for this MBean
// object
// Assign heartbeat using formula (2 * step) and hard code
// min & max values to "U" ("unknown").
ds = new RRDDataSource();
ds.setHeartbeat(2 * JMXDataCollectionConfigFactory
.getInstance().getStep(collectionName));
// For completeness, adding a minval option to the variable.
String ds_minval = attr.getMinval();
if (ds_minval == null) {
ds_minval = "U";
}
ds.setMax(ds_minval);
// In order to handle counter wraps, we need to set a max
// value for the variable.
String ds_maxval = attr.getMaxval();
if (ds_maxval == null) {
ds_maxval = "U";
}
ds.setMax(ds_maxval);
ds.setInstance(collectionName);
// Truncate MBean object name/alias if it exceeds 19 char max
// for
// RRD data source names.
String ds_name = attr.getAlias();
if (ds_name.length() > MAX_DS_NAME_LENGTH) {
if (log.isEnabledFor(Priority.WARN))
log.warn("buildDataSourceList: alias '"
+ attr.getAlias()
+ "' exceeds 19 char maximum for RRD data source names, truncating.");
char[] temp = ds_name.toCharArray();
ds_name = String.copyValueOf(temp, 0, MAX_DS_NAME_LENGTH);
}
ds.setName(ds_name);
// Map MBean object data type to RRD data type
ds.setType(ds_type);
// Assign the data source object identifier and instance
//ds.setName(attr.getName());
ds.setOid(attr.getName());
if (log.isDebugEnabled())
log.debug("buildDataSourceList: ds_name: " + ds.getName()
+ " ds_oid: " + ds.getOid() + "."
+ ds.getInstance() + " ds_max: " + ds.getMax()
+ " ds_min: " + ds.getMin());
// Add the new data source to the list
dsList.put(attr.getName(), ds);
} else if (log.isEnabledFor(Priority.WARN)) {
log.warn("buildDataSourceList: Data type '"
+ attr.getType()
+ "' not supported. Only integer-type data may be stored in RRD.");
log.warn("buildDataSourceList: MBean object '"
+ attr.getAlias()
+ "' will not be mapped to RRD data source.");
}
}
return dsList;
}
/**
* This method is responsible for building a Capsd forceRescan event object
* and sending it out over the EventProxy.
*
* @param ifAddress
* interface address to which this event pertains
* @param eventProxy
* proxy over which an event may be sent to eventd
*/
private void generateForceRescanEvent(String ifAddress, EventProxy eventProxy) {
// Log4j category
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("generateForceRescanEvent: interface = " + ifAddress + " serviceName: " + serviceName);
// create the event to be sent
Event newEvent = new Event();
newEvent.setUei(EventConstants.FORCE_RESCAN_EVENT_UEI);
newEvent.setSource(serviceName.toUpperCase() + "ServiceMonitor");
newEvent.setInterface(ifAddress);
newEvent.setService(serviceName.toUpperCase());
if (m_host != null)
newEvent.setHost(m_host);
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Send event via EventProxy
try {
eventProxy.send(newEvent);
} catch (Exception e) {
if (log.isEnabledFor(Priority.ERROR))
log.error("generateForceRescanEvent: Unable to send forceRescan event.", e);
}
}
/**
* @param useFriedlyName The useFriedlyName to set.
*/
public void setUseFriendlyName(boolean useFriendlyName) {
this.useFriendlyName = useFriendlyName;
}
}
|
package cmput301f17t01.bronzify;
import android.drm.DrmStore;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.contrib.DrawerActions;
import android.support.test.espresso.contrib.NavigationViewActions;
import android.support.test.espresso.contrib.PickerActions;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.ThrowOnExtraProperties;
import org.hamcrest.Matchers;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import java.util.Calendar;
import java.util.Date;
import cmput301f17t01.bronzify.activities.LoginActivity;
import cmput301f17t01.bronzify.activities.MyHomeActivity;
import static android.support.test.espresso.Espresso.onData;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.isDialog;
import static android.support.test.espresso.matcher.ViewMatchers.hasSibling;
import static android.support.test.espresso.matcher.ViewMatchers.isClickable;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.isSelected;
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withInputType;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.text.InputType.TYPE_CLASS_TEXT;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anything;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.core.StringStartsWith.startsWith;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@LargeTest
public class EspressoTesting {
@Rule
public ActivityTestRule<LoginActivity> mActivityRule =
new ActivityTestRule(LoginActivity.class);
/**
* This test case will create the users with the name "test_user_001", "test_user_001"
* and "follow_user_001". It is commented out, because the users are already created.
* It can easily be run to create the users in a single step.
*
*/
@Test
public void test0CreateUsers() {
//Create user "test_user_001"
onView(withId(R.id.enter_id)).perform(typeText("test_user_001"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_001")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.register_button)).perform(click());
onView(withId(R.id.enter_id)).perform(clearText());
//Create user "follow_user_001"
onView(withId(R.id.enter_id)).perform(typeText("follow_user_001"));
onView(withId(R.id.enter_id)).check(matches(withText("follow_user_001")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.register_button)).perform(click());
onView(withId(R.id.enter_id)).perform(clearText());
//Create user "follow_user_002"
onView(withId(R.id.enter_id)).perform(typeText("follow_user_002"));
onView(withId(R.id.enter_id)).check(matches(withText("follow_user_002")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.register_button)).perform(click());
}
/**
* This test case will create a new habit type, with the name Running. It will
* log in and log out, and ensure that the data entered is correct
*
*/
@Test
public void test1CreateNewHabitType() {
//Login
onView(withId(R.id.enter_id)).perform(typeText("test_user_001"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_001")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHabits));
//Create a new habit
onView(withId(R.id.createNewHabit)).perform(click());
onView(withId(R.id.textHabitName)).perform(typeText("Running"));
onView(withId(R.id.textHabitName)).check(matches(withText("Running")));
onView(withId(R.id.textHabitReason)).perform(typeText("Get fit"));
onView(withId(R.id.textHabitReason)).check(matches(withText("Get fit")));
onView(withId(R.id.buttonSelectDate)).perform(click());
onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(2017, 12, 5));
onView(withText("OK")).perform(click());
onView(withId(R.id.buttonMonday)).perform(click());
onView(withId(R.id.buttonWednesday)).perform(click());
onView(withId(R.id.buttonFriday)).perform(click());
onView(withId(R.id.buttonCreate)).perform(closeSoftKeyboard());
onView(withId(R.id.buttonCreate)).perform(click());
//Logout
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.LogOut));
}
/**
* This test case will edit the habit type that was created in test1. It will change the name
* of the habit from "Running" to "Skating", as well as removing Wednesday from the recurring
* days every week.
*
*/
@Test
public void test2EditHabitType() {
//Login
onView(withId(R.id.enter_id)).perform(typeText("test_user_001"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_001")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHabits));
//Click on the correct habit in the list
onView(withId(R.id.habitTypeRow)).check(matches(withText(containsString("Running"))));
onView(withId(R.id.habitTypeRow)).perform(click());
//Edit the parameters of the habit
onView(withId(R.id.buttonEdit)).perform(click());
//onData(withId(R.id.textHabitName)).atPosition(0).perform(click());
onView(withId(R.id.textHabitName)).perform(replaceText("Skating"));
//onView(withText("Running")).perform(click());
//onView(withText("Running")).perform(replaceText("Skating"));
onView(withId(R.id.buttonEdit)).perform(closeSoftKeyboard());
onView(withId(R.id.buttonWednesday)).perform(click());
onView(withId(R.id.buttonEdit)).perform(click());
//Logout
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.LogOut));
}
/**
* This test case will delete the habit type that was created in test2. The habit event skating
* will no longer exist after it has been run.
*
*/
@Test
public void test3DeleteHabitType() {
//Login
onView(withId(R.id.enter_id)).perform(typeText("test_user_001"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_001")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHabits));
//Click on the correct habit in the list
onView(withId(R.id.habitTypeRow)).check(matches(withText(containsString("Skating"))));
onView(withId(R.id.habitTypeRow)).perform(click());
//Delete the habit
onView(withId(R.id.buttonEdit)).perform(click());
onView(withId(R.id.buttonDelete)).perform(click());
//Logout
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.LogOut));
}
/**
* This test case will log in as "follow_user_001" and will follow the user "test_user_001".
* Then "test_user_001" will log into their account to accept the follow request.
*
*/
@Test
public void test4FollowUser() {
//Login with the first user
onView(withId(R.id.enter_id)).perform(typeText("follow_user_001"));
onView(withId(R.id.enter_id)).check(matches(withText("follow_user_001")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.register_button)).perform(click());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyProfile));
onView(withId(R.id.followButton)).perform(click());
onView(allOf(withClassName(endsWith("EditText")))).perform(typeText("followed_user_002"));
onView(withText("OK")).perform(click());
//Logout from the first users account
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.LogOut));
//Login with the second user
//onView(withId(R.id.enter_id)).perform(typeText("followed_user_002"));
//onView(withId(R.id.enter_id)).check(matches(withText("followed_user_002")));
onView(withId(R.id.enter_id)).perform(typeText("followed_user_002"));
onView(withId(R.id.enter_id)).check(matches(withText("followed_user_002")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.register_button)).perform(click());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyProfile));
//onData(allOf(withText("Tommy"), hasSibling(withText("Tommy")))).atPosition(0).perform(click());
//onData(allOf(withId(R.id.acceptFollow), hasSibling(withText("Tommy")))).atPosition(0).perform(click());
//onData(allOf(withId(R.id.acceptFollow), hasSibling(withText("1")), hasSibling(withId(R.id.followReqRecycler)))).perform(click());
onView(withId(R.id.acceptFollow)).perform(click());
//onData(withText("Tommy")).perform(click());
//onView(withId(R.id.habitTypeRow)).perform(click());
}
/**
* This test case will add two new events to the user "test_user_002" and demonstrate that
* all the events that will occur today will display on the MyHome tab. The first event will
* not be completed and the second event will be completed.
*
*/
@Test
public void test5Today() {
//Login
onView(withId(R.id.enter_id)).perform(typeText("test_user_002"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_002")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.register_button)).perform(click());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHabits));
//Create the first habit
onView(withId(R.id.createNewHabit)).perform(click());
onView(withId(R.id.textHabitName)).perform(typeText("Rowing"));
onView(withId(R.id.textHabitName)).check(matches(withText("Rowing")));
onView(withId(R.id.textHabitReason)).perform(typeText("Get fit"));
onView(withId(R.id.textHabitReason)).check(matches(withText("Get fit")));
onView(withId(R.id.buttonSelectDate)).perform(click());
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(2017, 12, day));
onView(withText("OK")).perform(click());
onView(withId(R.id.buttonMonday)).perform(click());
onView(withId(R.id.buttonCreate)).perform(closeSoftKeyboard());
onView(withId(R.id.buttonCreate)).perform(click());
//Create the second habit
onView(withId(R.id.createNewHabit)).perform(click());
onView(withId(R.id.textHabitName)).perform(typeText("Swimming"));
onView(withId(R.id.textHabitName)).check(matches(withText("Swimming")));
onView(withId(R.id.textHabitReason)).perform(typeText("Too cold outside"));
onView(withId(R.id.textHabitReason)).check(matches(withText("Too cold outside")));
onView(withId(R.id.buttonSelectDate)).perform(click());
onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(2017, 12, day));
onView(withText("OK")).perform(click());
onView(withId(R.id.buttonMonday)).perform(click());
onView(withId(R.id.buttonCreate)).perform(closeSoftKeyboard());
onView(withId(R.id.buttonCreate)).perform(click());
//Change to MyHome
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHome));
//Logout
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.LogOut));
}
/**
* This test case will show all of the past events that the user has had, completed or not.
*
*/
@Test
public void test6HabitHistory() {
//Login
onView(withId(R.id.enter_id)).perform(typeText("test_user_001"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_001")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHistory));
//Logout
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.LogOut));
}
/**
* This test case will add and delete a user, validating that the user account is
* successfully deleted.
*
*/
@Test
public void test7AddDeleteUser() {
//Login
onView(withId(R.id.enter_id)).perform(typeText("test_user_003"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_003")));
onView(withId(R.id.register_button)).perform(closeSoftKeyboard());
onView(withId(R.id.register_button)).perform(click());
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyProfile));
onView(withId(R.id.deleteButton)).perform(click());
onView(withText("OK")).perform(click());
onView(withId(R.id.enter_id)).perform(typeText("test_user_003"));
onView(withId(R.id.enter_id)).check(matches(withText("test_user_003")));
onView(withId(R.id.login_button)).perform(closeSoftKeyboard());
onView(withId(R.id.login_button)).perform(click());
onView(withClassName(endsWith("TextView"))).check(matches(withText("Invalid User ID")));
}
}
|
package com.kuxhausen.huemore.editmood;
import java.util.ArrayList;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.gson.Gson;
import com.kuxhausen.huemore.NetworkManagedSherlockFragmentActivity;
import com.kuxhausen.huemore.R;
import com.kuxhausen.huemore.editmood.EditMoodActivity.OnCreateMoodListener;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.InternalArguments;
import com.kuxhausen.huemore.persistence.HueUrlEncoder;
import com.kuxhausen.huemore.persistence.Utils;
import com.kuxhausen.huemore.state.Event;
import com.kuxhausen.huemore.state.Mood;
import com.kuxhausen.huemore.state.api.BulbState;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v7.widget.GridLayout;
public class EditMoodStateGridFragment extends SherlockFragment implements OnClickListener, OnCreateMoodListener {
Gson gson = new Gson();
GridLayout grid;
int contextSpot;
public ArrayList<StateCell> dataRay = new ArrayList<StateCell>();
ArrayList<TimeslotStartTime> timedTimeslotDuration = new ArrayList<TimeslotStartTime>();
ArrayList<TimeslotStartTime> dailyTimeslotDuration = new ArrayList<TimeslotStartTime>();
private final static int defaultDuration = 10;
ImageButton addChannel, addTimeslot;
static String priorName;
static Mood priorMood;
public final static int SIMPLE_PAGE = 0, RELATIVE_START_TIME_PAGE=1, DAILY_PAGE = 2;
private int pageType;
public EditMoodActivity pager;
public void setMoodMode(int spinnerPos){
if(pageType!=spinnerPos){
if(spinnerPos==SIMPLE_PAGE)
setGridRows(1,0);
pageType = spinnerPos;
redrawGrid();
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
pager = (EditMoodActivity) activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View myView = inflater.inflate(R.layout.edit_mood_state_grid_fragment, null);
addTimeslot = (ImageButton) inflater.inflate(R.layout.edit_mood_down_arrow, null);
addTimeslot.setOnClickListener(this);
addChannel = (ImageButton) inflater.inflate(R.layout.edit_mood_right_arrow, null);
addChannel.setOnClickListener(this);
grid = (GridLayout) myView.findViewById(R.id.advancedGridLayout);
grid.removeAllViews();
timedTimeslotDuration.clear();
dailyTimeslotDuration.clear();
dataRay.clear();
grid.setColumnCount(initialCols+1+endingCols);
grid.setRowCount(initialRows+endingRows);
addRow(defaultDuration);
redrawGrid();
Bundle args = getArguments();
if (args != null && args.containsKey(InternalArguments.MOOD_NAME)) {
//load prior mood
priorName = args.getString(InternalArguments.MOOD_NAME);
loadMood(Utils.getMoodFromDatabase(priorName, this.getActivity()));
}
return myView;
}
private StateCell generateDefaultMoodRow(){
StateCell mr = new StateCell(this.getActivity());
BulbState example = new BulbState();
mr.hs = example;
return mr;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
dataRay.get(requestCode).hs = gson.fromJson(
data.getStringExtra(InternalArguments.HUE_STATE),
BulbState.class);
redrawGrid();
}
private void stopPreview(){
((NetworkManagedSherlockFragmentActivity)this.getActivity()).stopMood();
}
@Override
public void preview(){
((NetworkManagedSherlockFragmentActivity)this.getActivity()).startMood(getMood(), pager.getName());
}
public static int calculateMoodType(Mood m){
if (m.timeAddressingRepeatPolicy==true){
return DAILY_PAGE;
}else if(!m.usesTiming && m.events.length == 1) {
return SIMPLE_PAGE;
}else
return RELATIVE_START_TIME_PAGE;
}
private void loadMood(Mood mFromDB) {
//calculate & set the mood type
pageType = EditMoodStateGridFragment.calculateMoodType(mFromDB);
//calculate & set the number of grid rows
this.setGridCols(mFromDB.getNumChannels());
//calculate & set number of rows, and fill with times
int row = -1;
int time = -1;
for(Event e: mFromDB.events){
if(e.time!=time){
row++;
setGridRows(row+1, e.time - time);
time=e.time;
}
}
if(mFromDB.usesTiming)
setGridRows(row+1, mFromDB.loopIterationTimeLength - time);
row = -1;
time = -1;
for(Event e: mFromDB.events){
if(e.time!=time){
if(pageType == DAILY_PAGE || pageType == RELATIVE_START_TIME_PAGE){
dailyTimeslotDuration.get(row+1).setStartTime(e.time);
timedTimeslotDuration.get(row+1).setStartTime(e.time);
}
row++;
time = e.time;
}
dataRay.get(gridCols()*row + e.channel).hs = e.state;
}
//set loop button
pager.setChecked(mFromDB.isInfiniteLooping());
redrawGrid();
}
private Mood getMood() {
Mood m = new Mood();
m.usesTiming = true; //TODO not always the case...
m.setNumChannels(gridCols());
if(pageType == SIMPLE_PAGE || pageType == DAILY_PAGE)
m.timeAddressingRepeatPolicy=true;
else
m.timeAddressingRepeatPolicy = false;
m.setInfiniteLooping(pager.isChecked());
ArrayList<Event> events = new ArrayList<Event>();
for(int i = 0; i< dataRay.size(); i++){
StateCell mr = dataRay.get(i);
if(mr.hs!=null && !mr.hs.toString().equals("")){
int row = i / gridCols();
int col = i % gridCols();
Event e = new Event();
e.channel = col;
e.time = getTime(row);
e.state = mr.hs;
events.add(e);
}
}
Event[] eRay = new Event[events.size()];
for(int i = 0; i<eRay.length; i++)
eRay[i] = events.get(i);
m.events = eRay;
m.loopIterationTimeLength = getTime(this.gridRows());
return m;
}
private int getTime(int row){
if(pageType == DAILY_PAGE || pageType == RELATIVE_START_TIME_PAGE){
if(row<dailyTimeslotDuration.size())
return dailyTimeslotDuration.get(row).getStartTime();
else
return 0;
}
else
return 0;
}
public int computeMinimumValue(int position){
if(position <=0){
return 0;
} else{
if(pageType == DAILY_PAGE || pageType==RELATIVE_START_TIME_PAGE)
return (dailyTimeslotDuration.get(position-1)).getStartTime();
else
return 0;
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.clickable_layout:
stopPreview();
EditStatePagerDialogFragment cpdf = new EditStatePagerDialogFragment();
cpdf.setParrentMood(this);
Bundle args = new Bundle();
args.putString(InternalArguments.PREVIOUS_STATE,
gson.toJson(dataRay.get((Integer) v.getTag()).hs));
cpdf.setArguments(args);
cpdf.setTargetFragment(this, (Integer) v.getTag());
cpdf.show(getFragmentManager(),
InternalArguments.FRAG_MANAGER_DIALOG_TAG);
break;
case R.id.rightButton:
addCol();
redrawGrid();
break;
case R.id.downButton:
addRow(defaultDuration);
redrawGrid();
break;
}
}
public void redrawGrid() {
grid.removeAllViews();
LayoutInflater inflater = this.getActivity().getLayoutInflater();
for(int r = 0; r< gridRows(); r++)
for(int c = 0; c<gridCols(); c++){
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(c+initialCols);
vg.rowSpec = GridLayout.spec(r+initialRows);
View v = dataRay.get(r*gridCols()+c).getView((r*gridCols()+c), grid, this, this);
v.setTag(r*this.gridCols()+c);
grid.addView(v, vg);
}
//add timeslot button
if(pageType == RELATIVE_START_TIME_PAGE || pageType == DAILY_PAGE){
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(0);
vg.rowSpec = GridLayout.spec(initialRows+this.gridRows()+endingRows-1);
vg.setGravity(Gravity.CENTER);
grid.addView(addTimeslot, vg);
}
//add channel button
{
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(initialCols+this.gridCols()+endingCols-1);
vg.rowSpec = GridLayout.spec(0);
vg.setGravity(Gravity.CENTER);
grid.addView(addChannel, vg);
}
//timedTimeslotDuration views
if(pageType == RELATIVE_START_TIME_PAGE) {
for(int r = 0; r<timedTimeslotDuration.size(); r++){
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(0);
vg.rowSpec = GridLayout.spec(r+initialRows);
vg.setGravity(Gravity.CENTER);
View v = timedTimeslotDuration.get(r).getView();
if(v.getParent()!=null)
((ViewGroup)v.getParent()).removeView(v);
grid.addView(v, vg);
}
}
//dailytimeslotDuration views
if (pageType == DAILY_PAGE){
for(int r = 0; r<dailyTimeslotDuration.size(); r++){
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(0);
vg.rowSpec = GridLayout.spec(r+initialRows);
vg.setGravity(Gravity.CENTER);
View v = dailyTimeslotDuration.get(r).getView();
if(v.getParent()!=null)
((ViewGroup)v.getParent()).removeView(v);
grid.addView(v, vg);
}
}
//channel label
{
Button b =(Button) inflater.inflate(R.layout.grid_col_channels_label, null);
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Mood showChanM = new Mood();
showChanM.usesTiming = true;
showChanM.setNumChannels(gridCols());
//flash each channel 1.5 seconds apart
Event[] eRay = new Event[showChanM.getNumChannels()];
for(int i = 0; i< showChanM.getNumChannels(); i++){
BulbState bs = new BulbState();
bs.alert = "select";
bs.on = true;
Event e = new Event();
e.channel = i;
e.time = 15*i;
e.state = bs;
eRay[i]=e;
}
showChanM.events = eRay;
showChanM.loopIterationTimeLength = 15*showChanM.getNumChannels();
((NetworkManagedSherlockFragmentActivity)pager).startMood(showChanM, null);
}
});
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(initialCols, this.gridCols());
vg.rowSpec = GridLayout.spec(0);
vg.setGravity(Gravity.CENTER);
grid.addView(b, vg);
}
//vertical separator
if(pageType == RELATIVE_START_TIME_PAGE || pageType == DAILY_PAGE) {
ImageView rowView = (ImageView) inflater.inflate(R.layout.grid_vertical_seperator, null);
ColorDrawable cd = new ColorDrawable(0xFFB5B5E5);
rowView.setImageDrawable(cd);
rowView.setMinimumWidth(1);
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(1);
vg.rowSpec = GridLayout.spec(0, initialRows+gridRows());
vg.setGravity(Gravity.FILL_VERTICAL);
grid.addView(rowView, vg);
}
//horizontal separator
{
ImageView rowView = (ImageView) inflater.inflate(R.layout.grid_horizontal_seperator, null);
ColorDrawable cd = new ColorDrawable(0xFFB5B5E5);
rowView.setImageDrawable(cd);
rowView.setMinimumHeight(1);
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(0,initialCols+gridCols());
vg.rowSpec = GridLayout.spec(1);
vg.setGravity(Gravity.FILL_HORIZONTAL);
grid.addView(rowView, vg);
}
grid.invalidate();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
contextSpot = (Integer)v.getTag();
android.view.MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.context_state, menu);
android.view.MenuItem deleteTimeslot = menu.findItem(R.id.contextstatemenu_delete_timeslot);
if(pageType == SIMPLE_PAGE){
deleteTimeslot.setEnabled(false);
deleteTimeslot.setVisible(false);
}
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.contextstatemenu_edit:
stopPreview();
EditStatePagerDialogFragment cpdf = new EditStatePagerDialogFragment();
cpdf.setParrentMood(this);
Bundle args = new Bundle();
args.putString(InternalArguments.PREVIOUS_STATE,
gson.toJson(dataRay.get(contextSpot).hs));
cpdf.setArguments(args);
cpdf.setTargetFragment(this, contextSpot);
cpdf.show(getFragmentManager(),
InternalArguments.FRAG_MANAGER_DIALOG_TAG);
return true;
case R.id.contextstatemenu_delete:
delete(contextSpot);
redrawGrid();
return true;
case R.id.contextstatemenu_delete_timeslot:
deleteRow(contextSpot);
redrawGrid();
return true;
case R.id.contextstatemenu_delete_channel:
deleteCol(contextSpot);
redrawGrid();
return true;
default:
return super.onContextItemSelected(item);
}
}
private void addState() {
dataRay.add(generateDefaultMoodRow());
}
private void addState(int item) {
dataRay.add(item, generateDefaultMoodRow());
}
private void delete(int item){
dataRay.set(item, generateDefaultMoodRow());
}
private void deleteRow(int item){
if(gridRows()>1){
int row = (item / gridCols());
ArrayList<StateCell> toRemove = new ArrayList<StateCell>();
for(int i = 0; i<gridCols(); i++){
toRemove.add(dataRay.get(i + row*gridCols()));
}
for(StateCell kill : toRemove)
dataRay.remove(kill);
timedTimeslotDuration.remove(row);
dailyTimeslotDuration.remove(row);
grid.setRowCount(initialRows+endingRows + gridRows()-1);
}
redrawGrid();
}
private void deleteCol(int item){
if(gridCols()>1){
int col = item % gridCols();
ArrayList<StateCell> toRemove = new ArrayList<StateCell>();
for(int i = 0; i<gridRows(); i++){
toRemove.add(dataRay.get(col + i*gridCols()));
}
for(StateCell kill : toRemove)
dataRay.remove(kill);
grid.setColumnCount(endingCols+initialCols+gridCols()-1);
}
redrawGrid();
}
private void addRow(int duration){
if(gridRows()<=64){
grid.setRowCount(initialRows+endingRows + gridRows()+1);
TimeslotStartTime tdTimed, tdDaily;
tdDaily = new TimeOfDayTimeslot(this, getSpinnerId(), gridRows()-1);
tdTimed = new RelativeStartTimeslot(this, getSpinnerId(), gridRows()-1);
tdTimed.setStartTime(duration);
timedTimeslotDuration.add(tdTimed);
dailyTimeslotDuration.add(tdDaily);
for(int i = gridCols(); i>0; i
addState();
}
}else{
Toast t = Toast.makeText(getActivity(), R.string.advanced_timeslot_limit, Toast.LENGTH_LONG);
t.show();
}
}
private void addCol(){
if(gridCols()<64){
int width = gridCols();
grid.setColumnCount(1+width+initialCols+endingCols);
for(int i = dataRay.size(); i>0; i-=width){
addState(i);
}
}else{
Toast t = Toast.makeText(getActivity(), R.string.advanced_channel_limit, Toast.LENGTH_LONG);
t.show();
}
}
private final int initialRows = 2;
private final int initialCols = 2;
private final int endingRows = 1;
private final int endingCols = 1;
private final int gridRows(){
return grid.getRowCount()-initialRows-endingCols;
}
private final int gridCols(){
return grid.getColumnCount()-initialCols-endingCols;
}
private final void setGridRows(int num, int duration){
while(gridRows()!=num){
if(gridRows()<num)
addRow(duration);
else if(gridRows()>num)
deleteRow(gridRows()-1);
}
}
private final void setGridCols(int num){
while(gridCols()!=num){
if(gridCols()<num)
addCol();
else if(gridCols()>num)
deleteCol(gridCols()-1);
}
}
private int getSpinnerId(){
return usedSpinnerIDs++;
}
private int usedSpinnerIDs = 0;
@Override
public void onCreateMood(String moodname) {
ContentValues mNewValues = new ContentValues();
mNewValues.put(DatabaseDefinitions.MoodColumns.MOOD, moodname);
mNewValues.put(DatabaseDefinitions.MoodColumns.STATE, HueUrlEncoder.encode(getMood()));
getActivity().getContentResolver().insert(
DatabaseDefinitions.MoodColumns.MOODS_URI, mNewValues);
}
}
|
package at.barbot.barbot.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.nfc.Tag;
import android.util.Log;
public class BarBotDatabaseHelper extends SQLiteOpenHelper {
//Database Instance
private static BarBotDatabaseHelper sInstance;
//Database Info
private static final String DATABASE_NAME = "barBot";
private static final int DATABASE_VERSION = 1;
/**
* Table Names
*/
private static final String TABLE_BARBOT = "barbot";
private static final String TABLE_SLAVEUNIT = "slaveunit";
private static final String TABLE_INGREDIENT = "ingredient";
private static final String TABLE_DRINK_HAS_INGREDIENT = "drink_has_ingredient";
private static final String TABLE_DRINK = "drink";
/**
* Table Columns
*/
//Table BarBot columns
private static final String COLUMN_BARBOT_PK_ID_BARBOT = "pk_id_barbot";
private static final String COLUMN_BARBOT_NAME = "name";
//Table Slaveunit columns
private static final String COLUMN_SLAVEUNIT_PK_ID_SLAVEUNIT = "pk_id_slaveunit";
private static final String COLUMN_SLAVEUNIT_NAME = "name";
private static final String COLUMN_SLAVEUNIT_FILLING_LEVEL_IN_ML = "filling_level_in_ml";
private static final String COLUMN_SLAVEUNIT_FK_ID_BARBOT = "fk_id_barbot";
private static final String COLUMN_SLAVEUNIT_FK_ID_INGREDIENT = "fk_id_ingredient";
//Table Ingredient columns
private static final String COLUMN_INGREDIENT_PK_ID_INGREDIENT = "pk_id_ingredient";
private static final String COLUMN_INGREDIENT_NAME = "name";
private static final String COLUMN_INGREDIENT_VOL_PERCENT = "vol_percent";
//Table drink_has_ingredient columns
private static final String COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_DRINK = "pk_fk_id_drink";
private static final String COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_INGREDIENT = "pk_fk_id_ingredient";
private static final String COLUMN_DRINK_HAS_INGREDIENT_INGREDIENT_AMOUNT_IN_ML = "ingredient_amount_in_ml";
//Table drink columns
private static final String COLUMN_DRINK_PK_ID_DRINK = "pk_id_drink";
private static final String COLUMN_DRINK_NAME = "name";
private static final String COLUMN_DRINK_PICTURE = "picture";
private static final String COLUMN_DRINK_DESCRIPTION = "description";
private static final String TAG = "BarBotDatabaseHelper";
private BarBotDatabaseHelper (Context context){
super(context,DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized BarBotDatabaseHelper getInstance (Context context){
if (sInstance == null){
sInstance = new BarBotDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
@Override
public void onCreate(SQLiteDatabase db) {
String create_table_barbot = "CREATE TABLE IF NOT EXISTS" + TABLE_BARBOT +
"(" + COLUMN_BARBOT_PK_ID_BARBOT + " INTEGER PRIMARY KEY," +
COLUMN_BARBOT_NAME + " VARCHAR(45)" +
")";
String create_table_slaveunit = "CREATE TABLE IF NOT EXISTS" + TABLE_SLAVEUNIT +
"(" + COLUMN_SLAVEUNIT_PK_ID_SLAVEUNIT + " INTEGER PRIMARY KEY," +
COLUMN_SLAVEUNIT_NAME + " VARCHAR(45)," +
COLUMN_SLAVEUNIT_FILLING_LEVEL_IN_ML + " INTEGER," +
COLUMN_SLAVEUNIT_FK_ID_BARBOT + " INTEGER," +
COLUMN_SLAVEUNIT_FK_ID_INGREDIENT + " INTEGER," +
"FOREIGN KEY(" + COLUMN_SLAVEUNIT_FK_ID_BARBOT + ") REFERENCES " + TABLE_BARBOT + "(" + COLUMN_BARBOT_PK_ID_BARBOT + ")" +
")";
String create_table_ingredient = "CREATE TABLE" + TABLE_INGREDIENT +
"(" + COLUMN_INGREDIENT_PK_ID_INGREDIENT + " INTEGER PRIMARY KEY," +
COLUMN_INGREDIENT_NAME + " VARCHAR(100)," +
COLUMN_INGREDIENT_VOL_PERCENT + " INTEGER" +
")";
String create_table_drink_has_ingredient = "CREATE TABLE" + TABLE_DRINK_HAS_INGREDIENT +
"(" + COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_INGREDIENT + " INTEGER," +
COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_DRINK + " INTEGER," +
COLUMN_DRINK_HAS_INGREDIENT_INGREDIENT_AMOUNT_IN_ML + " INTEGER" +
"PRIMARY KEY (" + COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_INGREDIENT + "," + COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_DRINK + ")" +
"FOREIGN KEY(" + COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_INGREDIENT + ") REFERENCES " + TABLE_INGREDIENT + "(" + COLUMN_INGREDIENT_PK_ID_INGREDIENT + ")" +
"FOREIGN KEY(" + COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_DRINK + ") REFERENCES " + TABLE_DRINK + "(" + COLUMN_DRINK_PK_ID_DRINK + ")" +
")";
String create_table_drink = "CREATE TABLE" + TABLE_DRINK +
"(" + COLUMN_DRINK_PK_ID_DRINK + " INTEGER," +
COLUMN_DRINK_NAME + " VARCHAR(100)," +
COLUMN_DRINK_DESCRIPTION + " MEDIUMTEXT," +
COLUMN_DRINK_PICTURE + "VARCHAR(200)" +
")";
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
if (oldV != newV) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BARBOT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SLAVEUNIT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_INGREDIENT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DRINK_HAS_INGREDIENT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DRINK);
onCreate(db);
}
}
/**
* Einen neuen BarBot hinzufuegen
* @param barBot: Ein Model, welches den BarBot repraesentiert
*/
public void addBarBot (BarBot barBot){
// create and/or open database
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_BARBOT_PK_ID_BARBOT, barBot.pk_id_barbot);
values.put(COLUMN_BARBOT_NAME, barBot.name);
db.insertOrThrow(TABLE_BARBOT, null, values);
db.setTransactionSuccessful();
}catch (Exception e){
Log.d(TAG, "Error adding a new BarBot: " + e);
}finally {
db.endTransaction();
}
}
public void addSlaveunit (Slaveunit slave){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_SLAVEUNIT_PK_ID_SLAVEUNIT, slave.pk_id_slaveunit);
values.put(COLUMN_SLAVEUNIT_NAME, slave.name);
values.put(COLUMN_SLAVEUNIT_FILLING_LEVEL_IN_ML, slave.filling_level_in_ml);
values.put(COLUMN_SLAVEUNIT_FK_ID_BARBOT, slave.fk_id_barbot);
values.put(COLUMN_SLAVEUNIT_FK_ID_INGREDIENT, slave.fk_id_ingredient);
db.insertOrThrow(TABLE_SLAVEUNIT, null, values);
db.setTransactionSuccessful();
}catch (Exception e){
Log.d(TAG, "Error adding a new Slaveunit: " + e);
}finally {
db.endTransaction();
}
}
public void addIngredient (Ingredient ingredient){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_INGREDIENT_PK_ID_INGREDIENT, ingredient.pk_id_ingredient);
values.put(COLUMN_INGREDIENT_NAME, ingredient.name);
values.put(COLUMN_INGREDIENT_VOL_PERCENT, ingredient.vol_percent);
db.insertOrThrow(TABLE_INGREDIENT, null, values);
db.setTransactionSuccessful();
}catch (Exception e){
Log.d(TAG, "Error adding a new Ingredient: " + e);
}finally {
db.endTransaction();
}
}
public void addDrinkHasIngredient (Drink_has_ingredient drinkIngredient){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_INGREDIENT, drinkIngredient.pk_fk_id_ingredient);
values.put(COLUMN_DRINK_HAS_INGREDIENT_PK_FK_ID_DRINK, drinkIngredient.pk_fk_id_drink);
values.put(COLUMN_DRINK_HAS_INGREDIENT_INGREDIENT_AMOUNT_IN_ML, drinkIngredient.ingredient_amount_in_ml);
db.insertOrThrow(TABLE_DRINK_HAS_INGREDIENT, null, values);
db.setTransactionSuccessful();
}catch (Exception e){
Log.d(TAG, "Error adding a new drink_has_ingredient: " + e);
}finally {
db.endTransaction();
}
}
public void addDrink (Drink drink){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_DRINK_PK_ID_DRINK, drink.pk_id_drink);
values.put(COLUMN_DRINK_NAME, drink.name);
values.put(COLUMN_DRINK_DESCRIPTION, drink.description);
values.put(COLUMN_DRINK_PICTURE, drink.picture);
db.insertOrThrow(TABLE_DRINK, null, values);
db.setTransactionSuccessful();
}catch (Exception e){
Log.d(TAG, "Error adding a new Drink: " + e);
}finally {
db.endTransaction();
}
}
}
|
package co.epitre.aelf_lectures;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
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.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import co.epitre.aelf_lectures.data.AelfDate;
import co.epitre.aelf_lectures.data.LectureItem;
import co.epitre.aelf_lectures.data.LecturesController;
import co.epitre.aelf_lectures.data.WhatWhen;
import static co.epitre.aelf_lectures.data.WhatWhen.DATE_TODAY;
public class SectionOfficesFragment extends SectionFragmentBase implements
LectureLoadProgressListener,
DatePickerFragment.CalendarDialogListener,
NetworkStatusMonitor.NetworkStatusChangedListener
{
public static final String TAG = "SectionOfficesFragment";
/**
* Internal state
*/
WhatWhen whatwhen;
WhatWhen whatwhen_previous = null;
private boolean isLoading = false;
private boolean isSuccess = true;
DownloadXmlTask currentRefresh = null;
Lock preventCancel = new ReentrantLock();
/**
* Global managers / resources
*/
NetworkStatusMonitor networkStatusMonitor = NetworkStatusMonitor.getInstance();
SharedPreferences settings = null;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
LecturePagerAdapter lecturesPagerAdapter = null;
// This is called number of screen rotate + 1. The last time with a null argument :/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO: pass routing argument instead of loading intent
super.onCreateView(inflater, container, savedInstanceState);
// Load settings
Resources res = getResources();
settings = PreferenceManager.getDefaultSharedPreferences(getContext());
// Select where to go from here
whatwhen = new WhatWhen();
Uri uri = activity.getIntent().getData();
if (uri != null) {
parseIntentUri(uri);
} else if (canRestoreState(savedInstanceState)) {
// Restore saved instance state. Especially useful on screen rotate on older phones
whatwhen.what = LecturesController.WHAT.values()[savedInstanceState.getInt("what")];
whatwhen.position = savedInstanceState.getInt("position");
long timestamp = savedInstanceState.getLong("when");
if (timestamp == DATE_TODAY) {
whatwhen.when = new AelfDate();
whatwhen.today = true;
} else {
whatwhen.when = new AelfDate(timestamp);
whatwhen.today = false;
}
} else {
// Load the lectures for today. Based on the anonymous statistics
whatwhen.when = new AelfDate();
whatwhen.today = true;
whatwhen.position = 0;
if (settings.getString(SyncPrefActivity.KEY_PREF_SYNC_LECTURES, res.getString(R.string.pref_lectures_def)).equals("messe")) {
whatwhen.what = LecturesController.WHAT.MESSE;
} else {
long hour = whatwhen.when.get(Calendar.HOUR_OF_DAY);
if (hour < 3) {
whatwhen.what = LecturesController.WHAT.COMPLIES;
whatwhen.when.add(GregorianCalendar.DAY_OF_YEAR, -1);
} else if (hour < 4) {
whatwhen.what = LecturesController.WHAT.LECTURES;
} else if (hour < 8) {
whatwhen.what = LecturesController.WHAT.LAUDES;
} else if (hour < 15) {
whatwhen.what = LecturesController.WHAT.MESSE;
} else if (hour < 21) {
whatwhen.what = LecturesController.WHAT.VEPRES;
} else {
whatwhen.what = LecturesController.WHAT.COMPLIES;
}
}
}
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_section_offices, container, false);
// Load lecture
loadLecture(whatwhen);
// Return view
return view;
}
// Routing
// TODO: make real routing with "master" router in main activity, then delegate to fragments
// FIXME: this method has a huge side-effect (sets the whatwhen). Make it a loader ?
private void parseIntentUri(Uri uri) {
// Parse intent URI, update whatwhen in place
// http://www.aelf.org/#messe1_lecture4 --> messe du jour, lecture N
// http://www.aelf.org/2017-01-27/romain/messe#messe1_lecture3 --> messe du 2017-01-27, calendrier romain, lecture N
// http://www.aelf.org/2017-01-27/romain/complies#office_psaume1 --> office_TYPE[N]
// Legacy shortcut URLs:
String path = uri.getPath();
String host = uri.getHost();
String fragment = uri.getFragment();
// Set default values
whatwhen.what = LecturesController.WHAT.MESSE;
whatwhen.when = new AelfDate();
whatwhen.today = true;
whatwhen.position = 0; // 1st lecture of the office
if (host.equals("www.aelf.org")) {
// AELF Website
String[] chunks = path.split("/");
if (chunks.length == 2 && chunks[1].startsWith("office-")) {
// Attempt to parse a legacy URL
String office_name = chunks[1].substring(7).toUpperCase();
try {
whatwhen.what = LecturesController.WHAT.valueOf(office_name);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Failed to parse office '" + chunks[2] + "', falling back to messe", e);
whatwhen.what = LecturesController.WHAT.MESSE;
}
} else {
// Attempt to parse NEW url format, starting with a date
if (chunks.length >= 2) {
// Does it look like a date ?
String potential_date = chunks[1];
if (potential_date.matches("20[0-9]{2}-[0-9]{2}-[0-9]{2}")) {
String[] date_chunks = potential_date.split("-");
whatwhen.when.set(
Integer.parseInt(date_chunks[0]),
Integer.parseInt(date_chunks[1]) - 1,
Integer.parseInt(date_chunks[2])
);
} else {
Log.w(TAG, "String '" + potential_date + "' should look like a date, but it does not!");
}
}
// Attempt to parse office
if (chunks.length >= 4) {
String office_name = chunks[3].toUpperCase();
try {
whatwhen.what = LecturesController.WHAT.valueOf(office_name);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Failed to parse office '" + chunks[2] + "', falling back to messe", e);
whatwhen.what = LecturesController.WHAT.MESSE;
}
}
// Finally, grab anchor
whatwhen.anchor = fragment;
}
}
}
// Lifecycle
@Override
public void onResume() {
super.onResume();
networkStatusMonitor.registerNetworkStatusChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
networkStatusMonitor.unregisterNetworkStatusChangeListener(this);
}
private boolean canRestoreState(Bundle savedInstanceState) {
// We cant restore the state if
// - null
// - today AND more than an hour old
// The rational is, when praying on a day to day basis, you want to support short pauses and
// screen rotation but still open automatically on the most probable office, among the most
// often prayed. On the other hand, if the date was explicitely chosen to a specific one like
// when preparing the mass for the following sunday, we want to re-open it so that the user
// does not have to search for it.
if (savedInstanceState == null) {
return false;
}
long whenTimestamp = savedInstanceState.getLong("when");
long lastUpdateTimestamp = savedInstanceState.getLong("last-update", 0);
boolean wasToday = (whenTimestamp == DATE_TODAY);
// Not today ? Keep it!
if (!wasToday) {
return true;
}
// Less than 1 hour old ? Keep it
if ((System.currentTimeMillis() - lastUpdateTimestamp) < 1*3600*1000) {
return true;
}
return false;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (outState == null) return;
int position = 0; // first slide by default
int what = 0; // "Messe" by default
long when = DATE_TODAY;
if (whatwhen != null) {
if (whatwhen.what != null) what = whatwhen.what.getPosition();
if (mViewPager != null) position = mViewPager.getCurrentItem();
if (whatwhen.when != null && !whatwhen.today && !whatwhen.when.isToday()) {
when = whatwhen.when.getTimeInMillis();
}
}
outState.putInt("what", what);
outState.putInt("position", position);
outState.putLong("when", when);
outState.putLong("last-update", System.currentTimeMillis());
}
// Views
public void updateCalendarButtonLabel() {
if(mMenu == null) {
return;
}
MenuItem calendarItem = mMenu.findItem(R.id.action_calendar);
calendarItem.setTitle(whatwhen.when.toShortPrettyString());
}
// Option menu
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
// Inflate the menu; this adds items to the action bar
inflater.inflate(R.menu.toolbar_offices, menu);
// Make the share image white
Drawable normalDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_share_black_24dp);
Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable);
DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(activity, R.color.white));
// Update to date button with "this.date"
updateCalendarButtonLabel();
updateMenuNetworkVisibility();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
return onRefresh("menu");
case R.id.action_calendar:
return onCalendar();
case R.id.action_share:
return onShare();
}
return super.onOptionsItemSelected(item);
}
private void updateMenuNetworkVisibility() {
if(mMenu == null) {
return;
}
boolean visible = networkStatusMonitor.isNetworkAvailable();
mMenu.findItem(R.id.action_refresh).setVisible(visible);
mMenu.findItem(R.id.action_sync_do).setVisible(visible);
}
// Network
@Override
public void onNetworkStatusChanged(NetworkStatusMonitor.NetworkStatusEvent networkStatusEvent) {
updateMenuNetworkVisibility();
switch (networkStatusEvent) {
case NETWORK_ON:
// Attempt to reload current slide, If there was an error.
if (!this.isSuccess) {
onRefresh("networkUp");
}
break;
}
}
// Events
public boolean onRefresh(String reason) {
whatwhen.useCache = false;
whatwhen.anchor = null;
if (mViewPager != null) {
whatwhen.position = mViewPager.getCurrentItem();
} else {
whatwhen.position = 0;
}
this.whatwhen_previous = null;
loadLecture(whatwhen);
return true;
}
public boolean onCalendar() {
Bundle args = new Bundle();
args.putLong("time", whatwhen.when.getTimeInMillis());
DatePickerFragment calendarDialog = new DatePickerFragment();
calendarDialog.setListener(this);
calendarDialog.setArguments(args);
calendarDialog.show(activity.getSupportFragmentManager(), "datePicker");
return true;
}
public boolean onShare() {
// Make sure we DO have something to share
// FIXME: racy, the loader will update it and it's in a thread
if (lecturesPagerAdapter == null || mViewPager == null) {
return false;
}
// Get current position
int position = mViewPager.getCurrentItem();
LectureItem lecture = lecturesPagerAdapter.getLecture(position);
// Build URL
String url = "http:
if (lecture.key != null) {
url += "#"+lecture.key;
}
// Build the data
String prettyDate = whatwhen.when.toPrettyString();
// Build the subject and message
String message;
String subject;
if (whatwhen.what == LecturesController.WHAT.MESSE && whatwhen.today) {
// If this is Today's mass, let's be concise
if (lecture.title != null) {
message = lecture.title;
} else {
message = lecture.shortTitle;
}
} else {
// Generic case
message = lecture.shortTitle+" "+whatwhen.what.prettyName();
// Append date if not today
if (!whatwhen.today) {
message += " " + prettyDate;
}
// Append title if defined
if (lecture.title != null) {
message += ": "+lecture.title;
}
}
// Append the reference, IF defined AND not the same as the title
if (lecture.reference != null && !lecture.reference.equals("") && !lecture.reference.equalsIgnoreCase(lecture.shortTitle)) {
message += " ("+lecture.reference+")";
}
// Append the link
message += ". "+url;
// Generate the subject, let's be concise
subject = lecture.shortTitle+" "+whatwhen.what.prettyName();
if (!whatwhen.today) {
subject += " " + prettyDate;
}
// Create the intent
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
startActivity(Intent.createChooser(intent, getString(R.string.action_share)));
// All done !
return true;
}
public void onCalendarDialogPicked(int year, int month, int day) {
AelfDate date = new AelfDate(year, month, day);
// do not refresh if date did not change to avoid unnecessary flickering
if (whatwhen.when.isSameDay(date))
return;
// Reset pager
this.whatwhen_previous = whatwhen.copy();
whatwhen.today = date.isToday();
whatwhen.when = date;
whatwhen.position = 0;
whatwhen.anchor = null;
loadLecture(whatwhen);
// Update to date button with "this.date"
updateCalendarButtonLabel();
}
public void onLink(Uri link) {
parseIntentUri(link);
loadLecture(whatwhen);
}
// Loader
protected void setLoading(final boolean loading) {
// Do not trigger animations. That causes flickering.
if (isLoading == loading) {
return;
}
isLoading = loading;
View view = getView();
if (view == null) {
return;
}
final RelativeLayout loadingOverlay = view.findViewById(R.id.loadingOverlay);
final ProgressBar loadingIndicator = view.findViewById(R.id.loadingIndicator);
final Button cancelButton = view.findViewById(R.id.cancelButton);
loadingOverlay.post(new Runnable() {
public void run() {
if(loading) {
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator());
fadeIn.setDuration(500);
Animation buttonFadeIn = new AlphaAnimation(0, 1);
buttonFadeIn.setInterpolator(new DecelerateInterpolator());
buttonFadeIn.setStartOffset(2500);
buttonFadeIn.setDuration(500);
loadingIndicator.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), R.color.sepia_fg), android.graphics.PorterDuff.Mode.MULTIPLY);
cancelButton.setVisibility(View.VISIBLE);
cancelButton.setAnimation(buttonFadeIn);
loadingOverlay.setVisibility(View.VISIBLE);
loadingOverlay.setAnimation(fadeIn);
} else {
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new DecelerateInterpolator());
fadeOut.setDuration(250);
cancelButton.setVisibility(View.GONE);
loadingOverlay.setVisibility(View.INVISIBLE);
loadingOverlay.setAnimation(fadeOut);
}
}
});
}
// Navigate to new office, keep the current date. Used to navigate from menu
public boolean loadLecture(LecturesController.WHAT what) {
if (what == null) {
return false;
}
whatwhen.what = what;
whatwhen.position = 0; // on what change, move to 1st
whatwhen.anchor = null;
whatwhen_previous = whatwhen.copy();
// Load
this.loadLecture(whatwhen);
return true;
}
public void loadLecture(WhatWhen whatwhen) {
// Cancel any pending load
cancelLectureLoad(false);
// Refresh UI
actionBar.setTitle(whatwhen.what.actionBarName());
drawerView.setCheckedItem(whatwhen.what.getMenuId());
updateCalendarButtonLabel();
// Start Loading
preventCancel.lock();
try {
DownloadXmlTask loader = new DownloadXmlTask(getContext(), whatwhen, this);
loader.execute();
whatwhen.useCache = true; // cache override are one-shot
currentRefresh = loader;
} finally {
preventCancel.unlock();
}
}
public void cancelLectureLoad(boolean restore) {
preventCancel.lock();
try {
currentRefresh.cancel(true);
if (currentRefresh.future != null) {
currentRefresh.future.cancel(true);
}
Thread.sleep(100); // FIXME!!
} catch (NullPointerException e) {
} catch (InterruptedException e) {
} finally {
currentRefresh = null;
setLoading(false); // FIXME: should be in the cancel code path in the task imho
preventCancel.unlock();
}
// Restore readings
if (restore && whatwhen_previous != null) {
whatwhen = whatwhen_previous;
whatwhen_previous = null;
whatwhen.useCache = true; // Make it fast, we are restoring !
// Load lectures
loadLecture(whatwhen);
}
}
// Async load callbacks. Guaranted to be called on main UI thread
public void onLectureLoadProgress(LectureLoadProgress progress) {
switch (progress) {
case LOAD_START:
setLoading(true);
break;
case LOAD_FAIL:
setLoading(false);
Toast.makeText(getContext(), "Oups... Impossible de rafraîchir.", Toast.LENGTH_SHORT).show();
break;
case LOAD_DONE:
setLoading(false);
break;
}
}
public void onLectureLoaded(List<LectureItem> lectures, boolean isSuccess) {
preventCancel.lock();
this.isSuccess = isSuccess;
try {
// If we have an anchor, attempt to find corresponding position
if (isSuccess) {
if (whatwhen.anchor != null && lectures != null) {
int position = -1;
for (LectureItem lecture : lectures) {
position++;
if (whatwhen.anchor.equals(lecture.key)) {
whatwhen.position = position;
break;
}
}
}
} else {
whatwhen.position = 0;
}
// Set up the ViewPager with the sections adapter.
try {
// 1 slide fragment <==> 1 lecture
lecturesPagerAdapter = new LecturePagerAdapter(activity.getSupportFragmentManager(), lectures);
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
mViewPager = activity.findViewById(R.id.pager);
mViewPager.setAdapter(lecturesPagerAdapter);
mViewPager.setCurrentItem(whatwhen.position);
transaction.commit();
setLoading(false);
} catch (IllegalStateException e) {
// Fragment manager has gone away, will reload anyway so silently give up
} finally {
currentRefresh = null;
preventCancel.unlock();
}
} catch (Exception e) {
throw e;
}
}
}
|
package com.doplgangr.secrecy.Views;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.doplgangr.secrecy.CustomApp;
import com.doplgangr.secrecy.FileSystem.Encryption.Vault;
import com.doplgangr.secrecy.FileSystem.Encryption.VaultHolder;
import com.doplgangr.secrecy.Jobs.AddFileJob;
import com.doplgangr.secrecy.R;
import com.doplgangr.secrecy.Util;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
@EActivity(R.layout.activity_main)
public class FileImportActivity extends ActionBarActivity
implements
VaultsListFragment.OnVaultSelectedListener,
VaultsListFragment.OnFragmentFinishListener {
Vault secret;
@ViewById(R.id.toolbar)
Toolbar mToolbar;
@AfterViews
void afterViews() {
setSupportActionBar(mToolbar);
FileImportFragment_ fragment = new FileImportFragment_();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.drawer_layout, fragment, "mainactivitycontent") //Replace the whole drawer layout
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
@Override
public void onFinish(Fragment fragment) {
}
@Override
public void onNew(Bundle bundle, Fragment fragment) {
}
@Override
public void onVaultSelected(String vault, String passphrase) {
secret = VaultHolder.getInstance().createAndRetrieveVault(vault, passphrase);
if (secret.wrongPass) {
Util.alert(
this,
getString(R.string.Error__open_vault),
getString(R.string.Error__open_vault_message),
Util.emptyClickListener,
null
);
return;
}
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null)
handleSend(intent);
else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null)
handleSendMultiple(intent); // Handle multiple images being sent
}
@Background
void handleSend(Intent intent) {
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null)
handleData(uri);
done();
}
@Background
void handleSendMultiple(Intent intent) {
ArrayList<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
for (Uri uri : uris)
if (uri != null)
handleData(uri);
done();
}
@Background
void handleData(final Uri data) {
CustomApp.jobManager.addJobInBackground(new AddFileJob(this, secret, data));
}
@UiThread
public void done() {
//Intent intent = new Intent(context, ListFileActivity_.class);
//intent.putExtra(Config.vault_extra, secret.name);
//intent.putExtra(Config.password_extra, password);
//startActivity(intent);
Util.toast(this, getString(R.string.Import__finish), Toast.LENGTH_SHORT);
finish();
}
}
|
package com.example.ben.zhihudaily.network;
import android.text.TextUtils;
import android.util.Log;
import com.example.ben.zhihudaily.api.StoryApi;
import com.example.ben.zhihudaily.api.StoryThemeApi;
import com.example.ben.zhihudaily.ui.App;
import com.example.ben.zhihudaily.utils.NetUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class BenRetrofit {
private static final String BASE_URL = "http://news-at.zhihu.com/";
public static final String CACHE_CONTROL = "Cache-Control: public, max-age=";
public static final int CACHE_MAX_STALE_LONG = 60 * 60 * 24 * 3;
public static final int CHCHE_MAX_STALE_SHORT = 60;
private static final int DEFAULT_TIMEOUT = 5;
private OkHttpClient okHttpClient;
private static Retrofit retrofit;
private StoryThemeApi dailyThemeApi;
private StoryApi dailyNewsApi;
private static final String TAG = "LogInterceptor.java";
BenRetrofit() {
initOkHttpClient();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
}
private void initOkHttpClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
if (okHttpClient == null) {
synchronized (BenRetrofit.class) {
if (okHttpClient == null) {
// ,100Mb
Cache cache = new Cache(new File(App.getInstance().getCacheDir(), "HttpCache"),
1024 * 1024 * 100);
okHttpClient = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(loggingInterceptor) // logInterceptor logInterceptor ; loggingInterceptor
.addInterceptor(networkInterceptor)
.addNetworkInterceptor(networkInterceptor)
.retryOnConnectionFailure(true)
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
}
}
}
}
private Interceptor networkInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetUtils.isNetworkConnected()) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
Response response = chain.proceed(request);
if (NetUtils.isNetworkConnected()) {
//@Headers
String cacheControl = request.cacheControl().toString();
if (TextUtils.isEmpty(cacheControl)) {
cacheControl = "public, max-age=" + CHCHE_MAX_STALE_SHORT;
}
response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", cacheControl)
.build();
} else {
//Cache-Controlif-only-cachemax-stale
response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + CACHE_MAX_STALE_LONG)
.build();
}
return response;
}
};
//log interceptor
private Interceptor logInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//the request url
String url = request.url().toString();
//the request method
String method = request.method();
//the request headers
String headers = request.headers().toString();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
//the response state
Log.d(TAG, String.format(Locale.CHINA, "Received response is %s ,message[%s],code[%d]", response.isSuccessful() ? "success" : "fail", response.message(), response.code()));
//the response data
ResponseBody body = response.body();
BufferedSource source = body.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = Charset.defaultCharset();
MediaType contentType = body.contentType();
Log.d(TAG, method);
Log.d(TAG, url);
Log.d(TAG, headers);
Log.d(TAG, response.code() + "");
Log.d(TAG, response.headers() + "");
Log.d(TAG, (t2 - t1) / 1e6d + "ms");
if (contentType != null) {
charset = contentType.charset(charset);
}
String bodyString = buffer.clone().readString(charset);
Log.d(TAG, String.format("Received response json string [%s]", bodyString)); //requst result
return response;
}
};
public StoryThemeApi getStoryThemeApi() {
if (null == dailyThemeApi) {
dailyThemeApi = retrofit.create(StoryThemeApi.class);
}
return dailyThemeApi;
}
public StoryApi getStoryApi() {
if (null == dailyNewsApi) {
dailyNewsApi = retrofit.create(StoryApi.class);
}
return dailyNewsApi;
}
}
|
package com.florafinder.invasive_species;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class RestAsyncTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection serverConnection = null;
InputStream is = null;
Log.d("Debug:", "Attempting to connect to: " + params[0]);
try {
URL url = new URL( params[0] );
serverConnection = (HttpURLConnection) url.openConnection();
serverConnection.setRequestMethod(params[1]);
if (params[1].equals("POST") ||
params[1].equals("PUT") ||
params[1].equals("DELETE")) {
Log.d("DEBUG POST/PUT/DELETE:", "In post: params[0]=" + params[0] + ", params[1]=" + params[1] + ", params[2]=" + params[2]);
serverConnection.setDoOutput(true);
serverConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// params[2] contains the JSON String to send, make sure we send the
// content length to be the json string length
serverConnection.setRequestProperty("Content-Length", "" +
Integer.toString(params[2].toString().getBytes().length));
// Send POST data that was provided.
DataOutputStream out = new DataOutputStream(serverConnection.getOutputStream());
out.writeBytes(params[2].toString());
out.flush();
out.close();
}
int responseCode = serverConnection.getResponseCode();
Log.d("Debug:", "\nSending " + params[1] + " request to URL : " + params[0]);
Log.d("Debug: ", "Response Code : " + responseCode);
is = serverConnection.getInputStream();
if (params[1] == "GET" || params[1] == "POST" || params[1] == "PUT" || params[1] == "DELETE") {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
try {
JSONObject jsonData = new JSONObject(sb.toString());
return jsonData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
serverConnection.disconnect();
}
return "Should not get to this if the data has been sent/received correctly!";
}
/**
*
* @param result the result from the query
*/
protected void onPostExecute(String result) {
}
}
|
package com.ggstudios.dialogs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.json.JSONException;
import com.ggstudios.lolcraft.ItemInfo;
import com.ggstudios.lolcraft.LibraryManager;
import com.ggstudios.lolcraft.LibraryUtils;
import com.ggstudios.lolcraft.R;
import com.ggstudios.lolcraft.RuneInfo;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import timber.log.Timber;
public class RunePickerDialogFragment extends ItemPickerDialogFragment {
private static final int ANIMATION_DURATION = 250;
private GridView content;
private List<RuneInfo> runes;
private EditText searchField;
private ProgressBar pbar;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog_fragment_item_picker, container, false);
View filterPane = rootView.findViewById(R.id.filterPane);
filterPane.setVisibility(View.GONE);
pbar = (ProgressBar) rootView.findViewById(R.id.pbar);
searchField = (EditText) rootView.findViewById(R.id.searchField);
searchField.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
String str = s.toString();
ListAdapter adapter = content.getAdapter();
if (adapter != null) {
((RuneInfoAdapter) adapter).filter(str);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
content = (GridView) rootView.findViewById(R.id.itemGrid);
content.setNumColumns(GridView.AUTO_FIT);
content.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
content.setColumnWidth(getActivity().getResources().getDimensionPixelSize(R.dimen.rune_info_width));
runes = LibraryManager.getInstance().getRuneLibrary().getAllRuneInfo();
if (runes == null) {
initializeItemInfo();
} else {
pbar.setVisibility(View.GONE);
filterAndShowRunes();
}
content.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
Timber.d(((RuneInfo) parent.getItemAtPosition(position)).rawJson.toString());
return false;
}
});
content.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
((RunePickerDialogListener)getActivity()).onRunePicked((RuneInfo) parent.getItemAtPosition(position));
dismiss();
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Activity act = getActivity();
if (!(act instanceof RunePickerDialogListener)) {
throw new ClassCastException(act.getClass() + " must implement ItemPickerDialogListener");
}
}
private void filterAndShowRunes() {
content.setAdapter(new RuneInfoAdapter(getActivity(),
runes));
}
private void initializeItemInfo() {
new AsyncTask<Void, ItemInfo, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Activity act = getActivity();
if (act == null) return null;
runes = LibraryUtils.getAllRuneInfo(act);
LibraryManager.getInstance().getRuneLibrary().initialize(runes);
} catch (IOException | JSONException e) {
Timber.e("", e);
}
return null;
}
@Override
protected void onPostExecute(Void v) {
if (isAdded()) {
filterAndShowRunes();
new IconFetcher().execute(getActivity().getAssets());
}
}
}.execute();
}
private class ViewHolder {
ImageView icon;
TextView name;
TextView desc;
RuneInfo rune;
ViewHolder() {}
ViewHolder ViewHolder(){
return this;
}
}
public class RuneInfoAdapter extends BaseAdapter {
private Context context;
private List<RuneInfo> runes;
private List<RuneInfo> runesFull;
private LayoutInflater inflater;
private String lastQuery;
public RuneInfoAdapter(Context c, List<RuneInfo> runes) {
context = c;
this.runes = runes;
runesFull = runes;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return runes.size();
}
public Object getItem(int position) {
return runes.get(position);
}
public long getItemId(int position) {
return 0;
}
public void filter(String s) {
if (s == null || s.length() == 0) {
runes = runesFull;
} else {
List<RuneInfo> last = runes;
runes = new ArrayList<RuneInfo>();
s = s.toLowerCase(Locale.US);
if (lastQuery != null && s.startsWith(lastQuery)) {
for (RuneInfo i : last) {
if (i.lowerName.contains(s) || i.colloq.contains(s)) {
runes.add(i);
}
}
} else {
for (RuneInfo i : runesFull) {
if (i.lowerName.contains(s) || i.colloq.contains(s)) {
runes.add(i);
}
}
}
}
notifyDataSetChanged();
lastQuery = s;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) { // if it's not recycled, initialize some attributes
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_rune_info, parent, false);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.name = (TextView) convertView.findViewById(R.id.txtName);
holder.desc = (TextView) convertView.findViewById(R.id.txtDesc);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (holder.rune != null) {
holder.rune.tag = null;
holder.rune = null;
}
RuneInfo info = runes.get(position);
holder.name.setText(info.shortName);
holder.desc.setText(info.shortDesc);
if (info.icon != null) {
holder.icon.setImageDrawable(info.icon);
} else {
holder.icon.setImageDrawable(new ColorDrawable(Color.GRAY));
info.tag = holder.icon;
holder.rune = info;
}
return convertView;
}
}
private class IconFetcher extends AsyncTask<AssetManager, RuneInfo, Void> {
@Override
protected Void doInBackground(AssetManager... params) {
AssetManager assets = params[0];
for (RuneInfo rune : runes) {
if (rune.icon == null) {
try {
rune.icon = Drawable.createFromStream(assets.open("rune/" + rune.iconAssetName), null);
publishProgress(rune);
} catch (IOException e) {
Timber.e("", e);
}
}
}
return null;
}
@Override
protected void onProgressUpdate(RuneInfo... p) {
RuneInfo rune = p[0];
if (rune.tag != null) {
ImageView v = (ImageView) rune.tag;
final TransitionDrawable td =
new TransitionDrawable(new Drawable[] {
new ColorDrawable(Color.GRAY),
rune.icon
});
td.setCrossFadeEnabled(true);
v.setImageDrawable(td);
td.startTransition(ANIMATION_DURATION);
}
}
}
public interface RunePickerDialogListener {
public void onRunePicked(RuneInfo rune);
}
}
|
package guitests.guihandles;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import guitests.GuiRobot;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
import savvytodo.TestApp;
import savvytodo.model.task.ReadOnlyTask;
import savvytodo.model.task.Task;
import savvytodo.testutil.TestUtil;
/**
* Provides a handle for the panel containing the task list.
*/
public class TaskListPanelHandle extends GuiHandle {
public static final int NOT_FOUND = -1;
public static final String CARD_PANE_ID = "#cardPane";
private static final String TASK_LIST_VIEW_ID = "#taskListView";
public TaskListPanelHandle(GuiRobot guiRobot, Stage primaryStage) {
super(guiRobot, primaryStage, TestApp.APP_TITLE);
}
public List<ReadOnlyTask> getSelectedTasks() {
ListView<ReadOnlyTask> taskList = getListView();
return taskList.getSelectionModel().getSelectedItems();
}
public ListView<ReadOnlyTask> getListView() {
return getNode(TASK_LIST_VIEW_ID);
}
/**
* Returns true if the list is showing the task details correctly and in correct order.
* @param tasks A list of task in the correct order.
*/
public boolean isListMatching(ReadOnlyTask... tasks) {
return this.isListMatching(0, tasks);
}
/**
* Returns true if the list is showing the task details correctly and in correct order.
* @param startPosition The starting position of the sub list.
* @param tasks A list of task in the correct order.
*/
public boolean isListMatching(int startPosition, boolean ignoreOrder, ReadOnlyTask... tasks)
throws IllegalArgumentException {
if (tasks.length + startPosition != getListView().getItems().size()) {
throw new IllegalArgumentException(
"List size mismatched\n" + "Expected " + (getListView().getItems().size() - 1) + " tasks, got "
+ (tasks.length + startPosition) + " instead");
}
if (!ignoreOrder) {
assertTrue(this.containsInOrder(startPosition, tasks));
}
for (int i = 0; i < tasks.length; i++) {
final int scrollTo = i + startPosition;
guiRobot.interact(() -> getListView().scrollTo(scrollTo));
guiRobot.sleep(1);
if (!TestUtil.compareCardAndTask(getTaskCardHandle(startPosition + i), tasks[i])) {
return false;
}
}
return true;
}
//@@author A0140036X
/**
* Returns true if the list is showing the task details correctly in correct order.
* @param startPosition The starting position of the sub list.
* @param tasks A list of task in the correct order.
*/
public boolean isListMatching(int startPosition, ReadOnlyTask... tasks) {
return isListMatching(0, true, tasks);
}
//@@author A0140036X
/**
* Returns true if the list is showing the task details correctly.
* @param startPosition The starting position of the sub list.
* @param tasks A list of task in the correct order.
*/
public boolean isListMatchingIgnoreOrder(ReadOnlyTask... tasks) {
return isListMatching(0, false, tasks);
}
/**
* Clicks on the ListView.
*/
public void clickOnListView() {
Point2D point = TestUtil.getScreenMidPoint(getListView());
guiRobot.clickOn(point.getX(), point.getY());
}
/**
* Returns true if the {@code tasks} appear as the sub list (in that order) at position {@code startPosition}.
*/
public boolean containsInOrder(int startPosition, ReadOnlyTask... tasks) {
List<ReadOnlyTask> tasksInList = getListView().getItems();
// Return false if the list in panel is too short to contain the given list
if (startPosition + tasks.length > tasksInList.size()) {
return false;
}
// Return false if any of the tasks doesn't match
for (int i = 0; i < tasks.length; i++) {
if (!tasksInList.get(startPosition + i).getName().name.equals(tasks[i].getName().name)) {
return false;
}
}
return true;
}
public TaskCardHandle navigateToTask(String name) {
guiRobot.sleep(100); //Allow a bit of time for the list to be updated
final Optional<ReadOnlyTask> task = getListView().getItems().stream().filter(p -> p.getName().name.equals(name))
.findAny();
if (!task.isPresent()) {
throw new IllegalStateException("Name not found: " + name);
}
return navigateToTask(task.get());
}
/**
* Navigates the listview to display and select the task.
*/
public TaskCardHandle navigateToTask(ReadOnlyTask task) {
int index = getTaskIndex(task);
guiRobot.interact(() -> {
getListView().scrollTo(index);
guiRobot.sleep(1);
getListView().getSelectionModel().select(index);
});
guiRobot.sleep(1);
return getTaskCardHandle(task);
}
/**
* Returns the position of the task given, {@code NOT_FOUND} if not found in the list.
*/
public int getTaskIndex(ReadOnlyTask targetTask) {
List<ReadOnlyTask> tasksInList = getListView().getItems();
for (int i = 0; i < tasksInList.size(); i++) {
if (tasksInList.get(i).getName().equals(targetTask.getName())) {
return i;
}
}
return NOT_FOUND;
}
/**
* Gets a task from the list by index
*/
public ReadOnlyTask getTask(int index) {
return getListView().getItems().get(index);
}
public TaskCardHandle getTaskCardHandle(int index) {
return getTaskCardHandle(new Task(getListView().getItems().get(index)));
}
public TaskCardHandle getTaskCardHandle(ReadOnlyTask task) {
Set<Node> nodes = getAllCardNodes();
Optional<Node> taskCardNode = nodes.stream()
.filter(n -> new TaskCardHandle(guiRobot, primaryStage, n).isSameTask(task)).findFirst();
if (taskCardNode.isPresent()) {
return new TaskCardHandle(guiRobot, primaryStage, taskCardNode.get());
} else {
return null;
}
}
protected Set<Node> getAllCardNodes() {
return guiRobot.lookup(CARD_PANE_ID).queryAll();
}
public int getNumberOfTasks() {
return getListView().getItems().size();
}
}
|
package se.raddo.raddose3D.tests;
import java.util.HashMap;
import org.testng.annotations.Test;
import se.raddo.raddose3D.Crystal;
import se.raddo.raddose3D.CrystalCuboid;
import se.raddo.raddose3D.CrystalPolyhedron;
import se.raddo.raddose3D.Wedge;
public class CrystalPolyhedronTests {
@Test
public static void testFindDepthSimple()
{
double xdim = 60, ydim = 20, zdim = 40; // just like in the model file.
Double resolution = 0.5d;
String modelFile = "models/cuboid-30-20-10.obj";
String modelType = "obj";
HashMap<Object, Object> properties = new HashMap<Object, Object>();
properties.put(Crystal.CRYSTAL_RESOLUTION, resolution);
properties.put(Crystal.CRYSTAL_ANGLE_P, 0d);
properties.put(Crystal.CRYSTAL_ANGLE_L, 0d);
properties.put(CrystalPolyhedron.CRYSTAL_WIREFRAME_FILE, modelFile);
properties.put(CrystalPolyhedron.CRYSTAL_WIREFRAME_TYPE, modelType);
Crystal c = new CrystalPolyhedron(properties);
Wedge w = new Wedge(0d, 0d, 0d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d);
double[] crystCoords;
// this coordinate is in voxel coordinates.
// this translates to bottom left corner of the crystal
// in crystCoords (-45, -37, -20)
// and should therefore be first to intercept the beam and have
// a depth of 0.
for (int x = 0; x < xdim * resolution; x++) {
for (int y = 0; y < ydim * resolution; y++) {
for (int z = 0; z < zdim * resolution; z++) {
crystCoords = c.getCrystCoord(x, y, z);
Assertion.equals(crystCoords[0], -(xdim / 2) + (x / resolution),
"crystal coordinate x axis for voxel (" + x + ", " + y + ", " + z + ")", 0.01);
Assertion.equals(crystCoords[1], -(ydim / 2) + (y / resolution),
"crystal coordinate y axis for voxel (" + x + ", " + y + ", " + z + ")", 0.01);
Assertion.equals(crystCoords[2], -(zdim / 2) + (z / resolution),
"crystal coordinate z axis for voxel (" + x + ", " + y + ", " + z + ")", 0.01);
c.setupDepthFinding(0, w);
double depth = c.findDepth(crystCoords, 0, w);
// The depth finding overestimates by 10/resolution :(
// depth -= (10 / resolution);
// Because the crystal has not been rotated,
// the depth should just be z / resolution
Assertion.equals(depth, z / resolution, "depth at z=" + z, 2.0);
}
}
}
}
@Test
public static void testFindDepthConcave()
{
double xdim = 30, ydim = 20, zdim = 10; // just like in the model file.
Double resolution = 0.5d;
String modelFile = "models/concave_cuboid-30-20-10.obj";
String modelType = "obj";
HashMap<Object, Object> properties = new HashMap<Object, Object>();
properties.put(Crystal.CRYSTAL_RESOLUTION, resolution);
properties.put(Crystal.CRYSTAL_ANGLE_P, 0d);
properties.put(Crystal.CRYSTAL_ANGLE_L, 0d);
properties.put(CrystalPolyhedron.CRYSTAL_WIREFRAME_FILE, modelFile);
properties.put(CrystalPolyhedron.CRYSTAL_WIREFRAME_TYPE, modelType);
Crystal c = new CrystalPolyhedron(properties);
Wedge w = new Wedge(0d, 0d, 0d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d);
// this is where the beam should be going through the thickest
// part of the crystal
double [] crystCoordThiN = {3, 30.28, 8.4};
// thinnest part of the crystal
double [] crystCoordThiCK = {3.5, 29.9, -8.65};
c.setupDepthFinding(0, w);
double thickDepth = c.findDepth(crystCoordThick, 0, w);
Assertion.equals(thickDepth, 30.0, "Thick part of crystal about 30 um", 1.0);
double thinDepth = c.findDepth(crystCoordThin, 0, w);
Assertion.equals(thickDepth, 20.0, "Thin part of crystal about 20 um", 3.0);
}
}
|
package com.ibm.mobilefirstplatform.appid;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.ibm.bluemix.appid.android.api.AppID;
import com.ibm.bluemix.appid.android.api.AppIDAuthorizationManager;
import com.ibm.bluemix.appid.android.api.AuthorizationException;
import com.ibm.bluemix.appid.android.api.AuthorizationListener;
import com.ibm.bluemix.appid.android.api.LoginWidget;
import com.ibm.bluemix.appid.android.api.tokens.AccessToken;
import com.ibm.bluemix.appid.android.api.tokens.IdentityToken;
import com.ibm.bluemix.appid.android.api.userattributes.UserAttributeResponseListener;
import com.ibm.bluemix.appid.android.api.userattributes.UserAttributesException;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener;
import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.Logger;
import org.json.JSONObject;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private final static String mcaTenantId = "50d0beed-add7-48dd-8b0a-c818cb456bb4";
private final static String region = ".stage1.mybluemix.net";
private final static Logger logger = Logger.getLogger(MainActivity.class.getName());
private AppID appId;
private AppIDAuthorizationManager appIDAuthorizationManager;
@Override
protected void onCreate (Bundle savedInstanceState) {
logger.setLogLevel(Logger.LEVEL.DEBUG);
Logger.setSDKDebugLoggingEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BMSClient bmsClient= BMSClient.getInstance();
bmsClient.initialize(this, region);
// Initialize AppID SDK
appId = AppID.getInstance();
appId.initialize(this, mcaTenantId, region);
//uncomment to run locally
// Add integration with BMSClient. Optional.
this.appIDAuthorizationManager = new AppIDAuthorizationManager(this.appId);
bmsClient.setAuthorizationManager(appIDAuthorizationManager);
}
public void onAnonLoginClick (View v) {
logger.debug("onAnonLoginClick");
appId.loginAnonymously(getApplicationContext(), new AuthorizationListener() {
@Override
public void onAuthorizationFailure(AuthorizationException exception) {
logger.error("Anonymous authorization failure");
if (exception != null) {
logger.debug(exception.getLocalizedMessage(), exception);
}
hideProgress();
}
@Override
public void onAuthorizationCanceled() {
logger.warn("Anonymous authorization cancellation");
hideProgress();
}
@Override
public void onAuthorizationSuccess(AccessToken accessToken, IdentityToken identityToken) {
logger.info("Anonymous authorization success");
hideProgress();
extractAndDisplayDataFromIdentityToken(identityToken);
}
});
}
public void onLoginClick (View v) {
logger.debug("onLoginClick");
showProgress();
LoginWidget loginWidget = appId.getLoginWidget();
loginWidget.launch(this, new AuthorizationListener() {
@Override
public void onAuthorizationFailure (AuthorizationException exception) {
logger.info("onAuthorizationFailure");
hideProgress();
}
@Override
public void onAuthorizationCanceled () {
logger.info("onAuthorizationCanceled");
hideProgress();
}
@Override
public void onAuthorizationSuccess (AccessToken accessToken, IdentityToken identityToken) {
logger.info("onAuthorizationSuccess");
logger.info("access_token: " + accessToken.getRaw());
logger.info("id_token: " + identityToken.getRaw());
logger.info("access_token isExpired: " + accessToken.isExpired());
logger.info("id_token isExpired: " + identityToken.isExpired());
hideProgress();
extractAndDisplayDataFromIdentityToken(identityToken);
}
});
}
public void onProtectedRequestClick (View v) {
showResponse("");
showProgress();
Request r = new Request("http://appid-rotem.stage1.mybluemix.net/protectedResource", Request.GET);
r.send(this, new ResponseListener() {
@Override
public void onSuccess (Response response) {
logger.info("Request onSuccess");
hideProgress();
IdentityToken identityToken = appIDAuthorizationManager.getIdentityToken();
extractAndDisplayDataFromIdentityToken(identityToken);
showResponse(response.getResponseText());
}
@Override
public void onFailure (Response response, Throwable t, JSONObject extendedInfo) {
logger.error("Request onFailure");
hideProgress();
}
});
}
public void onPutAttributeClick(View v) {
String name = ((EditText)findViewById(R.id.editAttrName)).getText().toString();
String value = ((EditText)findViewById(R.id.editAttrValue)).getText().toString();
appId.getUserAttributeManager().setAttribute(name, value, new UserAttributeResponseListener() {
@Override
public void onSuccess(JSONObject attributes) {
showResponse(attributes.toString());
}
@Override
public void onFailure(UserAttributesException e) {
showResponse(e.getError() + " : " + e.getMessage());
}
});
}
public void onGetAttributeClick(View v) {
String name = ((EditText)findViewById(R.id.editAttrName)).getText().toString();
appId.getUserAttributeManager().getAttribute(name, new UserAttributeResponseListener() {
@Override
public void onSuccess(JSONObject attributes) {
showResponse(attributes.toString());
}
@Override
public void onFailure(UserAttributesException e) {
showResponse(e.getError() + " : " + e.getMessage());
}
});
}
public void onGetAllAttributesClick(View v) {
appId.getUserAttributeManager().getAllAttributes( new UserAttributeResponseListener() {
@Override
public void onSuccess(JSONObject attributes) {
showResponse(attributes.toString());
}
@Override
public void onFailure(UserAttributesException e) {
showResponse(e.getError() + " : " + e.getMessage());
}
});
}
public void onDeleteAttributeClick (View v) {
String name = ((EditText)findViewById(R.id.editAttrName)).getText().toString();
appId.getUserAttributeManager().deleteAttribute(name, new UserAttributeResponseListener() {
@Override
public void onSuccess(JSONObject attributes) {
showResponse(attributes.toString());
}
@Override
public void onFailure(UserAttributesException e) {
showResponse(e.getError() + " : " + e.getMessage());
}
});
}
private void extractAndDisplayDataFromIdentityToken (IdentityToken identityToken) {
String picUrl = null;
String displayName = null;
try {
if (identityToken.isAnonymous()){
picUrl = null;
displayName = "Anonymous User ( " + identityToken.getSubject() + " )";
} else {
picUrl = identityToken.getPicture();
displayName = identityToken.getName();
}
showPictureAndName(picUrl, displayName);
logger.info("extractAndDisplayDataFromIdentityToken done");
} catch (Exception e){
logger.error("ERROR", e);
}
}
private void showResponse (final String result) {
//run on main thread
runOnUiThread(new Runnable() {
@Override
public void run () {
TextView nameTextView = (TextView) findViewById(R.id.textViewProtectedResourceResponse);
nameTextView.setText(result);
hideProgress();
}
});
}
private void showPictureAndName (final String picUrl, final String displayName) {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
final Bitmap bmp = picUrl == null ?
null :
BitmapFactory.decodeStream(new URL(picUrl).openConnection().getInputStream());
//run on main thread
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageView profilePicture = (ImageView) findViewById(R.id.profilePic);
if(bmp == null) {
profilePicture.setImageResource(R.mipmap.ic_launcher);
}else {
profilePicture.setImageBitmap(bmp);
}
profilePicture.requestLayout();
profilePicture.getLayoutParams().height = 350;
profilePicture.getLayoutParams().width = 350;
profilePicture.setScaleType(ImageView.ScaleType.FIT_XY);
profilePicture.setVisibility(View.VISIBLE);
findViewById(R.id.anonloginButton).setVisibility(View.GONE);
TextView nameTextView = (TextView) findViewById(R.id.name);
nameTextView.setText(displayName);
}
});
} catch (Exception e) {
showResponse("Login error" + e.getMessage());
e.printStackTrace();
}
}
});
}
private void showProgress () {
runOnUiThread(new Runnable() {
@Override
public void run () {
findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
findViewById(R.id.loadingPanel).bringToFront();
findViewById(R.id.loginButton).setEnabled(false);
findViewById(R.id.protectedRequestButton).setEnabled(false);
}
});
}
private void hideProgress () {
runOnUiThread(new Runnable() {
@Override
public void run () {
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
findViewById(R.id.loginButton).setEnabled(true);
findViewById(R.id.protectedRequestButton).setEnabled(true);
}
});
}
}
|
package kikaha.mojo;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import kikaha.core.Main;
import lombok.RequiredArgsConstructor;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
/**
* @goal run
* @requiresDependencyResolution compile+runtime
*/
public class KikahaRunnerMojo extends AbstractMojo {
final static String SEPARATOR = System.getProperty( "path.separator" );
/**
* @parameter default-value="${project}"
* @required
* @readonly
*/
MavenProject project;
/**
* The profile configuration to load when running the server.
*
* @parameter default-value=""
*/
String profile;
/**
* @parameter default-value="${plugin}"
*/
PluginDescriptor plugin;
/** @parameter default-value="${localRepository}" */
ArtifactRepository localRepository;
/**
* Used to construct artifacts for deletion/resolution...
*
* @component
*/
ArtifactFactory factory;
/**
* @component
*/
ArtifactResolver resolver;
/**
* Name of the generated JAR.
*
* @parameter alias="jarName" expression="${jar.finalName}"
* default-value="${project.build.finalName}"
* @required
*/
String finalName;
/**
* Directory containing the build files.
*
* @parameter expression="${project.build.directory}"
*/
File buildDirectory;
StringBuilder classPath = new StringBuilder();
String standaloneJar;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
memorizeClassPathWithRunnableJar();
String commandLineString = getCommandLineString();
System.out.println( "CML: " + commandLineString );
run( commandLineString );
} catch ( Exception e ) {
throw new MojoExecutionException( "Can't initialize Kikaha.", e );
}
}
@SuppressWarnings( "unchecked" )
void memorizeClassPathWithRunnableJar()
throws DependencyResolutionRequiredException, ArtifactResolutionException, ArtifactNotFoundException {
final List<String> artifactsInClassPath = new ArrayList<>();
for ( Artifact artifact : (Set<Artifact>)this.project.getArtifacts() ) {
final String artifactAbsolutePath = getArtifactAbsolutePath( artifact );
if ( !artifactsInClassPath.contains( artifactAbsolutePath ) ) {
this.classPath.append( artifactAbsolutePath ).append( SEPARATOR );
artifactsInClassPath.add( artifactAbsolutePath );
}
}
this.classPath
.append( getFinalArtifactName() )
.append( SEPARATOR ).append( "." );
}
String getArtifactAbsolutePath( Artifact artifact )
throws ArtifactResolutionException, ArtifactNotFoundException {
this.resolver.resolve( artifact, Collections.EMPTY_LIST, this.localRepository );
return artifact.getFile().getAbsolutePath();
}
String getFinalArtifactName() {
String fileName = String.format( "%s.%s", this.finalName, this.project.getPackaging() );
return new File( this.buildDirectory, fileName ).getAbsolutePath();
}
String getCommandLineString() {
return String.format(
"java -cp \"%s\" %s %s",
this.classPath.toString(),
Main.class.getCanonicalName(),
this.profile != null ? this.profile : "" );
}
void run( String commandLineString ) throws IOException, InterruptedException {
final Runtime runtime = Runtime.getRuntime();
final Process exec = runtime.exec( commandLineString );
runtime.addShutdownHook( new ProcessDestroyer( exec ) );
printAsynchronously( exec.getInputStream() );
printAsynchronously( exec.getErrorStream() );
if ( exec.waitFor() > 0 )
throw new RuntimeException( "The Kikaha has failed to run." );
}
void printAsynchronously( InputStream stream ) {
new Thread( new ProcessOutputPrinter( stream ) ).start();
}
}
@RequiredArgsConstructor
class ProcessDestroyer extends Thread {
final Process process;
@Override
public void run() {
process.destroy();
System.out.println( "Kikaha has shutting down!" );
}
}
|
package it.geosolutions.geoserver.rest;
import it.geosolutions.geoserver.rest.decoder.RESTStyle;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
import org.springframework.core.io.ClassPathResource;
/**
*
* @author etj
*/
public class UtilTest extends GeoserverRESTTest {
private final static Logger LOGGER = LoggerFactory.getLogger(UtilTest.class);
@Test
public void testSearchStyle() throws IOException {
if (!enabled()) {
return;
}
deleteAll();
final String WORKSPACE = "testWorkspace";
final String WORKSPACE_DUMMY_STD = "stdWorkspace";
final String STYLENAME = "restteststyle";
File sldFile = new ClassPathResource("testdata/restteststyle.sld").getFile();
//first workspace if per definition standard. If our test workspace would be standard, geoserver does not differ
//global and workspace styles anymore.
publisher.createWorkspace(WORKSPACE_DUMMY_STD);
publisher.createWorkspace(WORKSPACE);
assertEquals(0, reader.getStyles().size());
assertEquals(0, reader.getStyles(WORKSPACE).size());
assertEquals(0, Util.searchStyles(reader, STYLENAME).size());
// insert style in workspace
assertTrue(publisher.publishStyleInWorkspace(WORKSPACE, sldFile, STYLENAME));
assertTrue(reader.existsStyle(WORKSPACE, STYLENAME));
// GeoServer returns workspace specific names if hte name is not found as global
assertFalse(reader.existsStyle(STYLENAME));
assertEquals(0, reader.getStyles().size());
assertEquals(1, reader.getStyles(WORKSPACE).size());
assertEquals(1, Util.searchStyles(reader, STYLENAME).size());
// insert global style
assertTrue(publisher.publishStyle(sldFile, STYLENAME));
assertTrue(reader.existsStyle(STYLENAME));
assertTrue(reader.existsStyle(WORKSPACE, STYLENAME));
// GeoServer problem
assertEquals(2, Util.searchStyles(reader, STYLENAME).size());
for(RESTStyle style : Util.searchStyles(reader, STYLENAME))
{
LOGGER.debug(style.getWorkspace() + " :: " + style.getName());
}
// there's a bug in geoserver here: the global style will include workspace info
// Commenting out all the concerned test code
// assertEquals(2, Util.searchStyles(reader, STYLENAME).size());
// assertEquals(1, reader.getStyles().size());
// assertEquals(1, reader.getStyles(WORKSPACE).size());
// List<RESTStyle> styles = Util.searchStyles(reader, STYLENAME);
// assertEquals(STYLENAME, styles.get(0).getName());
// // assertEquals(null, styles.get(0).getWorkspace()); // first one is the global one, if any
// assertEquals(STYLENAME, styles.get(1).getName());
// assertEquals(WORKSPACE, styles.get(1).getWorkspace());
}
}
|
package com.iuridiniz.checkmyecg.examiners;
import org.apache.commons.math3.util.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.TreeMap;
public class EkgExaminer {
public enum Orientation {
UP, DOWN
};
public static final double ONE_SQUARE_X = 0.04;
public static final double ONE_SQUARE_Y = 0.1;
private final double[] time;
private final double[] voltage;
private LinkedList<Integer> __peaksPositions = null;
private final Orientation normalOrientation;
public final LinkedList<Integer> getPeaksPositions() {
if (__peaksPositions != null)
return __peaksPositions;
/* parse peaks */
__peaksPositions = new LinkedList<Integer>();
int direction = 0;
if (time.length < 3) {
return __peaksPositions;
}
for (int i = 0; i < time.length; i++) {
int new_direction;
double volt_diff;
if (i == 0) {
/* fisrt */
}
if (i+1 == time.length) {
/* last */
if (direction == 1) {
__peaksPositions.add(i);
}
continue;
}
volt_diff = voltage[i+1] - voltage[i];
new_direction = 0;
if (volt_diff < 0 ) {
new_direction = -1;
} else if (volt_diff > 0 ){
new_direction = 1;
}
if (new_direction != 0 && new_direction != direction) {
if (new_direction == 1) {
/* depression */
} else if (new_direction == -1){
/* peak */
__peaksPositions.add(i);
}
direction = new_direction;
}
}
/* return the median point */
for (int i=0; i<__peaksPositions.size(); i++) {
int start_pos = __peaksPositions.get(i);
int pos = __peaksPositions.get(i);
if (pos == 0) {
/* peek at start */
} else {
/* backward start_pos to the first value lower than threshold */
while (start_pos > 0 && voltage[start_pos-1] >= voltage[pos]) {
start_pos
};
/* change to median point */
int point = (Integer) (pos - start_pos)/2 + start_pos;
__peaksPositions.set(i, point);
}
}
return __peaksPositions;
}
public final TreeMap<Integer, Double> getPeaksPositionsAndCoefficients(double smoothness, /* linear coefficient */
double threshold) {
LinkedList<Integer> peaks = getPeaksPositions();
TreeMap<Integer, Double> result = new TreeMap<>();
for (int pos: peaks) {
/* get previous points */
int start_pos = pos;
if (pos == 0) {
/* peek at start */
} else {
/* backward start_pos to the first value greather than threashold */
while (start_pos > 0 && (voltage[pos] - voltage[start_pos]) < threshold) {
start_pos
};
}
if (start_pos > 0) {
double dx = time[pos] - time[start_pos-1];
double dy = voltage[pos] - voltage[start_pos-1];
double coefficient = dy/dx;
if (coefficient >= smoothness) {
result.put(pos, coefficient);
}
}
}
return result;
}
public final LinkedList<Integer> getPeaksPositions(double smoothness, /* linear coefficient */
double threshold) {
TreeMap<Integer, Double> posAndCo = getPeaksPositionsAndCoefficients(smoothness, threshold);
return new LinkedList<>(posAndCo.keySet());
}
public final LinkedList<Integer> getAcutePeaksPositions() {
return getPeaksPositions(1.0, ONE_SQUARE_Y);
}
public final TreeMap<Integer, Double> getAcutePeaksPositionsAndCoefficients() {
return getPeaksPositionsAndCoefficients(1.0, ONE_SQUARE_Y);
}
public EkgExaminer(double[] signalX, double[] signalY) {
this(signalX, signalY, Orientation.DOWN);
}
public EkgExaminer(double[] time, double[] voltage, Orientation o) {
this.time = time;
this.voltage = voltage;
if (time.length != voltage.length) {
throw new IllegalArgumentException("time.lenght must be equal to voltage.lenght");
}
this.normalOrientation = o;
}
public double getFrequency() {
final TreeMap<Integer, Double> coefficients = getAcutePeaksPositionsAndCoefficients();
Integer[] peaks = coefficients.keySet().toArray(new Integer[0]);
if (peaks.length < 4) {
/* insufficient points to determine the frequency */
return 0.0;
}
class MyPair extends Pair<Integer, Integer> implements Comparable{
final double diffTime;
final double diffCoef;
final double diffVolt;
int points = 0;
int coefPoints;
final int voltPoints;
public MyPair(Integer o1, Integer o2) {
super(o1, o2);
diffTime = Math.abs(time[o1] - time[o2]);
diffCoef = Math.abs(coefficients.get(o1) - coefficients.get(o2));
diffVolt = Math.abs(voltage[o1] - voltage[o2]);
coefPoints = (int) (10.0/diffCoef);
points += coefPoints >50?50: coefPoints;
voltPoints = (int) (5.0/diffVolt);
points += voltPoints >100?100: voltPoints;
}
@Override
public int compareTo(Object o) {
return points - ((MyPair) o).points;
}
}
ArrayList<MyPair> a = new ArrayList<>();
for(int i = 0; i < peaks.length; i++) {
for (int j=i + 1;j< peaks.length; j++) {
MyPair p = new MyPair(peaks[i], peaks[j]);
a.add(p);
}
}
/* choose the best one */
Collections.sort(a);
Collections.reverse(a);
return 60.0/a.get(0).diffTime;
//return 60/a.get(0).diffTime;
}
}
|
package mealplaner.model;
import static mealplaner.model.MealplanerCalendar.getDaysBetween;
import static org.junit.Assert.assertEquals;
import java.util.Calendar;
import org.junit.Before;
import org.junit.Test;
public class MealplanerCalendarTest {
private MealplanerCalendar sut;
@Before
public void setup() {
sut = new MealplanerCalendar(Calendar.getInstance());
}
@Test
public void setDateTest() {
sut.setDate(2015, 0, 1);
Calendar expected = Calendar.getInstance();
expected.set(2015, 0, 1);
assertEquals(expected.getTime(), sut.getTime());
}
@Test
public void getDaysPassedToWithSomeDateInThePast() {
sut.setDate(2017, 0, 1);
Calendar compareToCalendar = getCustomCalendar(2015, 0, 1);
int daysPassed = sut.getDaysPassedTo(compareToCalendar);
assertEquals(0, daysPassed);
}
@Test
public void getDaysPassedToSameYear() {
sut.setDate(2016, 0, 1);
Calendar compareToCalendar = getCustomCalendar(2016, 5, 7);
int daysPassed = sut.getDaysPassedTo(compareToCalendar);
assertEquals(30 + 29 + 31 + 30 + 31 + 7, daysPassed);
}
@Test
public void getDaysPassedToSameYearNoLeapYear() {
sut.setDate(2015, 0, 1);
Calendar compareToCalendar = getCustomCalendar(2015, 5, 7);
int daysPassed = sut.getDaysPassedTo(compareToCalendar);
assertEquals(30 + 28 + 31 + 30 + 31 + 7, daysPassed);
}
@Test
public void getDaysPassedToLessThanAYear() {
sut.setDate(2015, 9, 5);
Calendar compareToCalendar = getCustomCalendar(2016, 1, 7);
int daysPassed = sut.getDaysPassedTo(compareToCalendar);
assertEquals(26 + 30 + 31 + 31 + 7, daysPassed);
}
@Test
public void getDaysPassedToMoreThanAYear() {
sut.setDate(2014, 0, 1);
Calendar compareToCalendar = getCustomCalendar(2016, 5, 7);
int daysPassed = sut.getDaysPassedTo(compareToCalendar);
assertEquals(364 + 365 + 31 + 29 + 31 + 30 + 31 + 7, daysPassed);
}
@Test
public void correctNumberOfDaysForDaysAppart() {
Calendar oldCal = Calendar.getInstance();
Calendar newCal = Calendar.getInstance();
oldCal.set(30, 10, 5, 20, 0, 0);
newCal.set(30, 10, 7, 20, 0, 0);
int daysPassed = getDaysBetween(oldCal, newCal);
assertEquals(2, daysPassed);
}
@Test
public void correctNumberOfDaysIfOldLiesInTheFutureAppart() {
Calendar oldCal = Calendar.getInstance();
Calendar newCal = Calendar.getInstance();
oldCal.set(31, 10, 5, 20, 0, 0);
newCal.set(30, 10, 7, 20, 0, 0);
int daysPassed = getDaysBetween(oldCal, newCal);
assertEquals(0, daysPassed);
}
@Test
public void correctNumberOfDaysForMonthsAndYearsAppart() {
Calendar oldCal = Calendar.getInstance();
Calendar newCal = Calendar.getInstance();
oldCal.set(30, 10, 5, 20, 0, 0);
newCal.set(32, 11, 7, 20, 0, 0);
int daysPassed = getDaysBetween(oldCal, newCal);
assertEquals(763, daysPassed);
}
@Test
public void correctNumberOfDaysForDaysAppartButNotMillis() {
Calendar oldCal = Calendar.getInstance();
Calendar newCal = Calendar.getInstance();
oldCal.set(30, 10, 5, 20, 0, 0);
newCal.set(30, 10, 6, 3, 0, 0);
int daysPassed = getDaysBetween(oldCal, newCal);
assertEquals(1, daysPassed);
}
private Calendar getCustomCalendar(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
return calendar;
}
}
|
package com.jamieadkins.gwent.card.list;
import android.support.annotation.NonNull;
import com.jamieadkins.gwent.card.CardFilter;
import com.jamieadkins.gwent.card.list.CardsContract;
import com.jamieadkins.gwent.data.CardDetails;
import com.jamieadkins.gwent.data.interactor.CardsInteractor;
import com.jamieadkins.gwent.data.interactor.RxDatabaseEvent;
import io.reactivex.Observable;
/**
* Listens to user actions from the UI, retrieves the data and updates the
* UI as required.
*/
public class CardsPresenter implements CardsContract.Presenter {
private final CardsInteractor mCardsInteractor;
private final CardsContract.View mCardsView;
public CardsPresenter(@NonNull CardsContract.View cardsView,
@NonNull CardsInteractor cardsInteractor) {
mCardsInteractor = cardsInteractor;
mCardsView = cardsView;
mCardsView.setPresenter(this);
}
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public Observable<RxDatabaseEvent<CardDetails>> getCards(CardFilter filter) {
return mCardsInteractor.getCards(filter);
}
}
|
package com.wisape.android.cordova;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.parse.codec.digest.DigestUtils;
import com.wisape.android.R;
import com.wisape.android.WisapeApplication;
import com.wisape.android.activity.MainActivity;
import com.wisape.android.activity.StoryMusicActivity;
import com.wisape.android.activity.StoryPreviewActivity;
import com.wisape.android.activity.StoryReleaseActivity;
import com.wisape.android.activity.StorySettingsActivity;
import com.wisape.android.activity.StoryTemplateActivity;
import com.wisape.android.api.ApiStory;
import com.wisape.android.common.StoryManager;
import com.wisape.android.content.StoryBroadcastReciver;
import com.wisape.android.content.StoryBroadcastReciverListener;
import com.wisape.android.database.StoryEntity;
import com.wisape.android.database.StoryMusicEntity;
import com.wisape.android.logic.StoryLogic;
import com.wisape.android.logic.UserLogic;
import com.wisape.android.model.StoryFontInfo;
import com.wisape.android.model.StoryTemplateInfo;
import com.wisape.android.network.DataSynchronizer;
import com.wisape.android.network.Requester;
import com.wisape.android.util.LogUtil;
import com.wisape.android.util.Utils;
import com.wisape.android.util.ZipUtils;
import com.wisape.android.widget.CustomProgress;
import org.apache.commons.io.FileUtils;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StoryTemplatePlugin extends AbsPlugin {
private static final String FILE_NAME_THUMB = "thumb.jpg";
private static final String FILE_NAME_STORY = "story.html";
private static final String FILE_NAME_PREVIEW = "preview.html";
private static final String FILE_NAME_TEMPLATE = "stage.html";
private static final String FILE_NAME_FONT = "fonts.css";
private static final String DIR_NAME_IMAGE = "img";
private static final String PREVIEW_HEADER = "www/views/header.html";
private static final String PREVIEW_FOOTER = "www/views/footer.html";
private static final String PLACE_HODLER_FONT_CSS = "FONT_STYLE_FILE_LOCATION";
public static final String ACTION_GET_STAGE_CATEGORY = "getStageCategory";
public static final String ACTION_GET_STAGE_LIST = "getStageList";
public static final String ACTION_START = "start";
public static final String ACTION_READ = "read";
public static final String ACTION_GET_FONTS = "getFonts";
public static final String ACTION_DOWNLOAD_FONT = "downloadFont";
public static final String ACTION_MUSIC_PATH = "getMusicPath";
public static final String ACTION_SAVE = "save";
public static final String ACTION_PREVIEW = "preview";
public static final String ACTION_PUBLISH = "publish";
public static final String ACTION_SETTING = "setting";
public static final String ACTION_BACK = "back";
public static final String ACTION_EDIT = "edit";
public static final String ACTION_GET_CONTENT = "getContent";
public static final String ACTION_CHECK_DOWNLOAD = "checkInitState";//onInitCompleted
public static final String ACTION_OPEN_LINK = "openLink";
private static final int WHAT_GET_STAGE_CATEGORY = 0x01;
private static final int WHAT_GET_STAGE_LIST = 0x02;
private static final int WHAT_START = 0x03;
private static final int WHAT_SAVE = 0x04;
private static final int WHAT_PREVIEW = 0x05;
private static final int WHAT_PUBLISH = 0x06;
private static final int WHAT_GET_FONTS = 0x07;
private static final int WHAT_DOWNLOAD_FONT = 0x08;
private static final int WHAT_EDIT_INIT = 0x09;
private static final String EXTRA_CATEGORY_ID = "extra_category_id";
private static final String EXTRA_TEMPLATE_ID = "extra_template_id";
private static final String EXTRA_FONT_NAME = "extra_font_name";
private static final String EXTRA_STORY_THUMB = "extra_story_thumb";
private static final String EXTRA_STORY_HTML = "extra_story_html";
private static final String EXTRA_FILE_PATH = "extra_file_path";
private CustomProgress customProgress;
private StoryLogic logic = StoryLogic.instance();
private WisapeApplication app = WisapeApplication.getInstance();
private CallbackContext callbackContext;
public void showProgressDialog() {
if (customProgress == null) {
customProgress = CustomProgress.show(getCurrentActivity(), getCurrentActivity().getResources()
.getString(R.string.progress_loading_data), true);
}
if (customProgress.isShowing()) {
customProgress.setMessage(getCurrentActivity().getResources().getString(R.string.progress_loading_data));
return;
}
customProgress.setMessage(getCurrentActivity().getResources().getString(R.string.progress_loading_data));
customProgress.show();
}
public void closeProgressDialog() {
if (customProgress != null && customProgress.isShowing()) {
customProgress.dismiss();
}
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}
private interface TemplateOp {
void run(Bundle bundle) throws Exception;
}
/* helper to execute functions async and handle the result codes
*
*/
private void threadhelper(final TemplateOp f, final Bundle bundle, final CallbackContext callbackContext){
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
f.run(bundle);
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
}
});
}
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (null == action || 0 == action.length()) {
return true;
}
this.callbackContext = callbackContext;
final Context context = getCurrentActivity().getApplicationContext();
if (ACTION_GET_STAGE_CATEGORY.equals(action)) {//getStageCategory
// System.out.println("getStageCategory");
// startLoad(WHAT_GET_STAGE_CATEGORY, null);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
JSONArray jsonStr = logic.listStoryTemplateTypeLocal(context);
LogUtil.d(":" + jsonStr);
callbackContext.success(jsonStr);
}
}, null, callbackContext);
} else if (ACTION_GET_STAGE_LIST.equals(action)) {//getStageList
Bundle bundle = new Bundle();
if (null != args && args.length() != 0) {
bundle.putInt(EXTRA_CATEGORY_ID, args.getInt(0));
}
// startLoad(WHAT_GET_STAGE_LIST, bundle);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
int type = bundle.getInt(EXTRA_CATEGORY_ID, 0);
List<StoryTemplateInfo> entities = logic.listStoryTemplateLocalByType(context, type);
LogUtil.d("story:" + entities.toString());
callbackContext.success(new Gson().toJson(entities));
}
}, bundle, callbackContext);
} else if (ACTION_START.equals(action)) {//start
Bundle bundle = new Bundle();
if (null != args && args.length() != 0) {
bundle.putInt(EXTRA_TEMPLATE_ID, args.getInt(0));
bundle.putInt(EXTRA_CATEGORY_ID, args.getInt(1));
}
// startLoad(WHAT_START, bundle);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
ApiStory.AttrTemplateInfo attr = new ApiStory.AttrTemplateInfo();
attr.id = bundle.getInt(EXTRA_TEMPLATE_ID, 0);
int categoryId = bundle.getInt(EXTRA_CATEGORY_ID, 1);
Requester.ServerMessage message = logic.getStoryTemplateUrl(context, attr, null);
if (!message.succeed()) {
callbackContext.error(message.status);
return;
}
if (cordova.getActivity() instanceof StoryTemplateActivity) {
StoryTemplateActivity activity = (StoryTemplateActivity) cordova.getActivity();
try {
activity.downloadTemplate(message.data.toString(), attr.id, categoryId);
} catch (JSONException e) {
callbackContext.error(-1);
}
}
}
}, bundle, callbackContext);
} else if (ACTION_READ.equals(action)) {//read
// if (null != args && args.length() != 0) {
// String path = args.getString(0);//
// String content = readHtml(path);
// callbackContext.success(content);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
if (null != args && args.length() != 0) {
String path = args.optString(0);
String content = readHtml(path);
callbackContext.success(content);
}
}
}, null, callbackContext);
} else if (ACTION_MUSIC_PATH.equals(action)) {//getMusicPath
// if (null != args && args.length() == 1) {
// int id = args.getInt(0);
// getMusicPath(id);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
if (null != args && args.length() == 1) {
int id = args.optInt(0);
getMusicPath(id);
}
}
}, null, callbackContext);
} else if (ACTION_GET_FONTS.equals(action)) {//getFonts
// startLoad(WHAT_GET_FONTS, null);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
StoryFontInfo[] fonts = logic.listFont(context, "getFonts");
List<StoryFontInfo> fontList = Arrays.asList(fonts);
System.out.println(fontList);
getFonts(fontList);
}
}, null, callbackContext);
} else if (ACTION_DOWNLOAD_FONT.equals(action)) {
Bundle bundle = new Bundle();
if (null != args && args.length() != 0) {
bundle.putString(EXTRA_FONT_NAME, args.getString(0));
}
// startLoad(WHAT_DOWNLOAD_FONT, bundle);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
String fontName = bundle.getString(EXTRA_FONT_NAME);
if (cordova.getActivity() instanceof StoryTemplateActivity) {
StoryTemplateActivity activity = (StoryTemplateActivity) cordova.getActivity();
activity.downloadFont(fontName);
}
}
}, bundle, callbackContext);
} else if (ACTION_SAVE.equals(action)) {//save
Bundle bundle = new Bundle();
if (null != args && args.length() == 3) {
bundle.putString(EXTRA_STORY_THUMB, args.getString(0));
bundle.putString(EXTRA_STORY_HTML, args.getString(1));
bundle.putString(EXTRA_FILE_PATH, args.getString(2));
}
// startLoad(WHAT_SAVE, bundle);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
String storyThumb = bundle.getString(EXTRA_STORY_THUMB);
String html = bundle.getString(EXTRA_STORY_HTML);
String path = bundle.getString(EXTRA_FILE_PATH);
com.alibaba.fastjson.JSONArray paths = JSON.parseArray(path);
LogUtil.d("story:" + storyThumb);
LogUtil.d("story:" + paths.toJSONString());
StoryEntity story = StoryLogic.instance().getStoryEntityFromShare();
story.status = ApiStory.AttrStoryInfo.STORY_STATUS_TEMPORARY;
File myStory = new File(StoryManager.getStoryDirectory(), story.storyLocal);
if (!myStory.exists()) {
myStory.mkdirs();
}
if (!saveStory(myStory, story, storyThumb, html, paths)) {
callbackContext.error(-1);
return;
}
StoryEntity storyEntity = StoryLogic.instance().updateStory(WisapeApplication.getInstance(), story);
if(null == storyEntity){
callbackContext.error(-1);
return;
}
StoryLogic.instance().saveStoryEntityToShare(storyEntity);
sendBroadcastUpdateStory();
MainActivity.launch(getCurrentActivity());
cordova.getActivity().finish();
}
}, bundle, callbackContext);
} else if (ACTION_PREVIEW.equals(action)) {//preview
Bundle bundle = new Bundle();
if (null != args && args.length() == 3) {
bundle.putString(EXTRA_STORY_THUMB, args.getString(0));
bundle.putString(EXTRA_STORY_HTML, args.getString(1));
bundle.putString(EXTRA_FILE_PATH, args.getString(2));
}
// startLoad(WHAT_PREVIEW, bundle);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
String storyThumb = bundle.getString(EXTRA_STORY_THUMB);
String html = bundle.getString(EXTRA_STORY_HTML);
String path = bundle.getString(EXTRA_FILE_PATH);
com.alibaba.fastjson.JSONArray paths = JSON.parseArray(path);
LogUtil.d("story:" + storyThumb);
LogUtil.d("story:" + paths.toJSONString());
StoryEntity story = StoryLogic.instance().getStoryEntityFromShare();
story.status = ApiStory.AttrStoryInfo.STORY_STATUS_TEMPORARY;
File myStory = new File(StoryManager.getStoryDirectory(), story.storyLocal);
if (!myStory.exists()) {
myStory.mkdirs();
}
if (!saveStory(myStory, story, storyThumb, html, paths)) {
callbackContext.error(-1);
return;
}
// StoryEntity storyEntity = StoryLogic.instance().updateStory(getCurrentActivity(), StoryLogic.instance().getStoryEntityFromShare());
StoryLogic.instance().saveStoryEntityToShare(story);
File previewFile = new File(myStory, FILE_NAME_PREVIEW);
if (saveStoryPreview(previewFile, html, story)) {
callbackContext.success();
StoryPreviewActivity.launch(cordova.getActivity(), previewFile.getAbsolutePath());
} else {
callbackContext.error(-1);
}
}
}, bundle, callbackContext);
} else if (ACTION_PUBLISH.equals(action)) {//publish
StoryReleaseActivity.launch(cordova.getActivity());
getCurrentActivity().finish();
// Bundle bundle = new Bundle();
// if (null != args && args.length() == 3) {
// bundle.putString(EXTRA_STORY_THUMB, args.getString(0));
// bundle.putString(EXTRA_STORY_HTML, args.getString(1));
// bundle.putString(EXTRA_FILE_PATH, args.getString(2));
// showProgressDialog();
//// startLoad(WHAT_PUBLISH, bundle);
// threadhelper(new TemplateOp() {
// public void run(Bundle bundle) {
//// String storyThumb = bundle.getString(EXTRA_STORY_THUMB);
//// String html = bundle.getString(EXTRA_STORY_HTML);
//// String path = bundle.getString(EXTRA_FILE_PATH);
//// com.alibaba.fastjson.JSONArray paths = JSON.parseArray(path);
//// LogUtil.d("story:" + storyThumb);
//// LogUtil.d("story:" + paths.toJSONString());
// }, bundle, callbackContext);
} else if (ACTION_SETTING.equals(action)) {
StoryMusicEntity musicEntity = new StoryMusicEntity();
StoryEntity storyEntity = StoryLogic.instance().getStoryEntityFromShare();
String musicName = storyEntity.storyMusicName;
musicEntity.musicLocal = storyEntity.storyMusicLocal;
musicEntity.name = storyEntity.storyMusicName;
musicEntity.serverId = storyEntity.musicServerId;
StoryMusicActivity.launch(getCurrentActivity(),musicEntity,0);
// StorySettingsActivity.launch(getCurrentActivity(), 0);
} else if (ACTION_BACK.equals(action)) {
cordova.getActivity().finish();
} else if (ACTION_EDIT.equals(action)) {
StoryEntity storyEntity = StoryLogic.instance().getStoryEntityFromShare();
if (storyEntity != null) {
doEditStory(storyEntity);
}
cordova.getActivity().finish();
} else if (ACTION_GET_CONTENT.equals(action)) {
if (cordova.getActivity() instanceof StoryTemplateActivity) {
StoryTemplateActivity activity = (StoryTemplateActivity) cordova.getActivity();
String html = activity.getContent();
callbackContext.success(html);
}
} else if (ACTION_CHECK_DOWNLOAD.equals(action)) {
// startLoad(WHAT_EDIT_INIT, null);
threadhelper(new TemplateOp() {
public void run(Bundle bundle) {
while (DataSynchronizer.getInstance().isDownloading()){
try{
Thread.sleep(300);
}catch (InterruptedException e){
}
}
StoryTemplateInfo templateInfo = DataSynchronizer.getInstance().getFirstTemplate();
String content = "";
if (templateInfo != null) {
File path = new File(StoryManager.getStoryTemplateDirectory(), templateInfo.temp_name + "/" + "stage.html");
content = readHtml(path.getAbsolutePath());
}
callbackContext.success(content);
}
}, null, callbackContext);
} else if (ACTION_OPEN_LINK.equals(action)) {
if (null != args && args.length() == 1) {
String url = args.getString(0);
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
Uri content_url = Uri.parse(url);
intent.setData(content_url);
cordova.getActivity().startActivity(intent);
}
callbackContext.success();
}
return true;
}
private void doEditStory(StoryEntity storyEntity) {
File file = new File(StoryManager.getStoryDirectory(), storyEntity.storyLocal + "/story.html");
String html = readFile(file.getAbsolutePath());
StoryTemplateActivity.launch(getCurrentActivity(), html, 0);
// callbackContext.success(html);
}
@Override
protected Message onLoadBackgroundRunning(int what, Bundle args) throws AsyncLoaderError {
return Message.obtain();
}
@Override
protected void onLoadCompleted(Message data) {
closeProgressDialog();
}
/**
* story.html
*
* @param myStory
* @param story
* @param storyThumb
* @param html
* @param paths
* @return
*/
private boolean saveStory(File myStory, StoryEntity story, String storyThumb, String html, com.alibaba.fastjson.JSONArray paths) {
if (paths == null || paths.size() == 0) {
return false;
}
//story
for (int i = 0; i < paths.size(); i++) {
LogUtil.d("story");
String path = paths.getString(i);
File imagePath = new File(path).getParentFile().getParentFile();
if (imagePath.getParentFile().getName().equals(StoryManager.TEMPLATE_DIRECTORY)) {
String templateName = imagePath.getName();
File newImagePath = new File(myStory.getAbsolutePath(), templateName);
html = html.replace(imagePath.getAbsolutePath(), newImagePath.getAbsolutePath());
}
}
File storyHTML = new File(myStory, FILE_NAME_STORY);
if(storyHTML.exists()){
LogUtil.d("storyHtml:" + storyHTML.delete());
}
PrintWriter writer = null;
try {
writer = new PrintWriter(storyHTML);
writer.write(html);
writer.close();
LogUtil.d("story.html");
} catch (IOException e) {
LogUtil.e("story", e);
return false;
} finally {
if (writer != null) {
writer.close();
}
}
//story
if (story.localCover == 0) {
try {
FileUtils.copyFile(new File(storyThumb),
new File(StoryManager.getStoryDirectory(), story.storyLocal + "/thumb.jpg"));
LogUtil.d("");
} catch (IOException e) {
LogUtil.e("", e);
}
}
File storyImg = new File(myStory, DIR_NAME_IMAGE);
if (!storyImg.exists()) {
storyImg.mkdirs();
}
for (int i = 0; i < paths.size(); i++) {
try {
String path = paths.getString(i);
File imagePath = new File(path).getParentFile().getParentFile();
String newPath = path;
if (imagePath.getParentFile().getName().equals(StoryManager.TEMPLATE_DIRECTORY)) {
String templateName = imagePath.getName();
File newImagePath = new File(myStory.getAbsolutePath(), templateName);
newPath = path.replace(imagePath.getAbsolutePath(), newImagePath.getAbsolutePath());
}
File file = new File(path);
File newPathFile = new File(newPath);
File imgDirectory = newPathFile.getParentFile();
if (!imgDirectory.exists()) {
imgDirectory.mkdirs();
}
File targetFile = new File(imgDirectory, file.getName());
if(!targetFile.exists()){
FileUtils.copyFile(file, targetFile);
}
} catch (IOException e) {
LogUtil.e("story", e);
return false;
}
}
return true;
}
/**
* wenjian
*
* @param previewFile
* @param html
* @param story story
* @return
*/
private boolean saveStoryPreview(File previewFile, String html, StoryEntity story) {
if(previewFile.exists()){
LogUtil.d("previewFile:" + previewFile.delete());
}
String header = getFromAssets(PREVIEW_HEADER);
String footer = getFromAssets(PREVIEW_FOOTER);
PrintWriter writer = null;
try {
writer = new PrintWriter(previewFile);
writer.println(header);
writer.println(html);
if (!Utils.isEmpty(story.storyMusicLocal)) {
writer.println("<div id=\"audio-btn\" class=\"on\" onclick=\"lanren.changeClass(this,'media')\">");
writer.println(String.format(" <audio loop=\"loop\" src=\"%s\" id=\"media\" preload=\"preload\"></audio>",
story.storyMusicLocal));
writer.println("</div>");
}
writer.println(footer);
writer.close();
} catch (IOException e) {
LogUtil.e("story:", e);
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}
private void copyAssetsFile(String src, String dest) {
InputStream in = null;
OutputStream out = null;
try {
out = new FileOutputStream(dest);
in = cordova.getActivity().getAssets().open(src);
byte[] buffer = new byte[1024];
int length = in.read(buffer);
while (length > 0) {
out.write(buffer, 0, length);
length = in.read(buffer);
}
out.flush();
in.close();
out.close();
} catch (IOException e) {
LogUtil.e("assets:" + src, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private String readFile(String path) {
StringBuffer content = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(path)));
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
return content.toString();
} catch (IOException e) {
LogUtil.e(":" + path, e);
return "";
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
public String getFromAssets(String fileName) {
try {
InputStreamReader inputReader = new InputStreamReader(cordova.getActivity().getResources().getAssets().open(fileName));
BufferedReader bufReader = new BufferedReader(inputReader);
String line;
StringBuffer result = new StringBuffer();
while ((line = bufReader.readLine()) != null) {
result.append(line);
}
File fontDirectory = StoryManager.getStoryFontDirectory();
String fontFile = new File(fontDirectory, FILE_NAME_FONT).getAbsolutePath();
return result.toString().replace(PLACE_HODLER_FONT_CSS, fontFile);
} catch (Exception e) {
LogUtil.e("assetes:" + fileName, e);
e.printStackTrace();
}
return "";
}
private String readHtml(String path) {
String parent = new File(path).getParent();
StringBuilder content = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(path)));
String line;
Pattern p = Pattern.compile("img/[a-zA-Z0-9-_]+(\\.jpg|\\.png)");
while ((line = reader.readLine()) != null) {
Matcher m = p.matcher(line);
while (m.find()) {
String result = m.group();
line = line.replace(result, new File(parent, result).getAbsolutePath());
}
content.append(line);
}
reader.close();
LogUtil.d("html:" + content.toString());
return content.toString();
} catch (IOException e) {
LogUtil.e("html:" + path, e);
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
private void getFonts(List<StoryFontInfo> fontList) {
JSONObject json = new JSONObject();
try {
File fontDirectory = StoryManager.getStoryFontDirectory();
File fontFile = new File(fontDirectory, FILE_NAME_FONT);
if (!fontFile.exists()) {
fontFile.createNewFile();
}
json.put("filePath", fontFile.getAbsolutePath());
for (StoryFontInfo font : fontList) {
File fontNameDirectory = new File(StoryManager.getStoryFontDirectory(), font.name);
File previewFile = new File(fontNameDirectory, "preview.jpg");
if (previewFile.exists()) {
font.preview_img_local = previewFile.getAbsolutePath();
}
font.downloaded = fontNameDirectory.listFiles().length == 5 ? 1 : 0;
}
json.put("fonts", fontList);
} catch (Exception e) {
callbackContext.success(1);
}
callbackContext.success(json);
}
private void getMusicPath(int id) {
Context context = getCurrentActivity().getApplicationContext();
StoryMusicEntity music = logic.getStoryMusicLocalById(context, id);
if (music != null) {
callbackContext.success(music.musicLocal);
} else {
callbackContext.error(1);//not fond
}
}
private void sendBroadcastUpdateStory() {
Intent intent = new Intent();
intent.setAction(StoryBroadcastReciver.STORY_ACTION);
intent.putExtra(StoryBroadcastReciver.EXTRAS_TYPE, StoryBroadcastReciverListener.TYPE_ADD_STORY);
WisapeApplication.getInstance().getApplicationContext().sendBroadcast(intent);
}
}
|
package de.danoeh.antennapod.fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.joanzapata.iconify.Iconify;
import com.joanzapata.iconify.widget.IconTextView;
import org.apache.commons.lang3.Validate;
import java.util.List;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.FeedInfoActivity;
import de.danoeh.antennapod.activity.FeedSettingsActivity;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.adapter.DefaultActionButtonCallback;
import de.danoeh.antennapod.adapter.FeedItemlistAdapter;
import de.danoeh.antennapod.core.asynctask.FeedRemover;
import de.danoeh.antennapod.core.dialog.ConfirmationDialog;
import de.danoeh.antennapod.core.dialog.DownloadRequestErrorDialogCreator;
import de.danoeh.antennapod.core.event.DownloadEvent;
import de.danoeh.antennapod.core.event.DownloaderUpdate;
import de.danoeh.antennapod.core.event.FeedItemEvent;
import de.danoeh.antennapod.core.feed.EventDistributor;
import de.danoeh.antennapod.core.feed.Feed;
import de.danoeh.antennapod.core.feed.FeedEvent;
import de.danoeh.antennapod.core.feed.FeedItem;
import de.danoeh.antennapod.core.feed.FeedItemFilter;
import de.danoeh.antennapod.core.feed.FeedMedia;
import de.danoeh.antennapod.core.glide.ApGlideSettings;
import de.danoeh.antennapod.core.glide.FastBlurTransformation;
import de.danoeh.antennapod.core.service.download.DownloadService;
import de.danoeh.antennapod.core.service.download.Downloader;
import de.danoeh.antennapod.core.storage.DBReader;
import de.danoeh.antennapod.core.storage.DBTasks;
import de.danoeh.antennapod.core.storage.DownloadRequestException;
import de.danoeh.antennapod.core.storage.DownloadRequester;
import de.danoeh.antennapod.core.util.FeedItemUtil;
import de.danoeh.antennapod.core.util.LongList;
import de.danoeh.antennapod.core.util.gui.MoreContentListFooterUtil;
import de.danoeh.antennapod.dialog.EpisodesApplyActionFragment;
import de.danoeh.antennapod.dialog.RenameFeedDialog;
import de.danoeh.antennapod.menuhandler.FeedItemMenuHandler;
import de.danoeh.antennapod.menuhandler.FeedMenuHandler;
import de.danoeh.antennapod.menuhandler.MenuItemUtils;
import de.greenrobot.event.EventBus;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* Displays a list of FeedItems.
*/
@SuppressLint("ValidFragment")
public class ItemlistFragment extends ListFragment {
private static final String TAG = "ItemlistFragment";
private static final int EVENTS = EventDistributor.UNREAD_ITEMS_UPDATE
| EventDistributor.FEED_LIST_UPDATE
| EventDistributor.PLAYER_STATUS_UPDATE;
public static final String EXTRA_SELECTED_FEEDITEM = "extra.de.danoeh.antennapod.activity.selected_feeditem";
private static final String ARGUMENT_FEED_ID = "argument.de.danoeh.antennapod.feed_id";
private FeedItemlistAdapter adapter;
private ContextMenu contextMenu;
private AdapterView.AdapterContextMenuInfo lastMenuInfo = null;
private long feedID;
private Feed feed;
private boolean itemsLoaded = false;
private boolean viewsCreated = false;
private boolean headerCreated = false;
private List<Downloader> downloaderList;
private MoreContentListFooterUtil listFooter;
private boolean isUpdatingFeed;
private TextView txtvTitle;
private IconTextView txtvFailure;
private ImageView imgvBackground;
private ImageView imgvCover;
private TextView txtvInformation;
private Disposable disposable;
/**
* Creates new ItemlistFragment which shows the Feeditems of a specific
* feed. Sets 'showFeedtitle' to false
*
* @param feedId The id of the feed to show
* @return the newly created instance of an ItemlistFragment
*/
public static ItemlistFragment newInstance(long feedId) {
ItemlistFragment i = new ItemlistFragment();
Bundle b = new Bundle();
b.putLong(ARGUMENT_FEED_ID, feedId);
i.setArguments(b);
return i;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
Bundle args = getArguments();
Validate.notNull(args);
feedID = args.getLong(ARGUMENT_FEED_ID);
}
@Override
public void onStart() {
super.onStart();
if (viewsCreated && itemsLoaded) {
onFragmentLoaded();
}
}
@Override
public void onResume() {
super.onResume();
EventDistributor.getInstance().register(contentUpdate);
EventBus.getDefault().registerSticky(this);
((MainActivity)getActivity()).getSupportActionBar().setTitle("");
updateProgressBarVisibility();
loadItems();
}
@Override
public void onPause() {
super.onPause();
EventDistributor.getInstance().unregister(contentUpdate);
EventBus.getDefault().unregister(this);
if(disposable != null) {
disposable.dispose();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
resetViewState();
}
private void resetViewState() {
adapter = null;
viewsCreated = false;
listFooter = null;
}
private final MenuItemUtils.UpdateRefreshMenuItemChecker updateRefreshMenuItemChecker = new MenuItemUtils.UpdateRefreshMenuItemChecker() {
@Override
public boolean isRefreshing() {
return feed != null && DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFile(feed);
}
};
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if(!isAdded()) {
return;
}
super.onCreateOptionsMenu(menu, inflater);
if (itemsLoaded) {
FeedMenuHandler.onCreateOptionsMenu(inflater, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView sv = (SearchView) MenuItemCompat.getActionView(searchItem);
MenuItemUtils.adjustTextColor(getActivity(), sv);
sv.setQueryHint(getString(R.string.search_hint));
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
sv.clearFocus();
if (itemsLoaded) {
((MainActivity) getActivity()).loadChildFragment(SearchFragment.newInstance(s, feed.getId()));
}
return true;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
if(feed == null || feed.getLink() == null) {
menu.findItem(R.id.share_link_item).setVisible(false);
menu.findItem(R.id.visit_website_item).setVisible(false);
}
isUpdatingFeed = MenuItemUtils.updateRefreshMenuItem(menu, R.id.refresh_item, updateRefreshMenuItemChecker);
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (itemsLoaded) {
FeedMenuHandler.onPrepareOptionsMenu(menu, feed);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!super.onOptionsItemSelected(item)) {
try {
if (!FeedMenuHandler.onOptionsItemClicked(getActivity(), item, feed)) {
switch (item.getItemId()) {
case R.id.episode_actions:
EpisodesApplyActionFragment fragment = EpisodesApplyActionFragment
.newInstance(feed.getItems());
((MainActivity)getActivity()).loadChildFragment(fragment);
return true;
case R.id.rename_item:
new RenameFeedDialog(getActivity(), feed).show();
return true;
case R.id.remove_item:
final FeedRemover remover = new FeedRemover(
getActivity(), feed) {
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
((MainActivity) getActivity()).loadFragment(EpisodesFragment.TAG, null);
}
};
ConfirmationDialog conDialog = new ConfirmationDialog(getActivity(),
R.string.remove_feed_label,
getString(R.string.feed_delete_confirmation_msg, feed.getTitle())) {
@Override
public void onConfirmButtonPressed(
DialogInterface dialog) {
dialog.dismiss();
remover.executeAsync();
}
};
conDialog.createNewDialog().show();
return true;
default:
return false;
}
} else {
return true;
}
} catch (DownloadRequestException e) {
e.printStackTrace();
DownloadRequestErrorDialogCreator.newRequestErrorDialog(getActivity(), e.getMessage());
return true;
}
} else {
return true;
}
}
private final FeedItemMenuHandler.MenuInterface contextMenuInterface = new FeedItemMenuHandler.MenuInterface() {
@Override
public void setItemVisibility(int id, boolean visible) {
if(contextMenu == null) {
return;
}
MenuItem item = contextMenu.findItem(id);
if (item != null) {
item.setVisible(visible);
}
}
};
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo adapterInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
// because of addHeaderView(), positions are increased by 1!
FeedItem item = itemAccess.getItem(adapterInfo.position-1);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.feeditemlist_context, menu);
if (item != null) {
menu.setHeaderTitle(item.getTitle());
}
contextMenu = menu;
lastMenuInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
FeedItemMenuHandler.onPrepareMenu(contextMenuInterface, item, true, null);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
if(menuInfo == null) {
menuInfo = lastMenuInfo;
}
// because of addHeaderView(), positions are increased by 1!
FeedItem selectedItem = itemAccess.getItem(menuInfo.position-1);
if (selectedItem == null) {
Log.i(TAG, "Selected item at position " + menuInfo.position + " was null, ignoring selection");
return super.onContextItemSelected(item);
}
return FeedItemMenuHandler.onMenuItemClicked(getActivity(), item.getItemId(), selectedItem);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
registerForContextMenu(getListView());
viewsCreated = true;
if (itemsLoaded) {
onFragmentLoaded();
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if(adapter == null) {
return;
}
position -= l.getHeaderViewsCount();
MainActivity activity = (MainActivity) getActivity();
long[] ids = FeedItemUtil.getIds(feed.getItems());
activity.loadChildFragment(ItemFragment.newInstance(ids, position));
activity.getSupportActionBar().setTitle(feed.getTitle());
}
public void onEvent(FeedEvent event) {
Log.d(TAG, "onEvent() called with: " + "event = [" + event + "]");
if(event.feedId == feedID) {
loadItems();
}
}
public void onEventMainThread(FeedItemEvent event) {
Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]");
if(feed == null || feed.getItems() == null || adapter == null) {
return;
}
for(FeedItem item : event.items) {
int pos = FeedItemUtil.indexOfItemWithId(feed.getItems(), item.getId());
if(pos >= 0) {
loadItems();
return;
}
}
}
public void onEventMainThread(DownloadEvent event) {
Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]");
DownloaderUpdate update = event.update;
downloaderList = update.downloaders;
if (isUpdatingFeed != event.update.feedIds.length > 0) {
updateProgressBarVisibility();
}
if(adapter != null && update.mediaIds.length > 0) {
adapter.notifyDataSetChanged();
}
}
private final EventDistributor.EventListener contentUpdate = new EventDistributor.EventListener() {
@Override
public void update(EventDistributor eventDistributor, Integer arg) {
if ((EVENTS & arg) != 0) {
Log.d(TAG, "Received contentUpdate Intent. arg " + arg);
refreshHeaderView();
loadItems();
updateProgressBarVisibility();
}
}
};
private void updateProgressBarVisibility() {
if (isUpdatingFeed != updateRefreshMenuItemChecker.isRefreshing()) {
getActivity().supportInvalidateOptionsMenu();
}
if (listFooter != null) {
listFooter.setLoadingState(DownloadRequester.getInstance().isDownloadingFeeds());
}
}
private void onFragmentLoaded() {
if(!isVisible()) {
return;
}
if (adapter == null) {
setListAdapter(null);
setupHeaderView();
setupFooterView();
adapter = new FeedItemlistAdapter(getActivity(), itemAccess, new DefaultActionButtonCallback(getActivity()), false, true);
setListAdapter(adapter);
}
refreshHeaderView();
setListShown(true);
adapter.notifyDataSetChanged();
getActivity().supportInvalidateOptionsMenu();
if (feed != null && feed.getNextPageLink() == null && listFooter != null) {
getListView().removeFooterView(listFooter.getRoot());
}
}
private void refreshHeaderView() {
if (getListView() == null || feed == null || !headerCreated) {
Log.e(TAG, "Unable to refresh header view");
return;
}
loadFeedImage();
if(feed.hasLastUpdateFailed()) {
txtvFailure.setVisibility(View.VISIBLE);
} else {
txtvFailure.setVisibility(View.GONE);
}
txtvTitle.setText(feed.getTitle());
if(feed.getItemFilter() != null) {
FeedItemFilter filter = feed.getItemFilter();
if(filter.getValues().length > 0) {
if(feed.hasLastUpdateFailed()) {
RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) txtvInformation.getLayoutParams();
p.addRule(RelativeLayout.BELOW, R.id.txtvFailure);
}
txtvInformation.setText("{fa-info-circle} " + this.getString(R.string.filtered_label));
Iconify.addIcons(txtvInformation);
txtvInformation.setVisibility(View.VISIBLE);
} else {
txtvInformation.setVisibility(View.GONE);
}
} else {
txtvInformation.setVisibility(View.GONE);
}
}
private void setupHeaderView() {
if (getListView() == null || feed == null) {
Log.e(TAG, "Unable to setup listview: recyclerView = null or feed = null");
return;
}
ListView lv = getListView();
LayoutInflater inflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View header = inflater.inflate(R.layout.feeditemlist_header, lv, false);
lv.addHeaderView(header);
txtvTitle = header.findViewById(R.id.txtvTitle);
TextView txtvAuthor = header.findViewById(R.id.txtvAuthor);
imgvBackground = header.findViewById(R.id.imgvBackground);
imgvCover = header.findViewById(R.id.imgvCover);
ImageButton butShowInfo = header.findViewById(R.id.butShowInfo);
ImageButton butShowSettings = header.findViewById(R.id.butShowSettings);
txtvInformation = header.findViewById(R.id.txtvInformation);
txtvFailure = header.findViewById(R.id.txtvFailure);
txtvTitle.setText(feed.getTitle());
txtvAuthor.setText(feed.getAuthor());
imgvBackground.setColorFilter(new LightingColorFilter(0xff828282, 0x000000));
loadFeedImage();
butShowInfo.setOnClickListener(v -> showFeedInfo());
imgvCover.setOnClickListener(v -> showFeedInfo());
butShowSettings.setOnClickListener(v -> {
if (viewsCreated && itemsLoaded) {
Intent startIntent = new Intent(getActivity(), FeedSettingsActivity.class);
startIntent.putExtra(FeedSettingsActivity.EXTRA_FEED_ID,
feed.getId());
startActivity(startIntent);
}
});
headerCreated = true;
}
private void showFeedInfo() {
if (viewsCreated && itemsLoaded) {
Intent startIntent = new Intent(getActivity(), FeedInfoActivity.class);
startIntent.putExtra(FeedInfoActivity.EXTRA_FEED_ID,
feed.getId());
startActivity(startIntent);
}
}
private void loadFeedImage() {
Glide.with(getActivity())
.load(feed.getImageLocation())
.apply(new RequestOptions()
.placeholder(R.color.image_readability_tint)
.error(R.color.image_readability_tint)
.diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY)
.transform(new FastBlurTransformation())
.dontAnimate())
.into(imgvBackground);
Glide.with(getActivity())
.load(feed.getImageLocation())
.apply(new RequestOptions()
.placeholder(R.color.light_gray)
.error(R.color.light_gray)
.diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY)
.fitCenter()
.dontAnimate())
.into(imgvCover);
}
private void setupFooterView() {
if (getListView() == null || feed == null) {
Log.e(TAG, "Unable to setup listview: recyclerView = null or feed = null");
return;
}
if (feed.isPaged() && feed.getNextPageLink() != null) {
ListView lv = getListView();
LayoutInflater inflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View header = inflater.inflate(R.layout.more_content_list_footer, lv, false);
lv.addFooterView(header);
listFooter = new MoreContentListFooterUtil(header);
listFooter.setClickListener(() -> {
if (feed != null) {
try {
DBTasks.loadNextPageOfFeed(getActivity(), feed, false);
} catch (DownloadRequestException e) {
e.printStackTrace();
DownloadRequestErrorDialogCreator.newRequestErrorDialog(getActivity(), e.getMessage());
}
}
});
}
}
private final FeedItemlistAdapter.ItemAccess itemAccess = new FeedItemlistAdapter.ItemAccess() {
@Override
public FeedItem getItem(int position) {
if (feed != null && 0 <= position && position < feed.getNumOfItems()) {
return feed.getItemAtIndex(position);
} else {
return null;
}
}
@Override
public LongList getQueueIds() {
LongList queueIds = new LongList();
if(feed == null) {
return queueIds;
}
for(FeedItem item : feed.getItems()) {
if(item.isTagged(FeedItem.TAG_QUEUE)) {
queueIds.add(item.getId());
}
}
return queueIds;
}
@Override
public int getCount() {
return (feed != null) ? feed.getNumOfItems() : 0;
}
@Override
public int getItemDownloadProgressPercent(FeedItem item) {
if (downloaderList != null) {
for (Downloader downloader : downloaderList) {
if (downloader.getDownloadRequest().getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA
&& downloader.getDownloadRequest().getFeedfileId() == item.getMedia().getId()) {
return downloader.getDownloadRequest().getProgressPercent();
}
}
}
return 0;
}
};
private void loadItems() {
if(disposable != null) {
disposable.dispose();
}
disposable = Observable.fromCallable(this::loadData)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
feed = result;
itemsLoaded = true;
if (viewsCreated) {
onFragmentLoaded();
}
}, error -> Log.e(TAG, Log.getStackTraceString(error)));
}
@Nullable
private Feed loadData() {
Feed feed = DBReader.getFeed(feedID);
if (feed == null) {
return null;
}
DBReader.loadAdditionalFeedItemListData(feed.getItems());
if (feed.getItemFilter() != null) {
FeedItemFilter filter = feed.getItemFilter();
feed.setItems(filter.filter(feed.getItems()));
}
return feed;
}
}
|
package de.danoeh.antennapod.menuhandler;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import androidx.appcompat.view.menu.MenuItemImpl;
import androidx.appcompat.widget.SearchView;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.util.ThemeUtils;
import de.danoeh.antennapod.fragment.SearchFragment;
import java.util.HashMap;
import java.util.Map;
/**
* Utilities for menu items.
*/
public class MenuItemUtils extends de.danoeh.antennapod.core.menuhandler.MenuItemUtils {
public static void refreshLockItem(Context context, Menu menu) {
final MenuItem queueLock = menu.findItem(R.id.queue_lock);
if (UserPreferences.isQueueLocked()) {
queueLock.setTitle(de.danoeh.antennapod.R.string.unlock_queue);
queueLock.setIcon(ThemeUtils.getDrawableFromAttr(context, R.attr.ic_lock_open));
} else {
queueLock.setTitle(de.danoeh.antennapod.R.string.lock_queue);
queueLock.setIcon(ThemeUtils.getDrawableFromAttr(context, R.attr.ic_lock_closed));
}
}
public static void setupSearchItem(Menu menu, MainActivity activity, long feedId, String feedTitle) {
MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView sv = (SearchView) searchItem.getActionView();
sv.setBackgroundColor(ThemeUtils.getColorFromAttr(activity, android.R.attr.windowBackground));
sv.setQueryHint(activity.getString(R.string.search_label));
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
sv.clearFocus();
activity.loadChildFragment(SearchFragment.newInstance(s, feedId, feedTitle));
searchItem.collapseActionView();
return true;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
private final Map<Integer, Integer> oldShowAsActionState = new HashMap<>();
@Override
public boolean onMenuItemActionExpand(MenuItem clickedItem) {
oldShowAsActionState.clear();
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
if (item.getItemId() != searchItem.getItemId()) {
oldShowAsActionState.put(item.getItemId(), getShowAsActionFlag(item));
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
}
}
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem collapsedItem) {
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
if (item.getItemId() != searchItem.getItemId()
&& oldShowAsActionState.containsKey(item.getItemId())) {
item.setShowAsAction(oldShowAsActionState.get(item.getItemId()));
}
}
return true;
}
});
}
@SuppressLint("RestrictedApi")
private static int getShowAsActionFlag(MenuItem item) {
if (!(item instanceof MenuItemImpl)) {
return MenuItemImpl.SHOW_AS_ACTION_NEVER;
}
MenuItemImpl itemImpl = ((MenuItemImpl) item);
if (itemImpl.requiresActionButton()) {
return MenuItemImpl.SHOW_AS_ACTION_ALWAYS;
} else if (itemImpl.requestsActionButton()) {
return MenuItemImpl.SHOW_AS_ACTION_IF_ROOM;
} else if (itemImpl.showsTextAsAction()) {
return MenuItemImpl.SHOW_AS_ACTION_WITH_TEXT;
} else {
return MenuItemImpl.SHOW_AS_ACTION_NEVER;
}
}
}
|
package org.codefx.demo.junit5.basics;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.EmptyStackException;
import java.util.Stack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisplayName("A stack")
class StackTest {
Stack<Object> stack;
@Test
@DisplayName("is instantiated with new Stack()")
void isInstantiatedWithNew() {
new Stack<>();
}
@Nested
@DisplayName("when new")
class WhenNew {
@BeforeEach
void createNewStack() {
stack = new Stack<>();
}
@Test
@DisplayName("is empty")
void isEmpty() {
assertTrue(stack.isEmpty());
}
@Test
@DisplayName("throws EmptyStackException when popped")
void throwsExceptionWhenPopped() {
assertThrows(EmptyStackException.class, () -> stack.pop());
}
@Test
@DisplayName("throws EmptyStackException when peeked")
void throwsExceptionWhenPeeked() {
assertThrows(EmptyStackException.class, () -> stack.peek());
}
@Nested
@DisplayName("after pushing an element")
class AfterPushing {
String anElement = "an element";
@BeforeEach
void pushAnElement() {
stack.push(anElement);
}
@Test
@DisplayName("it is no longer empty")
void isNotEmpty() {
assertFalse(stack.isEmpty());
}
@Test
@DisplayName("returns the element when popped and is empty")
void returnElementWhenPopped() {
assertEquals(anElement, stack.pop());
assertTrue(stack.isEmpty());
}
@Test
@DisplayName("returns the element when peeked but remains not empty")
void returnElementWhenPeeked() {
assertEquals(anElement, stack.peek());
assertFalse(stack.isEmpty());
}
}
}
}
|
package com.intellij.util.indexing;
import com.intellij.ide.startup.CacheUpdater;
import com.intellij.ide.startup.FileSystemSynchronizer;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.roots.CollectingContentIterator;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.VirtualFileManagerEx;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.impl.cache.impl.CacheUtil;
import com.intellij.psi.impl.search.CachesBasedRefSearcher;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.Processor;
import com.intellij.util.concurrency.Semaphore;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
@State(
name = "FileBasedIndex",
storages = {
@Storage(
id = "index",
file = "$APP_CONFIG$/index.xml")
}
)
public class FileBasedIndex implements ApplicationComponent, PersistentStateComponent<FileBasedIndexState> {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.indexing.FileBasedIndex");
private final Map<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>> myIndices = new HashMap<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>>();
private final TObjectIntHashMap<ID<?, ?>> myIndexIdToVersionMap = new TObjectIntHashMap<ID<?, ?>>();
private final Set<ID<?, ?>> myNeedContentLoading = new HashSet<ID<?, ?>>();
private FileBasedIndexState myPreviouslyRegistered;
private final Map<Document, AtomicLong> myLastIndexedDocStamps = new HashMap<Document, AtomicLong>();
private final Map<Document, CharSequence> myLastIndexedUnsavedContent = new HashMap<Document, CharSequence>();
private ChangedFilesUpdater myChangedFilesUpdater;
private final List<IndexableFileSet> myIndexableSets = new CopyOnWriteArrayList<IndexableFileSet>();
private final Set<ID<?, ?>> myRequiresRebuild = Collections.synchronizedSet(new HashSet<ID<?, ?>>());
private final ExecutorService myInvalidationService = ConcurrencyUtil.newSingleThreadExecutor("FileBasedIndex.InvalidationQueue");
private final VirtualFileManagerEx myVfManager;
private final Semaphore myUnsavedDataIndexingSemaphore = new Semaphore();
private final FileContentStorage myFileContentAttic;
public static interface InputFilter {
boolean acceptInput(VirtualFile file);
}
public static final class FileContent {
public final VirtualFile file;
public final String fileName;
public final CharSequence content;
public FileContent(final VirtualFile file, final CharSequence content) {
this.file = file;
// remember name explicitly because the file could be renamed afterwards
fileName = file.getName();
this.content = content;
}
}
public FileBasedIndex(final VirtualFileManagerEx vfManager) throws IOException {
myVfManager = vfManager;
final FileBasedIndexExtension[] extensions = Extensions.getExtensions(FileBasedIndexExtension.EXTENSION_POINT_NAME);
for (FileBasedIndexExtension<?, ?> extension : extensions) {
registerIndexer(extension);
}
dropUnregisteredIndices();
myChangedFilesUpdater = new ChangedFilesUpdater();
vfManager.addVirtualFileListener(myChangedFilesUpdater);
vfManager.registerRefreshUpdater(myChangedFilesUpdater);
myFileContentAttic = new FileContentStorage(new File(IndexInfrastructure.getPersistenceRoot(), "updates.tmp"));
}
public static FileBasedIndex getInstance() {
return ApplicationManager.getApplication().getComponent(FileBasedIndex.class);
}
/**
* @return true if registered index requires full rebuild for some reason, e.g. is just created or corrupted
* @param extension
*/
private <K, V> void registerIndexer(final FileBasedIndexExtension<K, V> extension) throws IOException {
final ID<K, V> name = extension.getName();
final int version = extension.getVersion();
if (extension.dependsOnFileContent()) {
myNeedContentLoading.add(name);
}
myIndexIdToVersionMap.put(name, version);
final File versionFile = IndexInfrastructure.getVersionFile(name);
if (IndexInfrastructure.versionDiffers(versionFile, version)) {
FileUtil.delete(IndexInfrastructure.getIndexRootDir(name));
IndexInfrastructure.rewriteVersion(versionFile, version);
}
for (int attempt = 0; attempt < 2; attempt++) {
try {
final MapIndexStorage<K, V> storage = new MapIndexStorage<K, V>(IndexInfrastructure.getStorageFile(name), extension.getKeyDescriptor(), extension.getValueExternalizer());
final MemoryIndexStorage<K, V> memStorage = new MemoryIndexStorage<K, V>(storage);
final UpdatableIndex<K, V, FileContent> index = createIndex(extension, memStorage);
myIndices.put(name, new Pair<UpdatableIndex<?,?, FileContent>, InputFilter>(index, extension.getInputFilter()));
break;
}
catch (IOException e) {
FileUtil.delete(IndexInfrastructure.getIndexRootDir(name));
IndexInfrastructure.rewriteVersion(versionFile, version);
}
}
}
private static <K, V> UpdatableIndex<K, V, FileContent> createIndex(final FileBasedIndexExtension<K, V> extension, final MemoryIndexStorage<K, V> memStorage) {
if (extension instanceof CustomImplementationFileBasedIndexExtension) {
return ((CustomImplementationFileBasedIndexExtension<K, V, FileContent>)extension).createIndexImplementation(memStorage);
}
else {
return new MapReduceIndex<K, V, FileContent>(extension.getIndexer(), memStorage);
}
}
@NonNls
@NotNull
public String getComponentName() {
return "FileBasedIndex";
}
public void initComponent() {
}
public void disposeComponent() {
myChangedFilesUpdater.forceUpdate();
myInvalidationService.shutdown();
try {
myInvalidationService.awaitTermination(30, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
LOG.error(e);
}
for (ID<?, ?> indexId : myIndices.keySet()) {
getIndex(indexId).dispose();
}
myVfManager.removeVirtualFileListener(myChangedFilesUpdater);
myVfManager.unregisterRefreshUpdater(myChangedFilesUpdater);
}
public FileBasedIndexState getState() {
return new FileBasedIndexState(myIndices.keySet());
}
public void loadState(final FileBasedIndexState state) {
myPreviouslyRegistered = state;
}
@NotNull
public <K> Collection<K> getAllKeys(final ID<K, ?> indexId) {
try {
checkRebuild(indexId);
indexUnsavedDocuments();
final UpdatableIndex<K, ?, FileContent> index = getIndex(indexId);
return index != null? index.getAllKeys() : Collections.<K>emptyList();
}
catch (StorageException e) {
requestRebuild(indexId);
LOG.error(e);
}
return Collections.emptyList();
}
@NotNull
public <K, V> List<V> getValues(final ID<K, V> indexId, K dataKey, Project project) {
final List<V> values = new ArrayList<V>();
processValuesImpl(indexId, dataKey, project, true, null, new ValueProcessor<V>() {
public void process(final VirtualFile file, final V value) {
values.add(value);
}
});
return values;
}
@NotNull
public <K, V> Collection<VirtualFile> getContainingFiles(final ID<K, V> indexId, K dataKey, @NotNull Project project) {
final Set<VirtualFile> files = new HashSet<VirtualFile>();
processValuesImpl(indexId, dataKey, project, false, null, new ValueProcessor<V>() {
public void process(final VirtualFile file, final V value) {
files.add(file);
}
});
return files;
}
public static interface ValueProcessor<V> {
void process(VirtualFile file, V value);
}
public <K, V> void processValues(final ID<K, V> indexId, final K dataKey, final Project project, final @Nullable VirtualFile inFile, ValueProcessor<V> processor) {
processValuesImpl(indexId, dataKey, project, false, inFile, processor);
}
private <K, V> void processValuesImpl(final ID<K, V> indexId, final K dataKey, final Project project, boolean ensureValueProcessedOnce,
final @Nullable VirtualFile restrictToFile, ValueProcessor<V> processor) {
try {
checkRebuild(indexId);
indexUnsavedDocuments();
final UpdatableIndex<K, V, FileContent> index = getIndex(indexId);
if (index == null) {
return;
}
final Lock readLock = index.getReadLock();
readLock.lock();
try {
final ValueContainer<V> container = index.getData(dataKey);
if (restrictToFile != null) {
final int restrictedFileId = getFileId(restrictToFile);
for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext();) {
final V value = valueIt.next();
if (container.isAssociated(value, restrictedFileId)) {
processor.process(restrictToFile, value);
}
}
}
else {
final DirectoryIndex dirIndex = DirectoryIndex.getInstance(project);
final PersistentFS fs = (PersistentFS)PersistentFS.getInstance();
for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext();) {
final V value = valueIt.next();
for (final ValueContainer.IntIterator inputIdsIterator = container.getInputIdsIterator(value); inputIdsIterator.hasNext();) {
final int id = inputIdsIterator.next();
if (CachesBasedRefSearcher.DEBUG) {
System.out.println("FileBasedIndex.processValuesImpl");
System.out.println("indexId = " + indexId);
System.out.println("id = " + id);
}
VirtualFile file = IndexInfrastructure.findFileById(dirIndex, fs, id);
if (file != null) {
if (CachesBasedRefSearcher.DEBUG) {
System.out.println("file = " + file.getPresentableUrl());
}
processor.process(file, value);
if (ensureValueProcessedOnce) {
break; // continue with the next value
}
}
}
}
}
}
finally {
readLock.unlock();
}
}
catch (StorageException e) {
requestRebuild(indexId);
LOG.error(e);
}
catch (RuntimeException e) {
final Throwable cause = e.getCause();
if (cause instanceof StorageException || cause instanceof IOException) {
requestRebuild(indexId);
LOG.error(e);
}
else {
throw e;
}
}
}
private void checkRebuild(final ID<?, ?> indexId) throws StorageException {
final boolean reallyRemoved = myRequiresRebuild.remove(indexId);
if (!reallyRemoved) {
return;
}
getIndex(indexId).clear();
try {
IndexInfrastructure.rewriteVersion(IndexInfrastructure.getVersionFile(indexId), myIndexIdToVersionMap.get(indexId));
}
catch (IOException e) {
LOG.error(e);
}
final Project[] projects = ProjectManager.getInstance().getOpenProjects();
final FileSystemSynchronizer synchronizer = new FileSystemSynchronizer();
synchronizer.setCancelable(false);
for (Project project : projects) {
synchronizer.registerCacheUpdater(new UnindexedFilesUpdater(project, ProjectRootManager.getInstance(project), this));
}
final Application application = ApplicationManager.getApplication();
if (application.isDispatchThread()) {
new Task.Modal(null, "Updating index", false) {
public void run(@NotNull final ProgressIndicator indicator) {
synchronizer.execute();
}
}.queue();
}
else {
final Semaphore semaphore = new Semaphore();
semaphore.down();
Runnable runnable = new Runnable() {
public void run() {
// due to current assertions in 'progress management' subsystem
// we have to queue the task only from event dispatch thread
// when these are solved, it is ok to remove invokeLater() calls from here
new Task.Backgroundable(null, "Updating index", false) {
public void run(@NotNull final ProgressIndicator indicator) {
try {
synchronizer.execute();
}
finally {
semaphore.up();
}
}
}.queue();
}
};
if (application.isUnitTestMode()) {
application.invokeLater(runnable, ModalityState.NON_MODAL);
}
else {
SwingUtilities.invokeLater(runnable);
}
semaphore.waitFor();
}
}
public void indexUnsavedDocuments() throws StorageException {
myChangedFilesUpdater.forceUpdate();
final FileDocumentManager fdManager = FileDocumentManager.getInstance();
final Document[] documents = fdManager.getUnsavedDocuments();
if (documents.length > 0) {
// now index unsaved data
setDataBufferingEnabled(true);
myUnsavedDataIndexingSemaphore.down();
try {
for (Document document : documents) {
final VirtualFile vFile = fdManager.getFile(document);
if (!vFile.isValid()) {
continue; // since the corresponding file is invalid, the document should be ignored
}
// Do not index content until document is committed. It will cause problems for indices, that depend on PSI otherwise.
if (isUncomitted(document)) continue;
final long currentDocStamp = document.getModificationStamp();
if (currentDocStamp != getLastIndexedStamp(document).getAndSet(currentDocStamp)) {
CharSequence lastIndexed = myLastIndexedUnsavedContent.get(document);
if (lastIndexed == null) {
lastIndexed = loadContent(vFile);
}
final FileContent oldFc = new FileContent(vFile, lastIndexed);
final FileContent newFc = new FileContent(vFile, document.getText());
for (ID<?, ?> indexId : myIndices.keySet()) {
if (getInputFilter(indexId).acceptInput(vFile)) {
final int inputId = Math.abs(getFileId(vFile));
if (CachesBasedRefSearcher.DEBUG) {
System.out.println("FileBasedIndex.indexUnsavedDocuments");
System.out.println("indexId = " + indexId);
System.out.println("Indexing inputId = " + inputId);
System.out.println("file = " + vFile.getPresentableUrl());
}
getIndex(indexId).update(inputId, newFc, oldFc);
}
}
myLastIndexedUnsavedContent.put(document, newFc.content);
}
}
}
finally {
myUnsavedDataIndexingSemaphore.up();
myUnsavedDataIndexingSemaphore.waitFor(); // may need to wait until another thread is done with indexing
}
}
}
@NotNull
private AtomicLong getLastIndexedStamp(final Document document) {
AtomicLong lastStamp;
synchronized (myLastIndexedDocStamps) {
lastStamp = myLastIndexedDocStamps.get(document);
if (lastStamp == null) {
lastStamp = new AtomicLong(0L);
myLastIndexedDocStamps.put(document, lastStamp);
}
}
return lastStamp;
}
private void setDataBufferingEnabled(final boolean enabled) {
for (ID<?, ?> indexId : myIndices.keySet()) {
final IndexStorage indexStorage = ((MapReduceIndex)getIndex(indexId)).getStorage();
((MemoryIndexStorage)indexStorage).setBufferingEnabled(enabled);
}
}
private void dropUnregisteredIndices() {
final Set<String> indicesToDrop = new HashSet<String>(myPreviouslyRegistered != null? myPreviouslyRegistered.registeredIndices : Collections.<String>emptyList());
for (ID<?, ?> key : myIndices.keySet()) {
indicesToDrop.remove(key.toString());
}
for (String s : indicesToDrop) {
FileUtil.delete(IndexInfrastructure.getIndexRootDir(new ID(s)));
}
}
public void requestRebuild(ID<?, ?> indexId) {
myRequiresRebuild.add(indexId);
}
@Nullable
private <K, V> UpdatableIndex<K, V, FileContent> getIndex(ID<K, V> indexId) {
final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId);
//noinspection unchecked
return pair != null? (UpdatableIndex<K,V, FileContent>)pair.getFirst() : null;
}
@Nullable
private InputFilter getInputFilter(ID<?, ?> indexId) {
final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId);
return pair != null? pair.getSecond() : null;
}
public void indexFileContent(com.intellij.ide.startup.FileContent content) {
final VirtualFile file = content.getVirtualFile();
FileContent fc = null;
FileContent oldContent = null;
final byte[] bytes = myFileContentAttic.remove(file);
for (ID<?, ?> indexId : myIndices.keySet()) {
if (getInputFilter(indexId).acceptInput(file)) {
if (fc == null) {
fc = new FileContent(file, CacheUtil.getContentText(content));
oldContent = bytes != null? new FileContent(file, LoadTextUtil.getTextByBinaryPresentation(bytes, file, false)) : null;
}
try {
updateSingleIndex(indexId, file, fc, oldContent);
}
catch (StorageException e) {
requestRebuild(indexId);
LOG.error(e);
}
}
}
}
private void updateSingleIndex(final ID<?, ?> indexId, final VirtualFile file, final FileContent currentFC, final FileContent oldFC)
throws StorageException {
setDataBufferingEnabled(false);
synchronized (myLastIndexedDocStamps) {
myLastIndexedDocStamps.clear();
myLastIndexedUnsavedContent.clear();
}
final int inputId = Math.abs(getFileId(file));
final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId);
index.update(inputId, currentFC, oldFC);
if (file.isValid()) {
if (currentFC != null) {
IndexingStamp.update(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId));
}
else {
// mark the file as unindexed
IndexingStamp.update(file, indexId, -1L);
}
}
}
public static int getFileId(final VirtualFile file) {
if (file instanceof VirtualFileWithId) {
return ((VirtualFileWithId)file).getId();
}
return 0;
}
private static CharSequence loadContent(VirtualFile file) {
return LoadTextUtil.loadText(file, true);
}
private final class ChangedFilesUpdater extends VirtualFileAdapter implements CacheUpdater{
private final Set<VirtualFile> myFilesToUpdate = Collections.synchronizedSet(new HashSet<VirtualFile>());
private final BlockingQueue<FutureTask<?>> myFutureInvalidations = new LinkedBlockingQueue<FutureTask<?>>();
// No need to react on movement events since files stay valid, their ids don't change and all associated attributes remain intact.
public void fileCreated(final VirtualFileEvent event) {
markDirty(event);
}
public void fileDeleted(final VirtualFileEvent event) {
myFilesToUpdate.remove(event.getFile()); // no need to update it anymore
}
public void fileCopied(final VirtualFileCopyEvent event) {
markDirty(event);
}
public void beforeFileDeletion(final VirtualFileEvent event) {
scheduleInvalidation(event.getFile(), false);
}
public void beforeContentsChange(final VirtualFileEvent event) {
scheduleInvalidation(event.getFile(), true);
}
public void contentsChanged(final VirtualFileEvent event) {
markDirty(event);
}
public void beforePropertyChange(final VirtualFilePropertyEvent event) {
if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) {
// indexes may depend on file name
final VirtualFile file = event.getFile();
if (!file.isDirectory()) {
scheduleInvalidation(file, false);
}
}
}
public void propertyChanged(final VirtualFilePropertyEvent event) {
if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) {
// indexes may depend on file name
if (!event.getFile().isDirectory()) {
markDirty(event);
}
}
}
private void markDirty(final VirtualFileEvent event) {
iterateIndexableFiles(event.getFile(), new Processor<VirtualFile>() {
public boolean process(final VirtualFile file) {
for (ID<?, ?> indexId : myIndices.keySet()) {
if (getInputFilter(indexId).acceptInput(file)) {
if (myNeedContentLoading.contains(indexId)) {
myFilesToUpdate.add(file);
}
else {
try {
updateSingleIndex(indexId, file, new FileContent(file, null), null);
}
catch (StorageException e) {
LOG.error(e);
requestRebuild(indexId);
}
}
}
}
return true;
}
});
}
private void scheduleInvalidation(final VirtualFile file, final boolean saveContent) {
if (file.isDirectory()) {
if (!(file instanceof NewVirtualFile) || ManagingFS.getInstance().areChildrenLoaded(file)) {
for (VirtualFile child : file.getChildren()) {
scheduleInvalidation(child, false);
}
}
}
else {
final List<ID<?, ?>> affectedIndices = new ArrayList<ID<?, ?>>(myIndices.size());
for (ID<?, ?> indexId : myIndices.keySet()) {
if (getInputFilter(indexId).acceptInput(file) && IndexingStamp.isFileIndexed(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId))) {
if (myNeedContentLoading.contains(indexId)) {
affectedIndices.add(indexId);
}
else {
// invalidate it synchronously
try {
updateSingleIndex(indexId, file, null, new FileContent(file, null));
}
catch (StorageException e) {
LOG.error(e);
requestRebuild(indexId);
}
}
}
}
if (affectedIndices.size() > 0) {
iterateIndexableFiles(file, new Processor<VirtualFile>() {
public boolean process(final VirtualFile file) {
myFilesToUpdate.add(file);
return true;
}
});
if (saveContent) {
myFileContentAttic.offer(file);
}
else {
final FileContent fc = new FileContent(file, loadContent(file));
final FutureTask<?> future = (FutureTask<?>)myInvalidationService.submit(new Runnable() {
public void run() {
for (ID<?, ?> indexId : affectedIndices) {
try {
updateSingleIndex(indexId, file, null, fc);
}
catch (StorageException e) {
LOG.error(e);
requestRebuild(indexId);
}
}
}
});
myFutureInvalidations.offer(future);
}
}
}
}
private void ensureAllInvalidateTasksCompleted() {
while (true) {
final FutureTask<?> future = myFutureInvalidations.poll();
if (future == null) {
return;
}
future.run(); // force the task run if it is has not been run yet
}
}
private void iterateIndexableFiles(final VirtualFile file, final Processor<VirtualFile> processor) {
if (file.isDirectory()) {
final ContentIterator iterator = new ContentIterator() {
public boolean processFile(final VirtualFile fileOrDir) {
if (!fileOrDir.isDirectory()) {
processor.process(fileOrDir);
}
return true;
}
};
for (IndexableFileSet set : myIndexableSets) {
set.iterateIndexableFilesIn(file, iterator);
}
}
else {
for (IndexableFileSet set : myIndexableSets) {
if (set.isInSet(file)) {
processor.process(file);
break;
}
}
}
}
public VirtualFile[] queryNeededFiles() {
synchronized (myFilesToUpdate) {
return myFilesToUpdate.toArray(new VirtualFile[myFilesToUpdate.size()]);
}
}
public void processFile(final com.intellij.ide.startup.FileContent fileContent) {
ensureAllInvalidateTasksCompleted();
processFileImpl(fileContent);
}
private final Semaphore myForceUpdateSemaphore = new Semaphore();
public void forceUpdate() {
ensureAllInvalidateTasksCompleted();
myForceUpdateSemaphore.down();
try {
for (VirtualFile file: queryNeededFiles()) {
processFileImpl(new com.intellij.ide.startup.FileContent(file));
}
}
finally {
myForceUpdateSemaphore.up();
myForceUpdateSemaphore.waitFor(); // possibly wait until another thread completes indexing
}
}
public void updatingDone() {
}
public void canceled() {
}
private void processFileImpl(final com.intellij.ide.startup.FileContent fileContent) {
final VirtualFile file = fileContent.getVirtualFile();
final boolean reallyRemoved = myFilesToUpdate.remove(file);
if (reallyRemoved && file.isValid()) {
indexFileContent(fileContent);
}
}
}
private class UnindexedFilesFinder implements CollectingContentIterator {
private final List<VirtualFile> myFiles = new ArrayList<VirtualFile>();
private final Collection<ID<?, ?>> myIndexIds;
private final Collection<ID<?, ?>> mySkipContentLoading;
private final ProgressIndicator myProgressIndicator;
public UnindexedFilesFinder(final Collection<ID<?, ?>> indexIds) {
myIndexIds = new ArrayList<ID<?, ?>>();
mySkipContentLoading = new ArrayList<ID<?, ?>>();
for (ID<?, ?> indexId : indexIds) {
if (myNeedContentLoading.contains(indexId)) {
myIndexIds.add(indexId);
}
else {
mySkipContentLoading.add(indexId);
}
}
myProgressIndicator = ProgressManager.getInstance().getProgressIndicator();
}
public List<VirtualFile> getFiles() {
return myFiles;
}
public boolean processFile(final VirtualFile file) {
if (!file.isDirectory()) {
for (ID<?, ?> indexId : myIndexIds) {
if (shouldIndexFile(file, indexId)) {
myFiles.add(file);
break;
}
}
for (ID<?, ?> indexId : mySkipContentLoading) {
if (shouldIndexFile(file, indexId)) {
try {
updateSingleIndex(indexId, file, new FileContent(file, null), null);
}
catch (StorageException e) {
LOG.info(e);
requestRebuild(indexId);
}
}
}
}
else {
if (myProgressIndicator != null) {
myProgressIndicator.setText("Scanning files to index");
myProgressIndicator.setText2(file.getPresentableUrl());
}
}
return true;
}
private boolean shouldIndexFile(final VirtualFile file, final ID<?, ?> indexId) {
return getInputFilter(indexId).acceptInput(file) && !IndexingStamp.isFileIndexed(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId));
}
}
public CollectingContentIterator createContentIterator() {
return new UnindexedFilesFinder(myIndices.keySet());
}
public void registerIndexableSet(IndexableFileSet set) {
myIndexableSets.add(set);
}
public void removeIndexableSet(IndexableFileSet set) {
myIndexableSets.remove(set);
}
private static boolean isUncomitted(Document doc) {
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
if (PsiDocumentManager.getInstance(project).isUncommited(doc)) {
return true;
}
}
return false;
}
}
|
package org.mitre.synthea.helpers;
import java.io.IOException;
import java.io.StringWriter;
import org.junit.Assert;
import org.junit.Test;
public class FactTableTest {
@Test
public void testFactTable() {
// Setup a basic fact table with a header.
FactTable table = new FactTable();
table.setHeader("ID,KEY,NAME,DESCRIPTION");
// Insert some facts.
int h = table.addFact("H", "Hydrogen,Highly flammable gas");
int he = table.addFact("He", "Helium,Inert gas");
// Test ID lookups.
Assert.assertTrue(table.getFactId("H") == h);
Assert.assertTrue(table.getFactId("He") == he);
// Make sure duplicate facts have the same ID.
int h2 = table.addFact("H", "Hydrogen,Highly flammable gas");
Assert.assertTrue(h == h2);
StringWriter writer = new StringWriter();
try {
table.write(writer);
} catch (IOException e) {
Assert.fail(e.getMessage());
}
String output = writer.toString();
Assert.assertTrue(output.contains(h + ",H"));
Assert.assertTrue(output.contains(he + ",He"));
}
@Test
public void testGetFactByKey() {
// Setup a basic fact table with a header.
FactTable table = new FactTable();
table.setHeader("ID,KEY,NAME,DESCRIPTION");
// Insert some facts.
int h = table.addFact("H", "Hydrogen,Highly flammable gas");
Assert.assertNull(table.getFactByKey("Iwcz&T&5+;N4Sb)kE+
}
}
|
package de.jotomo.ruffyscripter.commands;
import android.os.SystemClock;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import de.jotomo.ruffyscripter.PumpState;
public class SetTbrCommand extends BaseCommand {
private static final Logger log = LoggerFactory.getLogger(SetTbrCommand.class);
private final long percentage;
private final long duration;
public SetTbrCommand(long percentage, long duration) {
this.percentage = percentage;
this.duration = duration;
}
@Override
public List<String> validateArguments() {
List<String> violations = new ArrayList<>();
if (percentage % 10 != 0) {
violations.add("TBR percentage must be set in 10% steps");
}
if (percentage < 0 || percentage > 500) {
violations.add("TBR percentage must be within 0-500%");
}
if (percentage != 100) {
if (duration % 15 != 0) {
violations.add("TBR duration can only be set in 15 minute steps");
}
if (duration > 60 * 24) {
violations.add("Maximum TBR duration is 24 hours");
}
}
if (percentage == 0 && duration > 120) {
violations.add("Max allowed zero-temp duration is 2h");
}
return violations;
}
@Override
public CommandResult execute() {
try {
boolean cancellingTbr = percentage == 100;
PumpState pumpState = scripter.readPumpState();
// TODO hack, cancelling a TBR that isn't running is dealt with in CancelTbrCommand,
// this avoids setting a TBR twice until that AAPS bug is squished which calls this
// twice within a minute GL
if (!cancellingTbr
&& pumpState.tbrActive
&& pumpState.tbrPercent == percentage
&& (pumpState.tbrRemainingDuration == duration || pumpState.tbrRemainingDuration + 1 == duration)) {
return new CommandResult().success(true).enacted(false).message("Requested TBR already running");
}
enterTbrMenu();
boolean increasingPercentage = inputTbrPercentage();
verifyDisplayedTbrPercentage(increasingPercentage);
if (cancellingTbr) {
cancelTbrAndConfirmCancellationWarning();
} else {
// switch to TBR_DURATION menu by pressing menu key
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
scripter.pressMenuKey();
scripter.waitForMenuUpdate();
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
boolean increasingDuration = inputTbrDuration();
verifyDisplayedTbrDuration(increasingDuration);
// confirm TBR
scripter.pressCheckKey();
scripter.waitForMenuToBeLeft(MenuType.TBR_DURATION);
}
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU,
"Pump did not return to MAIN_MEU after setting TBR. " +
"Check pump manually, the TBR might not have been set/cancelled.");
// check main menu shows the same values we just set
if (cancellingTbr) {
verifyMainMenuShowsNoActiveTbr();
return new CommandResult().success(true).enacted(true).message("TBR was cancelled");
} else {
verifyMainMenuShowsExpectedTbrActive();
return new CommandResult().success(true).enacted(true).message(
String.format(Locale.US, "TBR set to %d%% for %d min", percentage, duration));
}
} catch (CommandException e) {
return e.toCommandResult();
}
}
private void enterTbrMenu() {
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU);
scripter.navigateToMenu(MenuType.TBR_MENU);
scripter.verifyMenuIsDisplayed(MenuType.TBR_MENU);
scripter.pressCheckKey();
scripter.waitForMenuUpdate();
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
}
private boolean inputTbrPercentage() {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long currentPercent = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE).longValue();
log.debug("Current TBR %: " + currentPercent);
long percentageChange = percentage - currentPercent;
long percentageSteps = percentageChange / 10;
boolean increasePercentage = true;
if (percentageSteps < 0) {
increasePercentage = false;
percentageSteps = Math.abs(percentageSteps);
}
log.debug("Pressing " + (increasePercentage ? "up" : "down") + " " + percentageSteps + " times");
for (int i = 0; i < percentageSteps; i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
log.debug("Push #" + (i + 1));
if (increasePercentage) scripter.pressUpKey();
else scripter.pressDownKey();
SystemClock.sleep(100);
}
return increasePercentage;
}
// TODO extract verification into a method TBR percentage, duration and bolus amount
private void verifyDisplayedTbrPercentage(boolean increasingPercentage) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
// wait up to 5s for any scrolling to finish
long displayedPercentage = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE).longValue();
long timeout = System.currentTimeMillis() + 10 * 1000;
while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedPercentage < percentage)
|| (!increasingPercentage && displayedPercentage > percentage))) {
log.debug("Waiting for pump to process scrolling input for percentage, current: "
+ displayedPercentage + ", desired: " + percentage + ", scrolling up: " + increasingPercentage);
SystemClock.sleep(50);
displayedPercentage = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE).longValue();
}
log.debug("Final displayed TBR percentage: " + displayedPercentage);
if (displayedPercentage != percentage) {
throw new CommandException().message("Failed to set TBR percentage, requested: " + percentage + ", actual: " + displayedPercentage);
}
// check again to ensure the displayed value hasn't change due to due scrolling taking extremely long
SystemClock.sleep(1000);
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long refreshedDisplayedTbrPecentage = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE).longValue();
if (displayedPercentage != refreshedDisplayedTbrPecentage) {
throw new CommandException().message("Failed to set TBR percentage: " +
"percentage changed after input stopped from "
+ displayedPercentage + " -> " + refreshedDisplayedTbrPecentage);
}
}
private boolean inputTbrDuration() {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
long currentDuration = scripter.readDisplayedDuration();
if (currentDuration % 15 != 0) {
// The duration displayed is how long an active TBR will still run,
// which might be something like 0:13, hence not in 15 minute steps.
// Pressing up will go to the next higher 15 minute step.
// Don't press down, from 0:13 it can't go down, so press up.
// Pressing up from 23:59 works to go to 24:00.
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
scripter.pressUpKey();
// TODO optimization: replace with logic that calculates the amount of
// steps including this one and issues them in one go, with a final wait
do {
currentDuration = scripter.readDisplayedDuration();
scripter.waitForMenuUpdate();
} while (currentDuration % 15 != 0);
}
log.debug("Current TBR duration: " + currentDuration);
long durationChange = duration - currentDuration;
long durationSteps = durationChange / 15;
boolean increaseDuration = true;
if (durationSteps < 0) {
increaseDuration = false;
durationSteps = Math.abs(durationSteps);
}
log.debug("Pressing " + (increaseDuration ? "up" : "down") + " " + durationSteps + " times");
for (int i = 0; i < durationSteps; i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
if (increaseDuration) scripter.pressUpKey();
else scripter.pressDownKey();
SystemClock.sleep(100);
log.debug("Push #" + (i + 1));
}
return increaseDuration;
}
private void verifyDisplayedTbrDuration(boolean increasingPercentage) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
// wait up to 5s for any scrolling to finish
long displayedDuration = scripter.readDisplayedDuration();
long timeout = System.currentTimeMillis() + 10 * 1000;
while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedDuration < duration)
|| (!increasingPercentage && displayedDuration > duration))) {
log.debug("Waiting for pump to process scrolling input for duration, current: "
+ displayedDuration + ", desired: " + duration + ", scrolling up: " + increasingPercentage);
SystemClock.sleep(50);
displayedDuration = scripter.readDisplayedDuration();
}
log.debug("Final displayed TBR duration: " + displayedDuration);
if (displayedDuration != duration) {
throw new CommandException().message("Failed to set TBR duration, requested: " + duration + ", actual: " + displayedDuration);
}
// check again to ensure the displayed value hasn't change due to due scrolling taking extremely long
SystemClock.sleep(1000);
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
long refreshedDisplayedTbrDuration = scripter.readDisplayedDuration();
if (displayedDuration != refreshedDisplayedTbrDuration) {
throw new CommandException().message("Failed to set TBR duration: " +
"duration changed after input stopped from "
+ displayedDuration + " -> " + refreshedDisplayedTbrDuration);
}
}
private void cancelTbrAndConfirmCancellationWarning() {
// confirm entered TBR
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
scripter.pressCheckKey();
// A "TBR CANCELLED alert" is only raised by the pump when the remaining time is
// greater than 60s (displayed as 0:01, the pump goes from there to finished.
// We could read the remaining duration from MAIN_MENU, but by the time we're here,
// the pumup could have moved from 0:02 to 0:01, so instead, check if a "TBR CANCELLED" alert
// is raised and if so dismiss it
long inFiveSeconds = System.currentTimeMillis() + 5 * 1000;
boolean alertProcessed = false;
while (System.currentTimeMillis() < inFiveSeconds && !alertProcessed) {
if (scripter.getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) {
// Check the raised alarm is TBR CANCELLED, so we're not accidentally cancelling
// a different alarm that might be raised at the same time.
// Note that the message is permanently displayed, while the error code is blinking.
// A wait till the error code can be read results in the code hanging, despite
// menu updates coming in, so just check the message.
// TODO v2 this only works when the pump's language is English
String errorMsg = (String) scripter.getCurrentMenu().getAttribute(MenuAttribute.MESSAGE);
if (!errorMsg.equals("TBR CANCELLED")) {
throw new CommandException().success(false).enacted(false)
.message("An alert other than the expected TBR CANCELLED was raised by the pump: "
+ errorMsg + ". Please check the pump.");
}
// confirm "TBR CANCELLED" alert
scripter.verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR);
scripter.pressCheckKey();
// dismiss "TBR CANCELLED" alert
scripter.verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR);
scripter.pressCheckKey();
scripter.waitForMenuToBeLeft(MenuType.WARNING_OR_ERROR);
alertProcessed = true;
}
SystemClock.sleep(10);
}
}
private void verifyMainMenuShowsNoActiveTbr() {
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU);
Double tbrPercentage = (Double) scripter.getCurrentMenu().getAttribute(MenuAttribute.TBR);
boolean runtimeDisplayed = scripter.getCurrentMenu().attributes().contains(MenuAttribute.RUNTIME);
if (tbrPercentage != 100 || runtimeDisplayed) {
throw new CommandException().message("Cancelling TBR failed, TBR is still set according to MAIN_MENU");
}
}
private void verifyMainMenuShowsExpectedTbrActive() {
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU);
// new TBR set; percentage and duration must be displayed ...
if (!scripter.getCurrentMenu().attributes().contains(MenuAttribute.TBR) ||
!scripter.getCurrentMenu().attributes().contains(MenuAttribute.RUNTIME)) {
throw new CommandException().message("Setting TBR failed, according to MAIN_MENU no TBR is active");
}
Double mmTbrPercentage = (Double) scripter.getCurrentMenu().getAttribute(MenuAttribute.TBR);
MenuTime mmTbrDuration = (MenuTime) scripter.getCurrentMenu().getAttribute(MenuAttribute.RUNTIME);
// ... and be the same as what we set
// note that displayed duration might have already counted down, e.g. from 30 minutes to
// 29 minutes and 59 seconds, so that 29 minutes are displayed
int mmTbrDurationInMinutes = mmTbrDuration.getHour() * 60 + mmTbrDuration.getMinute();
if (mmTbrPercentage != percentage || (mmTbrDurationInMinutes != duration && mmTbrDurationInMinutes + 1 != duration)) {
throw new CommandException().message("Setting TBR failed, TBR in MAIN_MENU differs from expected");
}
}
@Override
public String toString() {
return "SetTbrCommand{" +
"percentage=" + percentage +
", duration=" + duration +
'}';
}
}
|
package org.myrobotlab.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import org.junit.BeforeClass;
import org.junit.Test;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.test.AbstractTest;
public class InProcessCliTest extends AbstractTest {
static PipedOutputStream pipe = null;
static PipedInputStream in = null;
static ByteArrayOutputStream bos = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
pipe = new PipedOutputStream();
in = new PipedInputStream(pipe);
bos = new ByteArrayOutputStream();
}
public void write(String str) throws IOException {
pipe.write((str + "\n").getBytes());
pipe.flush();
// must read it off and process the data
sleep(50);
}
public void clear() {
bos.reset();
}
public String getResponse() {
String ret = new String(bos.toByteArray());
log.info("cd => {}", ret);
// clear();
return ret;
}
public String toJson(Object o) {
return CodecUtils.toPrettyJson(o);
}
@Test
public void testProcess() throws IOException, InterruptedException {
Runtime runtime = Runtime.getInstance();
runtime.startInteractiveMode();
runtime.stopInteractiveMode();
Thread.sleep(300);
runtime.startInteractiveMode(in, bos);
// wait for pipe to clear
Thread.sleep(300);
clear();
write("pwd");
String ret = getResponse();
Thread.sleep(200);
assertTrue(ret.startsWith("\"/\""));
clear();
write("ls");
Thread.sleep(200);
assertTrue(getResponse().contains(toJson(Runtime.getServiceNames())));
boolean virtual = runtime.isVirtual();
// boolean conversion
clear();
write("/runtime/setVirtual/false");
ret = getResponse();
Thread.sleep(200);
assertFalse(runtime.isVirtual());
write("/runtime/setVirtual/true");
Thread.sleep(200);
assertTrue(runtime.isVirtual());
// replace with original value
runtime.setVirtual(virtual);
// integer conversion
Clock clockCli = (Clock) Runtime.start("clockCli", "Clock");
write("/clockCli/setInterval/1234");
Integer check = 1234;
Thread.sleep(200);
assertEquals(check, clockCli.getInterval());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.