answer
stringlengths 17
10.2M
|
|---|
package org.ensembl.healthcheck.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.DatabaseMetaData;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.ensembl.healthcheck.DatabaseRegistry;
import org.ensembl.healthcheck.DatabaseServer;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.TestRunner;
import org.ensembl.healthcheck.testcase.EnsTestCase;
/**
* Various database utilities.
*/
public final class DBUtils {
private static Logger logger = Logger.getLogger("HealthCheckLogger");
private static List<DatabaseServer> mainDatabaseServers;
private static List<DatabaseServer> secondaryDatabaseServers;
private static DatabaseRegistry mainDatabaseRegistry;
private static DatabaseRegistry secondaryDatabaseRegistry;
// hide constructor to stop instantiation
private DBUtils() {
}
/**
* Open a connection to the database.
*
* @param driverClassName
* The class name of the driver to load.
* @param databaseURL
* The URL of the database to connect to.
* @param user
* The username to connect with.
* @param password
* Password for user.
* @return A connection to the database, or null.
*/
public static Connection openConnection(String driverClassName, String databaseURL, String user, String password) {
return ConnectionPool.getConnection(driverClassName, databaseURL, user, password);
} // openConnection
/**
* Get a list of the database names for a particular connection.
*
* @param con
* The connection to query.
* @return An array of Strings containing the database names.
*/
public static String[] listDatabases(Connection con) {
if (con == null) {
logger.severe("Database connection is null");
}
ArrayList<String> dbNames = new ArrayList<String>();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SHOW DATABASES");
while (rs.next()) {
dbNames.add(rs.getString(1));
}
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
String[] ret = new String[dbNames.size()];
return (String[]) dbNames.toArray(ret);
} // listDatabases
/**
* Get a list of the database names that match a certain pattern for a particular connection.
*
* @param conn
* The connection to query.
* @param regex
* A regular expression to match. If null, match all.
* @return An array of Strings containing the database names.
*/
public static String[] listDatabases(Connection con, String regex) {
ArrayList<String> dbMatches = new ArrayList<String>();
String[] allDBNames = listDatabases(con);
for (String name : allDBNames) {
if (regex == null) {
dbMatches.add(name);
} else if (name.matches(regex)) {
dbMatches.add(name);
}
}
String[] ret = new String[dbMatches.size()];
return (String[]) dbMatches.toArray(ret);
} // listDatabases
/**
* Compare a list of ResultSets to see if there are any differences. Note that if the ResultSets are large and/or there are many
* of them, this may take a long time!
*
* @return The number of differences.
* @param testCase
* The test case that is calling the comparison. Used for ReportManager.
* @param resultSetGroup
* The list of ResultSets to compare
*/
public static boolean compareResultSetGroup(List<ResultSet> resultSetGroup, EnsTestCase testCase, boolean comparingSchema) {
boolean same = true;
// avoid comparing the same two ResultSets more than once
// i.e. only need the upper-right triangle of the comparison matrix
int size = resultSetGroup.size();
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
ResultSet rsi = resultSetGroup.get(i);
ResultSet rsj = resultSetGroup.get(j);
same &= compareResultSets(rsi, rsj, testCase, "", true, true, "", comparingSchema);
}
}
return same;
} // compareResultSetGroup
/**
* Compare two ResultSets.
*
* @return True if all the following are true:
* <ol>
* <li>rs1 and rs2 have the same number of columns</li>
* <li>The name and type of each column in rs1 is equivalent to the corresponding column in rs2.</li>
* <li>All the rows in rs1 have the same type and value as the corresponding rows in rs2.</li>
* </ol>
* @param testCase
* The test case calling the comparison; used in ReportManager.
* @param text
* Additional text to put in any error reports.
* @param rs1
* The first ResultSet to compare.
* @param rs2
* The second ResultSet to compare.
* @param reportErrors
* If true, error details are stored in ReportManager as they are found.
* @param singleTableName
* If comparing 2 result sets from a single table (or from a DESCRIBE table) this should be the name of the table, to be
* output in any error text. Otherwise "".
*/
public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName, boolean comparingSchema) {
return compareResultSets(rs1, rs2, testCase, text, reportErrors, warnNull, singleTableName, null, comparingSchema);
}
public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName, int[] columns,
boolean comparingSchema) {
// quick tests first
// Check for object equality
if (rs1.equals(rs2)) {
return true;
}
try {
// get some information about the ResultSets
String name1 = getShortDatabaseName(rs1.getStatement().getConnection());
String name2 = getShortDatabaseName(rs2.getStatement().getConnection());
// Check for same column count, names and types
ResultSetMetaData rsmd1 = rs1.getMetaData();
ResultSetMetaData rsmd2 = rs2.getMetaData();
if (rsmd1.getColumnCount() != rsmd2.getColumnCount() && columns == null) {
ReportManager.problem(testCase, name1, "Column counts differ " + singleTableName + " " + name1 + ": " + rsmd1.getColumnCount() + " " + name2 + ": " + rsmd2.getColumnCount());
return false; // Deliberate early return for performance
// reasons
}
if (columns == null) {
columns = new int[rsmd1.getColumnCount()];
for (int i = 0; i < columns.length; i++) {
columns[i] = i + 1;
}
}
for (int j = 0; j < columns.length; j++) {
int i = columns[j];
// note columns indexed from l
if (!((rsmd1.getColumnName(i)).equals(rsmd2.getColumnName(i)))) {
ReportManager.problem(testCase, name1, "Column names differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnName(i) + " " + name2 + ": "
+ rsmd2.getColumnName(i));
// Deliberate early return for performance reasons
return false;
}
if (rsmd1.getColumnType(i) != rsmd2.getColumnType(i)) {
ReportManager.problem(testCase, name1, "Column types differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnType(i) + " " + name2 + ": "
+ rsmd2.getColumnType(i));
return false; // Deliberate early return for performance
// reasons
}
} // for column
// make sure both cursors are at the start of the ResultSet
// (default is before the start)
rs1.beforeFirst();
rs2.beforeFirst();
// if quick checks didn't cause return, try comparing row-wise
int row = 1;
while (rs1.next()) {
if (rs2.next()) {
for (int j = 0; j < columns.length; j++) {
int i = columns[j];
// note columns indexed from 1
if (!compareColumns(rs1, rs2, i, warnNull)) {
String str = name1 + " and " + name2 + text + " " + singleTableName + " differ at row " + row + " column " + i + " (" + rsmd1.getColumnName(i) + ")" + " Values: "
+ Utils.truncate(rs1.getString(i), 250, true) + ", " + Utils.truncate(rs2.getString(i), 250, true);
if (reportErrors) {
ReportManager.problem(testCase, name1, str);
}
return false;
}
}
row++;
} else {
// rs1 has more rows than rs2
ReportManager.problem(testCase, name1, singleTableName + " (or definition) has more rows in " + name1 + " than in " + name2);
return false;
}
} // while rs1
// if both ResultSets are the same, then we should be at the end of
// both, i.e. .next() should return false
String extra = comparingSchema ? ". This means that there are missing columns in the table, rectify!" : "";
if (rs1.next()) {
if (reportErrors) {
ReportManager.problem(testCase, name1, name1 + " " + singleTableName + " has additional rows that are not in " + name2 + extra);
}
return false;
} else if (rs2.next()) {
if (reportErrors) {
ReportManager.problem(testCase, name2, name2 + " " + singleTableName + " has additional rows that are not in " + name1 + extra);
}
return false;
}
} catch (SQLException se) {
se.printStackTrace();
}
return true;
} // compareResultSets
/**
* Compare a particular column in two ResultSets.
*
* @param rs1
* The first ResultSet to compare.
* @param rs2
* The second ResultSet to compare.
* @param i
* The index of the column to compare.
* @return True if the type and value of the columns match.
*/
public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i, boolean warnNull) {
try {
ResultSetMetaData rsmd = rs1.getMetaData();
Connection con1 = rs1.getStatement().getConnection();
Connection con2 = rs2.getStatement().getConnection();
if (rs1.getObject(i) == null) {
if (warnNull) {
logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con1));
}
return (rs2.getObject(i) == null); // true if both are null
}
if (rs2.getObject(i) == null) {
if (warnNull) {
logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con2));
}
return (rs1.getObject(i) == null); // true if both are null
}
// Note deliberate early returns for performance reasons
switch (rsmd.getColumnType(i)) {
case Types.INTEGER:
return rs1.getInt(i) == rs2.getInt(i);
case Types.SMALLINT:
return rs1.getInt(i) == rs2.getInt(i);
case Types.TINYINT:
return rs1.getInt(i) == rs2.getInt(i);
case Types.VARCHAR:
return rs1.getString(i).equals(rs2.getString(i));
case Types.FLOAT:
return rs1.getFloat(i) == rs2.getFloat(i);
case Types.DOUBLE:
return rs1.getDouble(i) == rs2.getDouble(i);
case Types.TIMESTAMP:
return rs1.getTimestamp(i).equals(rs2.getTimestamp(i));
default:
// treat everything else as a String (should deal with ENUM and
// TEXT)
if (rs1.getString(i) == null || rs2.getString(i) == null) {
return true;
} else {
return rs1.getString(i).equals(rs2.getString(i));
}
} // switch
} catch (SQLException se) {
se.printStackTrace();
}
return true;
} // compareColumns
/**
* Print a ResultSet to standard out. Optionally limit the number of rows.
*
* @param maxRows
* The maximum number of rows to print. -1 to print all rows.
* @param rs
* The ResultSet to print.
*/
public static void printResultSet(ResultSet rs, int maxRows) {
int row = 0;
try {
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rs.getString(i) + "\t");
}
System.out.println("");
if (maxRows != -1 && ++row >= maxRows) {
break;
}
}
} catch (SQLException se) {
se.printStackTrace();
}
} // printResultSet
/**
* Gets the database name, without the jdbc:// prefix.
*
* @param con
* The Connection to query.
* @return The name of the database (everything after the last / in the JDBC URL).
*/
public static String getShortDatabaseName(Connection con) {
String url = null;
try {
url = con.getMetaData().getURL();
} catch (SQLException se) {
se.printStackTrace();
}
String name = url.substring(url.lastIndexOf('/') + 1);
return name;
} // getShortDatabaseName
/**
* Generate a name for a temporary database. Should be fairly unique; name is _temp_{user}_{time} where user is current user and
* time is current time in ms.
*
* @return The temporary name. Will not have any spaces.
*/
public static String generateTempDatabaseName() {
StringBuffer buf = new StringBuffer("_temp_");
buf.append(System.getProperty("user.name"));
buf.append("_" + System.currentTimeMillis());
String str = buf.toString();
str = str.replace(' ', '_'); // filter any spaces
logger.fine("Generated temporary database name: " + str);
return str;
}
/**
* Get a list of all the table names.
*
* @param con
* The database connection to use.
* @return An array of Strings representing the names of the tables, obtained from the SHOW TABLES command.
*/
public static String[] getTableNames(Connection con) {
List<String> result = new ArrayList<String>();
if (con == null) {
logger.severe("getTableNames(): Database connection is null");
}
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SHOW TABLES");
while (rs.next()) {
result.add(rs.getString(1));
}
rs.close();
stmt.close();
} catch (SQLException se) {
logger.severe(se.getMessage());
}
return (String[]) result.toArray(new String[result.size()]);
}
/**
* Get a list of the table names that match a particular SQL pattern.
*
* @param con
* The database connection to use.
* @param pattern
* The SQL pattern to match the table names against.
* @return An array of Strings representing the names of the tables.
*/
public static String[] getTableNames(Connection con, String pattern) {
List<String> result = new ArrayList<String>();
if (con == null) {
logger.severe("getTableNames(): Database connection is null");
}
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SHOW TABLES LIKE '" + pattern + "'");
while (rs.next()) {
result.add(rs.getString(1));
}
rs.close();
stmt.close();
} catch (SQLException se) {
logger.severe(se.getMessage());
}
return (String[]) result.toArray(new String[result.size()]);
}
/**
* List the columns in a particular table.
*
* @param table
* The name of the table to list.
* @param con
* The connection to use.
* @return A List of Strings representing the column names.
*/
public static List<String> getColumnsInTable(Connection con, String table) {
List<String> result = new ArrayList<String>();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("DESCRIBE " + table);
while (rs.next()) {
result.add(rs.getString(1));
}
rs.close();
stmt.close();
} catch (SQLException se) {
logger.severe(se.getMessage());
}
return result;
}
/**
* List the column information in a table - names, types, defaults etc.
*
* @param table
* The name of the table to list.
* @param con
* The connection to use.
* @param typeFilter
* If not null, only return columns whose types start with this string (case insensitive).
* @return A List of 6-element String[] arrays representing: 0: Column name 1: Type 2: Null? 3: Key 4: Default 5: Extra
*/
public static List<String[]> getTableInfo(Connection con, String table, String typeFilter) {
List<String[]> result = new ArrayList<String[]>();
if (typeFilter != null) {
typeFilter = typeFilter.toLowerCase();
}
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("DESCRIBE " + table);
while (rs.next()) {
String[] info = new String[6];
for (int i = 0; i < 6; i++) {
info[i] = rs.getString(i + 1);
}
if (typeFilter == null || info[1].toLowerCase().startsWith(typeFilter)) {
result.add(info);
}
}
rs.close();
stmt.close();
} catch (SQLException se) {
logger.severe(se.getMessage());
}
return result;
}
/**
* Execute SQL and writes results to ReportManager.info().
*
* @param testCase
* testCase which created the sql statement
* @param con
* connection to execute sql on.
* @param sql
* sql statement to execute.
*/
public static void printRows(EnsTestCase testCase, Connection con, String sql) {
try {
ResultSet rs = con.createStatement().executeQuery(sql);
if (rs.next()) {
int nCols = rs.getMetaData().getColumnCount();
StringBuffer line = new StringBuffer();
do {
line.delete(0, line.length());
for (int i = 1; i <= nCols; ++i) {
line.append(rs.getString(i));
if (i < nCols) {
line.append("\t");
}
}
ReportManager.info(testCase, con, line.toString());
} while (rs.next());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Get the meta_value for a named key in the meta table.
*/
public static String getMetaValue(Connection con, String key) {
String result = "";
try {
ResultSet rs = con.createStatement().executeQuery("SELECT meta_value FROM meta WHERE meta_key='" + key + "'");
if (rs.next()) {
result = rs.getString(1);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
/**
* Get main database server list - build if necessary. Assumes properties file already read.
*/
public static List<DatabaseServer> getMainDatabaseServers() {
// EG replace literal reference to file with variable
Utils.readPropertiesFileIntoSystem(TestRunner.PROPERTIES_FILE, false);
if (mainDatabaseServers == null) {
mainDatabaseServers = new ArrayList<DatabaseServer>();
checkAndAddDatabaseServer(mainDatabaseServers, "host", "port", "user", "password", "driver");
checkAndAddDatabaseServer(mainDatabaseServers, "host1", "port1", "user1", "password1", "driver1");
checkAndAddDatabaseServer(mainDatabaseServers, "host2", "port2", "user2", "password2", "driver2");
}
logger.fine("Number of main database servers found: " + mainDatabaseServers.size());
return mainDatabaseServers;
}
/**
* Look for secondary database servers.
*/
public static List<DatabaseServer> getSecondaryDatabaseServers() {
Utils.readPropertiesFileIntoSystem(TestRunner.PROPERTIES_FILE, false);
if (secondaryDatabaseServers == null) {
secondaryDatabaseServers = new ArrayList<DatabaseServer>();
checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host", "secondary.port", "secondary.user", "secondary.password", "secondary.driver");
checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host1", "secondary.port1", "secondary.user1", "secondary.password1", "secondary.driver1");
checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host2", "secondary.port2", "secondary.user2", "secondary.password2", "secondary.driver2");
}
logger.fine("Number of secondary database servers found: " + secondaryDatabaseServers.size());
return secondaryDatabaseServers;
}
/**
* Check for the existence of a particular database server. Assumes properties file has already been read in. If it exists, add it
* to the list.
*/
private static void checkAndAddDatabaseServer(List<DatabaseServer> servers, String hostProp, String portProp, String userProp, String passwordProp, String driverProp) {
if (System.getProperty(hostProp) != null && System.getProperty(portProp) != null && System.getProperty(userProp) != null) {
DatabaseServer server = new DatabaseServer(System.getProperty(hostProp), System.getProperty(portProp), System.getProperty(userProp), System.getProperty(passwordProp), System
.getProperty(driverProp));
servers.add(server);
logger.fine("Added server: " + server.toString());
}
}
public static DatabaseRegistry getSecondaryDatabaseRegistry() {
if (secondaryDatabaseRegistry == null) {
secondaryDatabaseRegistry = new DatabaseRegistry(null, null, null, true);
}
return secondaryDatabaseRegistry;
}
public static void setMainDatabaseRegistry(DatabaseRegistry dbr) {
mainDatabaseRegistry = dbr;
}
public static DatabaseRegistry getMainDatabaseRegistry() {
if (mainDatabaseRegistry == null) {
mainDatabaseRegistry = new DatabaseRegistry(null, null, null, false);
}
return mainDatabaseRegistry;
}
public static void setSecondaryDatabaseRegistry(DatabaseRegistry dbr) {
secondaryDatabaseRegistry = dbr;
}
public static boolean tableExists(Connection con, String table) {
boolean result = false;
try {
DatabaseMetaData dbm = con.getMetaData();
ResultSet rs = dbm.getTables(null, null, table, null);
if (rs.next()) {
result = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public static boolean columnExists(Connection con, String table, String column) {
boolean result = false;
try {
DatabaseMetaData dbm = con.getMetaData();
ResultSet rs = dbm.getColumns(null, null, table, column);
if (rs.next()) {
result = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
} // DBUtils
|
package org.exist.xquery;
import java.util.ArrayList;
import java.util.List;
import org.exist.dom.DocumentSet;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
/**
* Implements an XQuery extension expression. An extension expression starts with
* a list of pragmas, followed by an expression enclosed in curly braces. For evaluation
* details check {{@link #eval(Sequence, Item)}.
*
* @author wolf
*
*/
public class ExtensionExpression extends AbstractExpression {
private Expression innerExpression;
private List pragmas = new ArrayList(3);
public ExtensionExpression(XQueryContext context) {
super(context);
}
public void setExpression(Expression inner) {
this.innerExpression = inner;
}
public void addPragma(Pragma pragma) {
pragmas.add(pragma);
}
/**
* For every pragma in the list, calls {@link Pragma#before(XQueryContext, Expression)} before evaluation.
* The method then tries to call {@link Pragma#eval(Sequence, Item)} on every pragma.
* If a pragma does not return null for this call, the returned Sequence will become the result
* of the extension expression. If more than one pragma returns something for eval, an exception
* will be thrown. If all pragmas return null, we call eval on the original expression and return
* that.
*/
public Sequence eval(Sequence contextSequence, Item contextItem)
throws XPathException {
callBefore();
Sequence result = null;
for (int i = 0; i < pragmas.size(); i++) {
Pragma pragma = (Pragma) pragmas.get(i);
Sequence temp = pragma.eval(contextSequence, contextItem);
if (temp != null) {
if (result != null)
throw new XPathException(getASTNode(), "Conflicting pragmas: only one should return a result for eval");
result = temp;
}
}
if (result == null)
result = innerExpression.eval(contextSequence, contextItem);
callAfter();
return result;
}
private void callAfter() throws XPathException {
for (int i = 0; i < pragmas.size(); i++) {
Pragma pragma = (Pragma) pragmas.get(i);
pragma.after(context, innerExpression);
}
}
private void callBefore() throws XPathException {
for (int i = 0; i < pragmas.size(); i++) {
Pragma pragma = (Pragma) pragmas.get(i);
pragma.before(context, innerExpression);
}
}
public int returnsType() {
return innerExpression.returnsType();
}
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
innerExpression.analyze(contextInfo);
}
public void dump(ExpressionDumper dumper) {
for (int i = 0; i < pragmas.size(); i++) {
Pragma pragma = (Pragma) pragmas.get(i);
dumper.nl().display("(# " + pragma.getQName().toString(), getASTNode());
if (pragma.getContents() != null)
dumper.display(' ').display(pragma.getContents());
dumper.display("
}
dumper.display('{').nl();
dumper.startIndent();
dumper.dump(innerExpression);
dumper.endIndent();
dumper.display('}').nl();
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#getDependencies()
*/
public int getDependencies() {
return innerExpression.getDependencies();
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#getCardinality()
*/
public int getCardinality() {
return innerExpression.getCardinality();
}
public void setContextDocSet(DocumentSet contextSet) {
super.setContextDocSet(contextSet);
innerExpression.setContextDocSet(contextSet);
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#resetState()
*/
public void resetState() {
super.resetState();
innerExpression.resetState();
}
public void accept(ExpressionVisitor visitor) {
visitor.visit(innerExpression);
}
}
|
package org.exist.xquery.value;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.Collator;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.Duration;
import org.exist.xquery.Constants;
import org.exist.xquery.XPathException;
/**
* @author <a href="mailto:piotr@ideanest.com">Piotr Kaminski</a>
*/
public class DurationValue extends ComputableValue {
public final static int YEAR = 0;
public final static int MONTH = 1;
public final static int DAY = 2;
public final static int HOUR = 3;
public final static int MINUTE = 4;
protected final Duration duration;
private Duration canonicalDuration;
protected static final BigInteger
TWELVE = BigInteger.valueOf(12),
TWENTY_FOUR = BigInteger.valueOf(24),
SIXTY = BigInteger.valueOf(60);
protected static final BigDecimal
SIXTY_DECIMAL = BigDecimal.valueOf(60),
ZERO_DECIMAL = BigDecimal.valueOf(0); // TODO: replace with BigDecimal.ZERO in JDK 1.5
protected static final Duration CANONICAL_ZERO_DURATION =
TimeUtils.getInstance().newDuration(true, null, null, null, null, null, ZERO_DECIMAL);
/**
* Create a new duration value of the most specific type allowed by the fields set in the given
* duration object. If no fields are set, return a xs:dayTimeDuration.
*
* @param duration the duration to wrap
* @return a new instance of the most specific subclass of <code>DurationValue</code>
*/
public static DurationValue wrap(Duration duration) {
try {
return new DayTimeDurationValue(duration);
} catch (XPathException e) {
try {
return new YearMonthDurationValue(duration);
} catch (XPathException e2) {
return new DurationValue(duration);
}
}
}
public DurationValue(Duration duration) {
this.duration = duration;
}
public DurationValue(String str) throws XPathException {
try {
this.duration = TimeUtils.getInstance().newDuration(StringValue.trimWhitespace(str));
} catch (IllegalArgumentException e) {
throw new XPathException("FORG0001: cannot construct " + Type.getTypeName(this.getItemType()) +
" from \"" + str + "\"");
}
}
public Duration getCanonicalDuration() {
canonicalize();
return canonicalDuration;
}
public int getType() {
return Type.DURATION;
}
protected DurationValue createSameKind(Duration d) throws XPathException {
return new DurationValue(d);
}
public DurationValue negate() throws XPathException {
return createSameKind(duration.negate());
}
public String getStringValue() {
canonicalize();
return canonicalDuration.toString();
}
private BigInteger nullIfZero(BigInteger x) {
if (BigInteger.ZERO.compareTo(x) == Constants.EQUAL) x = null;
return x;
}
private BigInteger zeroIfNull(BigInteger x) {
if (x == null) x = BigInteger.ZERO;
return x;
}
private BigDecimal nullIfZero(BigDecimal x) {
if (ZERO_DECIMAL.compareTo(x) == Constants.EQUAL) x = null;
return x;
}
private BigDecimal zeroIfNull(BigDecimal x) {
if (x == null) x = ZERO_DECIMAL;
return x;
}
private void canonicalize() {
if (canonicalDuration != null)
return;
BigInteger years, months, days, hours, minutes;
BigDecimal seconds;
BigInteger[] r;
r = monthsValue().divideAndRemainder(TWELVE);
years = nullIfZero(r[0]);
months = nullIfZero(r[1]);
// TODO: replace following segment with this for JDK 1.5
// BigDecimal[] rd = secondsValue().divideAndRemainder(SIXTY_DECIMAL);
// seconds = nullIfZero(rd[1]);
// r = rd[0].toBigInteger().divideAndRemainder(SIXTY);
// segment to be replaced:
BigDecimal secondsValue = secondsValue();
BigDecimal m = secondsValue.divide(SIXTY_DECIMAL, 0, BigDecimal.ROUND_DOWN);
seconds = nullIfZero(secondsValue.subtract(SIXTY_DECIMAL.multiply(m)));
r = m.toBigInteger().divideAndRemainder(SIXTY);
minutes = nullIfZero(r[1]);
r = r[0].divideAndRemainder(TWENTY_FOUR);
hours = nullIfZero(r[1]);
days = nullIfZero(r[0]);
if (years == null && months == null && days == null && hours == null && minutes == null && seconds == null) {
canonicalDuration = canonicalZeroDuration();
} else {
canonicalDuration = TimeUtils.getInstance().newDuration(
duration.getSign() >= 0,
years, months, days, hours, minutes, seconds);
}
}
protected BigDecimal secondsValue() {
return
new BigDecimal(
zeroIfNull((BigInteger) duration.getField(DatatypeConstants.DAYS))
.multiply(TWENTY_FOUR)
.add(zeroIfNull((BigInteger) duration.getField(DatatypeConstants.HOURS)))
.multiply(SIXTY)
.add(zeroIfNull((BigInteger) duration.getField(DatatypeConstants.MINUTES)))
.multiply(SIXTY)
).add(zeroIfNull((BigDecimal) duration.getField(DatatypeConstants.SECONDS)));
}
protected BigDecimal secondsValueSigned() {
BigDecimal x = secondsValue();
if (duration.getSign() < 0) x = x.negate();
return x;
}
protected BigInteger monthsValue() {
return
zeroIfNull((BigInteger) duration.getField(DatatypeConstants.YEARS))
.multiply(TWELVE)
.add(zeroIfNull((BigInteger) duration.getField(DatatypeConstants.MONTHS)));
}
protected BigInteger monthsValueSigned() {
BigInteger x = monthsValue();
if (duration.getSign() < 0) x = x.negate();
return x;
}
protected Duration canonicalZeroDuration() {
return CANONICAL_ZERO_DURATION;
}
public int getPart(int part) {
int r;
switch(part) {
case YEAR: r = duration.getYears(); break;
case MONTH: r = duration.getMonths(); break;
case DAY: r = duration.getDays(); break;
case HOUR: r = duration.getHours(); break;
case MINUTE: r = duration.getMinutes(); break;
default:
throw new IllegalArgumentException("Invalid argument to method getPart");
}
return r * duration.getSign();
}
public double getSeconds() {
Number n = duration.getField(DatatypeConstants.SECONDS);
return n == null ? 0 : n.doubleValue() * duration.getSign();
}
public AtomicValue convertTo(int requiredType) throws XPathException {
canonicalize();
switch(requiredType) {
case Type.ITEM:
case Type.ATOMIC:
case Type.DURATION:
return new DurationValue(canonicalDuration);
case Type.YEAR_MONTH_DURATION:
if (canonicalDuration.getField(DatatypeConstants.YEARS) != null ||
canonicalDuration.getField(DatatypeConstants.MONTHS) != null)
return new YearMonthDurationValue(TimeUtils.getInstance().newDurationYearMonth(
canonicalDuration.getSign() >= 0,
(BigInteger) canonicalDuration.getField(DatatypeConstants.YEARS),
(BigInteger) canonicalDuration.getField(DatatypeConstants.MONTHS)));
else
return new YearMonthDurationValue(YearMonthDurationValue.CANONICAL_ZERO_DURATION);
case Type.DAY_TIME_DURATION:
if (canonicalDuration.isSet(DatatypeConstants.DAYS) ||
canonicalDuration.isSet(DatatypeConstants.HOURS) ||
canonicalDuration.isSet(DatatypeConstants.MINUTES) ||
canonicalDuration.isSet(DatatypeConstants.SECONDS))
return new DayTimeDurationValue(TimeUtils.getInstance().newDuration(
canonicalDuration.getSign() >= 0,
null,
null,
(BigInteger) canonicalDuration.getField(DatatypeConstants.DAYS),
(BigInteger) canonicalDuration.getField(DatatypeConstants.HOURS),
(BigInteger) canonicalDuration.getField(DatatypeConstants.MINUTES),
(BigDecimal) canonicalDuration.getField(DatatypeConstants.SECONDS)));
else
return new DayTimeDurationValue(DayTimeDurationValue.CANONICAL_ZERO_DURATION);
case Type.STRING:
canonicalize();
return new StringValue(getStringValue());
case Type.UNTYPED_ATOMIC :
canonicalize();
return new UntypedAtomicValue(getStringValue());
default:
throw new XPathException(
"Type error: cannot cast ' + Type.getTypeName(getType()) 'to "
+ Type.getTypeName(requiredType));
}
}
public boolean compareTo(Collator collator, int operator, AtomicValue other) throws XPathException {
switch (operator) {
case Constants.EQ :
{
if (!(DurationValue.class.isAssignableFrom(other.getClass())))
throw new XPathException("FORG0006: invalid operand type: " + Type.getTypeName(other.getType()));
//TODO : upgrade so that P365D is *not* equal to P1Y
boolean r = duration.equals(((DurationValue)other).duration);
//compare fractional seconds to work around the JDK standard behaviour
if (r &&
((BigDecimal)duration.getField(DatatypeConstants.SECONDS)) != null &&
((BigDecimal)(((DurationValue) other).duration).getField(DatatypeConstants.SECONDS)) != null) {
r = ((BigDecimal)duration.getField(DatatypeConstants.SECONDS)).equals(
((BigDecimal)(((DurationValue) other).duration).getField(DatatypeConstants.SECONDS)));
}
return r;
}
case Constants.NEQ :
{
if (!(DurationValue.class.isAssignableFrom(other.getClass())))
throw new XPathException("FORG0006: invalid operand type: " + Type.getTypeName(other.getType()));
//TODO : upgrade so that P365D is *not* equal to P1Y
boolean r = duration.equals(((DurationValue)other).duration);
//compare fractional seconds to work around the JDK standard behaviour
if (r &&
((BigDecimal)duration.getField(DatatypeConstants.SECONDS)) != null &&
((BigDecimal)(((DurationValue) other).duration).getField(DatatypeConstants.SECONDS)) != null) {
r = ((BigDecimal)duration.getField(DatatypeConstants.SECONDS)).equals(
((BigDecimal)(((DurationValue) other).duration).getField(DatatypeConstants.SECONDS)));
}
return !r;
}
case Constants.LT :
case Constants.LTEQ :
case Constants.GT :
case Constants.GTEQ :
throw new XPathException("XPTY0004: " + Type.getTypeName(other.getType()) + " type can not be ordered");
default :
throw new IllegalArgumentException("Unknown comparison operator");
}
}
public int compareTo(Collator collator, AtomicValue other) throws XPathException {
if (!(DurationValue.class.isAssignableFrom(other.getClass())))
throw new XPathException("FORG0006: invalid operand type: " + Type.getTypeName(other.getType()));
//TODO : what to do with the collator ?
return duration.compare(((DurationValue)other).duration);
}
public AtomicValue max(Collator collator, AtomicValue other) throws XPathException {
throw new XPathException("FORG0001: invalid operation on " + Type.getTypeName(this.getType()));
}
public AtomicValue min(Collator collator, AtomicValue other) throws XPathException {
throw new XPathException("FORG0001: invalid operation on " + Type.getTypeName(this.getType()));
}
public ComputableValue plus(ComputableValue other) throws XPathException {
throw new XPathException("FORG0001: invalid operation on " + Type.getTypeName(this.getType()));
}
public ComputableValue minus(ComputableValue other) throws XPathException {
throw new XPathException("FORG0001: invalid operation on " + Type.getTypeName(this.getType()));
}
public ComputableValue mult(ComputableValue other) throws XPathException {
throw new XPathException("FORG0001: invalid operation on " + Type.getTypeName(this.getType()));
}
public ComputableValue div(ComputableValue other) throws XPathException {
throw new XPathException("FORG0001: invalid operation on " + Type.getTypeName(this.getType()));
}
public int conversionPreference(Class target) {
if (target.isAssignableFrom(getClass())) return 0;
if (target.isAssignableFrom(Duration.class)) return 1;
return Integer.MAX_VALUE;
}
public Object toJavaObject(Class target) throws XPathException {
if (target.isAssignableFrom(getClass())) return this;
if (target.isAssignableFrom(Duration.class)) return duration;
throw new XPathException("cannot convert value of type " + Type.getTypeName(getType()) + " to Java object of type " + target.getName());
}
public boolean effectiveBooleanValue() throws XPathException {
throw new XPathException("FORG0006: value of type " + Type.getTypeName(getType()) +
" has no boolean value.");
}
}
|
package org.jgroups.blocks;
import org.jgroups.*;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.TP;
import org.jgroups.protocols.relay.SiteAddress;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.StateTransferInfo;
import org.jgroups.util.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
/**
* Provides synchronous and asynchronous message sending with request-response
* correlation; i.e., matching responses with the original request.
* It also offers push-style message reception (by internally using the PullPushAdapter).
* <p>
* Channels are simple patterns to asynchronously send a receive messages.
* However, a significant number of communication patterns in group communication
* require synchronous communication. For example, a sender would like to send a
* message to the group and wait for all responses. Or another application would
* like to send a message to the group and wait only until the majority of the
* receivers have sent a response, or until a timeout occurred. MessageDispatcher
* offers a combination of the above pattern with other patterns.
* <p>
* Used on top of channel to implement group requests. Client's {@code handle()}
* method is called when request is received. Is the equivalent of RpcProtocol on
* the application instead of protocol level.
*
* @author Bela Ban
*/
public class MessageDispatcher implements RequestHandler, Closeable, ChannelListener {
protected JChannel channel;
protected RequestCorrelator corr;
protected Receiver receiver;
protected RequestHandler req_handler;
protected boolean async_dispatching;
protected boolean wrap_exceptions;
protected ProtocolAdapter prot_adapter;
protected volatile Collection<Address> members=new HashSet<>();
protected Address local_addr;
protected final Log log=LogFactory.getLog(MessageDispatcher.class);
protected final RpcStats rpc_stats=new RpcStats(false);
@SuppressWarnings("rawtypes")
protected static final RspList empty_rsplist;
@SuppressWarnings("rawtypes")
protected static final GroupRequest empty_group_request;
static {
empty_rsplist=new RspList<>();
empty_group_request=new GroupRequest<>(null, Collections.emptyList(), RequestOptions.SYNC());
empty_group_request.complete(empty_rsplist);
}
public MessageDispatcher() {
}
public MessageDispatcher(JChannel channel) {
this.channel=channel;
prot_adapter=new ProtocolAdapter();
if(channel != null) {
channel.addChannelListener(this);
local_addr=channel.getAddress();
installUpHandler(prot_adapter, true);
}
start();
}
public MessageDispatcher(JChannel channel, RequestHandler req_handler) {
this(channel);
setRequestHandler(req_handler);
}
public JChannel getChannel() {return channel;}
public RequestCorrelator getCorrelator() {return corr;}
public RequestCorrelator correlator() {return corr;}
public boolean getAsyncDispatching() {return async_dispatching;}
public boolean asyncDispatching() {return async_dispatching;}
public boolean getWrapExceptions() {return wrap_exceptions;}
public boolean wrapExceptions() {return wrap_exceptions;}
public UpHandler getProtocolAdapter() {return prot_adapter;}
public UpHandler protocolAdapter() {return prot_adapter;}
public RpcStats getRpcStats() {return rpc_stats;}
public RpcStats rpcStats() {return rpc_stats;}
public boolean getExtendedStats() {return rpc_stats.extendedStats();}
public boolean extendedStats() {return rpc_stats.extendedStats();}
public <X extends MessageDispatcher> X setExtendedStats(boolean fl) {return extendedStats(fl);}
public <X extends MessageDispatcher> X extendedStats(boolean fl) {rpc_stats.extendedStats(fl); return (X)this;}
public <X extends MessageDispatcher> X setChannel(JChannel ch) {
if(ch == null)
return (X)this;
this.channel=ch;
if(ch != null) {
local_addr=channel.getAddress();
ch.addChannelListener(this);
}
if(prot_adapter == null)
prot_adapter=new ProtocolAdapter();
// Don't force installing the UpHandler so subclasses can use this method
return installUpHandler(prot_adapter, false);
}
public <X extends MessageDispatcher> X setCorrelator(RequestCorrelator c) {return correlator(c);}
public <X extends MessageDispatcher> X correlator(RequestCorrelator c) {
if(c == null)
return (X)this;
stop();
this.corr=c;
corr.asyncDispatching(this.async_dispatching).wrapExceptions(this.wrap_exceptions);
start();
return (X)this;
}
public <X extends MessageDispatcher> X setReceiver(Receiver r) {
this.receiver=r;
return (X)this;
}
public <X extends MessageDispatcher> X setRequestHandler(RequestHandler rh) {
req_handler=rh;
if(corr != null)
corr.setRequestHandler(rh);
return (X)this;
}
public <X extends MessageDispatcher> X setAsynDispatching(boolean flag) {return asyncDispatching(flag);}
public <X extends MessageDispatcher> X asyncDispatching(boolean flag) {
async_dispatching=flag;
if(corr != null)
corr.asyncDispatching(flag);
return (X)this;
}
public <X extends MessageDispatcher> X setWrapExceptions(boolean flag) {return wrapExceptions(flag);}
public <X extends MessageDispatcher> X wrapExceptions(boolean flag) {
wrap_exceptions=flag;
if(corr != null)
corr.wrapExceptions(flag);
return (X)this;
}
protected <X extends MessageDispatcher> X setMembers(List<Address> new_mbrs) {
if(new_mbrs != null)
members=new HashSet<>(new_mbrs); // volatile write - seen by a subsequent read
return (X)this;
}
public <X extends MessageDispatcher> X start() {
if(corr == null)
corr=createRequestCorrelator(prot_adapter, this, local_addr)
.asyncDispatching(async_dispatching).wrapExceptions(this.wrap_exceptions);
corr.start();
if(channel != null) {
List<Address> tmp_mbrs=channel.getView() != null ? channel.getView().getMembers() : null;
setMembers(tmp_mbrs);
if(channel instanceof JChannel) {
TP transport=channel.getProtocolStack().getTransport();
corr.registerProbeHandler(transport);
}
}
return (X)this;
}
protected static RequestCorrelator createRequestCorrelator(Protocol transport, RequestHandler handler, Address local_addr) {
return new RequestCorrelator(transport, handler, local_addr);
}
@Override public void close() throws IOException {stop();}
public <X extends MessageDispatcher> X stop() {
if(corr != null) {
corr.stop();
if(channel instanceof JChannel) {
TP transport=channel.getProtocolStack().getTransport();
corr.unregisterProbeHandler(transport);
}
}
return (X)this;
}
/**
* Sets the given UpHandler as the UpHandler for the channel. If the relevant handler is already installed,
* the {@code canReplace} controls whether this method replaces it (after logging a WARN) or simply
* leaves {@code handler} uninstalled.<p>
* Passing {@code false} as the {@code canReplace} value allows callers to use this method to install defaults
* without concern about inadvertently overriding
*
* @param handler the UpHandler to install
* @param canReplace {@code true} if an existing Channel upHandler can be replaced; {@code false}
* if this method shouldn't install
*/
protected <X extends MessageDispatcher> X installUpHandler(UpHandler handler, boolean canReplace) {
UpHandler existing = channel.getUpHandler();
if (existing == null)
channel.setUpHandler(handler);
else if(canReplace) {
log.warn("Channel already has an up handler installed (%s) but now it is being overridden", existing);
channel.setUpHandler(handler);
}
return (X)this;
}
/**
* Sends a message to all members and expects responses from members in dests (if non-null).
* @param dests A list of group members from which to expect responses (if the call is blocking).
* @param msg The message to be sent
* @param opts A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details
* @return RspList A list of Rsp elements, or null if the RPC is asynchronous
* @throws Exception If the request cannot be sent
* @since 2.9
*/
public <T> RspList<T> castMessage(final Collection<Address> dests, Message msg, RequestOptions opts) throws Exception {
GroupRequest<T> req=cast(dests, msg, opts, true);
return req != null? req.getNow(null) : null;
}
/**
* Sends a message to all members and expects responses from members in dests (if non-null).
* @param dests A list of group members from which to expect responses (if the call is blocking).
* @param msg The message to be sent
* @param opts A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details
* @return CompletableFuture<T> A future from which the results (RspList) can be retrieved, or null if the request
* was sent asynchronously
* @throws Exception If the request cannot be sent
*/
public <T> CompletableFuture<RspList<T>> castMessageWithFuture(final Collection<Address> dests, Message msg,
RequestOptions opts) throws Exception {
return cast(dests, msg, opts,false);
}
protected <T> GroupRequest<T> cast(final Collection<Address> dests, Message msg, RequestOptions options,
boolean block_for_results) throws Exception {
if(options == null) {
log.warn("request options were null, using default of sync");
options=RequestOptions.SYNC();
}
List<Address> real_dests;
// we need to clone because we don't want to modify the original
if(dests != null)
real_dests=dests.stream().filter(dest -> dest instanceof SiteAddress || this.members.contains(dest))
.collect(ArrayList::new, (list,dest) -> {if(!list.contains(dest)) list.add(dest);}, (l,r) -> {});
else
real_dests=new ArrayList<>(members);
// Remove the local member from the target destination set if we should not deliver our own message
JChannel tmp=channel;
if((tmp != null && tmp.getDiscardOwnMessages()) || options.transientFlagSet(Message.TransientFlag.DONT_LOOPBACK)) {
if(local_addr == null)
local_addr=tmp != null? tmp.getAddress() : null;
real_dests.remove(local_addr);
}
if(options.hasExclusionList())
Stream.of(options.exclusionList()).forEach(real_dests::remove);
if(real_dests.isEmpty()) {
log.trace("destination list is empty, won't send message");
return empty_group_request;
}
boolean sync=options.mode() != ResponseMode.GET_NONE;
boolean non_blocking=!sync || !block_for_results, anycast=options.anycasting();
if(non_blocking)
updateStats(real_dests, anycast, sync, 0);
if(!sync) {
corr.sendRequest(real_dests, msg, null, options);
return null;
}
GroupRequest<T> req=new GroupRequest<>(corr, real_dests, options);
long start=non_blocking || !rpc_stats.extendedStats()? 0 : System.nanoTime();
req.execute(msg, block_for_results);
long time=non_blocking || !rpc_stats.extendedStats()? 0 : System.nanoTime() - start;
if(!non_blocking)
updateStats(real_dests, anycast, true, time);
return req;
}
public void done(long req_id) {
corr.done(req_id);
}
/**
* Sends a unicast message and - depending on the options - returns a result
* @param msg the payload to send
* @param opts the options to be used
* @return T the result. Null if the call is asynchronous (non-blocking) or if the response is null
* @throws Exception If there was problem sending the request, processing it at the receiver, or processing
* it at the sender.
* @throws TimeoutException If the call didn't succeed within the timeout defined in options (if set)
*/
public <T> T sendMessage(Message msg, RequestOptions opts) throws Exception {
Address dest=msg.getDest();
if(dest == null)
throw new IllegalArgumentException("message destination is null, cannot send message");
if(opts == null) {
log.warn("request options were null, using default of sync");
opts=RequestOptions.SYNC();
}
// invoke an async RPC directly and return null, without creating a UnicastRequest instance
if(opts.mode() == ResponseMode.GET_NONE) {
rpc_stats.add(RpcStats.Type.UNICAST, dest, false, 0);
corr.sendUnicastRequest(msg, null, opts);
return null;
}
// now it must be a sync RPC
UnicastRequest<T> req=new UnicastRequest<>(corr, dest, opts);
long start=!rpc_stats.extendedStats()? 0 : System.nanoTime();
try {
return req.execute(msg, true);
}
finally {
long time=!rpc_stats.extendedStats()? 0 : System.nanoTime() - start;
rpc_stats.add(RpcStats.Type.UNICAST, dest, true, time);
}
}
/**
* Sends a unicast message to the target defined by msg.getDest() and returns a future
* @param msg the payload to send
* @param opts the options
* @return CompletableFuture<T> A future from which the result can be fetched, or null if the call was asynchronous
* @throws Exception If there was problem sending the request, processing it at the receiver, or processing
* it at the sender. {@link java.util.concurrent.Future#get()} will throw this exception
*/
public <T> CompletableFuture<T> sendMessageWithFuture(Message msg, RequestOptions opts) throws Exception {
Address dest=msg.getDest();
if(dest == null)
throw new IllegalArgumentException("message destination is null, cannot send message");
if(opts == null) {
log.warn("request options were null, using default of sync");
opts=RequestOptions.SYNC();
}
rpc_stats.add(RpcStats.Type.UNICAST, dest, opts.mode() != ResponseMode.GET_NONE, 0);
if(opts.mode() == ResponseMode.GET_NONE) {
corr.sendUnicastRequest(msg, null, opts);
return null;
}
// if we get here, the RPC is synchronous
UnicastRequest<T> req=new UnicastRequest<>(corr, dest, opts);
req.execute(msg, false);
return req;
}
@Override
public Object handle(Message msg) throws Exception {
if(req_handler != null)
return req_handler.handle(msg);
return null;
}
@Override
public void handle(Message request, Response response) throws Exception {
if(req_handler != null) {
if(async_dispatching)
req_handler.handle(request, response);
else {
Object retval=req_handler.handle(request);
if(response != null)
response.send(retval, false);
}
return;
}
Object retval=handle(request);
if(response != null)
response.send(retval, false);
}
protected void updateStats(Collection<Address> dests, boolean anycast, boolean sync, long time) {
if(anycast)
rpc_stats.addAnycast(sync, time, dests);
else
rpc_stats.add(RpcStats.Type.MULTICAST, null, sync, time);
}
protected Object handleUpEvent(Event evt) throws Exception {
switch(evt.getType()) {
case Event.GET_APPLSTATE: // reply with GET_APPLSTATE_OK
byte[] tmp_state=null;
if(receiver != null) {
ByteArrayOutputStream output=new ByteArrayOutputStream(1024);
if(getState(output))
tmp_state=output.toByteArray();
}
return new StateTransferInfo(null, 0L, tmp_state);
case Event.GET_STATE_OK:
if(receiver != null) {
StateTransferResult result=evt.getArg();
if(result.hasBuffer()) {
ByteArrayInputStream input=new ByteArrayInputStream(result.getBuffer());
setState(input);
}
}
break;
case Event.STATE_TRANSFER_OUTPUTSTREAM:
OutputStream os=evt.getArg();
getState(os);
break;
case Event.STATE_TRANSFER_INPUTSTREAM:
InputStream is=evt.getArg();
setState(is);
break;
case Event.VIEW_CHANGE:
View v=evt.getArg();
List<Address> new_mbrs=v.getMembers();
setMembers(new_mbrs);
if(receiver != null)
receiver.viewAccepted(v);
break;
case Event.BLOCK:
if(receiver != null)
receiver.block();
break;
case Event.UNBLOCK:
if(receiver != null)
receiver.unblock();
break;
}
return null;
}
protected boolean getState(OutputStream out) throws Exception {
if(receiver == null || out == null)
return false;
try {
receiver.getState(out);
return true;
}
catch(UnsupportedOperationException un) {
return false;
}
}
protected boolean setState(InputStream in) throws Exception {
if(receiver == null || in == null)
return false;
try {
receiver.setState(in);
return true;
}
catch(UnsupportedOperationException un) {
return false;
}
}
public void channelDisconnected(JChannel channel) {
stop();
}
public void channelClosed(JChannel channel) {
stop();
}
class ProtocolAdapter extends Protocol implements UpHandler {
@Override
public String getName() {
return "MessageDispatcher";
}
public <T extends Protocol> T setAddress(Address addr) {
if(corr != null)
corr.setLocalAddress(addr);
return (T)this;
}
public UpHandler setLocalAddress(Address a) {
setAddress(a);
return this;
}
/**
* Called by channel (we registered before) when event is received. This is the UpHandler interface.
*/
@Override
public Object up(Event evt) {
if(corr != null && !corr.receive(evt)) {
try {
return handleUpEvent(evt);
}
catch(Throwable t) {
throw new RuntimeException(t);
}
}
return null;
}
public Object up(Message msg) {
if(corr != null)
corr.receiveMessage(msg);
return null;
}
public void up(MessageBatch batch) {
if(corr == null)
return;
corr.receiveMessageBatch(batch);
}
@Override
public Object down(Event evt) {
return channel != null? channel.down(evt) : null;
}
public Object down(Message msg) {
if(channel != null) {
if(!(channel.isConnected() || channel.isConnecting())) {
// return null;
throw new IllegalStateException("channel is not connected");
}
return channel.down(msg);
}
return null;
}
}
}
|
package org.jgroups.blocks;
import org.jgroups.*;
import org.jgroups.blocks.mux.Muxer;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.TP;
import org.jgroups.protocols.relay.SiteAddress;
import org.jgroups.stack.DiagnosticsHandler;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.StateTransferInfo;
import org.jgroups.util.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Provides synchronous and asynchronous message sending with request-response
* correlation; i.e., matching responses with the original request.
* It also offers push-style message reception (by internally using the PullPushAdapter).
* <p>
* Channels are simple patterns to asynchronously send a receive messages.
* However, a significant number of communication patterns in group communication
* require synchronous communication. For example, a sender would like to send a
* message to the group and wait for all responses. Or another application would
* like to send a message to the group and wait only until the majority of the
* receivers have sent a response, or until a timeout occurred. MessageDispatcher
* offers a combination of the above pattern with other patterns.
* <p>
* Used on top of channel to implement group requests. Client's <code>handle()</code>
* method is called when request is received. Is the equivalent of RpcProtocol on
* the application instead of protocol level.
*
* @author Bela Ban
*/
public class MessageDispatcher implements AsyncRequestHandler, ChannelListener {
protected Channel channel;
protected RequestCorrelator corr;
protected MessageListener msg_listener;
protected MembershipListener membership_listener;
protected RequestHandler req_handler;
protected boolean async_dispatching;
protected ProtocolAdapter prot_adapter;
protected volatile Collection<Address> members=new HashSet<Address>();
protected Address local_addr;
protected final Log log=LogFactory.getLog(getClass());
protected boolean hardware_multicast_supported=false;
protected final AtomicInteger sync_unicasts=new AtomicInteger(0);
protected final AtomicInteger async_unicasts=new AtomicInteger(0);
protected final AtomicInteger sync_multicasts=new AtomicInteger(0);
protected final AtomicInteger async_multicasts=new AtomicInteger(0);
protected final AtomicInteger sync_anycasts=new AtomicInteger(0);
protected final AtomicInteger async_anycasts=new AtomicInteger(0);
protected final Set<ChannelListener> channel_listeners=new CopyOnWriteArraySet<ChannelListener>();
protected final DiagnosticsHandler.ProbeHandler probe_handler=new MyProbeHandler();
public MessageDispatcher() {
}
public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2) {
this.channel=channel;
prot_adapter=new ProtocolAdapter();
if(channel != null) {
local_addr=channel.getAddress();
channel.addChannelListener(this);
}
setMessageListener(l);
setMembershipListener(l2);
if(channel != null)
installUpHandler(prot_adapter, true);
start();
}
public MessageDispatcher(Channel channel, RequestHandler req_handler) {
this(channel, null, null, req_handler);
}
public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler) {
this(channel, l, l2);
setRequestHandler(req_handler);
}
public boolean asyncDispatching() {return async_dispatching;}
public MessageDispatcher asyncDispatching(boolean flag) {
async_dispatching=flag;
if(corr != null)
corr.asyncDispatching(flag);
return this;
}
public UpHandler getProtocolAdapter() {
return prot_adapter;
}
/**
* If this dispatcher is using a user-provided PullPushAdapter, then need to set the members from the adapter
* initially since viewChange has most likely already been called in PullPushAdapter.
*/
protected void setMembers(List<Address> new_mbrs) {
if(new_mbrs != null)
members=new HashSet<Address>(new_mbrs); // volatile write - seen by a subsequent read
}
/**
* Adds a new channel listener to be notified on the channel's state change.
*/
public void addChannelListener(ChannelListener l) {
if(l != null)
channel_listeners.add(l);
}
public void removeChannelListener(ChannelListener l) {
if(l != null)
channel_listeners.remove(l);
}
public void start() {
if(corr == null)
corr=createRequestCorrelator(prot_adapter, this, local_addr).asyncDispatching(async_dispatching);
correlatorStarted();
corr.start();
if(channel != null) {
List<Address> tmp_mbrs=channel.getView() != null ? channel.getView().getMembers() : null;
setMembers(tmp_mbrs);
if(channel instanceof JChannel) {
TP transport=channel.getProtocolStack().getTransport();
corr.registerProbeHandler(transport);
}
TP transport=channel.getProtocolStack().getTransport();
hardware_multicast_supported=transport.supportsMulticasting();
transport.registerProbeHandler(probe_handler);
}
}
protected RequestCorrelator createRequestCorrelator(Protocol transport, RequestHandler handler, Address local_addr) {
return new RequestCorrelator(transport, handler, local_addr);
}
protected void correlatorStarted() {
;
}
public void stop() {
if(corr != null)
corr.stop();
if(channel instanceof JChannel) {
TP transport=channel.getProtocolStack().getTransport();
transport.unregisterProbeHandler(probe_handler);
corr.unregisterProbeHandler(transport);
}
}
public final void setMessageListener(MessageListener l) {
msg_listener=l;
}
public MessageListener getMessageListener() {
return msg_listener;
}
public final void setMembershipListener(MembershipListener l) {
membership_listener=l;
}
public final void setRequestHandler(RequestHandler rh) {
req_handler=rh;
}
public Channel getChannel() {
return channel;
}
public void setChannel(Channel ch) {
if(ch == null)
return;
this.channel=ch;
local_addr=channel.getAddress();
if(prot_adapter == null)
prot_adapter=new ProtocolAdapter();
// Don't force installing the UpHandler so subclasses can use this
// method and still integrate with a MuxUpHandler
installUpHandler(prot_adapter, false);
}
/**
* Sets the given UpHandler as the UpHandler for the channel, or, if the
* channel already has a Muxer installed as it's UpHandler, sets the given
* handler as the Muxer's {@link Muxer#setDefaultHandler(Object) default handler}.
* If the relevant handler is already installed, the <code>canReplace</code>
* controls whether this method replaces it (after logging a WARN) or simply
* leaves <code>handler</code> uninstalled.
* <p>
* Passing <code>false</code> as the <code>canReplace</code> value allows
* callers to use this method to install defaults without concern about
* inadvertently overriding
*
* @param handler the UpHandler to install
* @param canReplace <code>true</code> if an existing Channel upHandler or
* Muxer default upHandler can be replaced; <code>false</code>
* if this method shouldn't install
*/
protected void installUpHandler(UpHandler handler, boolean canReplace)
{
UpHandler existing = channel.getUpHandler();
if (existing == null) {
channel.setUpHandler(handler);
}
else if (existing instanceof Muxer<?>) {
@SuppressWarnings("unchecked")
Muxer<UpHandler> mux = (Muxer<UpHandler>) existing;
if (mux.getDefaultHandler() == null) {
mux.setDefaultHandler(handler);
}
else if (canReplace) {
log.warn("Channel Muxer already has a default up handler installed (" +
mux.getDefaultHandler() + ") but now it is being overridden");
mux.setDefaultHandler(handler);
}
}
else if (canReplace) {
log.warn("Channel already has an up handler installed (" + existing + ") but now it is being overridden");
channel.setUpHandler(handler);
}
}
/**
* Sends a message to all members and expects responses from members in dests (if non-null).
* @param dests A list of group members from which to expect responses (if the call is blocking).
* @param msg The message to be sent
* @param options A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details
* @return RspList A list of Rsp elements
* @throws Exception If the request cannot be sent
* @since 2.9
*/
public <T> RspList<T> castMessage(final Collection<Address> dests,
Message msg, RequestOptions options) throws Exception {
GroupRequest<T> req=cast(dests, msg, options, true);
return req != null? req.getResults() : new RspList();
}
/**
* Sends a message to all members and expects responses from members in dests (if non-null).
* @param dests A list of group members from which to expect responses (if the call is blocking).
* @param msg The message to be sent
* @param options A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details
* @param listener A FutureListener which will be registered (if non null) with the future <em>before</em> the call is invoked
* @return NotifyingFuture<T> A future from which the results (RspList) can be retrieved
* @throws Exception If the request cannot be sent
*/
public <T> NotifyingFuture<RspList<T>> castMessageWithFuture(final Collection<Address> dests,
Message msg,
RequestOptions options,
FutureListener<RspList<T>> listener) throws Exception {
GroupRequest<T> req=cast(dests,msg,options,false, listener);
return req != null? req : new NullFuture<RspList<T>>(new RspList<T>());
}
/**
* Sends a message to all members and expects responses from members in dests (if non-null).
* @param dests A list of group members from which to expect responses (if the call is blocking).
* @param msg The message to be sent
* @param options A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details
* @return NotifyingFuture<T> A future from which the results (RspList) can be retrieved
* @throws Exception If the request cannot be sent
*/
public <T> NotifyingFuture<RspList<T>> castMessageWithFuture(final Collection<Address> dests,
Message msg,
RequestOptions options) throws Exception {
return castMessageWithFuture(dests, msg, options, null);
}
protected <T> GroupRequest<T> cast(final Collection<Address> dests, Message msg, RequestOptions options,
boolean block_for_results, FutureListener<RspList<T>> listener) throws Exception {
if(msg.getDest() != null && !(msg.getDest() instanceof AnycastAddress))
throw new IllegalArgumentException("message destination is non-null, cannot send message");
if(options != null) {
msg.setFlag(options.getFlags()).setTransientFlag(options.getTransientFlags());
if(options.getScope() > 0)
msg.setScope(options.getScope());
}
List<Address> real_dests;
// we need to clone because we don't want to modify the original
if(dests != null) {
real_dests=new ArrayList<Address>();
for(Address dest: dests) {
if(dest instanceof SiteAddress || this.members.contains(dest)) {
if(!real_dests.contains(dest))
real_dests.add(dest);
}
}
}
else
real_dests=new ArrayList<Address>(members);
// if local delivery is off, then we should not wait for the message from the local member.
// therefore remove it from the membership
Channel tmp=channel;
if((tmp != null && tmp.getDiscardOwnMessages()) || msg.isTransientFlagSet(Message.TransientFlag.DONT_LOOPBACK)) {
if(local_addr == null)
local_addr=tmp != null? tmp.getAddress() : null;
if(local_addr != null)
real_dests.remove(local_addr);
}
if(options != null && options.hasExclusionList()) {
Address[] exclusion_list=options.exclusionList();
for(Address excluding: exclusion_list)
real_dests.remove(excluding);
}
// don't even send the message if the destination list is empty
if(log.isTraceEnabled())
log.trace("real_dests=" + real_dests);
if(real_dests.isEmpty()) {
if(log.isTraceEnabled())
log.trace("destination list is empty, won't send message");
return null;
}
if(options != null) {
boolean async=options.getMode() == ResponseMode.GET_NONE;
if(options.getAnycasting()) {
if(async) async_anycasts.incrementAndGet();
else sync_anycasts.incrementAndGet();
}
else {
if(async) async_multicasts.incrementAndGet();
else sync_multicasts.incrementAndGet();
}
}
GroupRequest<T> req=new GroupRequest<T>(msg, corr, real_dests, options);
if(listener != null)
req.setListener(listener);
if(options != null) {
req.setResponseFilter(options.getRspFilter());
req.setAnycasting(options.getAnycasting());
}
req.setBlockForResults(block_for_results);
req.execute();
return req;
}
protected <T> GroupRequest<T> cast(final Collection<Address> dests, Message msg, RequestOptions options,
boolean block_for_results) throws Exception {
return cast(dests, msg, options, block_for_results, null);
}
public void done(long req_id) {
corr.done(req_id);
}
/**
* Sends a unicast message and - depending on the options - returns a result
* @param msg the message to be sent. The destination needs to be non-null
* @param opts the options to be used
* @return T the result
* @throws Exception If there was problem sending the request, processing it at the receiver, or processing
* it at the sender.
* @throws TimeoutException If the call didn't succeed within the timeout defined in options (if set)
*/
public <T> T sendMessage(Message msg, RequestOptions opts) throws Exception {
Address dest=msg.getDest();
if(dest == null)
throw new IllegalArgumentException("message destination is null, cannot send message");
if(opts != null) {
msg.setFlag(opts.getFlags()).setTransientFlag(opts.getTransientFlags());
if(opts.getScope() > 0)
msg.setScope(opts.getScope());
if(opts.getMode() == ResponseMode.GET_NONE)
async_unicasts.incrementAndGet();
else
sync_unicasts.incrementAndGet();
}
UnicastRequest<T> req=new UnicastRequest<T>(msg, corr, dest, opts);
req.execute();
if(opts != null && opts.getMode() == ResponseMode.GET_NONE)
return null;
Rsp<T> rsp=req.getResult();
if(rsp.wasSuspected())
throw new SuspectedException(dest);
Throwable exception=rsp.getException();
if(exception != null) {
if(exception instanceof Error) throw (Error)exception;
else if(exception instanceof RuntimeException) throw (RuntimeException)exception;
else if(exception instanceof Exception) throw (Exception)exception;
else throw new RuntimeException(exception);
}
if(rsp.wasUnreachable())
throw new UnreachableException(dest);
if(!rsp.wasReceived() && !req.responseReceived())
throw new TimeoutException("timeout waiting for response from " + dest + ", request: " + req.toString());
return rsp.getValue();
}
/**
* Sends a unicast message to the target defined by msg.getDest() and returns a future
* @param msg The unicast message to be sent. msg.getDest() must not be null
* @param options
* @param listener A FutureListener which will be registered (if non null) with the future <em>before</em> the call is invoked
* @return NotifyingFuture<T> A future from which the result can be fetched
* @throws Exception If there was problem sending the request, processing it at the receiver, or processing
* it at the sender. {@link java.util.concurrent.Future#get()} will throw this exception
* @throws TimeoutException If the call didn't succeed within the timeout defined in options (if set)
*/
public <T> NotifyingFuture<T> sendMessageWithFuture(Message msg, RequestOptions options,
FutureListener<T> listener) throws Exception {
Address dest=msg.getDest();
if(dest == null)
throw new IllegalArgumentException("message destination is null, cannot send message");
if(options != null) {
msg.setFlag(options.getFlags()).setTransientFlag(options.getTransientFlags());
if(options.getScope() > 0)
msg.setScope(options.getScope());
if(options.getMode() == ResponseMode.GET_NONE)
async_unicasts.incrementAndGet();
else
sync_unicasts.incrementAndGet();
}
UnicastRequest<T> req=new UnicastRequest<T>(msg, corr, dest, options);
if(listener != null)
req.setListener(listener);
req.setBlockForResults(false);
req.execute();
if(options != null && options.getMode() == ResponseMode.GET_NONE)
return new NullFuture<T>(null);
return req;
}
/**
* Sends a unicast message to the target defined by msg.getDest() and returns a future
* @param msg The unicast message to be sent. msg.getDest() must not be null
* @param options
* @return NotifyingFuture<T> A future from which the result can be fetched
* @throws Exception If there was problem sending the request, processing it at the receiver, or processing
* it at the sender. {@link java.util.concurrent.Future#get()} will throw this exception
* @throws TimeoutException If the call didn't succeed within the timeout defined in options (if set)
*/
public <T> NotifyingFuture<T> sendMessageWithFuture(Message msg, RequestOptions options) throws Exception {
return sendMessageWithFuture(msg, options, null);
}
public Object handle(Message msg) throws Exception {
if(req_handler != null)
return req_handler.handle(msg);
return null;
}
public void handle(Message request, Response response) throws Exception {
if(req_handler != null) {
if(req_handler instanceof AsyncRequestHandler)
((AsyncRequestHandler)req_handler).handle(request, response);
else {
Object retval=req_handler.handle(request);
if(response != null)
response.send(retval, false);
}
return;
}
Object retval=handle(request);
if(response != null)
response.send(retval, false);
}
public void channelConnected(Channel channel) {
for(ChannelListener l: channel_listeners) {
try {
l.channelConnected(channel);
}
catch(Throwable t) {
log.warn("notifying channel listener " + l + " failed", t);
}
}
}
public void channelDisconnected(Channel channel) {
stop();
for(ChannelListener l: channel_listeners) {
try {
l.channelDisconnected(channel);
}
catch(Throwable t) {
log.warn("notifying channel listener " + l + " failed", t);
}
}
}
public void channelClosed(Channel channel) {
stop();
for(ChannelListener l: channel_listeners) {
try {
l.channelClosed(channel);
}
catch(Throwable t) {
log.warn("notifying channel listener " + l + " failed", t);
}
}
}
protected Object handleUpEvent(Event evt) throws Exception {
switch(evt.getType()) {
case Event.MSG:
if(msg_listener != null)
msg_listener.receive((Message) evt.getArg());
break;
case Event.GET_APPLSTATE: // reply with GET_APPLSTATE_OK
byte[] tmp_state=null;
if(msg_listener != null) {
ByteArrayOutputStream output=new ByteArrayOutputStream(1024);
msg_listener.getState(output);
tmp_state=output.toByteArray();
}
return new StateTransferInfo(null, 0L, tmp_state);
case Event.GET_STATE_OK:
if(msg_listener != null) {
StateTransferResult result=(StateTransferResult)evt.getArg();
if(result.hasBuffer()) {
ByteArrayInputStream input=new ByteArrayInputStream(result.getBuffer());
msg_listener.setState(input);
}
}
break;
case Event.STATE_TRANSFER_OUTPUTSTREAM:
OutputStream os=(OutputStream)evt.getArg();
if(msg_listener != null && os != null) {
msg_listener.getState(os);
}
break;
case Event.STATE_TRANSFER_INPUTSTREAM:
InputStream is=(InputStream)evt.getArg();
if(msg_listener != null && is!=null)
msg_listener.setState(is);
break;
case Event.VIEW_CHANGE:
View v=(View) evt.getArg();
List<Address> new_mbrs=v.getMembers();
setMembers(new_mbrs);
if(membership_listener != null)
membership_listener.viewAccepted(v);
break;
case Event.SET_LOCAL_ADDRESS:
if(log.isTraceEnabled())
log.trace("setting local_addr (" + local_addr + ") to " + evt.getArg());
local_addr=(Address)evt.getArg();
break;
case Event.SUSPECT:
if(membership_listener != null)
membership_listener.suspect((Address) evt.getArg());
break;
case Event.BLOCK:
if(membership_listener != null)
membership_listener.block();
break;
case Event.UNBLOCK:
if(membership_listener != null)
membership_listener.unblock();
break;
}
return null;
}
class MyProbeHandler implements DiagnosticsHandler.ProbeHandler {
public Map<String,String> handleProbe(String... keys) {
Map<String,String> retval=new HashMap<String,String>();
for(String key: keys) {
if("rpcs".equals(key)) {
String channel_name = channel != null ? channel.getClusterName() : "";
retval.put(channel_name + ": sync unicast RPCs", sync_unicasts.toString());
retval.put(channel_name + ": sync multicast RPCs", sync_multicasts.toString());
retval.put(channel_name + ": async unicast RPCs", async_unicasts.toString());
retval.put(channel_name + ": async multicast RPCs", async_multicasts.toString());
retval.put(channel_name + ": sync anycast RPCs", sync_anycasts.toString());
retval.put(channel_name + ": async anycast RPCs", async_anycasts.toString());
}
if("rpcs-reset".equals(key)) {
sync_unicasts.set(0);
sync_multicasts.set(0);
async_unicasts.set(0);
async_multicasts.set(0);
sync_anycasts.set(0);
async_anycasts.set(0);
}
}
return retval;
}
public String[] supportedKeys() {
return new String[]{"rpcs", "rpcs-reset"};
}
}
class ProtocolAdapter extends Protocol implements UpHandler {
public String getName() {
return "MessageDispatcher";
}
/**
* Called by channel (we registered before) when event is received. This is the UpHandler interface.
*/
public Object up(Event evt) {
if(corr != null) {
if(!corr.receive(evt)) {
try {
return handleUpEvent(evt);
}
catch(Throwable t) {
throw new RuntimeException(t);
}
}
}
return null;
}
public Object down(Event evt) {
if(channel != null) {
if(evt.getType() == Event.MSG && !(channel.isConnected() || channel.isConnecting()))
throw new IllegalStateException("channel is not connected");
return channel.down(evt);
}
return null;
}
}
}
|
package org.opencms.report;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsUUID;
import com.opencms.file.CmsObject;
import com.opencms.workplace.CmsXmlLanguageFile;
/**
* Provides a common Thread class for the reports.<p>
*
* @author Alexander Kandzior (a.kandzior@alkacon.com)
* @version $Revision: 1.8 $
*/
public abstract class A_CmsReportThread extends Thread {
/** The OpenCms request context to use */
private CmsObject m_cms;
/** Indicates if the Thread was already checked by the grim reaper */
private boolean m_doomed;
/** The id of this report */
private CmsUUID m_id;
/** The report that belongs to the thread */
private I_CmsReport m_report;
/** The time this report is running */
private long m_starttime;
/**
* Constructs a new report Thread with the given name.<p>
*
* @param cms the current OpenCms context object
* @param name the name of the Thread
*/
protected A_CmsReportThread(CmsObject cms, String name) {
super(OpenCms.getThreadStore().getThreadGroup(), name);
// report Threads are never daemon Threads
setDaemon(false);
// the session in the cms context must not be updated when it is used in a report
m_cms = cms;
m_cms.getRequestContext().setUpdateSessionEnabled(false);
// generate the report Thread id
m_id = new CmsUUID();
setName(name + " [" + m_id + "]");
// new Threads are not doomed
m_doomed = false;
// set start time
m_starttime = System.currentTimeMillis();
// add this Thread to the main Thread store
OpenCms.getThreadStore().addThread(this);
}
/**
* Returns the OpenCms context object this Thread is initialized with.<p>
*
* @return the OpenCms context object this Thread is initialized with
*/
protected CmsObject getCms() {
return m_cms;
}
/**
* Returns the error exception in case there was an error during the execution of
* this Thread, null otherwise.<p>
*
* @return the error exception in case there was an error, null otherwise
*/
public Throwable getError() {
return null;
}
/**
* Returns the id of this report thread.<p>
*
* @return the id of this report thread
*/
public CmsUUID getId() {
return m_id;
}
/**
* Returns the report where the output of this Thread is written to.<o>
*
* @return the report where the output of this Thread is written to
*/
protected I_CmsReport getReport() {
return m_report;
}
/**
* Returns the part of the report that is ready for output.<p>
*
* @return the part of the report that is ready for output
*/
public abstract String getReportUpdate();
/**
* Returns the time this report has been running.<p>
*
* @return the time this report has been running
*/
public long getRuntime() {
if (m_doomed) {
return m_starttime;
} else {
return System.currentTimeMillis() - m_starttime;
}
}
/**
* Initialize a HTML report for this Thread.<p>
*/
protected void initHtmlReport() {
String locale = CmsXmlLanguageFile.getCurrentUserLanguage(m_cms);
m_report = new CmsHtmlReport(locale);
}
/**
* Initialize a HTML report for this Thread with a specified resource bundle.<p>
*
* @param bundleName the name of the resource bundle with localized strings
*/
protected void initHtmlReport(String bundleName) {
String locale = CmsXmlLanguageFile.getCurrentUserLanguage(m_cms);
m_report = new CmsHtmlReport(bundleName, locale);
}
/**
* Returns true if this thread is already "doomed" to be deleted.<p>
*
* A OpenCms deamon Thread (the "Grim Reaper") will collect all
* doomed Threads, i.e. threads that are not longer active for some
* time.<p>
*
* @return true if this thread is already "doomed" to be deleted
*/
public synchronized boolean isDoomed() {
if (isAlive()) {
// as long as the Thread is still active it is never doomed
return false;
}
if (m_doomed) {
// not longer active, and already doomed, so rest in peace...
return true;
}
// condemn the Thread to be collected by the grim reaper next time
m_starttime = getRuntime();
m_doomed = true;
return false;
}
}
|
package org.usfirst.frc.team1492.robot;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Joystick.AxisType;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Robot extends SampleRobot {
Talon motorL;
Talon motorR;
Talon motorCenter; // Motor controller for the middle of the H
Talon motorElevator;
Joystick stickLeft;
Joystick stickRight;
Joystick stickAux;
DigitalInput limitSwitchElevatorTop;
DigitalInput limitSwitchElevatorBottom;
DigitalInput limitSwitchElevatorOne;
DigitalInput limitSwitchElevatorTwo;
DigitalInput limitSwitchElevatorThree;
double elevatorSpeed = 0;
double elevatorMaxSpeed = 1;
public Robot() {
motorL = new Talon(0);
motorR = new Talon(1);
motorCenter = new Talon(2);
motorElevator = new Talon(3);
stickLeft = new Joystick(0);
stickRight = new Joystick(1);
stickAux = new Joystick(2);
limitSwitchElevatorBottom = new DigitalInput(0);
limitSwitchElevatorTop = new DigitalInput(1);
limitSwitchElevatorOne = new DigitalInput(2);
limitSwitchElevatorTwo = new DigitalInput(3);
limitSwitchElevatorThree = new DigitalInput(4);
}
public void autonomous() {
}
public void operatorControl() {
// CameraThread c = new CameraThread();
while (isOperatorControl() && isEnabled()) {
driveControl();
manipulatorControl();
Timer.delay(0.005);
}
// c.finish();
}
public void test() {
}
public void driveControl() {
double leftSide = -stickLeft.getAxis(AxisType.kY);
double rightSide = stickRight.getAxis(AxisType.kY);
double horizontal = (stickLeft.getAxis(AxisType.kX) + stickRight
.getAxis(AxisType.kX)) / 2;
motorL.set(leftSide);
motorR.set(rightSide);
motorCenter.set(horizontal);
}
public void manipulatorControl() {
// elevator limit switches not edge ones
elevatorMaxSpeed = (stickAux.getAxis(AxisType.kZ) + 1) / 2;
SmartDashboard.putNumber("elevatorMaxSpeed", elevatorMaxSpeed);
SmartDashboard.putBoolean("!limitSwitchElevatorTop",
!limitSwitchElevatorTop.get());
SmartDashboard.putBoolean("!limitSwitchElevatorBottom",
!limitSwitchElevatorBottom.get());
SmartDashboard.putBoolean("!limitSwitchElevatorOne",
!limitSwitchElevatorOne.get());
if (!limitSwitchElevatorOne.get() /*
* || !limitSwitchElevatorTwo.get() ||
* !limitSwitchElevatorThree.get()
*/) {
elevatorSpeed = 0;
}
if (stickAux.getRawButton(3)) {
elevatorSpeed = -elevatorMaxSpeed;
}
if (stickAux.getRawButton(2)) {
elevatorSpeed = elevatorMaxSpeed;
}
if (!limitSwitchElevatorTop.get() || !limitSwitchElevatorBottom.get()) {
elevatorSpeed = 0;
}
motorElevator.set(elevatorSpeed);
}
}
|
package pathfinding.astar.arcs;
import java.awt.Graphics;
import config.Config;
import config.ConfigInfo;
import config.Configurable;
import config.DynamicConfigurable;
import container.Service;
import container.dependances.HighPFClass;
import container.dependances.LowPFClass;
import graphic.Fenetre;
import graphic.PrintBuffer;
import graphic.printable.Couleur;
import graphic.printable.Layer;
import graphic.printable.Printable;
import pathfinding.SensFinal;
import robot.CinematiqueObs;
import robot.RobotReal;
import table.GameElementNames;
import utils.Log;
import utils.Vec2RO;
import utils.Vec2RW;
public class CercleArrivee implements Service, Configurable, Printable, HighPFClass, LowPFClass, DynamicConfigurable
{
public Vec2RO position;
public double rayon;
public Vec2RO arriveeDStarLite;
public SensFinal sens;
private double rayonDefaut;
private boolean graphic;
private boolean symetrie = false;
protected Log log;
private PrintBuffer buffer;
public CercleArrivee(Log log, PrintBuffer buffer)
{
this.log = log;
this.buffer = buffer;
}
private void set(Vec2RO position, double orientationArriveeDStarLite, double rayon, SensFinal sens)
{
this.position = new Vec2RO(symetrie ? -position.getX() : position.getX(), position.getY());
this.arriveeDStarLite = new Vec2RW(rayon, symetrie ? Math.PI - orientationArriveeDStarLite : orientationArriveeDStarLite, false);
((Vec2RW)arriveeDStarLite).plus(position);
this.rayon = rayon;
this.sens = sens;
if(graphic)
synchronized(buffer)
{
buffer.notify();
}
log.debug("arriveeDStarLite : "+arriveeDStarLite);
}
public void set(GameElementNames element)
{
set(element.obstacle.getPosition(), element.orientationArriveeDStarLite, rayonDefaut, SensFinal.MARCHE_ARRIERE);
}
private Vec2RW tmp = new Vec2RW();
public boolean isArrived(CinematiqueObs robot)
{
position.copy(tmp);
tmp.minus(robot.getPosition());
double o = tmp.getFastArgument();
double diffo = (o - robot.orientationGeometrique) % (2*Math.PI);
if(diffo > Math.PI)
diffo -= 2*Math.PI;
return (robot.getPosition().distance(position) - rayon) < 11 && Math.abs(diffo) < 5 / 180. * Math.PI;
}
@Override
public void useConfig(Config config)
{
rayonDefaut = config.getInt(ConfigInfo.RAYON_CERCLE_ARRIVEE_PF);
graphic = config.getBoolean(ConfigInfo.GRAPHIC_CERCLE_ARRIVEE);
if(graphic)
buffer.add(this);
}
@Override
public void print(Graphics g, Fenetre f, RobotReal robot)
{
if(position != null)
{
g.setColor(Couleur.ROUGE.couleur);
g.drawOval(f.XtoWindow(position.getX()-rayon), f.YtoWindow(position.getY()+rayon), f.distanceXtoWindow((int)(2*rayon)), f.distanceYtoWindow((int)(2*rayon)));
}
}
@Override
public Layer getLayer()
{
return Layer.FOREGROUND;
}
public boolean isInCircle(Vec2RO position2)
{
return position2.squaredDistance(position) < rayon*rayon;
}
@Override
public String toString()
{
return position+", rayon "+rayon+", arrivee "+arriveeDStarLite;
}
@Override
public void updateConfig(Config config)
{
symetrie = config.getSymmetry();
}
}
|
package peergos.tests;
import org.junit.*;
import peergos.corenode.CoreNode;
import peergos.corenode.UserPublicKeyLink;
import peergos.crypto.*;
import java.time.LocalDate;
import java.util.*;
public class UserPublicKeyLinkTests {
@BeforeClass
public static void init() throws Exception {
// use insecure random otherwise tests take ages
UserTests.setFinalStatic(TweetNaCl.class.getDeclaredField("prng"), new Random(1));
}
@Test
public void createInitial() {
User user = User.random();
UserPublicKeyLink.UsernameClaim node = UserPublicKeyLink.UsernameClaim.create("someuser", user, LocalDate.now().plusYears(2));
UserPublicKeyLink upl = new UserPublicKeyLink(user.toUserPublicKey(), node);
testSerialization(upl);
}
public void testSerialization(UserPublicKeyLink link) {
byte[] serialized1 = link.toByteArray();
UserPublicKeyLink upl2 = UserPublicKeyLink.fromByteArray(link.owner, serialized1);
byte[] serialized2 = upl2.toByteArray();
if (!Arrays.equals(serialized1, serialized2))
throw new IllegalStateException("toByteArray not inverse of fromByteArray!");
}
@Test
public void createChain() {
User oldUser = User.random();
User newUser = User.random();
List<UserPublicKeyLink> links = UserPublicKeyLink.createChain(oldUser, newUser, "someuser", LocalDate.now().plusYears(2));
links.forEach(link -> testSerialization(link));
}
@Test
public void coreNode() throws Exception {
CoreNode core = CoreNode.getDefault();
User user = User.insecureRandom();
String username = "someuser";
// register the username
UserPublicKeyLink.UsernameClaim node = UserPublicKeyLink.UsernameClaim.create(username, user, LocalDate.now().plusYears(2));
UserPublicKeyLink upl = new UserPublicKeyLink(user.toUserPublicKey(), node);
boolean success = core.updateChain(username, Arrays.asList(upl));
List<UserPublicKeyLink> chain = core.getChain(username);
if (chain.size() != 1 || !chain.get(0).equals(upl))
throw new IllegalStateException("Retrieved chain element different "+chain +" != "+Arrays.asList(upl));
// now change the expiry
UserPublicKeyLink.UsernameClaim node2 = UserPublicKeyLink.UsernameClaim.create(username, user, LocalDate.now().plusYears(3));
UserPublicKeyLink upl2 = new UserPublicKeyLink(user.toUserPublicKey(), node2);
boolean success2 = core.updateChain(username, Arrays.asList(upl2));
List<UserPublicKeyLink> chain2 = core.getChain(username);
if (chain2.size() != 1 || !chain2.get(0).equals(upl2))
throw new IllegalStateException("Retrieved chain element different "+chain2 +" != "+Arrays.asList(upl2));
// now change the keys
User user2 = User.insecureRandom();
List<UserPublicKeyLink> chain3 = UserPublicKeyLink.createChain(user, user2, username, LocalDate.now().plusWeeks(1));
boolean success3 = core.updateChain(username, chain3);
List<UserPublicKeyLink> chain3Retrieved = core.getChain(username);
if (!chain3.equals(chain3Retrieved))
throw new IllegalStateException("Retrieved chain element different");
// update the expiry at the end of the chain
UserPublicKeyLink.UsernameClaim node4 = UserPublicKeyLink.UsernameClaim.create(username, user2, LocalDate.now().plusWeeks(2));
UserPublicKeyLink upl4 = new UserPublicKeyLink(user2.toUserPublicKey(), node4);
List<UserPublicKeyLink> chain4 = Arrays.asList(upl4);
boolean success4 = core.updateChain(username, chain4);
List<UserPublicKeyLink> chain4Retrieved = core.getChain(username);
if (!chain4.equals(Arrays.asList(chain4Retrieved.get(chain4Retrieved.size()-1))))
throw new IllegalStateException("Retrieved chain element different after expiry update");
// check username lookup
String uname = core.getUsername(user2.toUserPublicKey());
if (!uname.equals(username))
throw new IllegalStateException("Returned username is different! "+uname + " != "+username);
// try to claim the same username with a different key
User user3 = User.insecureRandom();
UserPublicKeyLink.UsernameClaim node3 = UserPublicKeyLink.UsernameClaim.create(username, user3, LocalDate.now().plusYears(2));
UserPublicKeyLink upl3 = new UserPublicKeyLink(user3.toUserPublicKey(), node3);
try {
boolean shouldFail = core.updateChain(username, Arrays.asList(upl3));
throw new RuntimeException("Should have failed before here!");
} catch (IllegalStateException e) {}
}
}
|
package org.broadinstitute.sting.gatk.walkers.genotyper;
import com.google.java.contract.Requires;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.AlignmentContextUtils;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.annotator.VariantAnnotatorEngine;
import org.broadinstitute.sting.utils.*;
import org.broadinstitute.sting.utils.baq.BAQ;
import org.broadinstitute.sting.utils.codecs.vcf.VCFConstants;
import org.broadinstitute.sting.utils.pileup.PileupElement;
import org.broadinstitute.sting.utils.pileup.ReadBackedExtendedEventPileup;
import org.broadinstitute.sting.utils.pileup.ReadBackedPileup;
import org.broadinstitute.sting.utils.variantcontext.Allele;
import org.broadinstitute.sting.utils.variantcontext.Genotype;
import org.broadinstitute.sting.utils.variantcontext.GenotypeLikelihoods;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;
import java.io.PrintStream;
import java.util.*;
public class UnifiedGenotyperEngine {
public static final String LOW_QUAL_FILTER_NAME = "LowQual";
public enum OUTPUT_MODE {
EMIT_VARIANTS_ONLY,
EMIT_ALL_CONFIDENT_SITES,
EMIT_ALL_SITES
}
// the unified argument collection
private final UnifiedArgumentCollection UAC;
// the annotation engine
private final VariantAnnotatorEngine annotationEngine;
// the model used for calculating genotypes
private ThreadLocal<Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel>> glcm = new ThreadLocal<Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel>>();
// the model used for calculating p(non-ref)
private ThreadLocal<AlleleFrequencyCalculationModel> afcm = new ThreadLocal<AlleleFrequencyCalculationModel>();
// because the allele frequency priors are constant for a given i, we cache the results to avoid having to recompute everything
private final double[] log10AlleleFrequencyPriorsSNPs;
private final double[] log10AlleleFrequencyPriorsIndels;
// the allele frequency likelihoods (allocated once as an optimization)
private ThreadLocal<double[]> log10AlleleFrequencyPosteriors = new ThreadLocal<double[]>();
// the priors object
private final GenotypePriors genotypePriorsSNPs;
private final GenotypePriors genotypePriorsIndels;
// samples in input
private final Set<String> samples;
// the various loggers and writers
private final Logger logger;
private final PrintStream verboseWriter;
// number of chromosomes (2 * samples) in input
private final int N;
// the standard filter to use for calls below the confidence threshold but above the emit threshold
private static final Set<String> filter = new HashSet<String>(1);
private final boolean BAQEnabledOnCMDLine;
// Public interface functions
@Requires({"toolkit != null", "UAC != null"})
public UnifiedGenotyperEngine(GenomeAnalysisEngine toolkit, UnifiedArgumentCollection UAC) {
this(toolkit, UAC, Logger.getLogger(UnifiedGenotyperEngine.class), null, null,
// get the number of samples
// if we're supposed to assume a single sample, do so
UAC.ASSUME_SINGLE_SAMPLE != null ?
new TreeSet<String>(Arrays.asList(UAC.ASSUME_SINGLE_SAMPLE)) :
SampleUtils.getSAMFileSamples(toolkit.getSAMFileHeader()));
}
@Requires({"toolkit != null", "UAC != null", "logger != null", "samples != null && samples.size() > 0"})
public UnifiedGenotyperEngine(GenomeAnalysisEngine toolkit, UnifiedArgumentCollection UAC, Logger logger, PrintStream verboseWriter, VariantAnnotatorEngine engine, Set<String> samples) {
this.BAQEnabledOnCMDLine = toolkit.getArguments().BAQMode != BAQ.CalculationMode.OFF;
this.samples = new TreeSet<String>(samples);
// note that, because we cap the base quality by the mapping quality, minMQ cannot be less than minBQ
this.UAC = UAC.clone();
this.UAC.MIN_MAPPING_QUALTY_SCORE = Math.max(UAC.MIN_MAPPING_QUALTY_SCORE, UAC.MIN_BASE_QUALTY_SCORE);
this.logger = logger;
this.verboseWriter = verboseWriter;
this.annotationEngine = engine;
N = 2 * this.samples.size();
log10AlleleFrequencyPriorsSNPs = new double[N+1];
log10AlleleFrequencyPriorsIndels = new double[N+1];
computeAlleleFrequencyPriors(N, log10AlleleFrequencyPriorsSNPs, GenotypeLikelihoodsCalculationModel.Model.SNP);
computeAlleleFrequencyPriors(N, log10AlleleFrequencyPriorsIndels, GenotypeLikelihoodsCalculationModel.Model.INDEL);
genotypePriorsSNPs = createGenotypePriors(GenotypeLikelihoodsCalculationModel.Model.SNP);
genotypePriorsIndels = createGenotypePriors(GenotypeLikelihoodsCalculationModel.Model.INDEL);
filter.add(LOW_QUAL_FILTER_NAME);
}
/**
* Compute full calls at a given locus. Entry point for engine calls from the UnifiedGenotyper.
*
* @param tracker the meta data tracker
* @param refContext the reference base
* @param rawContext contextual information around the locus
* @return the VariantCallContext object
*/
public VariantCallContext calculateLikelihoodsAndGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext) {
if ( UAC.COVERAGE_AT_WHICH_TO_ABORT > 0 && rawContext.size() > UAC.COVERAGE_AT_WHICH_TO_ABORT )
return null;
final GenotypeLikelihoodsCalculationModel.Model model = getCurrentGLModel(tracker, refContext, rawContext );
if( model == null ) {
return (UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_SITES && UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ? generateEmptyContext(tracker, refContext, null, rawContext) : null);
}
Map<String, AlignmentContext> stratifiedContexts = getFilteredAndStratifiedContexts(UAC, refContext, rawContext, model);
if ( stratifiedContexts == null ) {
return (UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_SITES && UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ? generateEmptyContext(tracker, refContext, stratifiedContexts, rawContext) : null);
}
VariantContext vc = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, null, true, model);
if ( vc == null )
return null;
return calculateGenotypes(tracker, refContext, rawContext, stratifiedContexts, vc, model);
}
/**
* Compute GLs at a given locus. Entry point for engine calls from UGCalcLikelihoods.
*
* @param tracker the meta data tracker
* @param refContext the reference base
* @param rawContext contextual information around the locus
* @return the VariantContext object
*/
public VariantContext calculateLikelihoods(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext) {
final GenotypeLikelihoodsCalculationModel.Model model = getCurrentGLModel( tracker, refContext, rawContext );
if( model == null )
return null;
Map<String, AlignmentContext> stratifiedContexts = getFilteredAndStratifiedContexts(UAC, refContext, rawContext, model);
if ( stratifiedContexts == null )
return null;
return calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, null, true, model);
}
/**
* Compute genotypes at a given locus. Entry point for engine calls from UGCallVariants.
*
* @param tracker the meta data tracker
* @param refContext the reference base
* @param rawContext contextual information around the locus
* @param vc the GL-annotated variant context
* @return the VariantCallContext object
*/
public VariantCallContext calculateGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext, VariantContext vc) {
final GenotypeLikelihoodsCalculationModel.Model model = getCurrentGLModel(tracker, refContext, rawContext );
if( model == null ) {
return null;
}
Map<String, AlignmentContext> stratifiedContexts = getFilteredAndStratifiedContexts(UAC, refContext, rawContext, model);
return calculateGenotypes(tracker, refContext, rawContext, stratifiedContexts, vc, model);
}
// Private implementation helpers
// private method called by both UnifiedGenotyper and UGCalcLikelihoods entry points into the engine
private VariantContext calculateLikelihoods(RefMetaDataTracker tracker, ReferenceContext refContext, Map<String, AlignmentContext> stratifiedContexts, AlignmentContextUtils.ReadOrientation type, Allele alternateAlleleToUse, boolean useBAQedPileup, final GenotypeLikelihoodsCalculationModel.Model model) {
// initialize the data for this thread if that hasn't been done yet
if ( glcm.get() == null ) {
glcm.set(getGenotypeLikelihoodsCalculationObject(logger, UAC));
}
Map<String, MultiallelicGenotypeLikelihoods> GLs = new HashMap<String, MultiallelicGenotypeLikelihoods>();
Allele refAllele = glcm.get().get(model).getLikelihoods(tracker, refContext, stratifiedContexts, type, getGenotypePriors(model), GLs, alternateAlleleToUse, useBAQedPileup && BAQEnabledOnCMDLine);
if ( refAllele != null )
return createVariantContextFromLikelihoods(refContext, refAllele, GLs);
else
return null;
}
private VariantCallContext generateEmptyContext(RefMetaDataTracker tracker, ReferenceContext ref, Map<String, AlignmentContext> stratifiedContexts, AlignmentContext rawContext) {
VariantContext vc;
if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
VariantContext vcInput = SNPGenotypeLikelihoodsCalculationModel.getSNPVCFromAllelesRod(tracker, ref, false, logger);
if ( vcInput == null )
return null;
vc = new VariantContext("UG_call", vcInput.getChr(), vcInput.getStart(), vcInput.getEnd(), vcInput.getAlleles());
} else {
// deal with bad/non-standard reference bases
if ( !Allele.acceptableAlleleBases(new byte[]{ref.getBase()}) )
return null;
Set<Allele> alleles = new HashSet<Allele>();
alleles.add(Allele.create(ref.getBase(), true));
vc = new VariantContext("UG_call", ref.getLocus().getContig(), ref.getLocus().getStart(), ref.getLocus().getStart(), alleles);
}
if ( annotationEngine != null ) {
// we want to use the *unfiltered* and *unBAQed* context for the annotations
ReadBackedPileup pileup = null;
if (rawContext.hasExtendedEventPileup())
pileup = rawContext.getExtendedEventPileup();
else if (rawContext.hasBasePileup())
pileup = rawContext.getBasePileup();
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup, UAC.ASSUME_SINGLE_SAMPLE);
vc = annotationEngine.annotateContext(tracker, ref, stratifiedContexts, vc).iterator().next();
}
return new VariantCallContext(vc, ref.getBase(), false);
}
private VariantContext createVariantContextFromLikelihoods(ReferenceContext refContext, Allele refAllele, Map<String, MultiallelicGenotypeLikelihoods> GLs) {
// no-call everyone for now
List<Allele> noCall = new ArrayList<Allele>();
noCall.add(Allele.NO_CALL);
Set<Allele> alleles = new LinkedHashSet<Allele>();
alleles.add(refAllele);
boolean addedAltAlleles = false;
HashMap<String, Genotype> genotypes = new HashMap<String, Genotype>();
for ( MultiallelicGenotypeLikelihoods GL : GLs.values() ) {
if ( !addedAltAlleles ) {
addedAltAlleles = true;
// ordering important to maintain consistency
for (Allele a: GL.getAlleles()) {
alleles.add(a);
}
}
HashMap<String, Object> attributes = new HashMap<String, Object>();
//GenotypeLikelihoods likelihoods = new GenotypeLikelihoods(GL.getLikelihoods());
GenotypeLikelihoods likelihoods = GenotypeLikelihoods.fromLog10Likelihoods(GL.getLikelihoods());
attributes.put(VCFConstants.DEPTH_KEY, GL.getDepth());
attributes.put(VCFConstants.PHRED_GENOTYPE_LIKELIHOODS_KEY, likelihoods);
genotypes.put(GL.getSample(), new Genotype(GL.getSample(), noCall, Genotype.NO_NEG_LOG_10PERROR, null, attributes, false));
}
GenomeLoc loc = refContext.getLocus();
int endLoc = calculateEndPos(alleles, refAllele, loc);
return new VariantContext("UG_call",
loc.getContig(),
loc.getStart(),
endLoc,
alleles,
genotypes,
VariantContext.NO_NEG_LOG_10PERROR,
null,
null);
}
// private method called by both UnifiedGenotyper and UGCallVariants entry points into the engine
private VariantCallContext calculateGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc, final GenotypeLikelihoodsCalculationModel.Model model) {
// initialize the data for this thread if that hasn't been done yet
if ( afcm.get() == null ) {
log10AlleleFrequencyPosteriors.set(new double[N+1]);
afcm.set(getAlleleFrequencyCalculationObject(N, logger, verboseWriter, UAC));
}
// estimate our confidence in a reference call and return
if ( vc.getNSamples() == 0 )
return (UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES ?
estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), false, 1.0) :
generateEmptyContext(tracker, refContext, stratifiedContexts, rawContext));
// 'zero' out the AFs (so that we don't have to worry if not all samples have reads at this position)
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(tracker, refContext, vc.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyPosteriors.get());
// find the most likely frequency
int bestAFguess = MathUtils.maxElementIndex(log10AlleleFrequencyPosteriors.get());
// calculate p(f>0)
double[] normalizedPosteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get());
double sum = 0.0;
for (int i = 1; i <= N; i++)
sum += normalizedPosteriors[i];
double PofF = Math.min(sum, 1.0); // deal with precision errors
double phredScaledConfidence;
if ( bestAFguess != 0 || UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(normalizedPosteriors[0]);
if ( Double.isInfinite(phredScaledConfidence) )
phredScaledConfidence = -10.0 * log10AlleleFrequencyPosteriors.get()[0];
} else {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(PofF);
if ( Double.isInfinite(phredScaledConfidence) ) {
sum = 0.0;
for (int i = 1; i <= N; i++) {
if ( log10AlleleFrequencyPosteriors.get()[i] == AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED )
break;
sum += log10AlleleFrequencyPosteriors.get()[i];
}
phredScaledConfidence = (MathUtils.compareDoubles(sum, 0.0) == 0 ? 0 : -10.0 * sum);
}
}
// return a null call if we don't pass the confidence cutoff or the most likely allele frequency is zero
if ( UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES && !passesEmitThreshold(phredScaledConfidence, bestAFguess) ) {
// technically, at this point our confidence in a reference call isn't accurately estimated
// because it didn't take into account samples with no data, so let's get a better estimate
return estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), true, 1.0 - PofF);
}
// create the genotypes
Map<String, Genotype> genotypes = afcm.get().assignGenotypes(vc, log10AlleleFrequencyPosteriors.get(), bestAFguess);
// print out stats if we have a writer
if ( verboseWriter != null )
printVerboseData(refContext.getLocus().toString(), vc, PofF, phredScaledConfidence, normalizedPosteriors, model);
HashMap<String, Object> attributes = new HashMap<String, Object>();
// if the site was downsampled, record that fact
if ( rawContext.hasPileupBeenDownsampled() )
attributes.put(VCFConstants.DOWNSAMPLED_KEY, true);
if ( !UAC.NO_SLOD && bestAFguess != 0 ) {
final boolean DEBUG_SLOD = false;
// the overall lod
VariantContext vcOverall = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(tracker, refContext, vcOverall.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyPosteriors.get());
//double overallLog10PofNull = log10AlleleFrequencyPosteriors.get()[0];
double overallLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get(), 1);
if ( DEBUG_SLOD ) System.out.println("overallLog10PofF=" + overallLog10PofF);
// the forward lod
VariantContext vcForward = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.FORWARD, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(tracker, refContext, vcForward.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyPosteriors.get());
//double[] normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double forwardLog10PofNull = log10AlleleFrequencyPosteriors.get()[0];
double forwardLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get(), 1);
if ( DEBUG_SLOD ) System.out.println("forwardLog10PofNull=" + forwardLog10PofNull + ", forwardLog10PofF=" + forwardLog10PofF);
// the reverse lod
VariantContext vcReverse = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.REVERSE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(tracker, refContext, vcReverse.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyPosteriors.get());
//normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double reverseLog10PofNull = log10AlleleFrequencyPosteriors.get()[0];
double reverseLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get(), 1);
if ( DEBUG_SLOD ) System.out.println("reverseLog10PofNull=" + reverseLog10PofNull + ", reverseLog10PofF=" + reverseLog10PofF);
double forwardLod = forwardLog10PofF + reverseLog10PofNull - overallLog10PofF;
double reverseLod = reverseLog10PofF + forwardLog10PofNull - overallLog10PofF;
if ( DEBUG_SLOD ) System.out.println("forward lod=" + forwardLod + ", reverse lod=" + reverseLod);
// strand score is max bias between forward and reverse strands
double strandScore = Math.max(forwardLod, reverseLod);
// rescale by a factor of 10
strandScore *= 10.0;
//logger.debug(String.format("SLOD=%f", strandScore));
attributes.put("SB", strandScore);
}
GenomeLoc loc = refContext.getLocus();
int endLoc = calculateEndPos(vc.getAlleles(), vc.getReference(), loc);
Set<Allele> myAlleles = vc.getAlleles();
// strip out the alternate allele if it's a ref call
if ( bestAFguess == 0 && UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.DISCOVERY ) {
myAlleles = new HashSet<Allele>(1);
myAlleles.add(vc.getReference());
}
VariantContext vcCall = new VariantContext("UG_call", loc.getContig(), loc.getStart(), endLoc,
myAlleles, genotypes, phredScaledConfidence/10.0, passesCallThreshold(phredScaledConfidence) ? null : filter, attributes);
if ( annotationEngine != null ) {
// Note: we want to use the *unfiltered* and *unBAQed* context for the annotations
ReadBackedPileup pileup = null;
if (rawContext.hasExtendedEventPileup())
pileup = rawContext.getExtendedEventPileup();
else if (rawContext.hasBasePileup())
pileup = rawContext.getBasePileup();
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup, UAC.ASSUME_SINGLE_SAMPLE);
Collection<VariantContext> variantContexts = annotationEngine.annotateContext(tracker, refContext, stratifiedContexts, vcCall);
vcCall = variantContexts.iterator().next(); // we know the collection will always have exactly 1 element.
}
VariantCallContext call = new VariantCallContext(vcCall, confidentlyCalled(phredScaledConfidence, PofF));
call.setRefBase(refContext.getBase());
return call;
}
private int calculateEndPos(Set<Allele> alleles, Allele refAllele, GenomeLoc loc) {
// TODO - temp fix until we can deal with extended events properly
// for indels, stop location is one more than ref allele length
boolean isSNP = true, hasNullAltAllele = false;
for (Allele a : alleles){
if (a.length() != 1) {
isSNP = false;
break;
}
}
for (Allele a : alleles){
if (a.isNull()) {
hasNullAltAllele = true;
break;
}
}
// standard deletion: ref allele length = del length. endLoc = startLoc + refAllele.length(), alt allele = null
// standard insertion: ref allele length = 0, endLos = startLoc
// mixed: want end loc = start Loc for case {A*,AT,T} but say {ATG*,A,T} : want then end loc = start loc + refAllele.length
// So, in general, end loc = startLoc + refAllele.length, except in complex substitutions where it's one less
// todo - this is unnecessarily complicated and is so just because of Tribble's arbitrary vc conventions, should be cleaner/simpler,
// the whole vc processing infrastructure seems too brittle and riddled with special case handling
int endLoc = loc.getStart();
if ( !isSNP) {
endLoc += refAllele.length();
if(!hasNullAltAllele)
endLoc
}
return endLoc;
}
private Map<String, AlignmentContext> getFilteredAndStratifiedContexts(UnifiedArgumentCollection UAC, ReferenceContext refContext, AlignmentContext rawContext, final GenotypeLikelihoodsCalculationModel.Model model) {
Map<String, AlignmentContext> stratifiedContexts = null;
if ( model == GenotypeLikelihoodsCalculationModel.Model.INDEL ) {
if (UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES) {
// regular pileup in this case
ReadBackedPileup pileup = rawContext.getBasePileup() .getMappingFilteredPileup(UAC.MIN_MAPPING_QUALTY_SCORE);
// don't call when there is no coverage
if ( pileup.size() == 0 && UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES )
return null;
// stratify the AlignmentContext and cut by sample
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup, UAC.ASSUME_SINGLE_SAMPLE);
} else {
// todo - tmp will get rid of extended events so this wont be needed
if (!rawContext.hasExtendedEventPileup())
return null;
ReadBackedExtendedEventPileup rawPileup = rawContext.getExtendedEventPileup();
// filter the context based on min mapping quality
ReadBackedExtendedEventPileup pileup = rawPileup.getMappingFilteredPileup(UAC.MIN_MAPPING_QUALTY_SCORE);
// don't call when there is no coverage
if ( pileup.size() == 0 && UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES )
return null;
// stratify the AlignmentContext and cut by sample
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup, UAC.ASSUME_SINGLE_SAMPLE);
}
} else if ( model == GenotypeLikelihoodsCalculationModel.Model.SNP ) {
if ( !BaseUtils.isRegularBase( refContext.getBase() ) )
return null;
// stratify the AlignmentContext and cut by sample
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(rawContext.getBasePileup(), UAC.ASSUME_SINGLE_SAMPLE);
if( !(UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_SITES && UAC.GenotypingMode != GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES) ) {
int numDeletions = 0;
for( final PileupElement p : rawContext.getBasePileup() ) {
if( p.isDeletion() ) { numDeletions++; }
}
if( ((double) numDeletions) / ((double) rawContext.getBasePileup().size()) > UAC.MAX_DELETION_FRACTION ) {
return null;
}
}
}
return stratifiedContexts;
}
protected static void clearAFarray(double[] AFs) {
for ( int i = 0; i < AFs.length; i++ )
AFs[i] = AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED;
}
private VariantCallContext estimateReferenceConfidence(VariantContext vc, Map<String, AlignmentContext> contexts, double theta, boolean ignoreCoveredSamples, double initialPofRef) {
if ( contexts == null )
return null;
double P_of_ref = initialPofRef;
// for each sample that we haven't examined yet
for ( String sample : samples ) {
boolean isCovered = contexts.containsKey(sample);
if ( ignoreCoveredSamples && isCovered )
continue;
int depth = 0;
if (isCovered) {
AlignmentContext context = contexts.get(sample);
if (context.hasBasePileup())
depth = context.getBasePileup().size();
else if (context.hasExtendedEventPileup())
depth = context.getExtendedEventPileup().size();
}
P_of_ref *= 1.0 - (theta / 2.0) * MathUtils.binomialProbability(0, depth, 0.5);
}
return new VariantCallContext(vc, QualityUtils.phredScaleErrorRate(1.0 - P_of_ref) >= UAC.STANDARD_CONFIDENCE_FOR_CALLING, false);
}
protected void printVerboseData(String pos, VariantContext vc, double PofF, double phredScaledConfidence, double[] normalizedPosteriors, final GenotypeLikelihoodsCalculationModel.Model model) {
Allele refAllele = null, altAllele = null;
for ( Allele allele : vc.getAlleles() ) {
if ( allele.isReference() )
refAllele = allele;
else
altAllele = allele;
}
for (int i = 0; i <= N; i++) {
StringBuilder AFline = new StringBuilder("AFINFO\t");
AFline.append(pos);
AFline.append("\t");
AFline.append(refAllele);
AFline.append("\t");
if ( altAllele != null )
AFline.append(altAllele);
else
AFline.append("N/A");
AFline.append("\t");
AFline.append(i + "/" + N + "\t");
AFline.append(String.format("%.2f\t", ((float)i)/N));
AFline.append(String.format("%.8f\t", getAlleleFrequencyPriors(model)[i]));
if ( log10AlleleFrequencyPosteriors.get()[i] == AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED)
AFline.append("0.00000000\t");
else
AFline.append(String.format("%.8f\t", log10AlleleFrequencyPosteriors.get()[i]));
AFline.append(String.format("%.8f\t", normalizedPosteriors[i]));
verboseWriter.println(AFline.toString());
}
verboseWriter.println("P(f>0) = " + PofF);
verboseWriter.println("Qscore = " + phredScaledConfidence);
verboseWriter.println();
}
protected boolean passesEmitThreshold(double conf, int bestAFguess) {
return (UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_CONFIDENT_SITES || bestAFguess != 0) && conf >= Math.min(UAC.STANDARD_CONFIDENCE_FOR_CALLING, UAC.STANDARD_CONFIDENCE_FOR_EMITTING);
}
protected boolean passesCallThreshold(double conf) {
return conf >= UAC.STANDARD_CONFIDENCE_FOR_CALLING;
}
protected boolean confidentlyCalled(double conf, double PofF) {
return conf >= UAC.STANDARD_CONFIDENCE_FOR_CALLING ||
(UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES && QualityUtils.phredScaleErrorRate(PofF) >= UAC.STANDARD_CONFIDENCE_FOR_CALLING);
}
// decide whether we are currently processing SNPs, indels, or neither
private GenotypeLikelihoodsCalculationModel.Model getCurrentGLModel(final RefMetaDataTracker tracker, final ReferenceContext refContext,
final AlignmentContext rawContext ) {
if (rawContext.hasExtendedEventPileup() ) {
// todo - remove this code
if ((UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.INDEL) &&
(UAC.GenotypingMode != GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) )
return GenotypeLikelihoodsCalculationModel.Model.INDEL;
}
else {
// no extended event pileup
// if we're genotyping given alleles and we have a requested SNP at this position, do SNP
if (UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES) {
VariantContext vcInput = SNPGenotypeLikelihoodsCalculationModel.getSNPVCFromAllelesRod(tracker, refContext, false, logger);
if (vcInput == null)
return null;
// todo - no support to genotype MNP's yet
if (vcInput.isMNP())
return null;
if (vcInput.isSNP()) {
if (( UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.SNP))
return GenotypeLikelihoodsCalculationModel.Model.SNP;
else
// ignore SNP's if user chose INDEL mode
return null;
}
else if ((vcInput.isIndel() || vcInput.isMixed()) && (UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.INDEL))
return GenotypeLikelihoodsCalculationModel.Model.INDEL;
}
else {
// todo - this assumes SNP's take priority when BOTH is selected, should do a smarter way once extended events are removed
if( UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.SNP)
return GenotypeLikelihoodsCalculationModel.Model.SNP;
else if (UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.INDEL)
return GenotypeLikelihoodsCalculationModel.Model.INDEL;
}
}
return null;
}
protected void computeAlleleFrequencyPriors(int N, final double[] priors, final GenotypeLikelihoodsCalculationModel.Model model) {
// calculate the allele frequency priors for 1-N
double sum = 0.0;
double heterozygosity;
if (model == GenotypeLikelihoodsCalculationModel.Model.INDEL)
heterozygosity = UAC.INDEL_HETEROZYGOSITY;
else
heterozygosity = UAC.heterozygosity;
for (int i = 1; i <= N; i++) {
double value = heterozygosity / (double)i;
priors[i] = Math.log10(value);
sum += value;
}
// null frequency for AF=0 is (1 - sum(all other frequencies))
priors[0] = Math.log10(1.0 - sum);
}
protected double[] getAlleleFrequencyPriors( final GenotypeLikelihoodsCalculationModel.Model model ) {
switch( model ) {
case SNP:
return log10AlleleFrequencyPriorsSNPs;
case INDEL:
return log10AlleleFrequencyPriorsIndels;
default: throw new IllegalArgumentException("Unexpected GenotypeCalculationModel " + model);
}
}
private static GenotypePriors createGenotypePriors( final GenotypeLikelihoodsCalculationModel.Model model ) {
GenotypePriors priors;
switch ( model ) {
case SNP:
// use flat priors for GLs
priors = new DiploidSNPGenotypePriors();
break;
case INDEL:
// create flat priors for Indels, actual priors will depend on event length to be genotyped
priors = new DiploidIndelGenotypePriors();
break;
default: throw new IllegalArgumentException("Unexpected GenotypeCalculationModel " + model);
}
return priors;
}
protected GenotypePriors getGenotypePriors( final GenotypeLikelihoodsCalculationModel.Model model ) {
switch( model ) {
case SNP:
return genotypePriorsSNPs;
case INDEL:
return genotypePriorsIndels;
default: throw new IllegalArgumentException("Unexpected GenotypeCalculationModel " + model);
}
}
private static Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel> getGenotypeLikelihoodsCalculationObject(Logger logger, UnifiedArgumentCollection UAC) {
Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel> glcm = new HashMap<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel>();
glcm.put(GenotypeLikelihoodsCalculationModel.Model.SNP, new SNPGenotypeLikelihoodsCalculationModel(UAC, logger));
glcm.put(GenotypeLikelihoodsCalculationModel.Model.INDEL, new IndelGenotypeLikelihoodsCalculationModel(UAC, logger));
return glcm;
}
private static AlleleFrequencyCalculationModel getAlleleFrequencyCalculationObject(int N, Logger logger, PrintStream verboseWriter, UnifiedArgumentCollection UAC) {
AlleleFrequencyCalculationModel afcm;
switch ( UAC.AFmodel ) {
case EXACT:
afcm = new ExactAFCalculationModel(UAC, N, logger, verboseWriter);
break;
case GRID_SEARCH:
afcm = new GridSearchAFEstimation(UAC, N, logger, verboseWriter);
break;
default: throw new IllegalArgumentException("Unexpected AlleleFrequencyCalculationModel " + UAC.AFmodel);
}
return afcm;
}
}
|
package com.rackspira.kristiawan.rackmonthpicker;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.rackspira.kristiawan.rackmonthpicker.listener.DateMonthDialogListener;
import com.rackspira.kristiawan.rackmonthpicker.listener.OnCancelMonthDialogListener;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class RackMonthPicker {
private AlertDialog mAlertDialog;
private RackMonthPicker.Builder builder;
private Context context;
private Button mPositiveButton;
private Button mNegativeButton;
private DateMonthDialogListener dateMonthDialogListener;
private OnCancelMonthDialogListener onCancelMonthDialogListener;
private boolean isBuild = false;
public RackMonthPicker(Context context) {
this.context = context;
builder = new Builder();
}
public void show() {
if (isBuild) {
mAlertDialog.show();
} else {
builder.build();
isBuild = true;
}
}
public RackMonthPicker setPositiveButton(DateMonthDialogListener dateMonthDialogListener) {
this.dateMonthDialogListener = dateMonthDialogListener;
mPositiveButton.setOnClickListener(builder.positiveButtonClick());
return this;
}
public RackMonthPicker setNegativeButton(OnCancelMonthDialogListener onCancelMonthDialogListener) {
this.onCancelMonthDialogListener = onCancelMonthDialogListener;
mNegativeButton.setOnClickListener(builder.negativeButtonClick());
return this;
}
public RackMonthPicker setPositiveText(String text) {
mPositiveButton.setText(text);
return this;
}
public RackMonthPicker setNegativeText(String text) {
mNegativeButton.setText(text);
return this;
}
public RackMonthPicker setLocale(Locale locale) {
builder.setLocale(locale);
return this;
}
public RackMonthPicker setSelectedMonth(int index) {
builder.setSelectedMonth(index);
return this;
}
public RackMonthPicker setSelectedYear(int year) {
builder.setSelectedYear(year);
return this;
}
public RackMonthPicker setColorTheme(int color) {
builder.setColorTheme(color);
return this;
}
public void dismiss() {
mAlertDialog.dismiss();
}
private class Builder implements MonthAdapter.OnSelectedListener {
private MonthAdapter monthAdapter;
private TextView mTitleView;
private TextView mYear;
private int year = 2018;
private AlertDialog.Builder alertBuilder;
private View contentView;
private Builder() {
alertBuilder = new AlertDialog.Builder(context);
contentView = LayoutInflater.from(context).inflate(R.layout.dialog_month_picker, null);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
mTitleView = (TextView) contentView.findViewById(R.id.title);
mYear = (TextView) contentView.findViewById(R.id.text_year);
Button next = (Button) contentView.findViewById(R.id.btn_next);
next.setOnClickListener(nextButtonClick());
Button previous = (Button) contentView.findViewById(R.id.btn_previous);
previous.setOnClickListener(previousButtonClick());
mPositiveButton = (Button) contentView.findViewById(R.id.btn_p);
mNegativeButton = (Button) contentView.findViewById(R.id.btn_n);
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
year = cal.get(Calendar.YEAR);
monthAdapter = new MonthAdapter(context, this);
RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(context, 4));
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(monthAdapter);
mTitleView.setText(monthAdapter.getShortMonth() + ", " + year);
mYear.setText(year + "");
}
public void setLocale(Locale locale) {
monthAdapter.setLocale(locale);
}
public void setSelectedMonth(int index) {
monthAdapter.setSelectedItem(index);
mTitleView.setText(monthAdapter.getShortMonth() + ", " + year);
}
public void setSelectedYear(int year) {
this.year = year;
mYear.setText(year + "");
mTitleView.setText(monthAdapter.getShortMonth() + ", " + year);
}
public void setColorTheme(int color) {
LinearLayout linearToolbar = (LinearLayout) contentView.findViewById(R.id.linear_toolbar);
linearToolbar.setBackgroundResource(color);
monthAdapter.setBackgroundMonth(color);
mPositiveButton.setTextColor(ContextCompat.getColor(context, color));
mNegativeButton.setTextColor(ContextCompat.getColor(context, color));
}
public void build() {
mAlertDialog = alertBuilder.create();
mAlertDialog.show();
mAlertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mAlertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE);
mAlertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mAlertDialog.getWindow().setBackgroundDrawableResource(R.drawable.material_dialog_window);
mAlertDialog.getWindow().setContentView(contentView);
}
public View.OnClickListener nextButtonClick() {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
year++;
mYear.setText(year + "");
mTitleView.setText(monthAdapter.getShortMonth() + ", " + year);
}
};
}
public View.OnClickListener previousButtonClick() {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
year
mYear.setText(year + "");
mTitleView.setText(monthAdapter.getShortMonth() + ", " + year);
}
};
}
public View.OnClickListener positiveButtonClick() {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
dateMonthDialogListener.onDateMonth(
monthAdapter.getMonth(),
monthAdapter.getStartDate(),
monthAdapter.getEndDate(),
year, mTitleView.getText().toString());
mAlertDialog.dismiss();
}
};
}
public View.OnClickListener negativeButtonClick() {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
onCancelMonthDialogListener.onCancel(mAlertDialog);
}
};
}
@Override
public void onContentSelected() {
mTitleView.setText(monthAdapter.getShortMonth() + ", " + year);
}
}
}
|
package com.ctrip.xpipe.redis.meta.server.impl;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import com.ctrip.xpipe.api.codec.Codec;
import com.ctrip.xpipe.redis.core.entity.ClusterMeta;
import com.ctrip.xpipe.redis.core.entity.KeeperMeta;
import com.ctrip.xpipe.redis.core.entity.RedisMeta;
import com.ctrip.xpipe.redis.core.metaserver.META_SERVER_SERVICE;
import com.ctrip.xpipe.redis.core.metaserver.MetaServerConsoleService.PrimaryDcChangeMessage;
import com.ctrip.xpipe.redis.core.metaserver.MetaServerConsoleService.PrimaryDcCheckMessage;
import com.ctrip.xpipe.redis.core.metaserver.MetaServerService;
import com.ctrip.xpipe.redis.meta.server.MetaServer;
import com.ctrip.xpipe.redis.meta.server.cluster.ClusterServerInfo;
import com.ctrip.xpipe.redis.meta.server.cluster.impl.AbstractRemoteClusterServer;
import com.ctrip.xpipe.redis.meta.server.rest.ForwardInfo;
import com.ctrip.xpipe.redis.meta.server.rest.exception.CircularForwardException;
import com.ctrip.xpipe.rest.ForwardType;
/**
* @author wenchao.meng
*
* Aug 3, 2016
*/
public class RemoteMetaServer extends AbstractRemoteClusterServer implements MetaServer{
private String changeClusterPath;
private String upstreamChangePath;
private String getActiveKeeperPath;
private String changePrimaryDcCheckPath;
private String makeMasterReadonlyPath;
private String changePrimaryDcPath;
public RemoteMetaServer(int currentServerId, int serverId) {
super(currentServerId, serverId);
}
public RemoteMetaServer(int currentServerId, int serverId, ClusterServerInfo clusterServerInfo) {
super(currentServerId, serverId, clusterServerInfo);
if(getHttpHost() != null){
changeClusterPath = META_SERVER_SERVICE.CLUSTER_CHANGE.getRealPath(getHttpHost());
upstreamChangePath = META_SERVER_SERVICE.UPSTREAM_CHANGE.getRealPath(getHttpHost());
getActiveKeeperPath = META_SERVER_SERVICE.GET_ACTIVE_KEEPER.getRealPath(getHttpHost());
changePrimaryDcCheckPath = META_SERVER_SERVICE.CHANGE_PRIMARY_DC_CHECK.getRealPath(getHttpHost());
makeMasterReadonlyPath = META_SERVER_SERVICE.MAKE_MASTER_READONLY.getRealPath(getHttpHost());
changePrimaryDcPath = META_SERVER_SERVICE.CHANGE_PRIMARY_DC.getRealPath(getHttpHost());
}
}
@Override
public KeeperMeta getActiveKeeper(String clusterId, String shardId, ForwardInfo forwardInfo){
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo);
logger.info("[getActiveKeeper][forward]{},{},{} --> {}", clusterId, shardId, forwardInfo, this);
HttpEntity<Void> entity = new HttpEntity<>(headers);
ResponseEntity<KeeperMeta> response = restTemplate.exchange(getActiveKeeperPath, HttpMethod.GET, entity, KeeperMeta.class, clusterId, shardId);
return response.getBody();
}
@Override
public RedisMeta getRedisMaster(String clusterId, String shardId) {
throw new UnsupportedOperationException();
}
@Override
public void clusterAdded(ClusterMeta clusterMeta, ForwardInfo forwardInfo) {
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo, META_SERVER_SERVICE.CLUSTER_CHANGE.getForwardType());
logger.info("[clusterAdded][forward]{},{}--> {}", clusterMeta.getId(), forwardInfo, this);
HttpEntity<ClusterMeta> entity = new HttpEntity<>(clusterMeta, headers);
restTemplate.exchange(changeClusterPath, HttpMethod.POST, entity, String.class, clusterMeta.getId());
}
@Override
public void clusterModified(ClusterMeta clusterMeta, ForwardInfo forwardInfo) {
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo, META_SERVER_SERVICE.CLUSTER_CHANGE.getForwardType());
logger.info("[clusterModified][forward]{},{} --> {}", clusterMeta.getId(), forwardInfo, this);
HttpEntity<ClusterMeta> entity = new HttpEntity<>(clusterMeta, headers);
restTemplate.exchange(changeClusterPath, HttpMethod.PUT, entity, String.class, clusterMeta.getId());
}
@Override
public void clusterDeleted(String clusterId, ForwardInfo forwardInfo) {
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo, META_SERVER_SERVICE.CLUSTER_CHANGE.getForwardType());
logger.info("[clusterDeleted][forward]{},{} --> {}", clusterId, forwardInfo, this);
HttpEntity<ClusterMeta> entity = new HttpEntity<>(headers);
restTemplate.exchange(changeClusterPath, HttpMethod.DELETE, entity, String.class, clusterId);
}
@Override
public void updateUpstream(String clusterId, String shardId, String ip, int port, ForwardInfo forwardInfo)
throws Exception {
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo, META_SERVER_SERVICE.UPSTREAM_CHANGE.getForwardType());
logger.info("[updateUpstream][forward]{},{},{}:{}, {}--> {}", clusterId, shardId, ip, port, forwardInfo, this);
HttpEntity<ClusterMeta> entity = new HttpEntity<>(headers);
restTemplate.exchange(upstreamChangePath, HttpMethod.PUT, entity, String.class, clusterId, shardId, ip, port);
}
@Override
public PrimaryDcCheckMessage changePrimaryDcCheck(String clusterId, String shardId, String newPrimaryDc,
ForwardInfo forwardInfo) {
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo, META_SERVER_SERVICE.CHANGE_PRIMARY_DC_CHECK.getForwardType());
logger.info("[changePrimaryDcCheck][forward]{},{},{}, {}--> {}", clusterId, shardId, newPrimaryDc, forwardInfo, this);
HttpEntity<ClusterMeta> entity = new HttpEntity<>(headers);
ResponseEntity<PrimaryDcCheckMessage> result = restTemplate.exchange(changePrimaryDcCheckPath, HttpMethod.GET, entity, PrimaryDcCheckMessage.class, clusterId, shardId, newPrimaryDc);
return result.getBody();
}
@Override
public void makeMasterReadOnly(String clusterId, String shardId, boolean readOnly, ForwardInfo forwardInfo) {
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo, META_SERVER_SERVICE.MAKE_MASTER_READONLY.getForwardType());
logger.info("[makeMasterReadOnly][forward]{},{},{}, {}--> {}", clusterId, shardId, readOnly, forwardInfo, this);
HttpEntity<ClusterMeta> entity = new HttpEntity<>(headers);
restTemplate.exchange(makeMasterReadonlyPath, HttpMethod.PUT, entity, String.class, clusterId, shardId, readOnly);
}
@Override
public PrimaryDcChangeMessage doChangePrimaryDc(String clusterId, String shardId, String newPrimaryDc,
ForwardInfo forwardInfo) {
HttpHeaders headers = checkCircularAndGetHttpHeaders(forwardInfo, META_SERVER_SERVICE.CHANGE_PRIMARY_DC.getForwardType());
logger.info("[doChangePrimaryDc][forward]{},{},{}, {}--> {}", clusterId, shardId, newPrimaryDc, forwardInfo, this);
HttpEntity<ClusterMeta> entity = new HttpEntity<>(headers);
ResponseEntity<PrimaryDcChangeMessage> resposne = restTemplate.exchange(changePrimaryDcPath, HttpMethod.PUT,
entity, PrimaryDcChangeMessage.class, clusterId, shardId, newPrimaryDc);
return resposne.getBody();
}
private HttpHeaders checkCircularAndGetHttpHeaders(ForwardInfo forwardInfo, ForwardType forwardType) {
checkCircular(forwardInfo);
if(forwardInfo == null){
forwardInfo = new ForwardInfo(forwardType);
}else{
forwardInfo.setType(forwardType);
}
forwardInfo.addForwardServers(getCurrentServerId());
HttpHeaders headers = new HttpHeaders();
headers.add(MetaServerService.HTTP_HEADER_FOWRARD, Codec.DEFAULT.encode(forwardInfo));
return headers;
}
private HttpHeaders checkCircularAndGetHttpHeaders(ForwardInfo forwardInfo) {
return checkCircularAndGetHttpHeaders(forwardInfo, ForwardType.FORWARD);
}
private void checkCircular(ForwardInfo forwardInfo) {
if(forwardInfo != null && forwardInfo.hasServer(getCurrentServerId())){
throw new CircularForwardException(forwardInfo, getCurrentServerId());
}
}
@Override
public String getCurrentMeta() {
return null;
}
}
|
package com.example.bot.spring.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONObject;
import com.linecorp.bot.model.action.MessageAction;
import com.linecorp.bot.model.message.TemplateMessage;
import com.linecorp.bot.model.message.template.CarouselColumn;
import com.linecorp.bot.model.message.template.CarouselTemplate;
import se.walkercrou.places.GooglePlaces;
import se.walkercrou.places.Param;
import se.walkercrou.places.Place;
public class RestaurantService {
private static RestaurantService instance = new RestaurantService();
public static RestaurantService getInstance() {
return instance;
}
public RestaurantService() {}
public TemplateMessage getRestaurant(double lat, double lng) {
String apiKey = "AIzaSyB6t-XO4BEyDh1jBzHmeZn5hVB0WQkZLe8";
GooglePlaces client = new GooglePlaces(apiKey);
List<Place> places =
client.getNearbyPlaces(
lat,
lng,
1000,
Param.name("type").value("restaurant"),
Param.name("language").value("zh-TW"));
List<CarouselColumn> carusels = new ArrayList<CarouselColumn>();
String photoUrl =
"https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&key="
+ apiKey
+ "&photoreference=";
places.sort(
(Place p1, Place p2) ->
p1.getRating() > p2.getRating() ? -1 : (p1.getRating() < p2.getRating() ? 1 : 0));
for (Place p : places) {
JSONObject json = p.getJson();
if (json.isNull("photos")) continue;
String imageUrl =
photoUrl + json.getJSONArray("photos").getJSONObject(0).getString("photo_reference");
if (carusels.size() == 5) break;
CarouselColumn temp =
new CarouselColumn(
imageUrl,
Double.toString(p.getRating()),
p.getVicinity(),
Arrays.asList(new MessageAction(p.getName(), p.getStatus().toString())));
carusels.add(temp);
}
TemplateMessage templateMessage =
new TemplateMessage("Carousel alt text", new CarouselTemplate(carusels));
return templateMessage;
}
}
|
package com.smartdevicelink.transport;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import com.smartdevicelink.util.AndroidTools;
import com.smartdevicelink.util.DebugTool;
import com.smartdevicelink.util.SdlAppInfo;
import com.smartdevicelink.util.ServiceFinder;
import java.util.List;
import java.util.Vector;
import static com.smartdevicelink.transport.TransportConstants.FOREGROUND_EXTRA;
@RequiresApi(12)
public class USBAccessoryAttachmentActivity extends Activity {
private static final String TAG = USBAccessoryAttachmentActivity.class.getSimpleName();
private static final int USB_SUPPORTED_ROUTER_SERVICE_VERSION = 8;
UsbAccessory usbAccessory;
Parcelable permissionGranted;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
checkUsbAccessoryIntent("Resume");
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
this.setIntent(intent);
}
private synchronized void checkUsbAccessoryIntent(String sourceAction) {
if(usbAccessory != null){
return;
}
final Intent intent = getIntent();
String action = intent.getAction();
Log.d(TAG, sourceAction + " with action: " + action);
if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
usbAccessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
permissionGranted = intent.getParcelableExtra(UsbManager.EXTRA_PERMISSION_GRANTED);
wakeUpRouterService(getApplicationContext());
}
}
@SuppressWarnings("deprecation")
private void wakeUpRouterService(final Context context){
new ServiceFinder(context, context.getPackageName(), new ServiceFinder.ServiceFinderCallback() {
@Override
public void onComplete(Vector<ComponentName> routerServices) {
Vector<ComponentName> runningBluetoothServicePackage = new Vector<>(routerServices);
if (runningBluetoothServicePackage.isEmpty()) {
//If there isn't a service running we should try to start one
//We will try to sort the SDL enabled apps and find the one that's been installed the longest
Intent serviceIntent;
List<SdlAppInfo> sdlAppInfoList = AndroidTools.querySdlAppInfo(context, new SdlAppInfo.BestRouterComparator());
if (sdlAppInfoList != null && !sdlAppInfoList.isEmpty()) {
SdlAppInfo optimalRouterService = sdlAppInfoList.get(0);
if(optimalRouterService.getRouterServiceVersion() < USB_SUPPORTED_ROUTER_SERVICE_VERSION){
// The most optimal router service doesn't support the USB connection
// At this point to ensure that USB connection is still possible it might be
// worth trying to use the legacy USB transport scheme
attemptLegacyUsbConnection();
return;
}
serviceIntent = new Intent();
serviceIntent.setComponent(optimalRouterService.getRouterServiceComponentName());
} else{
Log.d(TAG, "No SDL Router Services found");
Log.d(TAG, "WARNING: This application has not specified its SdlRouterService correctly in the manifest. THIS WILL THROW AN EXCEPTION IN FUTURE RELEASES!!");
// At this point to ensure that USB connection is still possible it might be
// worth trying to use the legacy USB transport scheme
attemptLegacyUsbConnection();
return;
}
serviceIntent.setAction(TransportConstants.BIND_REQUEST_TYPE_ALT_TRANSPORT);
ComponentName startedService;
try {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
startedService = context.startService(serviceIntent);
}else {
serviceIntent.putExtra(FOREGROUND_EXTRA, true);
startedService = context.startForegroundService(serviceIntent);
}
if(startedService == null){
// A router service was not started or is not running.
DebugTool.logError(TAG + " - Error starting router service. Attempting legacy connection ");
attemptLegacyUsbConnection();
return;
}
//Make sure to send this out for old apps to close down
SdlRouterService.LocalRouterService self = SdlRouterService.getLocalRouterService(serviceIntent, serviceIntent.getComponent());
Intent restart = new Intent(SdlRouterService.REGISTER_NEWER_SERVER_INSTANCE_ACTION);
restart.putExtra(SdlBroadcastReceiver.LOCAL_ROUTER_SERVICE_EXTRA, self);
restart.putExtra(SdlBroadcastReceiver.LOCAL_ROUTER_SERVICE_DID_START_OWN, true);
context.sendBroadcast(restart);
if (usbAccessory!=null) {
new UsbTransferProvider(context, serviceIntent.getComponent(), usbAccessory, new UsbTransferProvider.UsbTransferCallback() {
@Override
public void onUsbTransferUpdate(boolean success) {
finish();
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "Security exception, process is bad");
}
} else {
if (usbAccessory!=null) {
new UsbTransferProvider(context,runningBluetoothServicePackage.get(0),usbAccessory, new UsbTransferProvider.UsbTransferCallback(){
@Override
public void onUsbTransferUpdate(boolean success) {
finish();
}
});
}
}
}
});
}
private void attemptLegacyUsbConnection(){
DebugTool.logInfo("Attempting to send USB connection intent using legacy method");
Intent usbAccessoryAttachedIntent = new Intent(USBTransport.ACTION_USB_ACCESSORY_ATTACHED);
usbAccessoryAttachedIntent.putExtra(UsbManager.EXTRA_ACCESSORY, usbAccessory);
usbAccessoryAttachedIntent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, permissionGranted);
AndroidTools.sendExplicitBroadcast(getApplicationContext(),usbAccessoryAttachedIntent,null);
finish();
}
}
|
package uk.ac.ic.wlgitbridge.writelatex.filestore.node;
import uk.ac.ic.wlgitbridge.bridge.RawDirectoryContents;
import uk.ac.ic.wlgitbridge.writelatex.api.request.exception.FailedConnectionException;
import uk.ac.ic.wlgitbridge.writelatex.api.request.getforversion.SnapshotAttachment;
import uk.ac.ic.wlgitbridge.writelatex.api.request.getforversion.SnapshotFile;
import uk.ac.ic.wlgitbridge.writelatex.filestore.RepositoryFile;
import uk.ac.ic.wlgitbridge.writelatex.filestore.store.FileIndexStore;
import uk.ac.ic.wlgitbridge.writelatex.filestore.store.WLFileStore;
import uk.ac.ic.wlgitbridge.writelatex.model.Snapshot;
import uk.ac.ic.wlgitbridge.writelatex.model.db.PersistentStoreAPI;
import uk.ac.ic.wlgitbridge.writelatex.model.db.PersistentStoreSource;
import uk.ac.ic.wlgitbridge.writelatex.model.db.PersistentStoreUpdater;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class WLDirectoryNode implements PersistentStoreSource, PersistentStoreUpdater<Void> {
private final String projectName;
private Map<String, FileNode> fileNodeTable;
private FileIndexStore fileIndexStore;
public WLDirectoryNode(String projectName, PersistentStoreAPI persistentStore) {
this(projectName);
initFromPersistentStore(persistentStore);
}
private WLDirectoryNode(String projectName) {
this.projectName = projectName;
}
private WLDirectoryNode(String projectName, Map<String, FileNode> fileNodeTable, FileIndexStore fileIndexStore) {
this.projectName = projectName;
this.fileNodeTable = fileNodeTable;
this.fileIndexStore = fileIndexStore;
}
@Override
public void initFromPersistentStore(PersistentStoreAPI persistentStore) {
fileNodeTable = new HashMap<String, FileNode>();
for (FileNode fileNode : persistentStore.getFileNodesForProjectName(projectName)) {
fileNodeTable.put(fileNode.getFilePath(), fileNode);
}
fileIndexStore = new FileIndexStore(projectName, persistentStore);
}
@Override
public void updatePersistentStore(PersistentStoreAPI persistentStore, Void info) {
updateFileNodeTableInPersistentStore(persistentStore);
fileIndexStore.updatePersistentStore(persistentStore, projectName);
}
private void updateFileNodeTableInPersistentStore(PersistentStoreAPI persistentStore) {
persistentStore.deleteFileNodesForProjectName(projectName);
for (FileNode fileNode : fileNodeTable.values()) {
fileNode.updatePersistentStore(persistentStore, projectName);
}
}
public List<FileNode> getFileNodes() {
return new LinkedList<FileNode>(fileNodeTable.values());
}
public List<FileNode> updateFromSnapshot(Snapshot snapshot) throws FailedConnectionException {
Map<String, FileNode> updatedFileNodeTable = new HashMap<String, FileNode>();
List<SnapshotFile> srcs = snapshot.getSrcs();
List<SnapshotAttachment> atts = snapshot.getAtts();
for (SnapshotFile src : srcs) {
BlobNode blobNode = new BlobNode(src, fileNodeTable);
updatedFileNodeTable.put(blobNode.getFilePath(), blobNode);
}
for (SnapshotAttachment att : atts) {
AttachmentNode attachmentNode = new AttachmentNode(att, fileNodeTable, fileIndexStore);
updatedFileNodeTable.put(attachmentNode.getFilePath(), attachmentNode);
}
LinkedList<FileNode> fileNodes = new LinkedList<FileNode>(updatedFileNodeTable.values());
fileNodeTable = updatedFileNodeTable;
fileIndexStore = new FileIndexStore(fileNodes);
return fileNodes;
}
public WLDirectoryNode createFromRawDirectoryContents(RawDirectoryContents rawDirectoryContents, File attachmentDirectory) throws IOException, FailedConnectionException {
Map<String, FileNode> candidateFileNodeTable = new HashMap<String, FileNode>();
File projectAttDirectory = new File(attachmentDirectory, projectName);
projectAttDirectory.mkdirs();
WLFileStore.deleteInDirectory(projectAttDirectory);
for (Entry<String, byte[]> fileContents : rawDirectoryContents.getFileContentsTable().entrySet()) {
BlobNode blobNode = new BlobNode(new RepositoryFile(fileContents), fileNodeTable, projectAttDirectory);
candidateFileNodeTable.put(blobNode.getFilePath(), blobNode);
}
return new WLDirectoryNode(projectName, candidateFileNodeTable,
new FileIndexStore(new LinkedList<FileNode>(candidateFileNodeTable.values())));
}
@Override
public String toString() {
return fileNodeTable.toString();
}
}
|
package com.evolutionnext.selenium;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.safari.SafariDriver;
import static org.fest.assertions.Assertions.assertThat;
public class VerifyNewAlbum {
private String baseUrl;
private WebDriver driver;
private String chromeDriverUrl;
@Before
public void setUp() throws Exception {
baseUrl = System.getenv("selenium_baseurl");
if (baseUrl == null) throw new NullPointerException("selenium_baseurl not set");
String selenium_browser = System.getenv("selenium_browser");
if (selenium_browser == null) throw new NullPointerException("selenium_browser not set");
chromeDriverUrl = System.getenv("chrome_driver_url");
if (chromeDriverUrl == null) throw new NullPointerException("chrome_driver_url not set");
switch (selenium_browser) {
case "Firefox":
driver = new FirefoxDriver();
break;
case "IE":
driver = new InternetExplorerDriver();
break;
case "Safari":
driver = new SafariDriver();
break;
case "Chrome":
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
switch (osName) {
case "Windows":
setChromeSystemProperty("chromedriver-windows32.exe");
break;
case "MacOSX":
setChromeSystemProperty("chromedriver-mac32");
break;
case "Linux":
if (osArch.equals("amd64")) {
setChromeSystemProperty("chromedriver-linux64");
} else {
setChromeSystemProperty("chromedriver-linux32");
}
break;
}
driver = new ChromeDriver();
break;
default:
throw new RuntimeException("No browser specified");
}
}
@SuppressWarnings("ConstantConditions")
private void setChromeSystemProperty(String osName) {
System.out.println("Web driver location used: " + chromeDriverUrl + "/" + osName);
System.setProperty("webdriver.chrome.driver", chromeDriverUrl + "/" + osName);
}
@Test
public void testPage() throws InterruptedException {
driver.get(baseUrl + "/simple-maven-app/create.xhtml");
driver.findElement(By.name("album_form:j_idt6")).clear();
driver.findElement(By.name("album_form:j_idt6")).sendKeys("Senses Working Overtime");
driver.findElement(By.name("album_form:j_idt8")).click();
Thread.sleep(5000);
assertThat(driver.getTitle()).isEqualTo("List of Albums");
driver.quit();
}
}
|
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.ide.intro;
import org.eclipse.ui.internal.ide.application.DelayedEventsProcessor;
import org.eclipse.ui.internal.ide.application.IDEWorkbenchAdvisor;
@SuppressWarnings("restriction")
public class PhaserWorkbenchAdvisor extends IDEWorkbenchAdvisor {
public PhaserWorkbenchAdvisor() {
super();
}
public PhaserWorkbenchAdvisor(DelayedEventsProcessor processor) {
super(processor);
}
@Override
public String getInitialWindowPerspectiveId() {
return "phasereditor.ide.ui.perspective";
}
//@formatter:off
// XXX: just do not load the JS editor at startup, it creates a strange
// behavior!
// @Override
// public void postStartup() {
// super.postStartup();
// // an ugly work around to ensure all the JS stuff is loaded at the
// // startup
// IEditorPart editor;
// long t = currentTimeMillis();
// try {
// IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
// editor = IDE.openEditor(page, new StringEditorInput("closing", ""),
// "org.eclipse.wst.jsdt.ui.CompilationUnitEditor");
// out.println("Loaded " + editor + " " + (currentTimeMillis() - t));
// page.closeEditor(editor, false);
// } catch (PartInitException e) {
// e.printStackTrace();
//@formatter:on
}
|
package cgeo.geocaching.maps;
import cgeo.geocaching.IWaypoint;
import cgeo.geocaching.LiveMapInfo;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.Settings;
import cgeo.geocaching.StoredList;
import cgeo.geocaching.UpdateDirectionCallback;
import cgeo.geocaching.UpdateLocationCallback;
import cgeo.geocaching.cgBase;
import cgeo.geocaching.cgCache;
import cgeo.geocaching.cgDirection;
import cgeo.geocaching.cgGeo;
import cgeo.geocaching.cgWaypoint;
import cgeo.geocaching.cgeoapplication;
import cgeo.geocaching.cgeocaches;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.gc.GCBase;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.Viewport;
import cgeo.geocaching.go4cache.Go4Cache;
import cgeo.geocaching.go4cache.Go4CacheUser;
import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapActivityImpl;
import cgeo.geocaching.maps.interfaces.MapControllerImpl;
import cgeo.geocaching.maps.interfaces.MapProvider;
import cgeo.geocaching.maps.interfaces.MapViewImpl;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl;
import cgeo.geocaching.network.Login;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.LeastRecentlyUsedSet;
import cgeo.geocaching.utils.Log;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Class representing the Map in c:geo
*/
public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFactory {
/** max. number of caches displayed in the Live Map */
public static final int MAX_CACHES = 500;
/** Handler Messages */
private static final int HIDE_PROGRESS = 0;
private static final int SHOW_PROGRESS = 1;
private static final int UPDATE_TITLE = 0;
private static final int INVALIDATE_MAP = 1;
private static final int UPDATE_PROGRESS = 0;
private static final int FINISHED_LOADING_DETAILS = 1;
//Menu
private static final String EXTRAS_GEOCODE = "geocode";
private static final String EXTRAS_LONGITUDE = "longitude";
private static final String EXTRAS_LATITUDE = "latitude";
private static final String EXTRAS_WPTTYPE = "wpttype";
private static final String EXTRAS_MAPSTATE = "mapstate";
private static final String EXTRAS_SEARCH = "search";
private static final int MENU_SELECT_MAPVIEW = 1;
private static final int MENU_MAP_LIVE = 2;
private static final int MENU_STORE_CACHES = 3;
private static final int MENU_TRAIL_MODE = 4;
private static final int SUBMENU_STRATEGY = 5;
private static final int MENU_STRATEGY_FASTEST = 51;
private static final int MENU_STRATEGY_FAST = 52;
private static final int MENU_STRATEGY_AUTO = 53;
private static final int MENU_STRATEGY_DETAILED = 74;
private static final int MENU_CIRCLE_MODE = 6;
private static final int MENU_AS_LIST = 7;
private static final String EXTRAS_MAP_TITLE = "mapTitle";
private Resources res = null;
private MapProvider mapProvider = null;
private Activity activity = null;
private MapViewImpl mapView = null;
private MapControllerImpl mapController = null;
private cgeoapplication app = null;
private cgGeo geo = null;
private cgDirection dir = null;
private UpdateLocationCallback geoUpdate = new UpdateLoc();
private UpdateDirectionCallback dirUpdate = new UpdateDir();
private SearchResult searchIntent = null;
private String geocodeIntent = null;
private Geopoint coordsIntent = null;
private WaypointType waypointTypeIntent = null;
private int[] mapStateIntent = null;
// status data
private SearchResult search = null;
private String[] tokens = null;
private boolean noMapTokenShowed = false;
// map status data
private boolean followMyLocation = false;
private Integer centerLatitude = null;
private Integer centerLongitude = null;
private Integer spanLatitude = null;
private Integer spanLongitude = null;
private Integer centerLatitudeUsers = null;
private Integer centerLongitudeUsers = null;
private Integer spanLatitudeUsers = null;
private Integer spanLongitudeUsers = null;
private int zoom = -100;
// threads
private LoadTimer loadTimer = null;
private Go4CacheTimer go4CacheTimer = null;
private LoadDetails loadDetailsThread = null;
/** Time of last {@link LoadRunnable} run */
private volatile long loadThreadRun = 0L;
/** Time of last {@link Go4CacheRunnable} run */
private volatile long go4CacheThreadRun = 0L;
//Interthread communication flag
private volatile boolean downloaded = false;
// overlays
private CachesOverlay overlayCaches = null;
private OtherCachersOverlay overlayGo4Cache = null;
private ScaleOverlay overlayScale = null;
private PositionOverlay overlayPosition = null;
// data for overlays
private static final int[][] INSET_RELIABLE = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; // center, 33x40 / 45x51
private static final int[][] INSET_TYPE = { { 5, 8, 6, 10 }, { 4, 4, 5, 11 } }; // center, 22x22 / 36x36
private static final int[][] INSET_OWN = { { 21, 0, 0, 26 }, { 25, 0, 0, 35 } }; // top right, 12x12 / 16x16
private static final int[][] INSET_FOUND = { { 0, 0, 21, 28 }, { 0, 0, 25, 35 } }; // top left, 12x12 / 16x16
private static final int[][] INSET_USERMODIFIEDCOORDS = { { 21, 28, 0, 0 }, { 19, 25, 0, 0 } }; // bottom right, 12x12 / 26x26
private static final int[][] INSET_PERSONALNOTE = { { 0, 28, 21, 0 }, { 0, 25, 19, 0 } }; // bottom left, 12x12 / 26x26
private static Map<Integer, LayerDrawable> overlaysCache = new HashMap<Integer, LayerDrawable>();
private int cachesCnt = 0;
/** List of caches in the viewport */
private final LeastRecentlyUsedSet<cgCache> caches = new LeastRecentlyUsedSet<cgCache>(MAX_CACHES);
// storing for offline
private ProgressDialog waitDialog = null;
private int detailTotal = 0;
private int detailProgress = 0;
private long detailProgressTime = 0L;
// views
private ImageSwitcher myLocSwitch = null;
// other things
private boolean live = true; // live map (live, dead) or rest (displaying caches on map)
private boolean liveChanged = false; // previous state for loadTimer
private boolean centered = false; // if map is already centered
private boolean alreadyCentered = false; // -""- for setting my location
private static Set<String> dirtyCaches = null;
// Thread pooling
private static BlockingQueue<Runnable> displayQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor displayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, displayQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> downloadQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor downloadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, downloadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> loadQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor loadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, loadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> Go4CacheQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor Go4CacheExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, Go4CacheQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> go4CacheDisplayQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor go4CacheDisplayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, go4CacheDisplayQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
// handlers
/** Updates the titles */
final private Handler displayHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
final int what = msg.what;
switch (what) {
case UPDATE_TITLE:
// set title
final StringBuilder title = new StringBuilder();
if (live) {
title.append(res.getString(R.string.map_live));
} else {
title.append(mapTitle);
}
countVisibleCaches();
if (caches != null && caches.size() > 0 && !mapTitle.contains("[")) {
title.append(" [").append(cachesCnt);
if (cachesCnt != caches.size()) {
title.append('/').append(caches.size());
}
title.append(']');
}
ActivityMixin.setTitle(activity, title.toString());
break;
case INVALIDATE_MAP:
mapView.repaintRequired(null);
break;
default:
break;
}
}
};
/** Updates the progress. */
final private Handler showProgressHandler = new Handler() {
private int counter = 0;
@Override
public void handleMessage(Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
ActivityMixin.showProgress(activity, false);
}
} else if (what == SHOW_PROGRESS) {
ActivityMixin.showProgress(activity, true);
counter++;
}
}
};
final private class LoadDetailsHandler extends CancellableHandler {
@Override
public void handleRegularMessage(Message msg) {
if (msg.what == UPDATE_PROGRESS) {
if (waitDialog != null) {
int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else if (secondsRemaining < 90) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + (secondsRemaining / 60) + " " + res.getString(R.string.caches_eta_min));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + (secondsRemaining / 60) + " " + res.getString(R.string.caches_eta_mins));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS) {
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog.setOnCancelListener(null);
}
if (geo == null) {
geo = app.startGeo(geoUpdate);
}
if (Settings.isUseCompass() && dir == null) {
dir = app.startDir(activity, dirUpdate);
}
}
}
@Override
public void handleCancel(final Object extra) {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
if (geo == null) {
geo = app.startGeo(geoUpdate);
}
if (Settings.isUseCompass() && dir == null) {
dir = app.startDir(activity, dirUpdate);
}
}
}
final private Handler noMapTokenHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (!noMapTokenShowed) {
ActivityMixin.showToast(activity, res.getString(R.string.map_token_err));
noMapTokenShowed = true;
}
}
};
/**
* calling activities can set the map title via extras
*/
private String mapTitle;
public CGeoMap(MapActivityImpl activity) {
super(activity);
}
protected void countVisibleCaches() {
final ArrayList<cgCache> protectedCaches = new ArrayList<cgCache>(caches);
int count = 0;
if (protectedCaches.size() > 0) {
final GeoPointImpl mapCenter = mapView.getMapViewCenter();
final int mapCenterLat = mapCenter.getLatitudeE6();
final int mapCenterLon = mapCenter.getLongitudeE6();
final int mapSpanLat = mapView.getLatitudeSpan();
final int mapSpanLon = mapView.getLongitudeSpan();
for (cgCache cache : protectedCaches) {
if (cache != null && cache.getCoords() != null) {
if (Viewport.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, cache.getCoords())) {
count++;
}
}
}
}
cachesCnt = count;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// class init
res = this.getResources();
activity = this.getActivity();
app = (cgeoapplication) activity.getApplication();
mapProvider = Settings.getMapProvider();
// reset status
noMapTokenShowed = false;
ActivityMixin.keepScreenOn(activity, true);
// set layout
ActivityMixin.setTheme(activity);
activity.setContentView(mapProvider.getMapLayoutId());
ActivityMixin.setTitle(activity, res.getString(R.string.map_map));
if (geo == null) {
geo = app.startGeo(geoUpdate);
}
if (Settings.isUseCompass() && dir == null) {
dir = app.startDir(activity, dirUpdate);
}
// initialize map
mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId());
mapView.setMapSource();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mapView.preLoad();
mapView.setOnDragListener(this);
// initialize overlays
mapView.clearOverlays();
if (overlayPosition == null) {
overlayPosition = mapView.createAddPositionOverlay(activity);
}
if (Settings.isPublicLoc() && overlayGo4Cache == null) {
overlayGo4Cache = mapView.createAddUsersOverlay(activity, getResources().getDrawable(R.drawable.user_location));
}
if (overlayCaches == null) {
overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker));
}
if (overlayScale == null) {
overlayScale = mapView.createAddScaleOverlay(activity);
}
mapView.repaintRequired(null);
mapController = mapView.getMapController();
mapController.setZoom(Settings.getMapZoom());
// start location and directory services
if (geo != null) {
geoUpdate.updateLocation(geo);
}
if (dir != null) {
dirUpdate.updateDirection(dir);
}
// get parameters
Bundle extras = activity.getIntent().getExtras();
if (extras != null) {
searchIntent = (SearchResult) extras.getParcelable(EXTRAS_SEARCH);
geocodeIntent = extras.getString(EXTRAS_GEOCODE);
final double latitudeIntent = extras.getDouble(EXTRAS_LATITUDE);
final double longitudeIntent = extras.getDouble(EXTRAS_LONGITUDE);
coordsIntent = new Geopoint(latitudeIntent, longitudeIntent);
waypointTypeIntent = WaypointType.findById(extras.getString(EXTRAS_WPTTYPE));
mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE);
mapTitle = extras.getString(EXTRAS_MAP_TITLE);
if (coordsIntent.getLatitude() == 0.0 || coordsIntent.getLongitude() == 0.0) {
coordsIntent = null;
}
}
if (StringUtils.isBlank(mapTitle)) {
mapTitle = res.getString(R.string.map_map);
}
// live map, if no arguments are given
live = (searchIntent == null && geocodeIntent == null && coordsIntent == null);
if (null == mapStateIntent) {
followMyLocation = live;
} else {
followMyLocation = 1 == mapStateIntent[3] ? true : false;
}
if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) {
centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent);
}
// prepare my location button
myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position);
myLocSwitch.setFactory(this);
myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out);
myLocSwitch.setOnClickListener(new MyLocationListener());
switchMyLocationButton();
prepareFilterBar();
if (!Settings.getHideLiveMapHint()) {
Intent hintIntent = new Intent(activity, LiveMapInfo.class);
activity.startActivity(hintIntent);
}
}
private void prepareFilterBar() {
// show the filter warning bar if the filter is set
if (Settings.getCacheType() != CacheType.ALL) {
String cacheType = Settings.getCacheType().getL10n();
((TextView) activity.findViewById(R.id.filter_text)).setText(cacheType);
activity.findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
} else {
activity.findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
@Override
public void onResume() {
super.onResume();
app.setAction(StringUtils.defaultIfBlank(geocodeIntent, null));
if (geo == null) {
geo = app.startGeo(geoUpdate);
}
if (Settings.isUseCompass() && dir == null) {
dir = app.startDir(activity, dirUpdate);
}
geoUpdate.updateLocation(geo);
if (dir != null) {
dirUpdate.updateDirection(dir);
}
if (!CollectionUtils.isEmpty(dirtyCaches)) {
for (String geocode : dirtyCaches) {
cgCache cache = app.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS);
// remove to update the cache
caches.remove(cache);
caches.add(cache);
}
dirtyCaches.clear();
// Update display
GeoPointImpl mapCenterNow = mapView.getMapViewCenter();
int centerLatitudeNow = mapCenterNow.getLatitudeE6();
int centerLongitudeNow = mapCenterNow.getLongitudeE6();
int spanLatitudeNow = mapView.getLatitudeSpan();
int spanLongitudeNow = mapView.getLongitudeSpan();
displayExecutor.execute(new DisplayRunnable(centerLatitudeNow, centerLongitudeNow, spanLatitudeNow, spanLongitudeNow));
}
startTimer();
}
@Override
public void onStop() {
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
if (dir != null) {
dir = app.removeDir();
}
if (geo != null) {
geo = app.removeGeo();
}
savePrefs();
if (mapView != null) {
mapView.destroyDrawingCache();
}
super.onStop();
}
@Override
public void onPause() {
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
if (dir != null) {
dir = app.removeDir();
}
if (geo != null) {
geo = app.removeGeo();
}
savePrefs();
if (mapView != null) {
mapView.destroyDrawingCache();
}
super.onPause();
}
@Override
public void onDestroy() {
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
if (dir != null) {
dir = app.removeDir();
}
if (geo != null) {
geo = app.removeGeo();
}
savePrefs();
if (mapView != null) {
mapView.destroyDrawingCache();
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu submenu = menu.addSubMenu(1, MENU_SELECT_MAPVIEW, 0, res.getString(R.string.map_view_map)).setIcon(android.R.drawable.ic_menu_mapmode);
addMapViewMenuItems(submenu);
menu.add(0, MENU_MAP_LIVE, 0, res.getString(R.string.map_live_disable)).setIcon(R.drawable.ic_menu_refresh);
menu.add(0, MENU_STORE_CACHES, 0, res.getString(R.string.caches_store_offline)).setIcon(android.R.drawable.ic_menu_set_as).setEnabled(false);
menu.add(0, MENU_TRAIL_MODE, 0, res.getString(R.string.map_trail_hide)).setIcon(R.drawable.ic_menu_trail);
Strategy strategy = Settings.getLiveMapStrategy();
SubMenu subMenuStrategy = menu.addSubMenu(0, SUBMENU_STRATEGY, 0, res.getString(R.string.map_strategy)).setIcon(android.R.drawable.ic_menu_preferences);
subMenuStrategy.setHeaderTitle(res.getString(R.string.map_strategy_title));
subMenuStrategy.add(2, MENU_STRATEGY_FASTEST, 0, Strategy.FASTEST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FASTEST);
subMenuStrategy.add(2, MENU_STRATEGY_FAST, 0, Strategy.FAST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FAST);
subMenuStrategy.add(2, MENU_STRATEGY_AUTO, 0, Strategy.AUTO.getL10n()).setCheckable(true).setChecked(strategy == Strategy.AUTO);
subMenuStrategy.add(2, MENU_STRATEGY_DETAILED, 0, Strategy.DETAILED.getL10n()).setCheckable(true).setChecked(strategy == Strategy.DETAILED);
subMenuStrategy.setGroupCheckable(2, true, true);
menu.add(0, MENU_CIRCLE_MODE, 0, res.getString(R.string.map_circles_hide)).setIcon(R.drawable.ic_menu_circle);
menu.add(0, MENU_AS_LIST, 0, res.getString(R.string.map_as_list)).setIcon(android.R.drawable.ic_menu_agenda);
return true;
}
private static void addMapViewMenuItems(final Menu menu) {
MapProviderFactory.addMapviewMenuItems(menu, 1, Settings.getMapSource());
menu.setGroupCheckable(1, true, true);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item;
try {
item = menu.findItem(MENU_TRAIL_MODE); // show trail
if (Settings.isMapTrail()) {
item.setTitle(res.getString(R.string.map_trail_hide));
} else {
item.setTitle(res.getString(R.string.map_trail_show));
}
item = menu.findItem(MENU_MAP_LIVE); // live map
if (live) {
if (Settings.isLiveMap()) {
item.setTitle(res.getString(R.string.map_live_disable));
} else {
item.setTitle(res.getString(R.string.map_live_enable));
}
} else {
item.setEnabled(false);
item.setTitle(res.getString(R.string.map_live_enable));
}
menu.findItem(MENU_STORE_CACHES).setEnabled(live && !isLoading() && CollectionUtils.isNotEmpty(caches) && app.hasUnsavedCaches(search));
item = menu.findItem(MENU_CIRCLE_MODE); // show circles
if (overlayCaches != null && overlayCaches.getCircles()) {
item.setTitle(res.getString(R.string.map_circles_hide));
} else {
item.setTitle(res.getString(R.string.map_circles_show));
}
item = menu.findItem(MENU_AS_LIST);
item.setEnabled(live && CollectionUtils.isNotEmpty(caches));
menu.findItem(SUBMENU_STRATEGY).setEnabled(live);
} catch (Exception e) {
Log.e(Settings.tag, "cgeomap.onPrepareOptionsMenu: " + e.toString());
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
switch (id) {
case MENU_TRAIL_MODE:
Settings.setMapTrail(!Settings.isMapTrail());
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_MAP_LIVE:
Settings.setLiveMap(!Settings.isLiveMap());
liveChanged = true;
search = null;
searchIntent = null;
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_STORE_CACHES:
if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) {
final List<String> geocodes = new ArrayList<String>();
List<cgCache> cachesProtected = new ArrayList<cgCache>(caches);
try {
if (cachesProtected.size() > 0) {
final GeoPointImpl mapCenter = mapView.getMapViewCenter();
final int mapCenterLat = mapCenter.getLatitudeE6();
final int mapCenterLon = mapCenter.getLongitudeE6();
final int mapSpanLat = mapView.getLatitudeSpan();
final int mapSpanLon = mapView.getLongitudeSpan();
for (cgCache cache : cachesProtected) {
if (cache != null && cache.getCoords() != null) {
if (Viewport.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, cache.getCoords()) && !app.isOffline(cache.getGeocode(), null)) {
geocodes.add(cache.getGeocode());
}
}
}
}
} catch (Exception e) {
Log.e(Settings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString());
}
detailTotal = geocodes.size();
detailProgress = 0;
if (detailTotal == 0) {
ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing));
return true;
}
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler();
waitDialog = new ProgressDialog(activity);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage());
waitDialog.setMax(detailTotal);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
if (geo == null) {
geo = app.startGeo(geoUpdate);
}
if (Settings.isUseCompass() && dir == null) {
dir = app.startDir(activity, dirUpdate);
}
} catch (Exception e) {
Log.e(Settings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString());
}
}
});
float etaTime = detailTotal * 7.0f / 60.0f;
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else if (etaTime < 1.5) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + Math.round(etaTime) + " " + res.getString(R.string.caches_eta_min));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + Math.round(etaTime) + " " + res.getString(R.string.caches_eta_mins));
}
waitDialog.show();
detailProgressTime = System.currentTimeMillis();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes);
loadDetailsThread.start();
}
return true;
case MENU_CIRCLE_MODE:
if (overlayCaches == null) {
return false;
}
overlayCaches.switchCircles();
mapView.repaintRequired(overlayCaches);
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_AS_LIST: {
cgeocaches.startActivityMap(activity, search);
return true;
}
case MENU_STRATEGY_FASTEST: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FASTEST);
return true;
}
case MENU_STRATEGY_FAST: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FAST);
return true;
}
case MENU_STRATEGY_AUTO: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.AUTO);
return true;
}
case MENU_STRATEGY_DETAILED: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.DETAILED);
return true;
}
default:
if (MapProviderFactory.isValidSourceId(MapProviderFactory.getMapSourceFromMenuId(id))) {
item.setChecked(true);
int mapSource = MapProviderFactory.getMapSourceFromMenuId(id);
boolean mapRestartRequired = switchMapSource(mapSource);
if (mapRestartRequired) {
// close old mapview
activity.finish();
// prepare information to restart a similar view
Intent mapIntent = new Intent(activity, Settings.getMapProvider().getMapClass());
mapIntent.putExtra(EXTRAS_SEARCH, searchIntent);
mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent);
if (coordsIntent != null) {
mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude());
mapIntent.putExtra(EXTRAS_LONGITUDE, coordsIntent.getLongitude());
}
mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null);
int[] mapState = new int[4];
GeoPointImpl mapCenter = mapView.getMapViewCenter();
mapState[0] = mapCenter.getLatitudeE6();
mapState[1] = mapCenter.getLongitudeE6();
mapState[2] = mapView.getMapZoomLevel();
mapState[3] = followMyLocation ? 1 : 0;
mapIntent.putExtra(EXTRAS_MAPSTATE, mapState);
mapIntent.putExtra(EXTRAS_MAP_TITLE, mapTitle);
// start the new map
activity.startActivity(mapIntent);
}
return true;
}
}
return false;
}
private boolean switchMapSource(int sourceId) {
boolean mapRestartRequired = !MapProviderFactory.isSameProvider(Settings.getMapSource(), sourceId);
Settings.setMapSource(sourceId);
if (!mapRestartRequired) {
mapView.setMapSource();
}
return mapRestartRequired;
}
private void savePrefs() {
if (mapView == null) {
return;
}
Settings.setMapZoom(mapView.getMapZoomLevel());
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle() {
if (followMyLocation && geo != null) {
centerMap(geo.coordsNow);
}
}
// class: update location
private class UpdateLoc implements UpdateLocationCallback {
@Override
public void updateLocation(cgGeo geo) {
if (geo == null) {
return;
}
try {
boolean repaintRequired = false;
if (overlayPosition == null && mapView != null) {
overlayPosition = mapView.createAddPositionOverlay(activity);
}
if (overlayPosition != null && geo.location != null) {
overlayPosition.setCoordinates(geo.location);
}
if (geo.coordsNow != null) {
if (followMyLocation) {
myLocationInMiddle();
} else {
repaintRequired = true;
}
}
if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h
overlayPosition.setHeading(geo.bearingNow);
repaintRequired = true;
}
if (repaintRequired && mapView != null) {
mapView.repaintRequired(overlayPosition);
}
} catch (Exception e) {
Log.w(Settings.tag, "Failed to update location.");
}
}
}
// class: update direction
private class UpdateDir implements UpdateDirectionCallback {
@Override
public void updateDirection(cgDirection dir) {
if (dir == null || dir.directionNow == null) {
return;
}
if (overlayPosition != null && mapView != null && (geo == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h
overlayPosition.setHeading(dir.directionNow);
mapView.repaintRequired(overlayPosition);
}
}
}
/**
* Starts the {@link LoadTimer} and {@link Go4CacheTimer}.
*/
public synchronized void startTimer() {
if (coordsIntent != null) {
// display just one point
(new DisplayPointThread()).start();
} else {
// start timer
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
loadTimer = new LoadTimer();
loadTimer.start();
}
if (Settings.isPublicLoc()) {
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
go4CacheTimer = new Go4CacheTimer();
go4CacheTimer.start();
}
}
/**
* loading timer Triggers every 250ms and checks for viewport change and starts a {@link LoadRunnable}.
*/
private class LoadTimer extends Thread {
public LoadTimer() {
super("Load Timer");
}
private volatile boolean stop = false;
public void stopIt() {
stop = true;
}
@Override
public void run() {
while (!stop) {
try {
sleep(250);
if (mapView != null) {
// get current viewport
GeoPointImpl mapCenterNow = mapView.getMapViewCenter();
int centerLatitudeNow = mapCenterNow.getLatitudeE6();
int centerLongitudeNow = mapCenterNow.getLongitudeE6();
int spanLatitudeNow = mapView.getLatitudeSpan();
int spanLongitudeNow = mapView.getLongitudeSpan();
int zoomNow = mapView.getMapZoomLevel();
// check if map moved or zoomed
//TODO Portree Use Rectangle inside with bigger search window. That will stop reloading on every move
boolean moved = false;
if (liveChanged) {
moved = true;
} else if (live && Settings.isLiveMap() && !downloaded) {
moved = true;
} else if (centerLatitude == null || centerLongitude == null) {
moved = true;
} else if (spanLatitude == null || spanLongitude == null) {
moved = true;
} else if (zoomNow != zoom) {
moved = true;
} else if (((Math.abs(spanLatitudeNow - spanLatitude) > 50) || (Math.abs(spanLongitudeNow - spanLongitude) > 50) || // changed zoom
(Math.abs(centerLatitudeNow - centerLatitude) > (spanLatitudeNow / 4)) || (Math.abs(centerLongitudeNow - centerLongitude) > (spanLongitudeNow / 4)) // map moved
) && (cachesCnt <= 0 || CollectionUtils.isEmpty(caches)
|| !Viewport.isInViewPort(centerLatitude, centerLongitude, centerLatitudeNow, centerLongitudeNow, spanLatitude, spanLongitude, spanLatitudeNow, spanLongitudeNow))) {
moved = true;
}
// update title on any change
if (moved || zoomNow != zoom || spanLatitudeNow != spanLatitude || spanLongitudeNow != spanLongitude || centerLatitudeNow != centerLatitude || centerLongitudeNow != centerLongitude) {
displayHandler.sendEmptyMessage(UPDATE_TITLE);
}
zoom = zoomNow;
// save new values
if (moved) {
liveChanged = false;
long currentTime = System.currentTimeMillis();
if (1000 < (currentTime - loadThreadRun)) {
centerLatitude = centerLatitudeNow;
centerLongitude = centerLongitudeNow;
spanLatitude = spanLatitudeNow;
spanLongitude = spanLongitudeNow;
loadExecutor.execute(new LoadRunnable(centerLatitude, centerLongitude, spanLatitude, spanLongitude));
}
}
}
yield();
} catch (Exception e) {
Log.w(Settings.tag, "cgeomap.LoadTimer.run: " + e.toString());
}
}
}
public boolean isLoading() {
return loadExecutor.getActiveCount() > 0 ||
downloadExecutor.getActiveCount() > 0 ||
displayExecutor.getActiveCount() > 0;
}
}
/**
* Timer triggering every 250 ms to start the {@link Go4CacheRunnable} for displaying user.
*/
private class Go4CacheTimer extends Thread {
public Go4CacheTimer() {
super("Users Timer");
}
private volatile boolean stop = false;
public void stopIt() {
stop = true;
}
@Override
public void run() {
while (!stop) {
try {
sleep(250);
if (mapView != null) {
// get current viewport
GeoPointImpl mapCenterNow = mapView.getMapViewCenter();
int centerLatitudeNow = mapCenterNow.getLatitudeE6();
int centerLongitudeNow = mapCenterNow.getLongitudeE6();
int spanLatitudeNow = mapView.getLatitudeSpan();
int spanLongitudeNow = mapView.getLongitudeSpan();
// check if map moved or zoomed
boolean moved = false;
long currentTime = System.currentTimeMillis();
if (60000 < (currentTime - go4CacheThreadRun)) {
moved = true;
} else if (centerLatitudeUsers == null || centerLongitudeUsers == null) {
moved = true;
} else if (spanLatitudeUsers == null || spanLongitudeUsers == null) {
moved = true;
} else if (((Math.abs(spanLatitudeNow - spanLatitudeUsers) > 50) || (Math.abs(spanLongitudeNow - spanLongitudeUsers) > 50) || // changed zoom
(Math.abs(centerLatitudeNow - centerLatitudeUsers) > (spanLatitudeNow / 4)) || (Math.abs(centerLongitudeNow - centerLongitudeUsers) > (spanLongitudeNow / 4)) // map moved
) && !Viewport.isInViewPort(centerLatitudeUsers, centerLongitudeUsers, centerLatitudeNow, centerLongitudeNow, spanLatitudeUsers, spanLongitudeUsers, spanLatitudeNow, spanLongitudeNow)) {
moved = true;
}
// save new values
if (moved && (1000 < (currentTime - go4CacheThreadRun))) {
centerLatitudeUsers = centerLatitudeNow;
centerLongitudeUsers = centerLongitudeNow;
spanLatitudeUsers = spanLatitudeNow;
spanLongitudeUsers = spanLongitudeNow;
Go4CacheExecutor.execute(new Go4CacheRunnable(centerLatitudeNow, centerLongitudeNow, spanLatitudeNow, spanLongitudeNow));
}
}
yield();
} catch (Exception e) {
Log.w(Settings.tag, "cgeomap.LoadUsersTimer.run: " + e.toString());
}
}
}
}
/**
* Worker thread that loads caches and waypoints from the database and then spawns the {@link DownloadRunnable}.
* started by {@link LoadTimer}
*/
private class LoadRunnable extends DoRunnable {
public LoadRunnable(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) {
super(centerLatIn, centerLonIn, spanLatIn, spanLonIn);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
loadThreadRun = System.currentTimeMillis();
// stage 1 - pull and render from the DB only for live map
if (searchIntent != null || geocodeIntent != null) {
// map started from another activity
search = new SearchResult(searchIntent);
if (geocodeIntent != null) {
search.addGeocode(geocodeIntent);
}
} else {
// live map
if (!live || !Settings.isLiveMap()) {
search = new SearchResult(app.getStoredInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()));
} else {
search = new SearchResult(app.getCachedInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()));
}
}
if (search != null) {
downloaded = true;
caches.addAll(search.getCachesFromSearchResult(LoadFlags.LOAD_WAYPOINTS));
}
if (live) {
final boolean excludeMine = Settings.isExcludeMyCaches();
final boolean excludeDisabled = Settings.isExcludeDisabledCaches();
final ArrayList<cgCache> tempList = new ArrayList<cgCache>(caches);
for (cgCache cache : tempList) {
if ((cache.isFound() && excludeMine) || (cache.isOwn() && excludeMine) || (cache.isDisabled() && excludeDisabled)) {
caches.remove(cache);
}
}
}
//render
displayExecutor.execute(new DisplayRunnable(centerLat, centerLon, spanLat, spanLon));
if (live && Settings.isLiveMap()) {
downloadExecutor.execute(new DownloadRunnable(centerLat, centerLon, spanLat, spanLon));
}
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
}
/**
* Worker thread downloading caches from the internet.
* Started by {@link LoadRunnable}. Duplicate Code with {@link Go4CacheRunnable}
*/
private class DownloadRunnable extends DoRunnable {
public DownloadRunnable(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) {
super(centerLatIn, centerLonIn, spanLatIn, spanLonIn);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS); // show progress
int count = 0;
do {
if (tokens == null) {
tokens = GCBase.getTokens();
if (noMapTokenHandler != null && tokens == null) {
noMapTokenHandler.sendEmptyMessage(0);
}
}
final Viewport viewport = new Viewport(new Geopoint(centerLat / 1e6, centerLon / 1e6), 0.8 * spanLat / 1e6, 0.8 * spanLon / 1e6);
search = ConnectorFactory.searchByViewport(viewport, tokens);
if (search != null) {
downloaded = true;
if (search.getError() == StatusCode.NOT_LOGGED_IN) {
Login.login();
tokens = null;
} else {
break;
}
}
count++;
} while (count < 2);
if (search != null) {
Set<cgCache> result = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
// to update the caches they have to be removed first
caches.removeAll(result);
caches.addAll(result);
}
//render
displayExecutor.execute(new DisplayRunnable(centerLat, centerLon, spanLat, spanLon));
} catch (ThreadDeath e) {
Log.d(Settings.tag, "DownloadThread stopped");
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
}
/**
* Thread to Display (down)loaded caches. Started by {@link LoadRunnable} and {@link DownloadRunnable}
*/
private class DisplayRunnable extends DoRunnable {
public DisplayRunnable(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) {
super(centerLatIn, centerLonIn, spanLatIn, spanLonIn);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
if (mapView == null || caches == null) {
throw new ThreadDeath();
}
// display caches
final List<cgCache> cachesToDisplay = new ArrayList<cgCache>(caches);
final List<CachesOverlayItemImpl> itemsToDisplay = new ArrayList<CachesOverlayItemImpl>();
if (!cachesToDisplay.isEmpty()) {
for (cgCache cache : cachesToDisplay) {
if (cache.getCoords() == null) {
continue;
}
// display cache waypoints
if (cache.hasWaypoints()
// Only show waypoints for single view or setting
// when less than showWaypointsthreshold Caches shown
&& (cachesToDisplay.size() == 1 || (cachesToDisplay.size() < Settings.getWayPointsThreshold()))) {
for (cgWaypoint waypoint : cache.getWaypoints()) {
if (waypoint.getCoords() == null) {
continue;
}
itemsToDisplay.add(getItem(waypoint, null, waypoint));
}
}
itemsToDisplay.add(getItem(cache, cache, null));
}
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
cachesCnt = cachesToDisplay.size();
} else {
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
}
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} catch (ThreadDeath e) {
Log.d(Settings.tag, "DisplayThread stopped");
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS);
}
}
}
/**
* Thread to load users from Go 4 Cache
*/
private class Go4CacheRunnable extends DoRunnable {
public Go4CacheRunnable(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) {
super(centerLatIn, centerLonIn, spanLatIn, spanLonIn);
}
@Override
public void run() {
final Geopoint center = new Geopoint((int) centerLat, (int) centerLon);
final Viewport viewport = new Viewport(center, spanLat / 1e6 * 1.5, spanLon / 1e6 * 1.5);
try {
go4CacheThreadRun = System.currentTimeMillis();
List<Go4CacheUser> go4CacheUsers = Go4Cache.getGeocachersInViewport(Settings.getUsername(), viewport);
go4CacheDisplayExecutor.execute(new Go4CacheDisplayRunnable(go4CacheUsers, centerLat, centerLon, spanLat, spanLon));
} finally {
}
}
}
/**
* Thread to display users of Go 4 Cache started from {@link Go4CacheRunnable}
*/
private class Go4CacheDisplayRunnable extends DoRunnable {
private List<Go4CacheUser> users = null;
public Go4CacheDisplayRunnable(List<Go4CacheUser> usersIn, long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) {
super(centerLatIn, centerLonIn, spanLatIn, spanLonIn);
users = usersIn;
}
@Override
public void run() {
try {
if (mapView == null || CollectionUtils.isEmpty(users)) {
return;
}
// display users
List<OtherCachersOverlayItemImpl> items = new ArrayList<OtherCachersOverlayItemImpl>();
int counter = 0;
OtherCachersOverlayItemImpl item = null;
for (Go4CacheUser userOne : users) {
if (userOne.getCoords() == null) {
continue;
}
item = mapProvider.getOtherCachersOverlayItemBase(activity, userOne);
items.add(item);
counter++;
if ((counter % 10) == 0) {
overlayGo4Cache.updateItems(items);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
}
}
overlayGo4Cache.updateItems(items);
} finally {
}
}
}
/**
* Thread to display one point. Started on opening if in single mode.
*/
private class DisplayPointThread extends Thread {
@Override
public void run() {
if (mapView == null || caches == null) {
return;
}
if (coordsIntent != null) {
final cgWaypoint waypoint = new cgWaypoint("some place", waypointTypeIntent != null ? waypointTypeIntent : WaypointType.WAYPOINT, false);
waypoint.setCoords(coordsIntent);
final CachesOverlayItemImpl item = getItem(waypoint, null, waypoint);
overlayCaches.updateItems(item);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
cachesCnt = 1;
} else {
cachesCnt = 0;
}
displayHandler.sendEmptyMessage(UPDATE_TITLE);
}
}
private abstract class DoRunnable implements Runnable {
protected long centerLat = 0L;
protected long centerLon = 0L;
protected long spanLat = 0L;
protected long spanLon = 0L;
public DoRunnable(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) {
centerLat = centerLatIn;
centerLon = centerLonIn;
spanLat = spanLatIn;
spanLon = spanLonIn;
}
public abstract void run();
}
/**
* get if map is loading something
*
* @return
*/
private synchronized boolean isLoading() {
if (loadTimer != null) {
return loadTimer.isLoading();
}
return false;
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
final private CancellableHandler handler;
final private List<String> geocodes;
private long last = 0L;
public LoadDetails(final CancellableHandler handler, final List<String> geocodes) {
this.handler = handler;
this.geocodes = geocodes;
}
public void stopIt() {
handler.cancel();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
if (dir != null) {
dir = app.removeDir();
}
if (geo != null) {
geo = app.removeGeo();
}
for (String geocode : geocodes) {
try {
if (handler.isCancelled()) {
break;
}
if (!app.isOffline(geocode, null)) {
if ((System.currentTimeMillis() - last) < 1500) {
try {
int delay = 1000 + (int) (Math.random() * 1000.0) - (int) (System.currentTimeMillis() - last);
if (delay < 0) {
delay = 500;
}
sleep(delay);
} catch (Exception e) {
// nothing
}
}
if (handler.isCancelled()) {
Log.i(Settings.tag, "Stopped storing process.");
break;
}
cgBase.storeCache(activity, null, geocode, StoredList.STANDARD_LIST_ID, false, handler);
}
} catch (Exception e) {
Log.e(Settings.tag, "cgeocaches.LoadDetails.run: " + e.toString());
} finally {
// one more cache over
detailProgress++;
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
// FIXME: what does this yield() do here?
yield();
last = System.currentTimeMillis();
}
// we're done
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
}
}
// center map to desired location
private void centerMap(final Geopoint coords) {
if (coords == null) {
return;
}
if (mapView == null) {
return;
}
if (!alreadyCentered) {
alreadyCentered = true;
mapController.setCenter(makeGeoPoint(coords));
} else {
mapController.animateTo(makeGeoPoint(coords));
}
}
// move map to view results of searchIntent
private void centerMap(String geocodeCenter, final SearchResult searchCenter, final Geopoint coordsCenter, int[] mapState) {
if (!centered && mapState != null) {
try {
mapController.setCenter(mapProvider.getGeoPointBase(new Geopoint(mapState[0] / 1.0e6, mapState[1] / 1.0e6)));
mapController.setZoom(mapState[2]);
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
} else if (!centered && (geocodeCenter != null || searchIntent != null)) {
try {
List<Number> viewport = null;
if (geocodeCenter != null) {
viewport = app.getBounds(geocodeCenter);
} else {
if (searchCenter != null) {
viewport = app.getBounds(searchCenter.getGeocodes());
}
}
if (viewport == null || viewport.size() < 5) {
return;
}
int cnt = (Integer) viewport.get(0);
if (cnt <= 0) {
return;
}
int minLat = (int) ((Double) viewport.get(1) * 1e6);
int maxLat = (int) ((Double) viewport.get(2) * 1e6);
int maxLon = (int) ((Double) viewport.get(3) * 1e6);
int minLon = (int) ((Double) viewport.get(4) * 1e6);
int centerLat = 0;
int centerLon = 0;
if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) {
centerLat = minLat + ((maxLat - minLat) / 2);
} else {
centerLat = maxLat;
}
if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) {
centerLon = minLon + ((maxLon - minLon) / 2);
} else {
centerLon = maxLon;
}
mapController.setCenter(mapProvider.getGeoPointBase(new Geopoint(centerLat, centerLon)));
if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) {
mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
}
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
} else if (!centered && coordsCenter != null) {
try {
mapController.setCenter(makeGeoPoint(coordsCenter));
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
}
}
// switch My Location button image
private void switchMyLocationButton() {
if (followMyLocation) {
myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on);
myLocationInMiddle();
} else {
myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off);
}
}
// set my location listener
private class MyLocationListener implements View.OnClickListener {
public void onClick(View view) {
followMyLocation = !followMyLocation;
switchMyLocationButton();
}
}
@Override
public void onDrag() {
if (followMyLocation) {
followMyLocation = false;
switchMyLocationButton();
}
}
// make geopoint
private GeoPointImpl makeGeoPoint(final Geopoint coords) {
return mapProvider.getGeoPointBase(coords);
}
// close activity and open homescreen
@Override
public void goHome(View view) {
ActivityMixin.goHome(activity);
}
// open manual entry
@Override
public void goManual(View view) {
ActivityMixin.goManual(activity, "c:geo-live-map");
}
@Override
public View makeView() {
ImageView imageView = new ImageView(activity);
imageView.setScaleType(ScaleType.CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return imageView;
}
private static Intent newIntent(final Context context) {
return new Intent(context, Settings.getMapProvider().getMapClass());
}
public static void startActivitySearch(final Activity fromActivity, final SearchResult search, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_SEARCH, search);
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityLiveMap(final Activity fromActivity) {
fromActivity.startActivity(newIntent(fromActivity));
}
public static void startActivityCoords(final Activity fromActivity, final Geopoint coords, final WaypointType type, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_LATITUDE, coords.getLatitude());
mapIntent.putExtra(EXTRAS_LONGITUDE, coords.getLongitude());
if (type != null) {
mapIntent.putExtra(EXTRAS_WPTTYPE, type.id);
}
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityGeoCode(final Activity fromActivity, final String geocode) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_GEOCODE, geocode);
mapIntent.putExtra(EXTRAS_MAP_TITLE, geocode);
fromActivity.startActivity(mapIntent);
}
public static void markCacheAsDirty(final String geocode) {
if (dirtyCaches == null) {
dirtyCaches = new HashSet<String>();
}
dirtyCaches.add(geocode);
}
/**
* Returns a OverlayItem represented by an icon
*
* @param coord
* The coords
* @param cache
* Cache
* @param waypoint
* Waypoint. Mutally exclusive with cache
* @return
*/
private CachesOverlayItemImpl getItem(IWaypoint coord, cgCache cache, cgWaypoint waypoint) {
if (cache != null) {
CachesOverlayItemImpl item = mapProvider.getCachesOverlayItem(coord, cache.getType());
int hashcode = new HashCodeBuilder()
.append(cache.isReliableLatLon())
.append(cache.getType().id)
.append(cache.isDisabled() || cache.isArchived())
.append(cache.isOwn())
.append(cache.isFound())
.append(cache.hasUserModifiedCoords())
.append(cache.getPersonalNote())
.append(cache.isLogOffline())
.append(cache.getListId() > 0)
.toHashCode();
LayerDrawable ldFromCache = CGeoMap.overlaysCache.get(hashcode);
if (ldFromCache != null) {
item.setMarker(ldFromCache);
return item;
}
ArrayList<Drawable> layers = new ArrayList<Drawable>();
ArrayList<int[]> insets = new ArrayList<int[]>();
// background: disabled or not
Drawable marker = getResources().getDrawable(R.drawable.marker);
if (cache.isDisabled() || cache.isArchived()) {
marker = getResources().getDrawable(R.drawable.marker_disabled);
}
layers.add(marker);
int resolution = marker.getIntrinsicWidth() > 40 ? 1 : 0;
// reliable or not
if (!cache.isReliableLatLon()) {
insets.add(INSET_RELIABLE[resolution]);
layers.add(getResources().getDrawable(R.drawable.marker_notreliable));
}
// cache type
layers.add(getResources().getDrawable(cache.getType().markerId));
insets.add(INSET_TYPE[resolution]);
// own
if ( cache.isOwn() ) {
layers.add(getResources().getDrawable(R.drawable.marker_own));
insets.add(INSET_OWN[resolution]);
// if not, checked if stored
} else if (cache.getListId() > 0) {
layers.add(getResources().getDrawable(R.drawable.marker_stored));
insets.add(INSET_OWN[resolution]);
}
// found
if (cache.isFound()) {
layers.add(getResources().getDrawable(R.drawable.marker_found));
insets.add(INSET_FOUND[resolution]);
// if not, perhaps logged offline
} else if (cache.isLogOffline()) {
layers.add(getResources().getDrawable(R.drawable.marker_found_offline));
insets.add(INSET_FOUND[resolution]);
}
// user modified coords
if (cache.hasUserModifiedCoords()) {
layers.add(getResources().getDrawable(R.drawable.marker_usermodifiedcoords));
insets.add(INSET_USERMODIFIEDCOORDS[resolution]);
}
// personal note
if (cache.getPersonalNote() != null) {
layers.add(getResources().getDrawable(R.drawable.marker_personalnote));
insets.add(INSET_PERSONALNOTE[resolution]);
}
LayerDrawable ld = new LayerDrawable(layers.toArray(new Drawable[layers.size()]));
int index = 1;
for ( int[] inset : insets) {
ld.setLayerInset(index++, inset[0], inset[1], inset[2], inset[3]);
}
CGeoMap.overlaysCache.put(hashcode, ld);
item.setMarker(ld);
return item;
} else if (waypoint != null) {
CachesOverlayItemImpl item = mapProvider.getCachesOverlayItem(coord, null);
Drawable[] layers = new Drawable[2];
layers[0] = getResources().getDrawable(R.drawable.marker);
layers[1] = getResources().getDrawable(waypoint.getWaypointType().markerId);
LayerDrawable ld = new LayerDrawable(layers);
if (layers[0].getIntrinsicWidth() > 40) {
ld.setLayerInset(1, 9, 12, 10, 13);
} else {
ld.setLayerInset(1, 9, 12, 8, 12);
}
item.setMarker(ld);
return item;
}
return null;
}
}
|
package io.spine.client;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Any;
import com.google.protobuf.Message;
import io.spine.annotation.Internal;
import io.spine.core.ActorContext;
import io.spine.core.Command;
import io.spine.core.CommandContext;
import io.spine.core.Commands;
import io.spine.core.TenantId;
import io.spine.core.UserId;
import io.spine.protobuf.AnyPacker;
import io.spine.time.ZoneOffset;
import io.spine.validate.ValidationException;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.time.Time.getCurrentTime;
import static io.spine.validate.Validate.checkValid;
/**
* Public API for creating {@link Command} instances, using the {@code ActorRequestFactory}
* configuration.
*
* <p>During the creation of {@code Command} instances the source {@code Message} instances, passed
* into creation methods, are validated. The validation is performed according to the constraints
* set in Protobuf definition of each {@code Message}. In case the message isn't valid,
* an {@linkplain ValidationException exception} is thrown.
*
* <p>Therefore it is recommended to use a corresponding
* {@linkplain io.spine.validate.ValidatingBuilder ValidatingBuilder} implementation to create
* a command message.
*
* @see ActorRequestFactory#command()
*/
public final class CommandFactory {
private final ActorRequestFactory actorRequestFactory;
CommandFactory(ActorRequestFactory actorRequestFactory) {
this.actorRequestFactory = checkNotNull(actorRequestFactory);
}
/**
* Creates new {@code Command} with the passed message.
*
* <p>The command contains a {@code CommandContext} instance with the current time.
*
* @param message the command message
* @return new command instance
* @throws ValidationException if the passed message does not satisfy the constraints
* set for it in its Protobuf definition
*/
public Command create(Message message) throws ValidationException {
checkNotNull(message);
checkValid(message);
final CommandContext context = createContext();
final Command result = createCommand(message, context);
return result;
}
/**
* Creates new {@code Command} with the passed message and target entity version.
*
* <p>The command contains a {@code CommandContext} instance with the current time.
*
* <p>The message passed is validated according to the constraints set in its Protobuf
* definition. In case the message isn't valid, an {@linkplain ValidationException
* exception} is thrown.
*
* <p>The {@code targetVersion} parameter defines the version of the entity which handles
* the resulting command. Note that the framework performs no validation of the target version
* before a command is handled. The validation may be performed by the user themselves instead.
*
* @param message the command message
* @param targetVersion the version of the entity for which this command is intended
* @return new command instance
* @throws ValidationException if the passed message does not satisfy the constraints
* set for it in its Protobuf definition
*/
public Command create(Message message, int targetVersion) throws ValidationException {
checkNotNull(message);
checkValid(message);
final CommandContext context = createContext(targetVersion);
final Command result = createCommand(message, context);
return result;
}
/**
* Creates new {@code Command} with the passed {@code message} and {@code context}.
*
* <p>The timestamp of the resulting command is the <i>same</i> as in
* the passed {@code CommandContext}.
*
* @param message the command message
* @param context the command context
* @return a new command instance
* @throws ValidationException if the passed message does not satisfy the constraints
* set for it in its Protobuf definition
*/
@Internal
public Command createWithContext(Message message, CommandContext context)
throws ValidationException {
checkNotNull(message);
checkNotNull(context);
checkValid(message);
final Command result = createCommand(message, context);
return result;
}
/**
* Creates new {@code Command} with the passed message, using the existing context.
*
* <p>The produced command is created with a {@code CommandContext} instance, copied from
* the given one, but with the current time set as a context timestamp.
*
* @param message the command message
* @param context the command context to use as a base for the new command
* @return new command instance
* @throws ValidationException if the passed message does not satisfy the constraints
* set for it in its Protobuf definition
*/
@Internal
public Command createBasedOnContext(Message message, CommandContext context)
throws ValidationException {
checkNotNull(message);
checkNotNull(context);
checkValid(message);
final CommandContext newContext = contextBasedOn(context);
final Command result = createCommand(message, newContext);
return result;
}
/**
* Creates a command instance with the given {@code message} and the {@code context}.
*
* <p>If {@code Any} instance is passed as the first parameter it will be used as is.
* Otherwise, the command message will be packed into {@code Any}.
*
* <p>The ID of the new command instance is automatically generated.
*
* @param message the command message
* @param context the context of the command
* @return a new command
*/
private static Command createCommand(Message message, CommandContext context) {
checkNotNull(message);
checkNotNull(context);
final Any packed = AnyPacker.pack(message);
final Command.Builder result = Command.newBuilder()
.setId(Commands.generateId())
.setMessage(packed)
.setContext(context);
return result.build();
}
/**
* Creates command context for a new command.
*/
@VisibleForTesting
CommandContext createContext() {
return createContext(actorRequestFactory.getTenantId(),
actorRequestFactory.getActor(),
actorRequestFactory.getZoneOffset());
}
/**
* Creates command context for a new command with entity ID.
*/
private CommandContext createContext(int targetVersion) {
return createContext(actorRequestFactory.getTenantId(),
actorRequestFactory.getActor(),
actorRequestFactory.getZoneOffset(), targetVersion);
}
/**
* Creates a new command context with the current time.
*
* @param tenantId the ID of the tenant or {@code null} for single-tenant applications
* @param userId the actor ID
* @param zoneOffset the offset of the timezone in which the user works
* @return new {@code CommandContext}
* @see CommandFactory#create(Message)
*/
private static CommandContext createContext(@Nullable TenantId tenantId,
UserId userId,
ZoneOffset zoneOffset) {
checkNotNull(userId);
checkNotNull(zoneOffset);
final CommandContext.Builder result = newContextBuilder(tenantId, userId, zoneOffset);
return result.build();
}
/**
* Creates a new command context with the current time.
*
* @param tenantId the ID of the tenant or {@code null} for single-tenant applications
* @param userId the actor id
* @param zoneOffset the offset of the timezone in which the user works
* @param targetVersion the version of the entity for which this command is intended
* @return new {@code CommandContext}
* @see CommandFactory#create(Message)
*/
@VisibleForTesting
static CommandContext createContext(@Nullable TenantId tenantId,
UserId userId,
ZoneOffset zoneOffset,
int targetVersion) {
checkNotNull(userId);
checkNotNull(zoneOffset);
final CommandContext.Builder builder = newContextBuilder(tenantId, userId, zoneOffset);
final CommandContext result = builder.setTargetVersion(targetVersion)
.build();
return result;
}
private static CommandContext.Builder newContextBuilder(@Nullable TenantId tenantId,
UserId userId,
ZoneOffset zoneOffset) {
final ActorContext.Builder actorContext = ActorContext.newBuilder()
.setActor(userId)
.setTimestamp(getCurrentTime())
.setZoneOffset(zoneOffset);
if (tenantId != null) {
actorContext.setTenantId(tenantId);
}
final CommandContext.Builder result = CommandContext.newBuilder()
.setActorContext(actorContext);
return result;
}
/**
* Creates a new instance of {@code CommandContext} based on the passed one.
*
* <p>The returned instance gets new {@code timestamp} set to the time of the call.
*
* @param value the instance from which to copy values
* @return new {@code CommandContext}
*/
private static CommandContext contextBasedOn(CommandContext value) {
checkNotNull(value);
final ActorContext.Builder withCurrentTime = value.getActorContext()
.toBuilder()
.setTimestamp(getCurrentTime());
final CommandContext.Builder result = value.toBuilder()
.setActorContext(withCurrentTime);
return result.build();
}
}
|
// FILE: c:/projects/jetel/org/jetel/data/StringDataField.java
package org.jetel.data;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharacterCodingException;
import org.jetel.exception.BadDataFormatException;
import org.jetel.metadata.DataFieldMetadata;
/**
* A class that represents String type data field.<br>
* It can hold String of arbitrary length, however due
* to use of short value as length specifier when serializing/
* deserializing value to/from ByteBuffer, the maximum length
* is limited to 32762 characters (Short.MAX_VALUE);
*
* @author D.Pavlis
* @since March 27, 2002
* @revision $Revision$
* @created January 26, 2003
* @see org.jetel.metadata.DataFieldMetadata
*/
public class StringDataField extends DataField implements CharSequence{
private StringBuffer value;
// Attributes
/**
* An attribute that represents ...
*
* @since
*/
private final static int INITIAL_STRING_BUFFER_CAPACITY = 32;
private final static int STRING_LENGTH_INDICATOR_SIZE = 2; // sizeof(short)
// Associations
// Operations
/**
* Constructor for the StringDataField object
*
* @param _metadata Description of Parameter
* @since April 23, 2002
*/
public StringDataField(DataFieldMetadata _metadata) {
super(_metadata);
if (_metadata.getSize() < 1) {
value = new StringBuffer(INITIAL_STRING_BUFFER_CAPACITY);
} else {
value = new StringBuffer(_metadata.getSize());
}
}
/**
* Constructor for the StringDataField object
*
* @param _metadata Description of Parameter
* @param _value Description of Parameter
* @since April 23, 2002
*/
public StringDataField(DataFieldMetadata _metadata, String _value) {
this(_metadata);
setValue(_value);
}
/**
* Private constructor used internally when clonning
*
* @param _metadata
* @param _value
*/
private StringDataField(DataFieldMetadata _metadata, StringBuffer _value){
super(_metadata);
this.value=new StringBuffer(_value.length());
this.value.append(_value);
}
/* (non-Javadoc)
* @see org.jetel.data.DataField#copy()
*/
public DataField duplicate(){
StringDataField newField=new StringDataField(metadata,value);
newField.setNull(this.isNull());
return newField;
}
/* (non-Javadoc)
* @see org.jetel.data.DataField#copyField(org.jetel.data.DataField)
*/
public void copyFrom(DataField fieldFrom){
if (fieldFrom instanceof StringDataField ){
if (!fieldFrom.isNull){
this.value.setLength(0);
this.value.append(((StringDataField)fieldFrom).value);
}
setNull(fieldFrom.isNull);
}else{
throw new ClassCastException("Incompatible DataField type "+DataFieldMetadata.type2Str(fieldFrom.getType()));
}
}
/**
* Sets the Value attribute of the StringDataField object
*
* @param value The new value value
* @exception BadDataFormatException Description of the Exception
* @since April 23, 2002
*/
public void setValue(Object value) throws BadDataFormatException {
this.value.setLength(0);
if (value instanceof StringDataField){
this.value.append(((StringDataField)value).value);
}else if (value instanceof String){
this.value.append((String)value);
}else if (value instanceof StringBuffer){
this.value.append((StringBuffer)value);
}else if (value instanceof char[]){
this.value.append((char[])value);
}else if (value instanceof CharSequence){
this.value.append((CharSequence)value);
}else if (value==null){
if (this.metadata.isNullable()) {
setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
return;
}
if (this.value.length()!=0){
setNull(false);
}else{
if (this.metadata.isNullable()) {
setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
}
}
/**
* Sets the value attribute of the StringDataField object
*
* @param seq The character sequence from which to set the value (either
* String, StringBuffer or Char Buffer)
* @since October 29, 2002
*/
public void setValue(CharSequence seq) {
value.setLength(0);
if (seq != null && seq.length() > 0) {
value.append(seq);
setNull(false);
} else {
if (this.metadata.isNullable()) {
super.setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
return;
}
}
/**
* Sets the Null value indicator
*
* @param isNull The new Null value
* @since October 29, 2002
*/
public void setNull(boolean isNull) {
super.setNull(isNull);
if (isNull) {
value.setLength(0);
}
}
/**
* Gets the Null value indicator
*
* @return The Null value
* @since October 29, 2002
*/
public boolean isNull() {
return super.isNull();
}
/**
* Gets the Value attribute of the StringDataField object
*
* @return The Value value
* @since April 23, 2002
*/
public Object getValue() {
return (isNull ? null : value);
}
/**
* Gets the value of the StringDataField object as charSequence
*
* @return The charSequence value
*/
public CharSequence getCharSequence() {
return value;
}
/**
* Gets the Type attribute of the StringDataField object
*
* @return The Type value
* @since April 23, 2002
*/
public char getType() {
return DataFieldMetadata.STRING_FIELD;
}
/**
* Description of the Method
*
* @param dataBuffer Description of Parameter
* @param decoder Description of Parameter
* @exception CharacterCodingException Description of Exception
* @since October 31, 2002
*/
public void fromByteBuffer(ByteBuffer dataBuffer, CharsetDecoder decoder) throws CharacterCodingException {
fromString(decoder.decode(dataBuffer).toString());
}
/**
* Description of the Method
*
* @param dataBuffer Description of Parameter
* @param encoder Description of Parameter
* @exception CharacterCodingException Description of Exception
* @since October 31, 2002
*/
public void toByteBuffer(ByteBuffer dataBuffer, CharsetEncoder encoder) throws CharacterCodingException {
dataBuffer.put(encoder.encode(CharBuffer.wrap(toString())));
}
/**
* Description of the Method
*
* @return Description of the Returned Value
* @since April 23, 2002
*/
public String toString() {
return value.toString();
}
/**
* Description of the Method
*
* @param value Description of the Parameter
* @since April 23, 2002
*/
public void fromString(String value) {
setValue(value);
}
/**
* Description of the Method
*
* @param buffer Description of Parameter
* @since April 23, 2002
*/
public void serialize(ByteBuffer buffer) {
int length = value.length();
int chars = length;
do {
buffer.put((byte)(0x80 | (byte) length));
length = length >> 7;
} while((length >> 7) > 0);
buffer.put((byte) length);
for(int counter = 0; counter < chars; counter++) {
buffer.putChar(value.charAt(counter));
}
}
/**
* Description of the Method
*
* @param buffer Description of Parameter
* @since April 23, 2002
*/
public void deserialize(ByteBuffer buffer) {
int length;
int size;
length = size = 0;
int count = 0;
do {
size = buffer.get();
length = length | ((size & 0x7F) << (7 * count++));
} while(size < 0);
// empty value - so we can store new string
value.setLength(0);
if (length == 0) {
setNull(true);
} else {
for(int counter = 0; counter < length; counter++){
value.append(buffer.getChar());
}
setNull(false);
}
}
/**
* Description of the Method
*
* @param obj Description of Parameter
* @return Description of the Returned Value
* @since April 23, 2002
*/
public boolean equals(Object obj) {
if (obj==null || isNull) return false;
CharSequence data;
if (obj instanceof StringDataField){
if (((StringDataField)obj).isNull()) return false;
data = (CharSequence)((StringDataField) obj).getValue();
}else if (obj instanceof CharSequence){
data = (CharSequence)obj;
}else{
throw new ClassCastException("Can't compare StringDataField and "+obj.getClass().getName());
}
if (value.length() != data.length()) {
return false;
}
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) != data.charAt(i)) {
return false;
}
}
return true;
}
/**
* Compares this object with the specified object for order.
*
* @param obj Any object implementing CharSequence interface
* @return Description -1;0;1 based on comparison result
*/
public int compareTo(Object obj) {
CharSequence strObj;
if (obj==null) return 1;
if (isNull) return -1;
if (obj instanceof StringDataField) {
if (((StringDataField) obj).isNull())
return 1;
strObj=((StringDataField) obj).value;
}else if (obj instanceof CharSequence) {
strObj = (CharSequence) obj;
}else {
throw new ClassCastException("Can't compare StringDataField to "
+ obj.getClass().getName());
}
int valueLenght = value.length();
int strObjLenght = strObj.length();
int compLength = (valueLenght < strObjLenght ? valueLenght
: strObjLenght);
for (int i = 0; i < compLength; i++) {
if (value.charAt(i) > strObj.charAt(i)) {
return 1;
} else if (value.charAt(i) < strObj.charAt(i)) {
return -1;
}
}
// strings seem to be the same (so far), decide according to the
// length
if (valueLenght == strObjLenght) {
return 0;
} else if (valueLenght > strObjLenght) {
return 1;
} else {
return -1;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode(){
int hash=5381;
for (int i=0;i<value.length();i++){
hash = ((hash << 5) + hash) + value.charAt(i);
}
return (hash & 0x7FFFFFFF);
}
/**
* Returns how many bytes will be occupied when this field with current
* value is serialized into ByteBuffer
*
* @return The size value
* @see org.jetel.data.DataField
*/
public int getSizeSerialized() {
// lentgh in characters multiplied of 2 (each char occupies 2 bytes in UNICODE) plus
// size of length indicator (basically int variable)
int length=value.length();
int count=0;
do{
count++;
length=length>>7;
}while(length>0x7F);
return value.length()*2+count;
}
/**
* Method which implements charAt method of CharSequence interface
*
* @param position
* @return
*/
public char charAt(int position){
return value.charAt(position);
}
/**Method which implements length method of CharSequence interfaceMethod which ...
*
* @return
*/
public int length(){
return value.length();
}
/**
* Method which implements subSequence method of CharSequence interface
*
* @param start
* @param end
* @return
*/
public CharSequence subSequence(int start, int end){
return value.subSequence(start,end);
}
}
/*
* end class StringDataField
*/
|
// FILE: c:/projects/jetel/org/jetel/data/StringDataField.java
package org.jetel.data;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharacterCodingException;
import org.jetel.exception.BadDataFormatException;
import org.jetel.metadata.DataFieldMetadata;
/**
* A class that represents String type data field.<br>
* It can hold String of arbitrary length, however due
* to use of short value as length specifier when serializing/
* deserializing value to/from ByteBuffer, the maximum length
* is limited to 32762 characters (Short.MAX_VALUE);
*
* @author D.Pavlis
* @since March 27, 2002
* @revision $Revision$
* @created January 26, 2003
* @see org.jetel.metadata.DataFieldMetadata
*/
public class StringDataField extends DataField implements CharSequence{
private StringBuffer value;
// Attributes
/**
* An attribute that represents ...
*
* @since
*/
private final static int INITIAL_STRING_BUFFER_CAPACITY = 32;
private final static int STRING_LENGTH_INDICATOR_SIZE = 2; // sizeof(short)
private static final int SIZE_OF_CHAR = 2;
// Associations
// Operations
/**
* Constructor for the StringDataField object
*
* @param _metadata Description of Parameter
* @since April 23, 2002
*/
public StringDataField(DataFieldMetadata _metadata) {
super(_metadata);
if (_metadata.getSize() < 1) {
value = new StringBuffer(INITIAL_STRING_BUFFER_CAPACITY);
} else {
value = new StringBuffer(_metadata.getSize());
}
}
/**
* Constructor for the StringDataField object
*
* @param _metadata Description of Parameter
* @param _value Description of Parameter
* @since April 23, 2002
*/
public StringDataField(DataFieldMetadata _metadata, String _value) {
this(_metadata);
setValue(_value);
}
/**
* Private constructor used internally when clonning
*
* @param _metadata
* @param _value
*/
private StringDataField(DataFieldMetadata _metadata, StringBuffer _value){
super(_metadata);
this.value=new StringBuffer(_value.length());
this.value.append(_value);
}
/* (non-Javadoc)
* @see org.jetel.data.DataField#copy()
*/
public DataField duplicate(){
StringDataField newField=new StringDataField(metadata,value);
newField.setNull(this.isNull());
return newField;
}
/* (non-Javadoc)
* @see org.jetel.data.DataField#copyField(org.jetel.data.DataField)
*/
public void copyFrom(DataField fieldFrom){
if (fieldFrom instanceof StringDataField ){
if (!fieldFrom.isNull){
this.value.setLength(0);
this.value.append(((StringDataField)fieldFrom).value);
}
setNull(fieldFrom.isNull);
}else{
throw new ClassCastException("Incompatible DataField type "+DataFieldMetadata.type2Str(fieldFrom.getType()));
}
}
/**
* Sets the Value attribute of the StringDataField object
*
* @param value The new value value
* @exception BadDataFormatException Description of the Exception
* @since April 23, 2002
*/
public void setValue(Object value) throws BadDataFormatException {
this.value.setLength(0);
if (value instanceof StringDataField){
this.value.append(((StringDataField)value).value);
}else if (value instanceof String){
this.value.append((String)value);
}else if (value instanceof StringBuffer){
this.value.append((StringBuffer)value);
}else if (value instanceof char[]){
this.value.append((char[])value);
}else if (value instanceof CharSequence){
CharSequence str=(CharSequence)value;
for (int i=0;i<str.length();this.value.append(str.charAt(i++)));
}else if (value==null){
if (this.metadata.isNullable()) {
setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
return;
}
if (this.value.length()!=0){
setNull(false);
}else{
if (this.metadata.isNullable()) {
setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
}
}
/**
* Sets the value attribute of the StringDataField object
*
* @param seq The character sequence from which to set the value (either
* String, StringBuffer or Char Buffer)
* @since October 29, 2002
*/
public void setValue(CharSequence seq) {
value.setLength(0);
if (seq != null && seq.length() > 0) {
value.append(seq);
setNull(false);
} else {
if (this.metadata.isNullable()) {
super.setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
return;
}
}
/**
* Sets the Null value indicator
*
* @param isNull The new Null value
* @since October 29, 2002
*/
public void setNull(boolean isNull) {
super.setNull(isNull);
if (isNull) {
value.setLength(0);
}
}
/**
* Gets the Null value indicator
*
* @return The Null value
* @since October 29, 2002
*/
public boolean isNull() {
return super.isNull();
}
/**
* Gets the Value attribute of the StringDataField object
*
* @return The Value value
* @since April 23, 2002
*/
public Object getValue() {
return (isNull ? null : value);
}
/**
* Gets the value of the StringDataField object as charSequence
*
* @return The charSequence value
*/
public CharSequence getCharSequence() {
return value;
}
/**
* Gets the Type attribute of the StringDataField object
*
* @return The Type value
* @since April 23, 2002
*/
public char getType() {
return DataFieldMetadata.STRING_FIELD;
}
/**
* Description of the Method
*
* @param dataBuffer Description of Parameter
* @param decoder Description of Parameter
* @exception CharacterCodingException Description of Exception
* @since October 31, 2002
*/
public void fromByteBuffer(ByteBuffer dataBuffer, CharsetDecoder decoder) throws CharacterCodingException {
fromString(decoder.decode(dataBuffer).toString());
}
/**
* Description of the Method
*
* @param dataBuffer Description of Parameter
* @param encoder Description of Parameter
* @exception CharacterCodingException Description of Exception
* @since October 31, 2002
*/
public void toByteBuffer(ByteBuffer dataBuffer, CharsetEncoder encoder) throws CharacterCodingException {
dataBuffer.put(encoder.encode(CharBuffer.wrap(toString())));
}
/**
* Description of the Method
*
* @return Description of the Returned Value
* @since April 23, 2002
*/
public String toString() {
return value.toString();
}
/**
* Description of the Method
*
* @param value Description of the Parameter
* @since April 23, 2002
*/
public void fromString(String value) {
setValue(value);
}
/**
* Description of the Method
*
* @param buffer Description of Parameter
* @since April 23, 2002
*/
public void serialize(ByteBuffer buffer) {
int length = value.length();
int chars = length;
do {
buffer.put((byte)(0x80 | (byte) length));
length = length >> 7;
} while((length >> 7) > 0);
buffer.put((byte) length);
for(int counter = 0; counter < chars; counter++) {
buffer.putChar(value.charAt(counter));
}
}
/**
* Description of the Method
*
* @param buffer Description of Parameter
* @since April 23, 2002
*/
public void deserialize(ByteBuffer buffer) {
int length;
int size;
length = size = 0;
int count = 0;
do {
size = buffer.get();
length = length | ((size & 0x7F) << (7 * count++));
} while(size < 0);
// empty value - so we can store new string
value.setLength(0);
if (length == 0) {
setNull(true);
} else {
for(int counter = 0; counter < length; counter++){
value.append(buffer.getChar());
}
setNull(false);
}
}
/**
* Description of the Method
*
* @param obj Description of Parameter
* @return Description of the Returned Value
* @since April 23, 2002
*/
public boolean equals(Object obj) {
if (isNull || obj==null ) return false;
if (this==obj) return true;
CharSequence data;
if (obj instanceof StringDataField){
if (((StringDataField)obj).isNull()) return false;
data = (CharSequence)((StringDataField) obj).getValue();
}else if (obj instanceof CharSequence){
data = (CharSequence)obj;
}else{
return false;
}
if (value.length() != data.length()) {
return false;
}
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) != data.charAt(i)) {
return false;
}
}
return true;
}
/**
* Compares this object with the specified object for order.
*
* @param obj Any object implementing CharSequence interface
* @return Description -1;0;1 based on comparison result
*/
public int compareTo(Object obj) {
CharSequence strObj;
if (isNull) return -1;
if (obj instanceof StringDataField) {
if (((StringDataField) obj).isNull())
return 1;
strObj=((StringDataField) obj).value;
}else if (obj instanceof CharSequence) {
strObj = (CharSequence) obj;
}else {
throw new ClassCastException("Can't compare StringDataField to "
+ obj.getClass().getName());
}
int valueLenght = value.length();
int strObjLenght = strObj.length();
int compLength = (valueLenght < strObjLenght ? valueLenght
: strObjLenght);
for (int i = 0; i < compLength; i++) {
if (value.charAt(i) > strObj.charAt(i)) {
return 1;
} else if (value.charAt(i) < strObj.charAt(i)) {
return -1;
}
}
// strings seem to be the same (so far), decide according to the
// length
if (valueLenght == strObjLenght) {
return 0;
} else if (valueLenght > strObjLenght) {
return 1;
} else {
return -1;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode(){
int hash=5381;
for (int i=0;i<value.length();i++){
hash = ((hash << 5) + hash) + value.charAt(i);
}
return (hash & 0x7FFFFFFF);
}
/**
* Returns how many bytes will be occupied when this field with current
* value is serialized into ByteBuffer
*
* @return The size value
* @see org.jetel.data.DataField
*/
public int getSizeSerialized() {
// lentgh in characters multiplied of 2 (each char occupies 2 bytes in UNICODE) plus
// size of length indicator (basically int variable)
int length=value.length();
int count=0;
do {
count++;
length = length >> 7;
} while((length >> 7) > 0);
count++;
return value.length()*SIZE_OF_CHAR+count;
}
/**
* Method which implements charAt method of CharSequence interface
*
* @param position
* @return
*/
public char charAt(int position){
return value.charAt(position);
}
/**Method which implements length method of CharSequence interfaceMethod which ...
*
* @return
*/
public int length(){
return value.length();
}
/**
* Method which implements subSequence method of CharSequence interface
*
* @param start
* @param end
* @return
*/
public CharSequence subSequence(int start, int end){
return value.subSequence(start,end);
}
}
/*
* end class StringDataField
*/
|
package org.jetel.database;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.HashSet;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;
import java.sql.Types;
import org.jetel.data.DataRecord;
import org.jetel.data.DataField;
import org.jetel.data.DateDataField;
import org.jetel.data.NumericDataField;
import org.jetel.data.IntegerDataField;
import org.jetel.data.StringDataField;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
/**
* Class for creating mappings between CloverETL's DataRecords and JDBC's
* ResultSets.<br>
* It also contains inner classes for translating various CloverETL's DataField
* types onto JDBC types.
*
*@author dpavlis
*@created 8. ervenec 2003
*@since October 7, 2002
*/
public abstract class CopySQLData {
/**
* Description of the Field
*
*@since October 7, 2002
*/
protected int fieldSQL;
/**
* Description of the Field
*
*@since October 7, 2002
*/
protected DataField field;
/**
* Constructor for the CopySQLData object
*
*@param record Clover record which will be source or target
*@param fieldSQL index of the field in SQL statement
*@param fieldJetel index of the field in Clover record
*@since October 7, 2002
*/
CopySQLData(DataRecord record, int fieldSQL, int fieldJetel) {
this.fieldSQL = fieldSQL + 1;
// fields in ResultSet start with index 1
field = record.getField(fieldJetel);
}
/**
* Sets value of Jetel/Clover data field based on value from SQL ResultSet
*
*@param resultSet Description of Parameter
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
public void sql2jetel(ResultSet resultSet) throws SQLException {
try {
setJetel(resultSet);
} catch (SQLException ex) {
throw new SQLException(ex.getMessage() + " with field " + field.getMetadata().getName());
}
}
/**
* Sets value of SQL field in PreparedStatement based on Jetel/Clover data
* field's value
*
*@param pStatement Description of Parameter
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
public void jetel2sql(PreparedStatement pStatement) throws SQLException {
try {
setSQL(pStatement);
} catch (SQLException ex) {
throw new SQLException(ex.getMessage() + " with field " + field.getMetadata().getName());
}
}
/**
* Sets the Jetel attribute of the CopySQLData object
*
*@param resultSet The new Jetel value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
abstract void setJetel(ResultSet resultSet) throws SQLException;
/**
* Sets the SQL attribute of the CopySQLData object
*
*@param pStatement The new SQL value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
abstract void setSQL(PreparedStatement pStatement) throws SQLException;
/**
* Creates translation array for copying data from Database record into Jetel
* record
*
*@param metadata Metadata describing Jetel data record
*@param record Jetel data record
*@return Array of CopySQLData objects which can be used when getting
* data from DB into Jetel record
*@since September 26, 2002
*/
public static CopySQLData[] sql2JetelTransMap(List fieldTypes,DataRecordMetadata metadata, DataRecord record) {
CopySQLData[] transMap = new CopySQLData[metadata.getNumFields()];
int i=0;
for(ListIterator iterator = fieldTypes.listIterator();iterator.hasNext();){
transMap[i] = createCopyObject(((Integer) iterator.next()).shortValue(), record, i, i);
i++;
}
// for (int i = 0; i < metadata.getNumFields(); i++) {
// switch (metadata.getField(i).getType()) {
// case DataFieldMetadata.STRING_FIELD:
// transMap[i] = new CopyString(record, i, i);
// break;
// case DataFieldMetadata.NUMERIC_FIELD:
// transMap[i] = new CopyNumeric(record, i, i);
// break;
// case DataFieldMetadata.INTEGER_FIELD:
// transMap[i] = new CopyInteger(record, i, i);
// break;
// case DataFieldMetadata.DATE_FIELD:
// transMap[i] = new CopyDate(record, i, i);
// break;
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record
*
*@param fieldTypes Description of Parameter
*@param record Description of Parameter
*@return Description of the Returned Value
*@exception SQLException Description of Exception
*@since October 4, 2002
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes, DataRecord record) throws SQLException {
int i = 0;
CopySQLData[] transMap = new CopySQLData[fieldTypes.size()];
ListIterator iterator = fieldTypes.listIterator();
while (iterator.hasNext()) {
transMap[i] = createCopyObject(((Integer) iterator.next()).shortValue(), record, i, i);
i++;
}
return transMap;
}
/**
* Description of the Method
*
*@param fieldTypes Description of the Parameter
*@param record Description of the Parameter
*@param skipList Description of the Parameter
*@return Description of the Return Value
*@exception SQLException Description of the Exception
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes, DataRecord record, int[] skipList) throws SQLException {
int i = 0;
int fromIndex = 0;
int toIndex = 0;
short jdbcType;
CopySQLData[] transMap = new CopySQLData[fieldTypes.size() - skipList.length];
ListIterator iterator = fieldTypes.listIterator();
Set skipSet = new HashSet();
for (int j = 0; j < skipList.length; j++) {
skipSet.add(new Integer(skipList[j]));
}
while (iterator.hasNext()) {
jdbcType=((Integer) iterator.next()).shortValue();
if (!skipSet.contains(new Integer(toIndex))) {
transMap[i++] = createCopyObject(jdbcType, record, fromIndex, toIndex);
fromIndex++;
}
toIndex++;
}
return transMap;
}
/**
* Description of the Method
*
*@param SQLType Description of the Parameter
*@param record Description of the Parameter
*@param fromIndex Description of the Parameter
*@param toIndex Description of the Parameter
*@return Description of the Return Value
*/
private static CopySQLData createCopyObject(int SQLType, DataRecord record, int fromIndex, int toIndex) {
char jetelFieldType=record.getMetadata().getFieldType(fromIndex);
switch (SQLType) {
case Types.CHAR:
case Types.LONGVARCHAR:
case Types.VARCHAR:
return new CopyString(record, fromIndex, toIndex);
case Types.INTEGER:
case Types.SMALLINT:
return new CopyInteger(record, fromIndex, toIndex);
case Types.BIGINT:
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.NUMERIC:
case Types.REAL:
// fix for copying when target is numeric and
// clover source is integer - no precision can be
// lost so we can use CopyInteger
if (jetelFieldType==DataFieldMetadata.INTEGER_FIELD){
return new CopyInteger(record, fromIndex, toIndex);
}else{
return new CopyNumeric(record, fromIndex, toIndex);
}
case Types.DATE:
case Types.TIME:
return new CopyDate(record, fromIndex, toIndex);
case Types.TIMESTAMP:
return new CopyTimestamp(record, fromIndex, toIndex);
case Types.BOOLEAN:
case Types.BIT:
if (jetelFieldType==DataFieldMetadata.STRING_FIELD){
return new CopyBoolean(record,fromIndex,toIndex);
}
default:
throw new RuntimeException("SQL data type not supported: " + SQLType);
}
}
/**
* Description of the Class
*
*@author dpavlis
*@created 8. ervenec 2003
*@since October 7, 2002
*/
static class CopyDate extends CopySQLData {
/**
* Constructor for the CopyDate object
*
*@param record Description of Parameter
*@param fieldSQL Description of Parameter
*@param fieldJetel Description of Parameter
*@since October 7, 2002
*/
CopyDate(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyDate object
*
*@param resultSet The new Jetel value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
((DateDataField) field).setValue(resultSet.getDate(fieldSQL));
}
/**
* Sets the SQL attribute of the CopyDate object
*
*@param pStatement The new SQL value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
pStatement.setDate(fieldSQL, (Date) field.getValue());
}
}
/**
* Description of the Class
*
*@author dpavlis
*@created 8. ervenec 2003
*@since October 7, 2002
*/
static class CopyNumeric extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
*@param record Description of Parameter
*@param fieldSQL Description of Parameter
*@param fieldJetel Description of Parameter
*@since October 7, 2002
*/
CopyNumeric(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
*@param resultSet The new Jetel value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
double i = resultSet.getDouble(fieldSQL);
if (resultSet.wasNull()) {
((NumericDataField) field).setValue(null);
} else {
((NumericDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
*@param pStatement The new SQL value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
pStatement.setDouble(fieldSQL, ((NumericDataField) field).getDouble());
}
}
/**
* Description of the Class
*
*@author dpavlis
*@created 8. ervenec 2003
*/
static class CopyInteger extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
*@param record Description of Parameter
*@param fieldSQL Description of Parameter
*@param fieldJetel Description of Parameter
*@since October 7, 2002
*/
CopyInteger(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
*@param resultSet The new Jetel value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
int i = resultSet.getInt(fieldSQL);
if (resultSet.wasNull()) {
((IntegerDataField) field).setValue(null);
} else {
((IntegerDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
*@param pStatement The new SQL value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
pStatement.setInt(fieldSQL, ((IntegerDataField) field).getInt());
}
}
/**
* Description of the Class
*
*@author dpavlis
*@created 8. ervenec 2003
*@since October 7, 2002
*/
static class CopyString extends CopySQLData {
/**
* Constructor for the CopyString object
*
*@param record Description of Parameter
*@param fieldSQL Description of Parameter
*@param fieldJetel Description of Parameter
*@since October 7, 2002
*/
CopyString(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyString object
*
*@param resultSet The new Jetel value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
field.fromString(resultSet.getString(fieldSQL));
}
/**
* Sets the SQL attribute of the CopyString object
*
*@param pStatement The new SQL value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
pStatement.setString(fieldSQL, field.toString());
}
}
/**
* Description of the Class
*
*@author dpavlis
*@created 8. ervenec 2003
*@since October 7, 2002
*/
static class CopyTimestamp extends CopySQLData {
Timestamp timeValue;
/**
* Constructor for the CopyTimestamp object
*
*@param record Description of Parameter
*@param fieldSQL Description of Parameter
*@param fieldJetel Description of Parameter
*@since October 7, 2002
*/
CopyTimestamp(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
timeValue=new Timestamp(0);
timeValue.setNanos(0); // we don't count with nanos!
}
/**
* Sets the Jetel attribute of the CopyTimestamp object
*
*@param resultSet The new Jetel value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
((DateDataField) field).setValue(resultSet.getTimestamp(fieldSQL));
}
/**
* Sets the SQL attribute of the CopyTimestamp object
*
*@param pStatement The new SQL value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
timeValue.setTime(((java.util.Date) field.getValue()).getTime());
pStatement.setTimestamp(fieldSQL, timeValue);
}
}
/**
* Copy object for boolean/bit type fields. Expects String data
* representation on Clover's side
* for logical
*
*@author dpavlis
*@since November 27, 2003
*/
static class CopyBoolean extends CopySQLData {
private static String _TRUE_="T";
private static String _FALSE_="F";
private static char _TRUE_CHAR_='T';
private static char _TRUE_SMCHAR_='t';
/**
* Constructor for the CopyString object
*
*@param record Description of Parameter
*@param fieldSQL Description of Parameter
*@param fieldJetel Description of Parameter
*@since October 7, 2002
*/
CopyBoolean(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyString object
*
*@param resultSet The new Jetel value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
field.fromString(resultSet.getBoolean(fieldSQL) ? _TRUE_ : _FALSE_);
}
/**
* Sets the SQL attribute of the CopyString object
*
*@param pStatement The new SQL value
*@exception SQLException Description of Exception
*@since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
char value=((StringDataField)field).getCharSequence().charAt(0);
pStatement.setBoolean(fieldSQL, ((value==_TRUE_CHAR_)||(value==_TRUE_SMCHAR_)) );
}
}
}
|
package net.silentchaos512.gems.core.util;
import java.util.List;
import org.lwjgl.input.Keyboard;
import net.minecraft.block.Block;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.silentchaos512.gems.SilentGems;
import net.silentchaos512.gems.api.IPlaceable;
import net.silentchaos512.gems.configuration.Config;
import net.silentchaos512.gems.enchantment.EnchantmentAOE;
import net.silentchaos512.gems.enchantment.ModEnchantments;
import net.silentchaos512.gems.item.CraftingMaterial;
import net.silentchaos512.gems.item.Gem;
import net.silentchaos512.gems.item.ModItems;
import net.silentchaos512.gems.item.tool.GemAxe;
import net.silentchaos512.gems.item.tool.GemBow;
import net.silentchaos512.gems.item.tool.GemHoe;
import net.silentchaos512.gems.item.tool.GemPickaxe;
import net.silentchaos512.gems.item.tool.GemShovel;
import net.silentchaos512.gems.item.tool.GemSickle;
import net.silentchaos512.gems.item.tool.GemSword;
import net.silentchaos512.gems.lib.EnumGem;
import net.silentchaos512.gems.lib.Names;
import net.silentchaos512.gems.material.ModMaterials;
/**
* The purpose of this class is to have shared code for tools in one place, to make updating/expanding the mod easier.
*/
public class ToolHelper {
public static final String[] TOOL_CLASSES = { "Sword", "Pickaxe", "Shovel", "Axe", "Hoe",
"Sickle", "Bow" };
/*
* NBT constants
*/
public static final String NBT_ROOT = SilentGems.MOD_ID + "Tool";
public static final String NBT_HEAD_L = "HeadL";
public static final String NBT_HEAD_M = "HeadM";
public static final String NBT_HEAD_R = "HeadR";
public static final String NBT_ROD = "Rod";
public static final String NBT_ROD_DECO = "RodDeco";
public static final String NBT_ROD_WOOL = "RodWool";
public static final String NBT_TIP = "Tip";
public static final String NBT_NO_GLINT = "NoGlint";
public static final String NBT_STATS_BLOCKS_MINED = "BlocksMined";
public static final String NBT_STATS_BLOCKS_PLACED = "BlocksPlaced";
public static final String NBT_STATS_HITS = "HitsLanded";
public static final String NBT_STATS_SHOTS_FIRED = "ShotsFired";
public static final String NBT_STATS_REDECORATED = "Redecorated";
/**
* Gets the "gem ID", or base material ID for a tool. Note that the regular and supercharged gems have the same ID
* (ie, regular ruby == supercharged ruby == 0). For gems, this number is in [0, 11]. Other IDs can be found in
* ModMaterials.
*
* @param tool
* @return The material ID, or -1 if it can't be determined.
*/
public static int getToolGemId(ItemStack tool) {
if (tool == null) {
return -1;
}
Item item = tool.getItem();
if (item instanceof GemSword) {
return ((GemSword) item).gemId;
} else if (item instanceof GemPickaxe) {
return ((GemPickaxe) item).gemId;
} else if (item instanceof GemShovel) {
return ((GemShovel) item).gemId;
} else if (item instanceof GemAxe) {
return ((GemAxe) item).gemId;
} else if (item instanceof GemHoe) {
return ((GemHoe) item).gemId;
} else if (item instanceof GemSickle) {
return ((GemSickle) item).gemId;
} else if (item instanceof GemBow) {
return ((GemBow) item).gemId;
} else {
LogHelper.debug("Called ToolHelper.getToolGemId on a non-Gems tool!");
return -1;
}
}
/**
* Determines whether the tool is "supercharged" or not.
*
* @param tool
* @return True for supercharged tools (ornate rod) or false for regular tools (wooden rod).
*/
public static boolean getToolIsSupercharged(ItemStack tool) {
if (tool == null) {
return false;
}
Item item = tool.getItem();
if (item instanceof GemSword) {
return ((GemSword) item).supercharged;
} else if (item instanceof GemPickaxe) {
return ((GemPickaxe) item).supercharged;
} else if (item instanceof GemShovel) {
return ((GemShovel) item).supercharged;
} else if (item instanceof GemAxe) {
return ((GemAxe) item).supercharged;
} else if (item instanceof GemHoe) {
return ((GemHoe) item).supercharged;
} else if (item instanceof GemSickle) {
return ((GemSickle) item).supercharged;
} else if (item instanceof GemBow) {
return ((GemBow) item).supercharged;
} else {
LogHelper.debug("Called ToolHelper.getToolIsSupercharged on a non-Gems tool!");
return false;
}
}
/**
* Gets the material ID for the given material, or -1 if it's not a recognized tool material.
*
* @param material
* @return
*/
public static int getIdFromMaterial(ItemStack material) {
Item item = material.getItem();
if (item instanceof Gem) {
return material.getItemDamage() & 0xF;
} else if (CraftingMaterial.doesStackMatch(material, Names.CHAOS_ESSENCE_PLUS_2)) {
return ModMaterials.CHAOS_GEM_ID;
} else if (item == Items.flint) {
return ModMaterials.FLINT_GEM_ID;
} else if (item == Items.fish) {
return ModMaterials.FISH_GEM_ID;
} else {
return -1;
}
}
public static ItemStack getCraftingMaterial(int gemId, boolean supercharged) {
if (gemId < EnumGem.values().length) {
return new ItemStack(ModItems.gem, 1, gemId | (supercharged ? 0x10 : 0));
}
switch (gemId) {
case ModMaterials.CHAOS_GEM_ID:
return CraftingMaterial.getStack(Names.CHAOS_ESSENCE_PLUS_2);
case ModMaterials.FLINT_GEM_ID:
return new ItemStack(Items.flint);
case ModMaterials.FISH_GEM_ID:
return new ItemStack(Items.fish);
default:
LogHelper.warning("ToolHelper.getCraftingMaterial: Unknown gem ID: " + gemId);
return null;
}
}
// Tooltip helpers
public static void addInformation(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
boolean keyControl = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)
|| Keyboard.isKeyDown(Keyboard.KEY_RCONTROL);
boolean keyShift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)
|| Keyboard.isKeyDown(Keyboard.KEY_RSHIFT);
String line;
// Old NBT warning.
if (hasOldNBT(tool)) {
addInformationOldNBT(tool, player, list, advanced);
return;
}
// Tool Upgrades
addInformationUpgrades(tool, player, list, advanced);
// Statistics
if (keyControl) {
addInformationStatistics(tool, player, list, advanced);
} else {
line = LocalizationHelper.getMiscText("PressCtrl");
list.add(EnumChatFormatting.YELLOW + line);
}
// Decoration debug
if (keyControl && keyShift) {
addInformationDecoDebug(tool, player, list, advanced);
}
// Chaos tools
int gemId = getToolGemId(tool);
if (gemId == ModMaterials.CHAOS_GEM_ID) {
Item item = tool.getItem();
// Work in progress warning
list.add(EnumChatFormatting.RED + "Work in progress, suggestions welcome.");
// No flying penalty
if (item instanceof GemPickaxe || item instanceof GemShovel || item instanceof GemAxe) {
line = LocalizationHelper.getMiscText("Tool.NoFlyingPenalty");
list.add(EnumChatFormatting.AQUA + line);
}
}
}
private static void addInformationUpgrades(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
String line;
// Tipped upgrades
int tip = getToolHeadTip(tool);
if (tip == 1) {
line = LocalizationHelper.getMiscText("Tool.IronTipped");
list.add(EnumChatFormatting.WHITE + line);
} else if (tip == 2) {
line = LocalizationHelper.getMiscText("Tool.DiamondTipped");
list.add(EnumChatFormatting.AQUA + line);
}
}
private static void addInformationStatistics(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
String line;
int amount;
String separator = EnumChatFormatting.DARK_GRAY
+ LocalizationHelper.getMiscText("Tool.Stats.Separator");
boolean isBow = tool.getItem() instanceof GemBow;
// Header
line = LocalizationHelper.getMiscText("Tool.Stats.Header");
list.add(EnumChatFormatting.YELLOW + line);
list.add(separator);
// Blocks mined
amount = getStatBlocksMined(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.Mined");
line = String.format(line, amount);
list.add(line);
// Blocks placed (mining tools only)
if (InventoryHelper.isGemMiningTool(tool)) {
amount = getStatBlocksPlaced(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.Placed");
line = String.format(line, amount);
list.add(line);
}
// Hits landed (I would like this to register arrow hits, WIP)
amount = getStatHitsLanded(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.Hits");
line = String.format(line, amount);
list.add(line);
// Shots fired (bows only)
if (isBow) {
amount = getStatShotsFired(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.ShotsFired");
line = String.format(line, amount);
list.add(line);
}
// Redecorated count
amount = getStatRedecorated(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.Redecorated");
line = String.format(line, amount);
list.add(line);
list.add(separator);
}
private static void addInformationDecoDebug(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
String line = "Deco:";
line += " HL:" + getToolHeadLeft(tool);
line += " HM:" + getToolHeadMiddle(tool);
line += " HR:" + getToolHeadRight(tool);
line += " RD:" + getToolRodDeco(tool);
line += " RW:" + getToolRodWool(tool);
line += " R:" + getToolRod(tool);
line += " T:" + getToolHeadTip(tool);
list.add(EnumChatFormatting.DARK_GRAY + line);
}
private static void addInformationOldNBT(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
String line;
line = LocalizationHelper.getMiscText("Tool.OldNBT1");
list.add(EnumChatFormatting.DARK_BLUE + line);
line = LocalizationHelper.getMiscText("Tool.OldNBT2");
list.add(EnumChatFormatting.DARK_BLUE + line);
}
// Mining, using, repairing, etc
/**
* Determines if a tool can be repaired with the given material in an anvil. It's not the desired why to repair tools,
* but it should be an option.
*
* @return True if the material can repair the tool, false otherwise.
*/
public static boolean getIsRepairable(ItemStack tool, ItemStack material) {
int baseMaterial = getToolGemId(tool);
boolean supercharged = getToolIsSupercharged(tool);
ItemStack correctMaterial = null;
if (baseMaterial < EnumGem.values().length) {
// Gem tools.
correctMaterial = new ItemStack(ModItems.gem, 1, baseMaterial | (supercharged ? 0x10 : 0));
} else if (baseMaterial == ModMaterials.FLINT_GEM_ID) {
// Flint tools.
correctMaterial = new ItemStack(Items.flint);
} else if (baseMaterial == ModMaterials.FISH_GEM_ID) {
// Fish tools.
correctMaterial = new ItemStack(Items.fish);
}
return correctMaterial != null && correctMaterial.getItem() == material.getItem()
&& correctMaterial.getItemDamage() == material.getItemDamage();
}
/**
* Gets the additional amount to add to the tool's max damage in getMaxDamage(ItemStack).
*
* @return The amount to add to max damage.
*/
public static int getDurabilityBoost(ItemStack tool) {
int tip = getToolHeadTip(tool);
switch (tip) {
case 2:
return Config.DURABILITY_BOOST_DIAMOND_TIP;
case 1:
return Config.DURABILITY_BOOST_IRON_TIP;
default:
return 0;
}
}
/**
* Adjusts the mining level of the tool if it has a tip upgrade.
*
* @param tool
* The tool.
* @param baseLevel
* The value returned by ItemTool.getHarvestLevel. May be -1 if the toolclasses is incorrect for the block
* being mined.
* @return The highest possible mining level, given the upgrades. Returns baseLevel if baseLevel is less than zero.
*/
public static int getAdjustedMiningLevel(ItemStack tool, int baseLevel) {
if (baseLevel < 0) {
return baseLevel;
}
int tip = getToolHeadTip(tool);
switch (tip) {
case 2:
return Math.max(baseLevel, Config.MINING_LEVEL_DIAMOND_TIP);
case 1:
return Math.max(baseLevel, Config.MINING_LEVEL_IRON_TIP);
default:
return baseLevel;
}
}
/**
* This controls the block placing ability of mining tools.
*/
public static boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y,
int z, int side, float hitX, float hitY, float hitZ) {
boolean used = false;
int toolSlot = player.inventory.currentItem;
int itemSlot = toolSlot + 1;
ItemStack nextStack = null;
ItemStack lastStack = player.inventory.getStackInSlot(8); // Slot 9 in hotbar
if (toolSlot < 8) {
// Get stack in slot after tool.
nextStack = player.inventory.getStackInSlot(itemSlot);
// If there's nothing there we can use, try slot 9 instead.
if (nextStack == null || (!(nextStack.getItem() instanceof ItemBlock)
&& !(nextStack.getItem() instanceof IPlaceable))) {
nextStack = lastStack;
}
if (nextStack != null) {
Item item = nextStack.getItem();
if (item instanceof ItemBlock || item instanceof IPlaceable) {
ForgeDirection d = ForgeDirection.VALID_DIRECTIONS[side];
int px = x + d.offsetX;
int py = y + d.offsetY;
int pz = z + d.offsetZ;
int playerX = (int) Math.floor(player.posX);
int playerY = (int) Math.floor(player.posY);
int playerZ = (int) Math.floor(player.posZ);
// Check for overlap with player, except for torches and torch bandolier
// if (Item.getIdFromItem(item) != Block.getIdFromBlock(Blocks.torch)
// && item != SRegistry.getItem(Names.TORCH_BANDOLIER) && px == playerX
// && (py == playerY || py == playerY + 1 || py == playerY - 1) && pz == playerZ) {
// return false;
// Check for block overlap with player, if necessary.
if (item instanceof ItemBlock) {
AxisAlignedBB blockBounds = AxisAlignedBB.getBoundingBox(px, py, pz, px + 1, py + 1,
pz + 1);
AxisAlignedBB playerBounds = player.boundingBox;
Block block = ((ItemBlock) item).field_150939_a;
if (block.getMaterial().blocksMovement() && playerBounds.intersectsWith(blockBounds)) {
return false;
}
}
used = item.onItemUse(nextStack, player, world, x, y, z, side, hitX, hitY, hitZ);
if (nextStack.stackSize < 1) {
nextStack = null;
player.inventory.setInventorySlotContents(itemSlot, null);
}
}
}
}
if (used) {
incrementStatBlocksPlaced(stack, 1);
}
return used;
}
/**
* Called by mining tools if block breaking isn't canceled.
*
* @return False in all cases, because this method is only called when Item.onBlockStartBreak returns false.
*/
public static boolean onBlockStartBreak(ItemStack stack, int x, int y, int z,
EntityPlayer player) {
// Number of blocks broken.
int amount = 1;
// Try to activate Area Miner enchantment.
if (EnchantmentHelper.getEnchantmentLevel(ModEnchantments.AOE_ID, stack) > 0) {
amount += EnchantmentAOE.tryActivate(stack, x, y, z, player);
}
// Increase number of blocks mined statistic.
ToolHelper.incrementStatBlocksMined(stack, amount);
return false;
}
public static void hitEntity(ItemStack tool) {
ToolHelper.incrementStatHitsLanded(tool, 1);
}
// NBT helper methods
private static int getTagByte(String name, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Get the requested value.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
if (!tags.hasKey(name)) {
return -1;
}
return tags.getByte(name);
}
private static void setTagByte(String name, int value, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Set the tag.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
tags.setByte(name, (byte) value);
}
private static int getTagInt(String name, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Get the requested value.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
if (!tags.hasKey(name)) {
return 0; // NOTE: This is 0, where the byte version is -1!
}
return tags.getInteger(name);
}
private static void setTagInt(String name, int value, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Set the tag.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
tags.setInteger(name, value);
}
// Tool design NBT
public static int getToolHeadLeft(ItemStack tool) {
return getTagByte(NBT_HEAD_L, tool);
}
public static void setToolHeadLeft(ItemStack tool, int id) {
setTagByte(NBT_HEAD_L, id, tool);
}
public static int getToolHeadMiddle(ItemStack tool) {
return getTagByte(NBT_HEAD_M, tool);
}
public static void setToolHeadMiddle(ItemStack tool, int id) {
setTagByte(NBT_HEAD_M, id, tool);
}
public static int getToolHeadRight(ItemStack tool) {
return getTagByte(NBT_HEAD_R, tool);
}
public static void setToolHeadRight(ItemStack tool, int id) {
setTagByte(NBT_HEAD_R, id, tool);
}
public static int getToolRodDeco(ItemStack tool) {
return getTagByte(NBT_ROD_DECO, tool);
}
public static void setToolRodDeco(ItemStack tool, int id) {
setTagByte(NBT_ROD_DECO, id, tool);
}
public static int getToolRodWool(ItemStack tool) {
return getTagByte(NBT_ROD_WOOL, tool);
}
public static void setToolRodWool(ItemStack tool, int id) {
setTagByte(NBT_ROD_WOOL, id, tool);
}
public static int getToolRod(ItemStack tool) {
return getTagByte(NBT_ROD, tool);
}
public static void setToolRod(ItemStack tool, int id) {
setTagByte(NBT_ROD, id, tool);
}
public static int getToolHeadTip(ItemStack tool) {
return getTagByte(NBT_TIP, tool);
}
public static void setToolHeadTip(ItemStack tool, int id) {
setTagByte(NBT_TIP, id, tool);
}
public static boolean getToolNoGlint(ItemStack tool) {
return getTagByte(NBT_NO_GLINT, tool) > 0;
}
public static void setToolNoGlint(ItemStack tool, boolean value) {
setTagByte(NBT_NO_GLINT, value ? 1 : 0, tool);
}
// Statistics NBT
public static int getStatBlocksMined(ItemStack tool) {
return getTagInt(NBT_STATS_BLOCKS_MINED, tool);
}
public static void incrementStatBlocksMined(ItemStack tool, int amount) {
setTagInt(NBT_STATS_BLOCKS_MINED, getStatBlocksMined(tool) + amount, tool);
}
public static int getStatBlocksPlaced(ItemStack tool) {
return getTagInt(NBT_STATS_BLOCKS_PLACED, tool);
}
public static void incrementStatBlocksPlaced(ItemStack tool, int amount) {
setTagInt(NBT_STATS_BLOCKS_PLACED, getStatBlocksPlaced(tool) + amount, tool);
}
public static int getStatHitsLanded(ItemStack tool) {
return getTagInt(NBT_STATS_HITS, tool);
}
public static void incrementStatHitsLanded(ItemStack tool, int amount) {
setTagInt(NBT_STATS_HITS, getStatHitsLanded(tool) + amount, tool);
}
public static int getStatRedecorated(ItemStack tool) {
return getTagInt(NBT_STATS_REDECORATED, tool);
}
public static void incrementStatRedecorated(ItemStack tool, int amount) {
setTagInt(NBT_STATS_REDECORATED, getStatRedecorated(tool) + amount, tool);
}
public static int getStatShotsFired(ItemStack tool) {
return getTagInt(NBT_STATS_SHOTS_FIRED, tool);
}
public static void incrementStatShotsFired(ItemStack tool, int amount) {
setTagInt(NBT_STATS_SHOTS_FIRED, getStatShotsFired(tool) + amount, tool);
}
// NBT converter methods
private static int getOldTag(ItemStack tool, String name) {
if (!tool.stackTagCompound.hasKey(name)) {
return -1;
}
return tool.stackTagCompound.getByte(name);
}
private static void removeOldTag(ItemStack tool, String name) {
tool.stackTagCompound.removeTag(name);
}
public static boolean hasOldNBT(ItemStack tool) {
return convertToNewNBT(tool.copy());
}
public static boolean convertToNewNBT(ItemStack tool) {
if (tool == null || tool.stackTagCompound == null || !InventoryHelper.isGemTool(tool)) {
return false;
}
boolean updated = false;
int headL = getOldTag(tool, "HeadL");
int headM = getOldTag(tool, "HeadM");
int headR = getOldTag(tool, "HeadR");
int rodDeco = getOldTag(tool, "Deco");
int rodWool = getOldTag(tool, "Rod");
int rod = getOldTag(tool, "Handle");
int tip = getOldTag(tool, "Tip");
if (headL > -1) {
setToolHeadLeft(tool, headL);
removeOldTag(tool, "HeadL");
updated = true;
}
if (headM > -1) {
setToolHeadMiddle(tool, headM);
removeOldTag(tool, "HeadM");
updated = true;
}
if (headR > -1) {
setToolHeadRight(tool, headR);
removeOldTag(tool, "HeadR");
updated = true;
}
if (rodDeco > -1) {
setToolRodDeco(tool, rodDeco);
removeOldTag(tool, "Deco");
updated = true;
}
if (rodWool > -1) {
setToolRodWool(tool, rodWool);
removeOldTag(tool, "Rod");
updated = true;
}
if (rod > -1) {
setToolRod(tool, rod);
removeOldTag(tool, "Handle");
updated = true;
}
if (tip > -1) {
setToolHeadTip(tool, tip);
removeOldTag(tool, "Tip");
updated = true;
}
return updated;
}
}
|
package net.silentchaos512.gems.lib;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.common.ForgeHooks;
import net.silentchaos512.gems.SilentGems;
import net.silentchaos512.lib.util.ChatHelper;
import net.silentchaos512.lib.util.PlayerHelper;
public class Greetings {
public static boolean IS_BETA_BUILD = false;
public static final String PREFIX = "[Silent's Gems] BETA: ";
// @formatter:off
public static final String[] LINES = new String[] {
"Try the new Tool Soul item! Also works on armor, in spite of the name... Check the guide for info. Any feedback is appreciated."
};
// @formatter:on
static List<String> extraMessages = Lists.newArrayList();
// For the strawpoll, so we don't spam players too much.
static Set<String> strawpollNotifiedPlayers = Sets.newHashSet();
/**
* Adds messages to the player's chat log. Use addExtraMessage to add messages to the list.
*/
public static void greetPlayer(EntityPlayer player) {
if (IS_BETA_BUILD)
doBetaGreeting(player);
// Strawpoll notification (new difficulty poll)
Calendar cal = Calendar.getInstance();
boolean strawpollNotExpired = cal.get(Calendar.YEAR) == 2017 && cal.get(Calendar.MONTH) <= Calendar.OCTOBER;
if (strawpollNotExpired && !strawpollNotifiedPlayers.contains(player.getName())) {
player.sendMessage(ForgeHooks.newChatWithLinks(TextFormatting.DARK_PURPLE
+ "[Silent's Gems]" + TextFormatting.RESET
+ " I'm looking for some feedback on difficulty. Your vote would be greatly appreciated!"
+ " http:
strawpollNotifiedPlayers.add(player.getName());
}
for (String str : extraMessages)
ChatHelper.sendMessage(player, "[Silent's Gems] " + str);
}
/**
* Random, funny beta greetings. Will be disabled in version 2.1.
*/
public static void doBetaGreeting(EntityPlayer player) {
// Reset the random object, because it seems to yield the same value each time. Huh?
SilentGems.instance.random.setSeed(System.currentTimeMillis());
String line = LINES[SilentGems.random.nextInt(LINES.length)];
line = PREFIX + line;
line = line.replaceAll("&", "\u00a7");
ChatHelper.sendMessage(player, TextFormatting.RED + line);
}
/**
* Add an additional message to display when the player logs in to a world.
*/
public static void addExtraMessage(String str) {
extraMessages.add(str);
}
}
|
package mtr.model;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import mtr.mappings.ModelDataWrapper;
import mtr.mappings.ModelMapper;
public class ModelClass802 extends ModelTrainBase {
private final ModelMapper window;
private final ModelMapper roof_3_r1;
private final ModelMapper roof_1_r1;
private final ModelMapper window_bottom_r1;
private final ModelMapper window_top_r1;
private final ModelMapper window_light;
private final ModelMapper window_exterior_1;
private final ModelMapper roof_2_r1;
private final ModelMapper roof_1_r2;
private final ModelMapper window_bottom_r2;
private final ModelMapper window_top_r2;
private final ModelMapper window_exterior_2;
private final ModelMapper roof_2_r2;
private final ModelMapper roof_1_r3;
private final ModelMapper window_bottom_r3;
private final ModelMapper window_top_r3;
private final ModelMapper window_exterior_3;
private final ModelMapper roof_2_r3;
private final ModelMapper roof_1_r4;
private final ModelMapper window_bottom_r4;
private final ModelMapper window_top_r4;
private final ModelMapper window_exterior_4;
private final ModelMapper roof_2_r4;
private final ModelMapper roof_1_r5;
private final ModelMapper window_bottom_r5;
private final ModelMapper window_top_r5;
private final ModelMapper window_exterior_5;
private final ModelMapper roof_2_r5;
private final ModelMapper roof_1_r6;
private final ModelMapper window_bottom_r6;
private final ModelMapper window_top_r6;
private final ModelMapper window_exterior_6;
private final ModelMapper roof_2_r6;
private final ModelMapper roof_1_r7;
private final ModelMapper window_bottom_r7;
private final ModelMapper window_top_r7;
private final ModelMapper window_exterior_7;
private final ModelMapper roof_2_r7;
private final ModelMapper roof_1_r8;
private final ModelMapper window_bottom_r8;
private final ModelMapper window_top_r8;
private final ModelMapper window_exterior_8;
private final ModelMapper roof_2_r8;
private final ModelMapper roof_1_r9;
private final ModelMapper window_bottom_r9;
private final ModelMapper window_top_r9;
private final ModelMapper window_exterior_9;
private final ModelMapper roof_2_r9;
private final ModelMapper roof_1_r10;
private final ModelMapper window_bottom_r10;
private final ModelMapper window_top_r10;
private final ModelMapper window_end_exterior_1;
private final ModelMapper window_end_exterior_1_1;
private final ModelMapper roof_2_r10;
private final ModelMapper roof_1_r11;
private final ModelMapper window_bottom_r11;
private final ModelMapper window_top_r11;
private final ModelMapper window_end_exterior_1_2;
private final ModelMapper roof_3_r2;
private final ModelMapper roof_2_r11;
private final ModelMapper window_bottom_r12;
private final ModelMapper window_top_r12;
private final ModelMapper window_end_exterior_2;
private final ModelMapper window_end_exterior_2_1;
private final ModelMapper roof_3_r3;
private final ModelMapper roof_2_r12;
private final ModelMapper window_bottom_r13;
private final ModelMapper window_top_r13;
private final ModelMapper window_end_exterior_2_2;
private final ModelMapper roof_4_r1;
private final ModelMapper roof_3_r4;
private final ModelMapper window_bottom_r14;
private final ModelMapper window_top_r14;
private final ModelMapper window_end_exterior_3;
private final ModelMapper window_end_exterior_3_1;
private final ModelMapper roof_4_r2;
private final ModelMapper roof_3_r5;
private final ModelMapper window_bottom_r15;
private final ModelMapper window_top_r15;
private final ModelMapper window_end_exterior_3_2;
private final ModelMapper roof_5_r1;
private final ModelMapper roof_4_r3;
private final ModelMapper window_bottom_r16;
private final ModelMapper window_top_r16;
private final ModelMapper window_end_exterior_4;
private final ModelMapper window_end_exterior_4_1;
private final ModelMapper roof_4_r4;
private final ModelMapper roof_3_r6;
private final ModelMapper window_bottom_r17;
private final ModelMapper window_top_r17;
private final ModelMapper window_end_exterior_4_2;
private final ModelMapper roof_5_r2;
private final ModelMapper roof_4_r5;
private final ModelMapper window_bottom_r18;
private final ModelMapper window_top_r18;
private final ModelMapper window_end_exterior_5;
private final ModelMapper window_end_exterior_5_1;
private final ModelMapper roof_5_r3;
private final ModelMapper roof_4_r6;
private final ModelMapper window_bottom_r19;
private final ModelMapper window_top_r19;
private final ModelMapper window_end_exterior_5_2;
private final ModelMapper roof_6_r1;
private final ModelMapper roof_5_r4;
private final ModelMapper window_bottom_r20;
private final ModelMapper window_top_r20;
private final ModelMapper window_end_exterior_6;
private final ModelMapper window_end_exterior_6_1;
private final ModelMapper roof_6_r2;
private final ModelMapper roof_5_r5;
private final ModelMapper window_bottom_r21;
private final ModelMapper window_top_r21;
private final ModelMapper window_end_exterior_6_2;
private final ModelMapper roof_7_r1;
private final ModelMapper roof_6_r3;
private final ModelMapper window_bottom_r22;
private final ModelMapper window_top_r22;
private final ModelMapper door;
private final ModelMapper door_1;
private final ModelMapper window_bottom_2_r1;
private final ModelMapper window_top_2_r1;
private final ModelMapper door_2;
private final ModelMapper window_bottom_3_r1;
private final ModelMapper window_top_3_r1;
private final ModelMapper door_exterior;
private final ModelMapper door_exterior_1;
private final ModelMapper window_bottom_1_r1;
private final ModelMapper window_top_1_r1;
private final ModelMapper door_exterior_2;
private final ModelMapper window_bottom_2_r2;
private final ModelMapper window_top_2_r2;
private final ModelMapper door_exterior_end;
private final ModelMapper door_exterior_end_1;
private final ModelMapper window_bottom_2_r3;
private final ModelMapper window_top_2_r3;
private final ModelMapper door_exterior_end_2;
private final ModelMapper window_bottom_3_r2;
private final ModelMapper window_top_3_r2;
private final ModelMapper roof_exterior;
private final ModelMapper end;
private final ModelMapper end_pillar_4_r1;
private final ModelMapper end_pillar_3_r1;
private final ModelMapper end_side_1;
private final ModelMapper roof_3_r7;
private final ModelMapper roof_1_r12;
private final ModelMapper window_bottom_r23;
private final ModelMapper window_top_r23;
private final ModelMapper end_side_2;
private final ModelMapper roof_4_r7;
private final ModelMapper roof_2_r13;
private final ModelMapper window_bottom_r24;
private final ModelMapper window_top_r24;
private final ModelMapper end_light;
private final ModelMapper end_translucent;
private final ModelMapper end_exterior;
private final ModelMapper end_exterior_side_1;
private final ModelMapper roof_4_r8;
private final ModelMapper roof_3_r8;
private final ModelMapper door_top_r1;
private final ModelMapper window_bottom_2_r4;
private final ModelMapper end_exterior_side_2;
private final ModelMapper roof_5_r6;
private final ModelMapper roof_4_r9;
private final ModelMapper door_top_r2;
private final ModelMapper window_bottom_3_r3;
private final ModelMapper roof_vent;
private final ModelMapper roof_vent_side_1;
private final ModelMapper vent_4_r1;
private final ModelMapper vent_3_r1;
private final ModelMapper vent_1_r1;
private final ModelMapper roof_vent_side_2;
private final ModelMapper vent_5_r1;
private final ModelMapper vent_4_r2;
private final ModelMapper vent_2_r1;
private final ModelMapper head_exterior;
private final ModelMapper head_side_1;
private final ModelMapper roof_4_r10;
private final ModelMapper roof_3_r9;
private final ModelMapper window_top_1_r2;
private final ModelMapper window_bottom_1_r2;
private final ModelMapper end_r1;
private final ModelMapper roof_11_r1;
private final ModelMapper roof_12_r1;
private final ModelMapper roof_11_r2;
private final ModelMapper roof_10_r1;
private final ModelMapper roof_10_r2;
private final ModelMapper roof_11_r3;
private final ModelMapper roof_10_r3;
private final ModelMapper roof_9_r1;
private final ModelMapper roof_8_r1;
private final ModelMapper roof_7_r2;
private final ModelMapper roof_4_r11;
private final ModelMapper roof_4_r12;
private final ModelMapper roof_3_r10;
private final ModelMapper roof_2_r14;
private final ModelMapper roof_3_r11;
private final ModelMapper roof_2_r15;
private final ModelMapper roof_1_r13;
private final ModelMapper head_side_2;
private final ModelMapper roof_5_r7;
private final ModelMapper roof_4_r13;
private final ModelMapper window_top_2_r4;
private final ModelMapper window_bottom_2_r5;
private final ModelMapper end_r2;
private final ModelMapper roof_12_r2;
private final ModelMapper roof_13_r1;
private final ModelMapper roof_12_r3;
private final ModelMapper roof_11_r4;
private final ModelMapper roof_11_r5;
private final ModelMapper roof_12_r4;
private final ModelMapper roof_11_r6;
private final ModelMapper roof_10_r4;
private final ModelMapper roof_9_r2;
private final ModelMapper roof_8_r2;
private final ModelMapper roof_5_r8;
private final ModelMapper roof_5_r9;
private final ModelMapper roof_4_r14;
private final ModelMapper roof_3_r12;
private final ModelMapper roof_4_r15;
private final ModelMapper roof_3_r13;
private final ModelMapper roof_2_r16;
private final ModelMapper middle;
private final ModelMapper roof_8_r3;
private final ModelMapper roof_7_r3;
private final ModelMapper roof_6_r4;
private final ModelMapper roof_5_r10;
private final ModelMapper roof_9_r3;
private final ModelMapper bottom_middle;
private final ModelMapper bottom_end;
private final ModelMapper seat;
private final ModelMapper seat_2_r1;
private final ModelMapper headlights;
private final ModelMapper headlight_2_r1;
private final ModelMapper headlight_1_r1;
private final ModelMapper tail_lights;
private final ModelMapper tail_lights_2_r1;
private final ModelMapper tail_lights_1_r1;
private final ModelMapper door_light_off;
private final ModelMapper door_light_off_r1;
private final ModelMapper door_light_on;
private final ModelMapper door_light_on_r1;
public ModelClass802() {
final int textureWidth = 432;
final int textureHeight = 432;
final ModelDataWrapper modelDataWrapper = new ModelDataWrapper(this, textureWidth, textureHeight);
window = new ModelMapper(modelDataWrapper);
window.setPos(0, 24, 0);
window.texOffs(230, 139).addBox(-19, 0, -15, 19, 1, 30, 0, false);
window.texOffs(82, 201).addBox(-20, -13, -15, 0, 6, 30, 0, false);
window.texOffs(30, 53).addBox(-15, -36, -15, 6, 0, 30, 0, false);
window.texOffs(0, 0).addBox(-7, -35, -15, 7, 0, 30, 0, false);
window.texOffs(237, 36).addBox(-18, -31, -15, 6, 1, 30, 0, false);
roof_3_r1 = new ModelMapper(modelDataWrapper);
roof_3_r1.setPos(-7, -35, 0);
window.addChild(roof_3_r1);
setRotationAngle(roof_3_r1, 0, 0, 0.3491F);
roof_3_r1.texOffs(14, 0).addBox(-3, 0, -15, 3, 0, 30, 0, false);
roof_1_r1 = new ModelMapper(modelDataWrapper);
roof_1_r1.setPos(-15, -36, 0);
window.addChild(roof_1_r1);
setRotationAngle(roof_1_r1, 0, 0, -0.7854F);
roof_1_r1.texOffs(49, 0).addBox(-3, 0, -15, 3, 0, 30, 0, false);
window_bottom_r1 = new ModelMapper(modelDataWrapper);
window_bottom_r1.setPos(-21, -7, 0);
window.addChild(window_bottom_r1);
setRotationAngle(window_bottom_r1, 0, 0, -0.2094F);
window_bottom_r1.texOffs(0, 120).addBox(1, 0, -15, 0, 8, 30, 0, false);
window_top_r1 = new ModelMapper(modelDataWrapper);
window_top_r1.setPos(-21, -13, 0);
window.addChild(window_top_r1);
setRotationAngle(window_top_r1, 0, 0, 0.1396F);
window_top_r1.texOffs(227, 205).addBox(1, -22, -15, 0, 22, 30, 0, false);
window_light = new ModelMapper(modelDataWrapper);
window_light.setPos(0, 24, 0);
window_light.texOffs(283, 44).addBox(-7, -35.1F, -15, 4, 0, 30, 0, false);
window_exterior_1 = new ModelMapper(modelDataWrapper);
window_exterior_1.setPos(0, 24, 0);
window_exterior_1.texOffs(32, 251).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r1 = new ModelMapper(modelDataWrapper);
roof_2_r1.setPos(-10.1709F, -40.8501F, 0);
window_exterior_1.addChild(roof_2_r1);
setRotationAngle(roof_2_r1, 0, 0, 1.0472F);
roof_2_r1.texOffs(32, 356).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r2 = new ModelMapper(modelDataWrapper);
roof_1_r2.setPos(-17.9382F, -34.7859F, 0);
window_exterior_1.addChild(roof_1_r2);
setRotationAngle(roof_1_r2, 0, 0, 0.6981F);
roof_1_r2.texOffs(299, 311).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r2 = new ModelMapper(modelDataWrapper);
window_bottom_r2.setPos(-21, -7, 0);
window_exterior_1.addChild(window_bottom_r2);
setRotationAngle(window_bottom_r2, 0, 0, -0.2094F);
window_bottom_r2.texOffs(203, 313).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r2 = new ModelMapper(modelDataWrapper);
window_top_r2.setPos(-21, -13, 0);
window_exterior_1.addChild(window_top_r2);
setRotationAngle(window_top_r2, 0, 0, 0.1396F);
window_top_r2.texOffs(82, 229).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_2 = new ModelMapper(modelDataWrapper);
window_exterior_2.setPos(0, 24, 0);
window_exterior_2.texOffs(160, 198).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r2 = new ModelMapper(modelDataWrapper);
roof_2_r2.setPos(-10.1709F, -40.8501F, 0);
window_exterior_2.addChild(roof_2_r2);
setRotationAngle(roof_2_r2, 0, 0, 1.0472F);
roof_2_r2.texOffs(331, 355).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r3 = new ModelMapper(modelDataWrapper);
roof_1_r3.setPos(-17.9382F, -34.7859F, 0);
window_exterior_2.addChild(roof_1_r3);
setRotationAngle(roof_1_r3, 0, 0, 0.6981F);
roof_1_r3.texOffs(299, 307).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r3 = new ModelMapper(modelDataWrapper);
window_bottom_r3.setPos(-21, -7, 0);
window_exterior_2.addChild(window_bottom_r3);
setRotationAngle(window_bottom_r3, 0, 0, -0.2094F);
window_bottom_r3.texOffs(313, 54).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r3 = new ModelMapper(modelDataWrapper);
window_top_r3.setPos(-21, -13, 0);
window_exterior_2.addChild(window_top_r3);
setRotationAngle(window_top_r3, 0, 0, 0.1396F);
window_top_r3.texOffs(160, 164).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_3 = new ModelMapper(modelDataWrapper);
window_exterior_3.setPos(0, 24, 0);
window_exterior_3.texOffs(160, 192).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r3 = new ModelMapper(modelDataWrapper);
roof_2_r3.setPos(-10.1709F, -40.8501F, 0);
window_exterior_3.addChild(roof_2_r3);
setRotationAngle(roof_2_r3, 0, 0, 1.0472F);
roof_2_r3.texOffs(221, 354).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r4 = new ModelMapper(modelDataWrapper);
roof_1_r4.setPos(-17.9382F, -34.7859F, 0);
window_exterior_3.addChild(roof_1_r4);
setRotationAngle(roof_1_r4, 0, 0, 0.6981F);
roof_1_r4.texOffs(299, 303).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r4 = new ModelMapper(modelDataWrapper);
window_bottom_r4.setPos(-21, -7, 0);
window_exterior_3.addChild(window_bottom_r4);
setRotationAngle(window_bottom_r4, 0, 0, -0.2094F);
window_bottom_r4.texOffs(0, 312).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r4 = new ModelMapper(modelDataWrapper);
window_top_r4.setPos(-21, -13, 0);
window_exterior_3.addChild(window_top_r4);
setRotationAngle(window_top_r4, 0, 0, 0.1396F);
window_top_r4.texOffs(98, 164).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_4 = new ModelMapper(modelDataWrapper);
window_exterior_4.setPos(0, 24, 0);
window_exterior_4.texOffs(98, 192).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r4 = new ModelMapper(modelDataWrapper);
roof_2_r4.setPos(-10.1709F, -40.8501F, 0);
window_exterior_4.addChild(roof_2_r4);
setRotationAngle(roof_2_r4, 0, 0, 1.0472F);
roof_2_r4.texOffs(299, 352).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r5 = new ModelMapper(modelDataWrapper);
roof_1_r5.setPos(-17.9382F, -34.7859F, 0);
window_exterior_4.addChild(roof_1_r5);
setRotationAngle(roof_1_r5, 0, 0, 0.6981F);
roof_1_r5.texOffs(299, 299).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r5 = new ModelMapper(modelDataWrapper);
window_bottom_r5.setPos(-21, -7, 0);
window_exterior_4.addChild(window_bottom_r5);
setRotationAngle(window_bottom_r5, 0, 0, -0.2094F);
window_bottom_r5.texOffs(94, 310).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r5 = new ModelMapper(modelDataWrapper);
window_top_r5.setPos(-21, -13, 0);
window_exterior_4.addChild(window_top_r5);
setRotationAngle(window_top_r5, 0, 0, 0.1396F);
window_top_r5.texOffs(161, 0).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_5 = new ModelMapper(modelDataWrapper);
window_exterior_5.setPos(0, 24, 0);
window_exterior_5.texOffs(0, 192).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r5 = new ModelMapper(modelDataWrapper);
roof_2_r5.setPos(-10.1709F, -40.8501F, 0);
window_exterior_5.addChild(roof_2_r5);
setRotationAngle(roof_2_r5, 0, 0, 1.0472F);
roof_2_r5.texOffs(189, 351).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r6 = new ModelMapper(modelDataWrapper);
roof_1_r6.setPos(-17.9382F, -34.7859F, 0);
window_exterior_5.addChild(roof_1_r6);
setRotationAngle(roof_1_r6, 0, 0, 0.6981F);
roof_1_r6.texOffs(297, 256).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r6 = new ModelMapper(modelDataWrapper);
window_bottom_r6.setPos(-21, -7, 0);
window_exterior_5.addChild(window_bottom_r6);
setRotationAngle(window_bottom_r6, 0, 0, -0.2094F);
window_bottom_r6.texOffs(298, 147).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r6 = new ModelMapper(modelDataWrapper);
window_top_r6.setPos(-21, -13, 0);
window_exterior_5.addChild(window_top_r6);
setRotationAngle(window_top_r6, 0, 0, 0.1396F);
window_top_r6.texOffs(160, 142).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_6 = new ModelMapper(modelDataWrapper);
window_exterior_6.setPos(0, 24, 0);
window_exterior_6.texOffs(160, 186).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r6 = new ModelMapper(modelDataWrapper);
roof_2_r6.setPos(-10.1709F, -40.8501F, 0);
window_exterior_6.addChild(roof_2_r6);
setRotationAngle(roof_2_r6, 0, 0, 1.0472F);
roof_2_r6.texOffs(0, 350).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r7 = new ModelMapper(modelDataWrapper);
roof_1_r7.setPos(-17.9382F, -34.7859F, 0);
window_exterior_6.addChild(roof_1_r7);
setRotationAngle(roof_1_r7, 0, 0, 0.6981F);
roof_1_r7.texOffs(158, 290).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r7 = new ModelMapper(modelDataWrapper);
window_bottom_r7.setPos(-21, -7, 0);
window_exterior_6.addChild(window_bottom_r7);
setRotationAngle(window_bottom_r7, 0, 0, -0.2094F);
window_bottom_r7.texOffs(298, 109).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r7 = new ModelMapper(modelDataWrapper);
window_top_r7.setPos(-21, -13, 0);
window_exterior_6.addChild(window_top_r7);
setRotationAngle(window_top_r7, 0, 0, 0.1396F);
window_top_r7.texOffs(158, 100).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_7 = new ModelMapper(modelDataWrapper);
window_exterior_7.setPos(0, 24, 0);
window_exterior_7.texOffs(98, 186).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r7 = new ModelMapper(modelDataWrapper);
roof_2_r7.setPos(-10.1709F, -40.8501F, 0);
window_exterior_7.addChild(roof_2_r7);
setRotationAngle(roof_2_r7, 0, 0, 1.0472F);
roof_2_r7.texOffs(92, 348).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r8 = new ModelMapper(modelDataWrapper);
roof_1_r8.setPos(-17.9382F, -34.7859F, 0);
window_exterior_7.addChild(roof_1_r8);
setRotationAngle(roof_1_r8, 0, 0, 0.6981F);
roof_1_r8.texOffs(158, 286).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r8 = new ModelMapper(modelDataWrapper);
window_bottom_r8.setPos(-21, -7, 0);
window_exterior_7.addChild(window_bottom_r8);
setRotationAngle(window_bottom_r8, 0, 0, -0.2094F);
window_bottom_r8.texOffs(297, 291).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r8 = new ModelMapper(modelDataWrapper);
window_top_r8.setPos(-21, -13, 0);
window_exterior_7.addChild(window_top_r8);
setRotationAngle(window_top_r8, 0, 0, 0.1396F);
window_top_r8.texOffs(158, 78).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_8 = new ModelMapper(modelDataWrapper);
window_exterior_8.setPos(0, 24, 0);
window_exterior_8.texOffs(0, 186).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r8 = new ModelMapper(modelDataWrapper);
roof_2_r8.setPos(-10.1709F, -40.8501F, 0);
window_exterior_8.addChild(roof_2_r8);
setRotationAngle(roof_2_r8, 0, 0, 1.0472F);
roof_2_r8.texOffs(345, 33).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r9 = new ModelMapper(modelDataWrapper);
roof_1_r9.setPos(-17.9382F, -34.7859F, 0);
window_exterior_8.addChild(roof_1_r9);
setRotationAngle(roof_1_r9, 0, 0, 0.6981F);
roof_1_r9.texOffs(281, 70).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r9 = new ModelMapper(modelDataWrapper);
window_bottom_r9.setPos(-21, -7, 0);
window_exterior_8.addChild(window_bottom_r9);
setRotationAngle(window_bottom_r9, 0, 0, -0.2094F);
window_bottom_r9.texOffs(296, 245).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r9 = new ModelMapper(modelDataWrapper);
window_top_r9.setPos(-21, -13, 0);
window_exterior_8.addChild(window_top_r9);
setRotationAngle(window_top_r9, 0, 0, 0.1396F);
window_top_r9.texOffs(158, 56).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_exterior_9 = new ModelMapper(modelDataWrapper);
window_exterior_9.setPos(0, 24, 0);
window_exterior_9.texOffs(0, 180).addBox(-21, -13, -15, 0, 6, 30, 0, false);
roof_2_r9 = new ModelMapper(modelDataWrapper);
roof_2_r9.setPos(-10.1709F, -40.8501F, 0);
window_exterior_9.addChild(roof_2_r9);
setRotationAngle(roof_2_r9, 0, 0, 1.0472F);
roof_2_r9.texOffs(330, 125).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r10 = new ModelMapper(modelDataWrapper);
roof_1_r10.setPos(-17.9382F, -34.7859F, 0);
window_exterior_9.addChild(roof_1_r10);
setRotationAngle(roof_1_r10, 0, 0, 0.6981F);
roof_1_r10.texOffs(281, 66).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r10 = new ModelMapper(modelDataWrapper);
window_bottom_r10.setPos(-21, -7, 0);
window_exterior_9.addChild(window_bottom_r10);
setRotationAngle(window_bottom_r10, 0, 0, -0.2094F);
window_bottom_r10.texOffs(296, 205).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r10 = new ModelMapper(modelDataWrapper);
window_top_r10.setPos(-21, -13, 0);
window_exterior_9.addChild(window_top_r10);
setRotationAngle(window_top_r10, 0, 0, 0.1396F);
window_top_r10.texOffs(0, 158).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_end_exterior_1 = new ModelMapper(modelDataWrapper);
window_end_exterior_1.setPos(0, 24, 0);
window_end_exterior_1_1 = new ModelMapper(modelDataWrapper);
window_end_exterior_1_1.setPos(-10.1709F, -40.8501F, 0);
window_end_exterior_1.addChild(window_end_exterior_1_1);
window_end_exterior_1_1.texOffs(161, 46).addBox(-10.8291F, 27.8501F, -15, 0, 6, 30, 0, false);
roof_2_r10 = new ModelMapper(modelDataWrapper);
roof_2_r10.setPos(0, 0, 0);
window_end_exterior_1_1.addChild(roof_2_r10);
setRotationAngle(roof_2_r10, 0, 0, 1.0472F);
roof_2_r10.texOffs(330, 92).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_1_r11 = new ModelMapper(modelDataWrapper);
roof_1_r11.setPos(-7.7673F, 6.0642F, 0);
window_end_exterior_1_1.addChild(roof_1_r11);
setRotationAngle(roof_1_r11, 0, 0, 0.6981F);
roof_1_r11.texOffs(281, 62).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r11 = new ModelMapper(modelDataWrapper);
window_bottom_r11.setPos(-10.8291F, 33.8501F, 0);
window_end_exterior_1_1.addChild(window_bottom_r11);
setRotationAngle(window_bottom_r11, 0, 0, -0.2094F);
window_bottom_r11.texOffs(287, 6).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r11 = new ModelMapper(modelDataWrapper);
window_top_r11.setPos(-10.8291F, 27.8501F, 0);
window_end_exterior_1_1.addChild(window_top_r11);
setRotationAngle(window_top_r11, 0, 0, 0.1396F);
window_top_r11.texOffs(98, 142).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_end_exterior_1_2 = new ModelMapper(modelDataWrapper);
window_end_exterior_1_2.setPos(10.1709F, -40.8501F, 0);
window_end_exterior_1.addChild(window_end_exterior_1_2);
window_end_exterior_1_2.texOffs(161, 46).addBox(10.8291F, 27.8501F, -15, 0, 6, 30, 0, true);
roof_3_r2 = new ModelMapper(modelDataWrapper);
roof_3_r2.setPos(0, 0, 0);
window_end_exterior_1_2.addChild(roof_3_r2);
setRotationAngle(roof_3_r2, 0, 0, -1.0472F);
roof_3_r2.texOffs(330, 92).addBox(-1, 3, -15, 1, 3, 30, 0, true);
roof_2_r11 = new ModelMapper(modelDataWrapper);
roof_2_r11.setPos(7.7673F, 6.0642F, 0);
window_end_exterior_1_2.addChild(roof_2_r11);
setRotationAngle(roof_2_r11, 0, 0, -0.6981F);
roof_2_r11.texOffs(281, 62).addBox(0, -4, -15, 0, 4, 30, 0, true);
window_bottom_r12 = new ModelMapper(modelDataWrapper);
window_bottom_r12.setPos(10.8291F, 33.8501F, 0);
window_end_exterior_1_2.addChild(window_bottom_r12);
setRotationAngle(window_bottom_r12, 0, 0, 0.2094F);
window_bottom_r12.texOffs(287, 6).addBox(-1, 0, -15, 1, 8, 30, 0, true);
window_top_r12 = new ModelMapper(modelDataWrapper);
window_top_r12.setPos(10.8291F, 27.8501F, 0);
window_end_exterior_1_2.addChild(window_top_r12);
setRotationAngle(window_top_r12, 0, 0, -0.1396F);
window_top_r12.texOffs(98, 142).addBox(0, -22, -15, 0, 22, 30, 0, true);
window_end_exterior_2 = new ModelMapper(modelDataWrapper);
window_end_exterior_2.setPos(0, 24, 0);
window_end_exterior_2_1 = new ModelMapper(modelDataWrapper);
window_end_exterior_2_1.setPos(-10.1709F, -40.8501F, 0);
window_end_exterior_2.addChild(window_end_exterior_2_1);
window_end_exterior_2_1.texOffs(161, 34).addBox(-10.8291F, 27.8501F, -15, 0, 6, 30, 0, false);
roof_3_r3 = new ModelMapper(modelDataWrapper);
roof_3_r3.setPos(0, 0, 0);
window_end_exterior_2_1.addChild(roof_3_r3);
setRotationAngle(roof_3_r3, 0, 0, 1.0472F);
roof_3_r3.texOffs(329, 319).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_2_r12 = new ModelMapper(modelDataWrapper);
roof_2_r12.setPos(-7.7673F, 6.0642F, 0);
window_end_exterior_2_1.addChild(roof_2_r12);
setRotationAngle(roof_2_r12, 0, 0, 0.6981F);
roof_2_r12.texOffs(278, 167).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r13 = new ModelMapper(modelDataWrapper);
window_bottom_r13.setPos(-10.8291F, 33.8501F, 0);
window_end_exterior_2_1.addChild(window_bottom_r13);
setRotationAngle(window_bottom_r13, 0, 0, -0.2094F);
window_bottom_r13.texOffs(265, 283).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r13 = new ModelMapper(modelDataWrapper);
window_top_r13.setPos(-10.8291F, 27.8501F, 0);
window_end_exterior_2_1.addChild(window_top_r13);
setRotationAngle(window_top_r13, 0, 0, 0.1396F);
window_top_r13.texOffs(0, 136).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_end_exterior_2_2 = new ModelMapper(modelDataWrapper);
window_end_exterior_2_2.setPos(10.1709F, -40.8501F, 0);
window_end_exterior_2.addChild(window_end_exterior_2_2);
window_end_exterior_2_2.texOffs(161, 34).addBox(10.8291F, 27.8501F, -15, 0, 6, 30, 0, true);
roof_4_r1 = new ModelMapper(modelDataWrapper);
roof_4_r1.setPos(0, 0, 0);
window_end_exterior_2_2.addChild(roof_4_r1);
setRotationAngle(roof_4_r1, 0, 0, -1.0472F);
roof_4_r1.texOffs(329, 319).addBox(-1, 3, -15, 1, 3, 30, 0, true);
roof_3_r4 = new ModelMapper(modelDataWrapper);
roof_3_r4.setPos(7.7673F, 6.0642F, 0);
window_end_exterior_2_2.addChild(roof_3_r4);
setRotationAngle(roof_3_r4, 0, 0, -0.6981F);
roof_3_r4.texOffs(278, 167).addBox(0, -4, -15, 0, 4, 30, 0, true);
window_bottom_r14 = new ModelMapper(modelDataWrapper);
window_bottom_r14.setPos(10.8291F, 33.8501F, 0);
window_end_exterior_2_2.addChild(window_bottom_r14);
setRotationAngle(window_bottom_r14, 0, 0, 0.2094F);
window_bottom_r14.texOffs(265, 283).addBox(-1, 0, -15, 1, 8, 30, 0, true);
window_top_r14 = new ModelMapper(modelDataWrapper);
window_top_r14.setPos(10.8291F, 27.8501F, 0);
window_end_exterior_2_2.addChild(window_top_r14);
setRotationAngle(window_top_r14, 0, 0, -0.1396F);
window_top_r14.texOffs(0, 136).addBox(0, -22, -15, 0, 22, 30, 0, true);
window_end_exterior_3 = new ModelMapper(modelDataWrapper);
window_end_exterior_3.setPos(0, 24, 0);
window_end_exterior_3_1 = new ModelMapper(modelDataWrapper);
window_end_exterior_3_1.setPos(-10.1709F, -40.8501F, 0);
window_end_exterior_3.addChild(window_end_exterior_3_1);
window_end_exterior_3_1.texOffs(161, 28).addBox(-10.8291F, 27.8501F, -15, 0, 6, 30, 0, false);
roof_4_r2 = new ModelMapper(modelDataWrapper);
roof_4_r2.setPos(0, 0, 0);
window_end_exterior_3_1.addChild(roof_4_r2);
setRotationAngle(roof_4_r2, 0, 0, 1.0472F);
roof_4_r2.texOffs(329, 286).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_3_r5 = new ModelMapper(modelDataWrapper);
roof_3_r5.setPos(-7.7673F, 6.0642F, 0);
window_end_exterior_3_1.addChild(roof_3_r5);
setRotationAngle(roof_3_r5, 0, 0, 0.6981F);
roof_3_r5.texOffs(278, 163).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r15 = new ModelMapper(modelDataWrapper);
window_bottom_r15.setPos(-10.8291F, 33.8501F, 0);
window_end_exterior_3_1.addChild(window_bottom_r15);
setRotationAngle(window_bottom_r15, 0, 0, -0.2094F);
window_bottom_r15.texOffs(62, 281).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r15 = new ModelMapper(modelDataWrapper);
window_top_r15.setPos(-10.8291F, 27.8501F, 0);
window_end_exterior_3_1.addChild(window_top_r15);
setRotationAngle(window_top_r15, 0, 0, 0.1396F);
window_top_r15.texOffs(74, 100).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_end_exterior_3_2 = new ModelMapper(modelDataWrapper);
window_end_exterior_3_2.setPos(10.1709F, -40.8501F, 0);
window_end_exterior_3.addChild(window_end_exterior_3_2);
window_end_exterior_3_2.texOffs(161, 28).addBox(10.8291F, 27.8501F, -15, 0, 6, 30, 0, true);
roof_5_r1 = new ModelMapper(modelDataWrapper);
roof_5_r1.setPos(0, 0, 0);
window_end_exterior_3_2.addChild(roof_5_r1);
setRotationAngle(roof_5_r1, 0, 0, -1.0472F);
roof_5_r1.texOffs(329, 286).addBox(-1, 3, -15, 1, 3, 30, 0, true);
roof_4_r3 = new ModelMapper(modelDataWrapper);
roof_4_r3.setPos(7.7673F, 6.0642F, 0);
window_end_exterior_3_2.addChild(roof_4_r3);
setRotationAngle(roof_4_r3, 0, 0, -0.6981F);
roof_4_r3.texOffs(278, 163).addBox(0, -4, -15, 0, 4, 30, 0, true);
window_bottom_r16 = new ModelMapper(modelDataWrapper);
window_bottom_r16.setPos(10.8291F, 33.8501F, 0);
window_end_exterior_3_2.addChild(window_bottom_r16);
setRotationAngle(window_bottom_r16, 0, 0, 0.2094F);
window_bottom_r16.texOffs(62, 281).addBox(-1, 0, -15, 1, 8, 30, 0, true);
window_top_r16 = new ModelMapper(modelDataWrapper);
window_top_r16.setPos(10.8291F, 27.8501F, 0);
window_end_exterior_3_2.addChild(window_top_r16);
setRotationAngle(window_top_r16, 0, 0, -0.1396F);
window_top_r16.texOffs(74, 100).addBox(0, -22, -15, 0, 22, 30, 0, true);
window_end_exterior_4 = new ModelMapper(modelDataWrapper);
window_end_exterior_4.setPos(0, 24, 0);
window_end_exterior_4_1 = new ModelMapper(modelDataWrapper);
window_end_exterior_4_1.setPos(-10.1709F, -40.8501F, 0);
window_end_exterior_4.addChild(window_end_exterior_4_1);
window_end_exterior_4_1.texOffs(161, 22).addBox(-10.8291F, 27.8501F, -15, 0, 6, 30, 0, false);
roof_4_r4 = new ModelMapper(modelDataWrapper);
roof_4_r4.setPos(0, 0, 0);
window_end_exterior_4_1.addChild(roof_4_r4);
setRotationAngle(roof_4_r4, 0, 0, 1.0472F);
roof_4_r4.texOffs(267, 329).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_3_r6 = new ModelMapper(modelDataWrapper);
roof_3_r6.setPos(-7.7673F, 6.0642F, 0);
window_end_exterior_4_1.addChild(roof_3_r6);
setRotationAngle(roof_3_r6, 0, 0, 0.6981F);
roof_3_r6.texOffs(278, 159).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r17 = new ModelMapper(modelDataWrapper);
window_bottom_r17.setPos(-10.8291F, 33.8501F, 0);
window_end_exterior_4_1.addChild(window_bottom_r17);
setRotationAngle(window_bottom_r17, 0, 0, -0.2094F);
window_bottom_r17.texOffs(281, 46).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r17 = new ModelMapper(modelDataWrapper);
window_top_r17.setPos(-10.8291F, 27.8501F, 0);
window_end_exterior_4_1.addChild(window_top_r17);
setRotationAngle(window_top_r17, 0, 0, 0.1396F);
window_top_r17.texOffs(0, 86).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_end_exterior_4_2 = new ModelMapper(modelDataWrapper);
window_end_exterior_4_2.setPos(10.1709F, -40.8501F, 0);
window_end_exterior_4.addChild(window_end_exterior_4_2);
window_end_exterior_4_2.texOffs(161, 22).addBox(10.8291F, 27.8501F, -15, 0, 6, 30, 0, true);
roof_5_r2 = new ModelMapper(modelDataWrapper);
roof_5_r2.setPos(0, 0, 0);
window_end_exterior_4_2.addChild(roof_5_r2);
setRotationAngle(roof_5_r2, 0, 0, -1.0472F);
roof_5_r2.texOffs(267, 329).addBox(-1, 3, -15, 1, 3, 30, 0, true);
roof_4_r5 = new ModelMapper(modelDataWrapper);
roof_4_r5.setPos(7.7673F, 6.0642F, 0);
window_end_exterior_4_2.addChild(roof_4_r5);
setRotationAngle(roof_4_r5, 0, 0, -0.6981F);
roof_4_r5.texOffs(278, 159).addBox(0, -4, -15, 0, 4, 30, 0, true);
window_bottom_r18 = new ModelMapper(modelDataWrapper);
window_bottom_r18.setPos(10.8291F, 33.8501F, 0);
window_end_exterior_4_2.addChild(window_bottom_r18);
setRotationAngle(window_bottom_r18, 0, 0, 0.2094F);
window_bottom_r18.texOffs(281, 46).addBox(-1, 0, -15, 1, 8, 30, 0, true);
window_top_r18 = new ModelMapper(modelDataWrapper);
window_top_r18.setPos(10.8291F, 27.8501F, 0);
window_end_exterior_4_2.addChild(window_top_r18);
setRotationAngle(window_top_r18, 0, 0, -0.1396F);
window_top_r18.texOffs(0, 86).addBox(0, -22, -15, 0, 22, 30, 0, true);
window_end_exterior_5 = new ModelMapper(modelDataWrapper);
window_end_exterior_5.setPos(0, 24, 0);
window_end_exterior_5_1 = new ModelMapper(modelDataWrapper);
window_end_exterior_5_1.setPos(-10.1709F, -40.8501F, 0);
window_end_exterior_5.addChild(window_end_exterior_5_1);
window_end_exterior_5_1.texOffs(74, 122).addBox(-10.8291F, 27.8501F, -15, 0, 6, 30, 0, false);
roof_5_r3 = new ModelMapper(modelDataWrapper);
roof_5_r3.setPos(0, 0, 0);
window_end_exterior_5_1.addChild(roof_5_r3);
setRotationAngle(roof_5_r3, 0, 0, 1.0472F);
roof_5_r3.texOffs(328, 253).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_4_r6 = new ModelMapper(modelDataWrapper);
roof_4_r6.setPos(-7.7673F, 6.0642F, 0);
window_end_exterior_5_1.addChild(roof_4_r6);
setRotationAngle(roof_4_r6, 0, 0, 0.6981F);
roof_4_r6.texOffs(278, 155).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r19 = new ModelMapper(modelDataWrapper);
window_bottom_r19.setPos(-10.8291F, 33.8501F, 0);
window_end_exterior_5_1.addChild(window_bottom_r19);
setRotationAngle(window_bottom_r19, 0, 0, -0.2094F);
window_bottom_r19.texOffs(233, 275).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r19 = new ModelMapper(modelDataWrapper);
window_top_r19.setPos(-10.8291F, 27.8501F, 0);
window_end_exterior_5_1.addChild(window_top_r19);
setRotationAngle(window_top_r19, 0, 0, 0.1396F);
window_top_r19.texOffs(74, 78).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_end_exterior_5_2 = new ModelMapper(modelDataWrapper);
window_end_exterior_5_2.setPos(10.1709F, -40.8501F, 0);
window_end_exterior_5.addChild(window_end_exterior_5_2);
window_end_exterior_5_2.texOffs(74, 122).addBox(10.8291F, 27.8501F, -15, 0, 6, 30, 0, true);
roof_6_r1 = new ModelMapper(modelDataWrapper);
roof_6_r1.setPos(0, 0, 0);
window_end_exterior_5_2.addChild(roof_6_r1);
setRotationAngle(roof_6_r1, 0, 0, -1.0472F);
roof_6_r1.texOffs(328, 253).addBox(-1, 3, -15, 1, 3, 30, 0, true);
roof_5_r4 = new ModelMapper(modelDataWrapper);
roof_5_r4.setPos(7.7673F, 6.0642F, 0);
window_end_exterior_5_2.addChild(roof_5_r4);
setRotationAngle(roof_5_r4, 0, 0, -0.6981F);
roof_5_r4.texOffs(278, 155).addBox(0, -4, -15, 0, 4, 30, 0, true);
window_bottom_r20 = new ModelMapper(modelDataWrapper);
window_bottom_r20.setPos(10.8291F, 33.8501F, 0);
window_end_exterior_5_2.addChild(window_bottom_r20);
setRotationAngle(window_bottom_r20, 0, 0, 0.2094F);
window_bottom_r20.texOffs(233, 275).addBox(-1, 0, -15, 1, 8, 30, 0, true);
window_top_r20 = new ModelMapper(modelDataWrapper);
window_top_r20.setPos(10.8291F, 27.8501F, 0);
window_end_exterior_5_2.addChild(window_top_r20);
setRotationAngle(window_top_r20, 0, 0, -0.1396F);
window_top_r20.texOffs(74, 78).addBox(0, -22, -15, 0, 22, 30, 0, true);
window_end_exterior_6 = new ModelMapper(modelDataWrapper);
window_end_exterior_6.setPos(0, 24, 0);
window_end_exterior_6_1 = new ModelMapper(modelDataWrapper);
window_end_exterior_6_1.setPos(-10.1709F, -40.8501F, 0);
window_end_exterior_6.addChild(window_end_exterior_6_1);
window_end_exterior_6_1.texOffs(0, 49).addBox(-10.8291F, 27.8501F, -15, 0, 6, 30, 0, false);
roof_6_r2 = new ModelMapper(modelDataWrapper);
roof_6_r2.setPos(0, 0, 0);
window_end_exterior_6_1.addChild(roof_6_r2);
setRotationAngle(roof_6_r2, 0, 0, 1.0472F);
roof_6_r2.texOffs(328, 218).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_5_r5 = new ModelMapper(modelDataWrapper);
roof_5_r5.setPos(-7.7673F, 6.0642F, 0);
window_end_exterior_6_1.addChild(roof_5_r5);
setRotationAngle(roof_5_r5, 0, 0, 0.6981F);
roof_5_r5.texOffs(32, 269).addBox(0, -4, -15, 0, 4, 30, 0, false);
window_bottom_r21 = new ModelMapper(modelDataWrapper);
window_bottom_r21.setPos(-10.8291F, 33.8501F, 0);
window_end_exterior_6_1.addChild(window_bottom_r21);
setRotationAngle(window_bottom_r21, 0, 0, -0.2094F);
window_bottom_r21.texOffs(0, 274).addBox(0, 0, -15, 1, 8, 30, 0, false);
window_top_r21 = new ModelMapper(modelDataWrapper);
window_top_r21.setPos(-10.8291F, 27.8501F, 0);
window_end_exterior_6_1.addChild(window_top_r21);
setRotationAngle(window_top_r21, 0, 0, 0.1396F);
window_top_r21.texOffs(74, 56).addBox(0, -22, -15, 0, 22, 30, 0, false);
window_end_exterior_6_2 = new ModelMapper(modelDataWrapper);
window_end_exterior_6_2.setPos(10.1709F, -40.8501F, 0);
window_end_exterior_6.addChild(window_end_exterior_6_2);
window_end_exterior_6_2.texOffs(0, 49).addBox(10.8291F, 27.8501F, -15, 0, 6, 30, 0, true);
roof_7_r1 = new ModelMapper(modelDataWrapper);
roof_7_r1.setPos(0, 0, 0);
window_end_exterior_6_2.addChild(roof_7_r1);
setRotationAngle(roof_7_r1, 0, 0, -1.0472F);
roof_7_r1.texOffs(328, 218).addBox(-1, 3, -15, 1, 3, 30, 0, true);
roof_6_r3 = new ModelMapper(modelDataWrapper);
roof_6_r3.setPos(7.7673F, 6.0642F, 0);
window_end_exterior_6_2.addChild(roof_6_r3);
setRotationAngle(roof_6_r3, 0, 0, -0.6981F);
roof_6_r3.texOffs(32, 269).addBox(0, -4, -15, 0, 4, 30, 0, true);
window_bottom_r22 = new ModelMapper(modelDataWrapper);
window_bottom_r22.setPos(10.8291F, 33.8501F, 0);
window_end_exterior_6_2.addChild(window_bottom_r22);
setRotationAngle(window_bottom_r22, 0, 0, 0.2094F);
window_bottom_r22.texOffs(0, 274).addBox(-1, 0, -15, 1, 8, 30, 0, true);
window_top_r22 = new ModelMapper(modelDataWrapper);
window_top_r22.setPos(10.8291F, 27.8501F, 0);
window_end_exterior_6_2.addChild(window_top_r22);
setRotationAngle(window_top_r22, 0, 0, -0.1396F);
window_top_r22.texOffs(74, 56).addBox(0, -22, -15, 0, 22, 30, 0, true);
door = new ModelMapper(modelDataWrapper);
door.setPos(0, 24, 0);
door_1 = new ModelMapper(modelDataWrapper);
door_1.setPos(0, 0, 0);
door.addChild(door_1);
door_1.texOffs(230, 86).addBox(-20, -13, 3, 1, 6, 13, 0, false);
window_bottom_2_r1 = new ModelMapper(modelDataWrapper);
window_bottom_2_r1.setPos(-20, -7, 0);
door_1.addChild(window_bottom_2_r1);
setRotationAngle(window_bottom_2_r1, 0, 0, -0.2094F);
window_bottom_2_r1.texOffs(199, 0).addBox(0, 0, 3, 1, 8, 13, 0, false);
window_top_2_r1 = new ModelMapper(modelDataWrapper);
window_top_2_r1.setPos(-20, -13, 0);
door_1.addChild(window_top_2_r1);
setRotationAngle(window_top_2_r1, 0, 0, 0.1396F);
window_top_2_r1.texOffs(172, 378).addBox(0, -21, 3, 1, 21, 13, 0, false);
door_2 = new ModelMapper(modelDataWrapper);
door_2.setPos(0, 0, 0);
door.addChild(door_2);
door_2.texOffs(230, 86).addBox(19, -13, 3, 1, 6, 13, 0, true);
window_bottom_3_r1 = new ModelMapper(modelDataWrapper);
window_bottom_3_r1.setPos(20, -7, 0);
door_2.addChild(window_bottom_3_r1);
setRotationAngle(window_bottom_3_r1, 0, 0, 0.2094F);
window_bottom_3_r1.texOffs(199, 0).addBox(-1, 0, 3, 1, 8, 13, 0, true);
window_top_3_r1 = new ModelMapper(modelDataWrapper);
window_top_3_r1.setPos(20, -13, 0);
door_2.addChild(window_top_3_r1);
setRotationAngle(window_top_3_r1, 0, 0, -0.1396F);
window_top_3_r1.texOffs(172, 378).addBox(-1, -21, 3, 1, 21, 13, 0, true);
door_exterior = new ModelMapper(modelDataWrapper);
door_exterior.setPos(0, 24, 0);
door_exterior_1 = new ModelMapper(modelDataWrapper);
door_exterior_1.setPos(0, 0, 0);
door_exterior.addChild(door_exterior_1);
door_exterior_1.texOffs(221, 63).addBox(-20, -13, 3, 0, 6, 13, 0, false);
window_bottom_1_r1 = new ModelMapper(modelDataWrapper);
window_bottom_1_r1.setPos(-20, -7, 0);
door_exterior_1.addChild(window_bottom_1_r1);
setRotationAngle(window_bottom_1_r1, 0, 0, -0.2094F);
window_bottom_1_r1.texOffs(199, 8).addBox(0, 0, 3, 0, 8, 13, 0, false);
window_top_1_r1 = new ModelMapper(modelDataWrapper);
window_top_1_r1.setPos(-20, -13, 0);
door_exterior_1.addChild(window_top_1_r1);
setRotationAngle(window_top_1_r1, 0, 0, 0.1396F);
window_top_1_r1.texOffs(227, 159).addBox(0, -21, 3, 0, 21, 13, 0, false);
door_exterior_2 = new ModelMapper(modelDataWrapper);
door_exterior_2.setPos(0, 0, 0);
door_exterior.addChild(door_exterior_2);
door_exterior_2.texOffs(221, 63).addBox(20, -13, 3, 0, 6, 13, 0, true);
window_bottom_2_r2 = new ModelMapper(modelDataWrapper);
window_bottom_2_r2.setPos(20, -7, 0);
door_exterior_2.addChild(window_bottom_2_r2);
setRotationAngle(window_bottom_2_r2, 0, 0, 0.2094F);
window_bottom_2_r2.texOffs(199, 8).addBox(0, 0, 3, 0, 8, 13, 0, true);
window_top_2_r2 = new ModelMapper(modelDataWrapper);
window_top_2_r2.setPos(20, -13, 0);
door_exterior_2.addChild(window_top_2_r2);
setRotationAngle(window_top_2_r2, 0, 0, -0.1396F);
window_top_2_r2.texOffs(227, 159).addBox(0, -21, 3, 0, 21, 13, 0, true);
door_exterior_end = new ModelMapper(modelDataWrapper);
door_exterior_end.setPos(0, 24, 0);
door_exterior_end_1 = new ModelMapper(modelDataWrapper);
door_exterior_end_1.setPos(0, 0, 0);
door_exterior_end.addChild(door_exterior_end_1);
door_exterior_end_1.texOffs(0, 11).addBox(-20, -13, 3, 0, 6, 13, 0, false);
window_bottom_2_r3 = new ModelMapper(modelDataWrapper);
window_bottom_2_r3.setPos(-20, -7, 0);
door_exterior_end_1.addChild(window_bottom_2_r3);
setRotationAngle(window_bottom_2_r3, 0, 0, -0.2094F);
window_bottom_2_r3.texOffs(0, 94).addBox(0, 0, 3, 0, 8, 13, 0, false);
window_top_2_r3 = new ModelMapper(modelDataWrapper);
window_top_2_r3.setPos(-20, -13, 0);
door_exterior_end_1.addChild(window_top_2_r3);
setRotationAngle(window_top_2_r3, 0, 0, 0.1396F);
window_top_2_r3.texOffs(0, 73).addBox(0, -21, 3, 0, 21, 13, 0, false);
door_exterior_end_2 = new ModelMapper(modelDataWrapper);
door_exterior_end_2.setPos(0, 0, 0);
door_exterior_end.addChild(door_exterior_end_2);
door_exterior_end_2.texOffs(0, 11).addBox(20, -13, 3, 0, 6, 13, 0, true);
window_bottom_3_r2 = new ModelMapper(modelDataWrapper);
window_bottom_3_r2.setPos(20, -7, 0);
door_exterior_end_2.addChild(window_bottom_3_r2);
setRotationAngle(window_bottom_3_r2, 0, 0, 0.2094F);
window_bottom_3_r2.texOffs(0, 94).addBox(0, 0, 3, 0, 8, 13, 0, true);
window_top_3_r2 = new ModelMapper(modelDataWrapper);
window_top_3_r2.setPos(20, -13, 0);
door_exterior_end_2.addChild(window_top_3_r2);
setRotationAngle(window_top_3_r2, 0, 0, -0.1396F);
window_top_3_r2.texOffs(0, 73).addBox(0, -21, 3, 0, 21, 13, 0, true);
roof_exterior = new ModelMapper(modelDataWrapper);
roof_exterior.setPos(0, 24, 0);
roof_exterior.texOffs(0, 86).addBox(-13, -39, -15, 13, 0, 30, 0, false);
roof_exterior.texOffs(360, 193).addBox(-19, 0, -15, 1, 2, 30, 0, false);
end = new ModelMapper(modelDataWrapper);
end.setPos(0, 24, 0);
end.texOffs(230, 76).addBox(9.5F, -34, 16.1F, 11, 34, 29, 0, false);
end.texOffs(310, 104).addBox(11, -34, 2.9F, 9, 34, 0, 0, false);
end.texOffs(227, 172).addBox(-20.5F, -34, 16.1F, 11, 34, 29, 0, false);
end.texOffs(307, 201).addBox(-20, -34, 2.9F, 9, 34, 0, 0, false);
end_pillar_4_r1 = new ModelMapper(modelDataWrapper);
end_pillar_4_r1.setPos(-11, 0, 2.9F);
end.addChild(end_pillar_4_r1);
setRotationAngle(end_pillar_4_r1, 0, 1.2217F, 0);
end_pillar_4_r1.texOffs(94, 381).addBox(0, -34, 0, 12, 34, 0, 0, false);
end_pillar_3_r1 = new ModelMapper(modelDataWrapper);
end_pillar_3_r1.setPos(11, 0, 2.9F);
end.addChild(end_pillar_3_r1);
setRotationAngle(end_pillar_3_r1, 0, -1.2217F, 0);
end_pillar_3_r1.texOffs(0, 383).addBox(-12, -34, 0, 12, 34, 0, 0, false);
end_side_1 = new ModelMapper(modelDataWrapper);
end_side_1.setPos(0, 0, 0);
end.addChild(end_side_1);
end_side_1.texOffs(0, 0).addBox(-13, -34, -8, 13, 0, 53, 0, false);
end_side_1.texOffs(0, 170).addBox(-19, 0, -15, 19, 1, 60, 0, false);
end_side_1.texOffs(189, 324).addBox(-17, -34, 3, 4, 1, 13, 0, false);
end_side_1.texOffs(214, 0).addBox(-20, -13, -15, 0, 6, 7, 0, false);
end_side_1.texOffs(9, 7).addBox(-15, -36, -15, 6, 0, 7, 0, false);
end_side_1.texOffs(9, 0).addBox(-7, -35, -15, 7, 0, 7, 0, false);
end_side_1.texOffs(227, 193).addBox(-18, -31, -15, 6, 1, 7, 0, false);
roof_3_r7 = new ModelMapper(modelDataWrapper);
roof_3_r7.setPos(-7, -35, 0);
end_side_1.addChild(roof_3_r7);
setRotationAngle(roof_3_r7, 0, 0, 0.3491F);
roof_3_r7.texOffs(0, 0).addBox(-3, 0, -15, 3, 0, 7, 0, false);
roof_1_r12 = new ModelMapper(modelDataWrapper);
roof_1_r12.setPos(-15, -36, 0);
end_side_1.addChild(roof_1_r12);
setRotationAngle(roof_1_r12, 0, 0, -0.7854F);
roof_1_r12.texOffs(0, 7).addBox(-3, 0, -15, 3, 0, 7, 0, false);
window_bottom_r23 = new ModelMapper(modelDataWrapper);
window_bottom_r23.setPos(-21, -7, 0);
end_side_1.addChild(window_bottom_r23);
setRotationAngle(window_bottom_r23, 0, 0, -0.2094F);
window_bottom_r23.texOffs(56, 101).addBox(1, 0, -15, 0, 8, 7, 0, false);
window_top_r23 = new ModelMapper(modelDataWrapper);
window_top_r23.setPos(-21, -13, 0);
end_side_1.addChild(window_top_r23);
setRotationAngle(window_top_r23, 0, 0, 0.1396F);
window_top_r23.texOffs(56, 79).addBox(1, -22, -15, 0, 22, 7, 0, false);
window_top_r23.texOffs(237, 36).addBox(1, -22, 3, 2, 1, 13, 0, false);
end_side_2 = new ModelMapper(modelDataWrapper);
end_side_2.setPos(0, 0, 0);
end.addChild(end_side_2);
end_side_2.texOffs(0, 0).addBox(0, -34, -8, 13, 0, 53, 0, true);
end_side_2.texOffs(0, 170).addBox(0, 0, -15, 19, 1, 60, 0, true);
end_side_2.texOffs(189, 324).addBox(13, -34, 3, 4, 1, 13, 0, true);
end_side_2.texOffs(214, 0).addBox(20, -13, -15, 0, 6, 7, 0, true);
end_side_2.texOffs(9, 7).addBox(9, -36, -15, 6, 0, 7, 0, true);
end_side_2.texOffs(9, 0).addBox(0, -35, -15, 7, 0, 7, 0, true);
end_side_2.texOffs(227, 193).addBox(12, -31, -15, 6, 1, 7, 0, true);
roof_4_r7 = new ModelMapper(modelDataWrapper);
roof_4_r7.setPos(7, -35, 0);
end_side_2.addChild(roof_4_r7);
setRotationAngle(roof_4_r7, 0, 0, -0.3491F);
roof_4_r7.texOffs(0, 0).addBox(0, 0, -15, 3, 0, 7, 0, true);
roof_2_r13 = new ModelMapper(modelDataWrapper);
roof_2_r13.setPos(15, -36, 0);
end_side_2.addChild(roof_2_r13);
setRotationAngle(roof_2_r13, 0, 0, 0.7854F);
roof_2_r13.texOffs(0, 7).addBox(0, 0, -15, 3, 0, 7, 0, true);
window_bottom_r24 = new ModelMapper(modelDataWrapper);
window_bottom_r24.setPos(21, -7, 0);
end_side_2.addChild(window_bottom_r24);
setRotationAngle(window_bottom_r24, 0, 0, 0.2094F);
window_bottom_r24.texOffs(56, 101).addBox(-1, 0, -15, 0, 8, 7, 0, true);
window_top_r24 = new ModelMapper(modelDataWrapper);
window_top_r24.setPos(21, -13, 0);
end_side_2.addChild(window_top_r24);
setRotationAngle(window_top_r24, 0, 0, -0.1396F);
window_top_r24.texOffs(56, 79).addBox(-1, -22, -15, 0, 22, 7, 0, true);
window_top_r24.texOffs(237, 36).addBox(-3, -22, 3, 2, 1, 13, 0, true);
end_light = new ModelMapper(modelDataWrapper);
end_light.setPos(0, 24, 0);
end_light.texOffs(317, 44).addBox(-7, -35.1F, -15, 14, 0, 4, 0, false);
end_translucent = new ModelMapper(modelDataWrapper);
end_translucent.setPos(0, 24, 0);
end_translucent.texOffs(237, 0).addBox(-20, -36, -8, 40, 36, 0, 0, false);
end_translucent.texOffs(381, 0).addBox(-10, -34, 45, 20, 34, 0, 0, false);
end_exterior = new ModelMapper(modelDataWrapper);
end_exterior.setPos(0, 24, 0);
end_exterior_side_1 = new ModelMapper(modelDataWrapper);
end_exterior_side_1.setPos(0, 0, 0);
end_exterior.addChild(end_exterior_side_1);
end_exterior_side_1.texOffs(362, 125).addBox(-21, -13, -15, 1, 6, 18, 0, false);
end_exterior_side_1.texOffs(360, 158).addBox(-21, -13, 16, 1, 6, 29, 0, false);
end_exterior_side_1.texOffs(325, 188).addBox(-21, 0, 3, 2, 1, 13, 0, false);
end_exterior_side_1.texOffs(303, 385).addBox(-20.5F, -34, 45, 11, 34, 0, 0, false);
end_exterior_side_1.texOffs(32, 274).addBox(-18, -39, 45, 18, 5, 0, 0, false);
roof_4_r8 = new ModelMapper(modelDataWrapper);
roof_4_r8.setPos(-10.1709F, -40.8501F, 0);
end_exterior_side_1.addChild(roof_4_r8);
setRotationAngle(roof_4_r8, 0, 0, 1.0472F);
roof_4_r8.texOffs(235, 321).addBox(0, 3, -15, 1, 3, 30, 0, false);
roof_4_r8.texOffs(319, 0).addBox(0, 3, 15, 1, 3, 30, 0, false);
roof_3_r8 = new ModelMapper(modelDataWrapper);
roof_3_r8.setPos(-17.9382F, -34.7859F, 0);
end_exterior_side_1.addChild(roof_3_r8);
setRotationAngle(roof_3_r8, 0, 0, 0.6981F);
roof_3_r8.texOffs(204, 241).addBox(0, -4, -15, 0, 4, 30, 0, false);
roof_3_r8.texOffs(0, 387).addBox(0, -4, 15, 1, 4, 30, 0, false);
door_top_r1 = new ModelMapper(modelDataWrapper);
door_top_r1.setPos(-21, -13, 0);
end_exterior_side_1.addChild(door_top_r1);
setRotationAngle(door_top_r1, 0, 0, 0.1396F);
door_top_r1.texOffs(265, 275).addBox(0, -22, 3, 1, 1, 13, 0, false);
door_top_r1.texOffs(173, 265).addBox(0, -22, 16, 1, 22, 29, 0, false);
door_top_r1.texOffs(265, 369).addBox(0, -22, -15, 1, 22, 18, 0, false);
window_bottom_2_r4 = new ModelMapper(modelDataWrapper);
window_bottom_2_r4.setPos(-21, -7, 0);
end_exterior_side_1.addChild(window_bottom_2_r4);
setRotationAngle(window_bottom_2_r4, 0, 0, -0.2094F);
window_bottom_2_r4.texOffs(127, 319).addBox(0, 0, 16, 1, 8, 29, 0, false);
window_bottom_2_r4.texOffs(360, 251).addBox(0, 0, -15, 1, 8, 18, 0, false);
end_exterior_side_2 = new ModelMapper(modelDataWrapper);
end_exterior_side_2.setPos(0, 0, 0);
end_exterior.addChild(end_exterior_side_2);
end_exterior_side_2.texOffs(362, 125).addBox(20, -13, -15, 1, 6, 18, 0, true);
end_exterior_side_2.texOffs(360, 158).addBox(20, -13, 16, 1, 6, 29, 0, true);
end_exterior_side_2.texOffs(325, 188).addBox(19, 0, 3, 2, 1, 13, 0, true);
end_exterior_side_2.texOffs(303, 385).addBox(9.5F, -34, 45, 11, 34, 0, 0, true);
end_exterior_side_2.texOffs(32, 274).addBox(0, -39, 45, 18, 5, 0, 0, true);
roof_5_r6 = new ModelMapper(modelDataWrapper);
roof_5_r6.setPos(10.1709F, -40.8501F, 0);
end_exterior_side_2.addChild(roof_5_r6);
setRotationAngle(roof_5_r6, 0, 0, -1.0472F);
roof_5_r6.texOffs(235, 321).addBox(-1, 3, -15, 1, 3, 30, 0, true);
roof_5_r6.texOffs(319, 0).addBox(-1, 3, 15, 1, 3, 30, 0, true);
roof_4_r9 = new ModelMapper(modelDataWrapper);
roof_4_r9.setPos(17.9382F, -34.7859F, 0);
end_exterior_side_2.addChild(roof_4_r9);
setRotationAngle(roof_4_r9, 0, 0, -0.6981F);
roof_4_r9.texOffs(204, 241).addBox(0, -4, -15, 0, 4, 30, 0, true);
roof_4_r9.texOffs(0, 387).addBox(-1, -4, 15, 1, 4, 30, 0, true);
door_top_r2 = new ModelMapper(modelDataWrapper);
door_top_r2.setPos(21, -13, 0);
end_exterior_side_2.addChild(door_top_r2);
setRotationAngle(door_top_r2, 0, 0, -0.1396F);
door_top_r2.texOffs(265, 275).addBox(-1, -22, 3, 1, 1, 13, 0, true);
door_top_r2.texOffs(173, 265).addBox(-1, -22, 16, 1, 22, 29, 0, true);
door_top_r2.texOffs(265, 369).addBox(-1, -22, -15, 1, 22, 18, 0, true);
window_bottom_3_r3 = new ModelMapper(modelDataWrapper);
window_bottom_3_r3.setPos(21, -7, 0);
end_exterior_side_2.addChild(window_bottom_3_r3);
setRotationAngle(window_bottom_3_r3, 0, 0, 0.2094F);
window_bottom_3_r3.texOffs(127, 319).addBox(-1, 0, 16, 1, 8, 29, 0, true);
window_bottom_3_r3.texOffs(360, 251).addBox(-1, 0, -15, 1, 8, 18, 0, true);
roof_vent = new ModelMapper(modelDataWrapper);
roof_vent.setPos(0, 24, 0);
roof_vent_side_1 = new ModelMapper(modelDataWrapper);
roof_vent_side_1.setPos(0, -42, 10);
roof_vent.addChild(roof_vent_side_1);
roof_vent_side_1.texOffs(76, 96).addBox(-6, 0, -70, 6, 4, 70, 0, false);
vent_4_r1 = new ModelMapper(modelDataWrapper);
vent_4_r1.setPos(0, 0, 0);
roof_vent_side_1.addChild(vent_4_r1);
setRotationAngle(vent_4_r1, -0.6981F, 0, 0);
vent_4_r1.texOffs(67, 53).addBox(-6, 0, 0, 6, 0, 5, 0, false);
vent_3_r1 = new ModelMapper(modelDataWrapper);
vent_3_r1.setPos(-6, 0, 0);
roof_vent_side_1.addChild(vent_3_r1);
setRotationAngle(vent_3_r1, 0, 0.6981F, 1.1345F);
vent_3_r1.texOffs(72, 58).addBox(0, 0, 0, 1, 6, 5, 0, false);
vent_1_r1 = new ModelMapper(modelDataWrapper);
vent_1_r1.setPos(-6, 0, -10);
roof_vent_side_1.addChild(vent_1_r1);
setRotationAngle(vent_1_r1, 0, 0, 1.1345F);
vent_1_r1.texOffs(161, 0).addBox(0, 0, -60, 3, 6, 70, 0, false);
roof_vent_side_2 = new ModelMapper(modelDataWrapper);
roof_vent_side_2.setPos(0, -42, 10);
roof_vent.addChild(roof_vent_side_2);
roof_vent_side_2.texOffs(76, 96).addBox(0, 0, -70, 6, 4, 70, 0, true);
vent_5_r1 = new ModelMapper(modelDataWrapper);
vent_5_r1.setPos(0, 0, 0);
roof_vent_side_2.addChild(vent_5_r1);
setRotationAngle(vent_5_r1, -0.6981F, 0, 0);
vent_5_r1.texOffs(67, 53).addBox(0, 0, 0, 6, 0, 5, 0, true);
vent_4_r2 = new ModelMapper(modelDataWrapper);
vent_4_r2.setPos(6, 0, 0);
roof_vent_side_2.addChild(vent_4_r2);
setRotationAngle(vent_4_r2, 0, -0.6981F, -1.1345F);
vent_4_r2.texOffs(72, 58).addBox(-1, 0, 0, 1, 6, 5, 0, true);
vent_2_r1 = new ModelMapper(modelDataWrapper);
vent_2_r1.setPos(6, 0, -10);
roof_vent_side_2.addChild(vent_2_r1);
setRotationAngle(vent_2_r1, 0, 0, -1.1345F);
vent_2_r1.texOffs(161, 0).addBox(-3, 0, -60, 3, 6, 70, 0, true);
head_exterior = new ModelMapper(modelDataWrapper);
head_exterior.setPos(0, 24, 0);
head_side_1 = new ModelMapper(modelDataWrapper);
head_side_1.setPos(0, 0, 0);
head_exterior.addChild(head_side_1);
head_side_1.texOffs(155, 97).addBox(-19, 0, -15, 1, 2, 73, 0, false);
head_side_1.texOffs(158, 192).addBox(-21, -13, -15, 1, 6, 67, 0, false);
head_side_1.texOffs(279, 44).addBox(-21, 0, -57, 2, 1, 13, 0, false);
head_side_1.texOffs(125, 356).addBox(-21, -13, -44, 1, 6, 29, 0, false);
head_side_1.texOffs(361, 286).addBox(-21, -13, -75, 1, 6, 18, 0, false);
roof_4_r10 = new ModelMapper(modelDataWrapper);
roof_4_r10.setPos(-10.1709F, -40.8501F, 0);
head_side_1.addChild(roof_4_r10);
setRotationAngle(roof_4_r10, 0, 0, 1.0472F);
roof_4_r10.texOffs(157, 326).addBox(0, 3, -75, 1, 3, 30, 0, false);
roof_4_r10.texOffs(328, 185).addBox(0, 3, -45, 1, 3, 30, 0, false);
roof_3_r9 = new ModelMapper(modelDataWrapper);
roof_3_r9.setPos(-17.9382F, -34.7859F, 0);
head_side_1.addChild(roof_3_r9);
setRotationAngle(roof_3_r9, 0, 0, 0.6981F);
roof_3_r9.texOffs(32, 261).addBox(0, -4, -75, 0, 4, 30, 0, false);
roof_3_r9.texOffs(32, 265).addBox(0, -4, -45, 0, 4, 30, 0, false);
window_top_1_r2 = new ModelMapper(modelDataWrapper);
window_top_1_r2.setPos(-21, -13, 0);
head_side_1.addChild(window_top_1_r2);
setRotationAngle(window_top_1_r2, 0, 0, 0.1396F);
window_top_1_r2.texOffs(362, 74).addBox(0, -22, -75, 1, 22, 18, 0, false);
window_top_1_r2.texOffs(113, 259).addBox(0, -22, -44, 1, 22, 29, 0, false);
window_top_1_r2.texOffs(237, 50).addBox(0, -22, -57, 1, 1, 13, 0, false);
window_top_1_r2.texOffs(93, 172).addBox(0, -22, -15, 1, 22, 65, 0, false);
window_bottom_1_r2 = new ModelMapper(modelDataWrapper);
window_bottom_1_r2.setPos(-21, -7, 0);
head_side_1.addChild(window_bottom_1_r2);
setRotationAngle(window_bottom_1_r2, 0, 0, -0.2094F);
window_bottom_1_r2.texOffs(161, 0).addBox(0, 0, -75, 1, 8, 18, 0, false);
window_bottom_1_r2.texOffs(62, 319).addBox(0, 0, -44, 1, 8, 29, 0, false);
window_bottom_1_r2.texOffs(0, 86).addBox(0, 0, -15, 1, 8, 72, 0, false);
end_r1 = new ModelMapper(modelDataWrapper);
end_r1.setPos(-19, 2, 33);
head_side_1.addChild(end_r1);
setRotationAngle(end_r1, 0, 0, -0.2618F);
end_r1.texOffs(204, 256).addBox(0, 0, 0, 0, 11, 26, 0, false);
roof_11_r1 = new ModelMapper(modelDataWrapper);
roof_11_r1.setPos(-16.8732F, -11.8177F, 56.7312F);
head_side_1.addChild(roof_11_r1);
setRotationAngle(roof_11_r1, 0.1745F, -1.0472F, 0);
roof_11_r1.texOffs(361, 319).addBox(-9.5F, -12, 0, 19, 24, 0, 0, false);
roof_12_r1 = new ModelMapper(modelDataWrapper);
roof_12_r1.setPos(-15.5128F, 10.8301F, 58.2552F);
head_side_1.addChild(roof_12_r1);
setRotationAngle(roof_12_r1, 0, -1.0472F, 0);
roof_12_r1.texOffs(161, 26).addBox(-3.5F, -1.5F, 0, 7, 3, 0, 0, false);
roof_11_r2 = new ModelMapper(modelDataWrapper);
roof_11_r2.setPos(-15.5954F, 7.1646F, 60.6123F);
head_side_1.addChild(roof_11_r2);
setRotationAngle(roof_11_r2, -0.5236F, -1.0472F, 0);
roof_11_r2.texOffs(134, 91).addBox(-5.5F, -2.5F, 0, 11, 5, 0, 0, false);
roof_10_r1 = new ModelMapper(modelDataWrapper);
roof_10_r1.setPos(-16.9278F, 3, 60.8042F);
head_side_1.addChild(roof_10_r1);
setRotationAngle(roof_10_r1, 0, -1.0472F, 0);
roof_10_r1.texOffs(134, 86).addBox(-6, -3, 0, 12, 5, 0, 0, false);
roof_10_r2 = new ModelMapper(modelDataWrapper);
roof_10_r2.setPos(-7, 0, 70);
head_side_1.addChild(roof_10_r2);
setRotationAngle(roof_10_r2, 0.2618F, -0.5236F, 0);
roof_10_r2.texOffs(218, 86).addBox(-9, -11, 0, 9, 11, 0, 0, false);
roof_11_r3 = new ModelMapper(modelDataWrapper);
roof_11_r3.setPos(-10.0747F, 10.7433F, 63.3255F);
head_side_1.addChild(roof_11_r3);
setRotationAngle(roof_11_r3, 0, -0.5236F, 0);
roof_11_r3.texOffs(28, 50).addBox(-5, -1.5F, 0, 10, 3, 0, 0, false);
roof_10_r3 = new ModelMapper(modelDataWrapper);
roof_10_r3.setPos(-7, 5, 70);
head_side_1.addChild(roof_10_r3);
setRotationAngle(roof_10_r3, -0.7854F, -0.5236F, 0);
roof_10_r3.texOffs(279, 58).addBox(-11, 0, 0, 11, 6, 0, 0, false);
roof_9_r1 = new ModelMapper(modelDataWrapper);
roof_9_r1.setPos(-7, 0, 70);
head_side_1.addChild(roof_9_r1);
setRotationAngle(roof_9_r1, 0, -0.5236F, 0);
roof_9_r1.texOffs(161, 13).addBox(-8, 0, 0, 8, 5, 0, 0, false);
roof_8_r1 = new ModelMapper(modelDataWrapper);
roof_8_r1.setPos(-12.533F, -16.0189F, 57.5648F);
head_side_1.addChild(roof_8_r1);
setRotationAngle(roof_8_r1, -0.2618F, 0.7854F, 1.0472F);
roof_8_r1.texOffs(158, 124).addBox(0, -6.5F, -14, 0, 13, 28, 0, false);
roof_7_r2 = new ModelMapper(modelDataWrapper);
roof_7_r2.setPos(-15.5298F, -29.8468F, 35.8167F);
head_side_1.addChild(roof_7_r2);
setRotationAngle(roof_7_r2, -0.1745F, 0.3491F, 1.0472F);
roof_7_r2.texOffs(0, 108).addBox(0, -6, -15, 0, 12, 30, 0, false);
roof_4_r11 = new ModelMapper(modelDataWrapper);
roof_4_r11.setPos(-2, -42, -9);
head_side_1.addChild(roof_4_r11);
setRotationAngle(roof_4_r11, 0, 0, 1.5708F);
roof_4_r11.texOffs(265, 289).addBox(0, -2, -6, 1, 4, 12, 0, false);
roof_4_r12 = new ModelMapper(modelDataWrapper);
roof_4_r12.setPos(-8.1369F, -39.4953F, 9.8171F);
head_side_1.addChild(roof_4_r12);
setRotationAngle(roof_4_r12, -0.1309F, 0.1309F, 1.3963F);
roof_4_r12.texOffs(32, 292).addBox(0, -3.5F, -13.5F, 0, 7, 27, 0, false);
roof_3_r10 = new ModelMapper(modelDataWrapper);
roof_3_r10.setPos(-13.6527F, -37.467F, 10.5898F);
head_side_1.addChild(roof_3_r10);
setRotationAngle(roof_3_r10, -0.0873F, 0.0873F, 1.0472F);
roof_3_r10.texOffs(204, 247).addBox(0, -3.5F, -14, 0, 7, 28, 0, false);
roof_2_r14 = new ModelMapper(modelDataWrapper);
roof_2_r14.setPos(-17.2178F, -34.6364F, 11.8407F);
head_side_1.addChild(roof_2_r14);
setRotationAngle(roof_2_r14, -0.0436F, 0.0436F, 0.6981F);
roof_2_r14.texOffs(204, 235).addBox(0, -3, -15, 0, 6, 30, 0, false);
roof_3_r11 = new ModelMapper(modelDataWrapper);
roof_3_r11.setPos(-6.6372F, -40.9654F, -9);
head_side_1.addChild(roof_3_r11);
setRotationAngle(roof_3_r11, 0, 0, 1.3963F);
roof_3_r11.texOffs(230, 139).addBox(-0.5F, -3.5F, -6, 1, 7, 12, 0, false);
roof_2_r15 = new ModelMapper(modelDataWrapper);
roof_2_r15.setPos(-12.519F, -38.9171F, -9);
head_side_1.addChild(roof_2_r15);
setRotationAngle(roof_2_r15, 0, 0, 1.0472F);
roof_2_r15.texOffs(0, 274).addBox(-0.5F, -3, -6, 1, 6, 12, 0, false);
roof_1_r13 = new ModelMapper(modelDataWrapper);
roof_1_r13.setPos(-16.2696F, -35.9966F, -9);
head_side_1.addChild(roof_1_r13);
setRotationAngle(roof_1_r13, 0, 0, 0.6981F);
roof_1_r13.texOffs(296, 243).addBox(-0.5F, -2, -6, 1, 4, 12, 0, false);
head_side_2 = new ModelMapper(modelDataWrapper);
head_side_2.setPos(0, 0, 0);
head_exterior.addChild(head_side_2);
head_side_2.texOffs(155, 97).addBox(18, 0, -15, 1, 2, 73, 0, true);
head_side_2.texOffs(158, 192).addBox(20, -13, -15, 1, 6, 67, 0, true);
head_side_2.texOffs(279, 44).addBox(19, 0, -57, 2, 1, 13, 0, true);
head_side_2.texOffs(125, 356).addBox(20, -13, -44, 1, 6, 29, 0, true);
head_side_2.texOffs(361, 286).addBox(20, -13, -75, 1, 6, 18, 0, true);
roof_5_r7 = new ModelMapper(modelDataWrapper);
roof_5_r7.setPos(10.1709F, -40.8501F, 0);
head_side_2.addChild(roof_5_r7);
setRotationAngle(roof_5_r7, 0, 0, -1.0472F);
roof_5_r7.texOffs(157, 326).addBox(-1, 3, -75, 1, 3, 30, 0, true);
roof_5_r7.texOffs(328, 185).addBox(-1, 3, -45, 1, 3, 30, 0, true);
roof_4_r13 = new ModelMapper(modelDataWrapper);
roof_4_r13.setPos(17.9382F, -34.7859F, 0);
head_side_2.addChild(roof_4_r13);
setRotationAngle(roof_4_r13, 0, 0, -0.6981F);
roof_4_r13.texOffs(32, 261).addBox(0, -4, -75, 0, 4, 30, 0, true);
roof_4_r13.texOffs(32, 265).addBox(0, -4, -45, 0, 4, 30, 0, true);
window_top_2_r4 = new ModelMapper(modelDataWrapper);
window_top_2_r4.setPos(21, -13, 0);
head_side_2.addChild(window_top_2_r4);
setRotationAngle(window_top_2_r4, 0, 0, -0.1396F);
window_top_2_r4.texOffs(362, 74).addBox(-1, -22, -75, 1, 22, 18, 0, true);
window_top_2_r4.texOffs(113, 259).addBox(-1, -22, -44, 1, 22, 29, 0, true);
window_top_2_r4.texOffs(237, 50).addBox(-1, -22, -57, 1, 1, 13, 0, true);
window_top_2_r4.texOffs(93, 172).addBox(-1, -22, -15, 1, 22, 65, 0, true);
window_bottom_2_r5 = new ModelMapper(modelDataWrapper);
window_bottom_2_r5.setPos(21, -7, 0);
head_side_2.addChild(window_bottom_2_r5);
setRotationAngle(window_bottom_2_r5, 0, 0, 0.2094F);
window_bottom_2_r5.texOffs(161, 0).addBox(-1, 0, -75, 1, 8, 18, 0, true);
window_bottom_2_r5.texOffs(62, 319).addBox(-1, 0, -44, 1, 8, 29, 0, true);
window_bottom_2_r5.texOffs(0, 86).addBox(-1, 0, -15, 1, 8, 72, 0, true);
end_r2 = new ModelMapper(modelDataWrapper);
end_r2.setPos(19, 2, 33);
head_side_2.addChild(end_r2);
setRotationAngle(end_r2, 0, 0, 0.2618F);
end_r2.texOffs(204, 256).addBox(0, 0, 0, 0, 11, 26, 0, true);
roof_12_r2 = new ModelMapper(modelDataWrapper);
roof_12_r2.setPos(16.8732F, -11.8177F, 56.7312F);
head_side_2.addChild(roof_12_r2);
setRotationAngle(roof_12_r2, 0.1745F, 1.0472F, 0);
roof_12_r2.texOffs(361, 319).addBox(-9.5F, -12, 0, 19, 24, 0, 0, true);
roof_13_r1 = new ModelMapper(modelDataWrapper);
roof_13_r1.setPos(15.5128F, 10.8301F, 58.2552F);
head_side_2.addChild(roof_13_r1);
setRotationAngle(roof_13_r1, 0, 1.0472F, 0);
roof_13_r1.texOffs(161, 26).addBox(-3.5F, -1.5F, 0, 7, 3, 0, 0, true);
roof_12_r3 = new ModelMapper(modelDataWrapper);
roof_12_r3.setPos(15.5954F, 7.1646F, 60.6123F);
head_side_2.addChild(roof_12_r3);
setRotationAngle(roof_12_r3, -0.5236F, 1.0472F, 0);
roof_12_r3.texOffs(134, 91).addBox(-5.5F, -2.5F, 0, 11, 5, 0, 0, true);
roof_11_r4 = new ModelMapper(modelDataWrapper);
roof_11_r4.setPos(16.9278F, 3, 60.8042F);
head_side_2.addChild(roof_11_r4);
setRotationAngle(roof_11_r4, 0, 1.0472F, 0);
roof_11_r4.texOffs(134, 86).addBox(-6, -3, 0, 12, 5, 0, 0, true);
roof_11_r5 = new ModelMapper(modelDataWrapper);
roof_11_r5.setPos(7, 0, 70);
head_side_2.addChild(roof_11_r5);
setRotationAngle(roof_11_r5, 0.2618F, 0.5236F, 0);
roof_11_r5.texOffs(218, 86).addBox(0, -11, 0, 9, 11, 0, 0, true);
roof_12_r4 = new ModelMapper(modelDataWrapper);
roof_12_r4.setPos(10.0747F, 10.7433F, 63.3255F);
head_side_2.addChild(roof_12_r4);
setRotationAngle(roof_12_r4, 0, 0.5236F, 0);
roof_12_r4.texOffs(28, 50).addBox(-5, -1.5F, 0, 10, 3, 0, 0, true);
roof_11_r6 = new ModelMapper(modelDataWrapper);
roof_11_r6.setPos(7, 5, 70);
head_side_2.addChild(roof_11_r6);
setRotationAngle(roof_11_r6, -0.7854F, 0.5236F, 0);
roof_11_r6.texOffs(279, 58).addBox(0, 0, 0, 11, 6, 0, 0, true);
roof_10_r4 = new ModelMapper(modelDataWrapper);
roof_10_r4.setPos(7, 0, 70);
head_side_2.addChild(roof_10_r4);
setRotationAngle(roof_10_r4, 0, 0.5236F, 0);
roof_10_r4.texOffs(161, 13).addBox(0, 0, 0, 8, 5, 0, 0, true);
roof_9_r2 = new ModelMapper(modelDataWrapper);
roof_9_r2.setPos(12.533F, -16.0189F, 57.5648F);
head_side_2.addChild(roof_9_r2);
setRotationAngle(roof_9_r2, -0.2618F, -0.7854F, -1.0472F);
roof_9_r2.texOffs(158, 124).addBox(0, -6.5F, -14, 0, 13, 28, 0, true);
roof_8_r2 = new ModelMapper(modelDataWrapper);
roof_8_r2.setPos(15.5298F, -29.8468F, 35.8167F);
head_side_2.addChild(roof_8_r2);
setRotationAngle(roof_8_r2, -0.1745F, -0.3491F, -1.0472F);
roof_8_r2.texOffs(0, 108).addBox(0, -6, -15, 0, 12, 30, 0, true);
roof_5_r8 = new ModelMapper(modelDataWrapper);
roof_5_r8.setPos(2, -42, -9);
head_side_2.addChild(roof_5_r8);
setRotationAngle(roof_5_r8, 0, 0, -1.5708F);
roof_5_r8.texOffs(265, 289).addBox(-1, -2, -6, 1, 4, 12, 0, true);
roof_5_r9 = new ModelMapper(modelDataWrapper);
roof_5_r9.setPos(8.1369F, -39.4953F, 9.8171F);
head_side_2.addChild(roof_5_r9);
setRotationAngle(roof_5_r9, -0.1309F, -0.1309F, -1.3963F);
roof_5_r9.texOffs(32, 292).addBox(0, -3.5F, -13.5F, 0, 7, 27, 0, true);
roof_4_r14 = new ModelMapper(modelDataWrapper);
roof_4_r14.setPos(13.6527F, -37.467F, 10.5898F);
head_side_2.addChild(roof_4_r14);
setRotationAngle(roof_4_r14, -0.0873F, -0.0873F, -1.0472F);
roof_4_r14.texOffs(204, 247).addBox(0, -3.5F, -14, 0, 7, 28, 0, true);
roof_3_r12 = new ModelMapper(modelDataWrapper);
roof_3_r12.setPos(17.2178F, -34.6364F, 11.8407F);
head_side_2.addChild(roof_3_r12);
setRotationAngle(roof_3_r12, -0.0436F, -0.0436F, -0.6981F);
roof_3_r12.texOffs(204, 235).addBox(0, -3, -15, 0, 6, 30, 0, true);
roof_4_r15 = new ModelMapper(modelDataWrapper);
roof_4_r15.setPos(6.6372F, -40.9654F, -9);
head_side_2.addChild(roof_4_r15);
setRotationAngle(roof_4_r15, 0, 0, -1.3963F);
roof_4_r15.texOffs(230, 139).addBox(-0.5F, -3.5F, -6, 1, 7, 12, 0, true);
roof_3_r13 = new ModelMapper(modelDataWrapper);
roof_3_r13.setPos(12.519F, -38.9171F, -9);
head_side_2.addChild(roof_3_r13);
setRotationAngle(roof_3_r13, 0, 0, -1.0472F);
roof_3_r13.texOffs(0, 274).addBox(-0.5F, -3, -6, 1, 6, 12, 0, true);
roof_2_r16 = new ModelMapper(modelDataWrapper);
roof_2_r16.setPos(16.2696F, -35.9966F, -9);
head_side_2.addChild(roof_2_r16);
setRotationAngle(roof_2_r16, 0, 0, -0.6981F);
roof_2_r16.texOffs(296, 243).addBox(-0.5F, -2, -6, 1, 4, 12, 0, true);
middle = new ModelMapper(modelDataWrapper);
middle.setPos(0, 0, 0);
head_exterior.addChild(middle);
middle.texOffs(181, 8).addBox(-7, 0, 70, 14, 5, 0, 0, false);
middle.texOffs(0, 50).addBox(-7, 9.2433F, 65.7571F, 14, 3, 0, 0, false);
middle.texOffs(0, 0).addBox(-19, 0, -15, 38, 1, 85, 0, false);
middle.texOffs(0, 231).addBox(-20, -42, -14.5F, 40, 42, 1, 0, false);
roof_8_r3 = new ModelMapper(modelDataWrapper);
roof_8_r3.setPos(0, 0, 70);
middle.addChild(roof_8_r3);
setRotationAngle(roof_8_r3, 0.3491F, 0, 0);
roof_8_r3.texOffs(32, 326).addBox(-8, -11, 0, 16, 11, 0, 0, false);
roof_7_r3 = new ModelMapper(modelDataWrapper);
roof_7_r3.setPos(0, -18.733F, 57.665F);
middle.addChild(roof_7_r3);
setRotationAngle(roof_7_r3, 0, -0.7854F, -1.5708F);
roof_7_r3.texOffs(0, 5).addBox(0, -10, -12.5F, 0, 20, 25, 0, false);
roof_6_r4 = new ModelMapper(modelDataWrapper);
roof_6_r4.setPos(0, -32.7021F, 34.7308F);
middle.addChild(roof_6_r4);
setRotationAngle(roof_6_r4, 0, -0.3491F, -1.5708F);
roof_6_r4.texOffs(0, 23).addBox(0, -13, -15, 0, 26, 30, 0, false);
roof_5_r10 = new ModelMapper(modelDataWrapper);
roof_5_r10.setPos(0, -42, -3);
middle.addChild(roof_5_r10);
setRotationAngle(roof_5_r10, 0, -0.1745F, -1.5708F);
roof_5_r10.texOffs(144, 241).addBox(0, -10, 0, 0, 20, 24, 0, false);
roof_9_r3 = new ModelMapper(modelDataWrapper);
roof_9_r3.setPos(0, 5, 70);
middle.addChild(roof_9_r3);
setRotationAngle(roof_9_r3, -0.7854F, 0, 0);
roof_9_r3.texOffs(230, 158).addBox(-7, 0, 0, 14, 6, 0, 0, false);
bottom_middle = new ModelMapper(modelDataWrapper);
bottom_middle.setPos(0, 24, 0);
bottom_middle.texOffs(264, 235).addBox(-17, 2, -15, 1, 10, 30, 0, false);
bottom_end = new ModelMapper(modelDataWrapper);
bottom_end.setPos(0, 24, 0);
bottom_end.texOffs(0, 0).addBox(-17, 2, -7, 1, 10, 14, 0, false);
seat = new ModelMapper(modelDataWrapper);
seat.setPos(0, 24, 0);
seat.texOffs(181, 0).addBox(-4, -6, -4, 8, 1, 7, 0, false);
seat.texOffs(214, 0).addBox(-3.5F, -22.644F, 4.0686F, 7, 5, 1, 0, false);
seat_2_r1 = new ModelMapper(modelDataWrapper);
seat_2_r1.setPos(0, -6, 2);
seat.addChild(seat_2_r1);
setRotationAngle(seat_2_r1, -0.1745F, 0, 0);
seat_2_r1.texOffs(161, 0).addBox(-4, -12, 0, 8, 12, 1, 0, false);
headlights = new ModelMapper(modelDataWrapper);
headlights.setPos(0, 24, 0);
headlight_2_r1 = new ModelMapper(modelDataWrapper);
headlight_2_r1.setPos(12.533F, -16.0189F, 57.5648F);
headlights.addChild(headlight_2_r1);
setRotationAngle(headlight_2_r1, -0.2618F, -0.7854F, -1.0472F);
headlight_2_r1.texOffs(345, 54).addBox(0.1F, -1.5F, -2.9F, 0, 5, 12, 0, true);
headlight_1_r1 = new ModelMapper(modelDataWrapper);
headlight_1_r1.setPos(-12.533F, -16.0189F, 57.5648F);
headlights.addChild(headlight_1_r1);
setRotationAngle(headlight_1_r1, -0.2618F, 0.7854F, 1.0472F);
headlight_1_r1.texOffs(345, 54).addBox(-0.1F, -1.5F, -2.9F, 0, 5, 12, 0, false);
tail_lights = new ModelMapper(modelDataWrapper);
tail_lights.setPos(0, 24, 0);
tail_lights_2_r1 = new ModelMapper(modelDataWrapper);
tail_lights_2_r1.setPos(12.533F, -16.0189F, 57.5648F);
tail_lights.addChild(tail_lights_2_r1);
setRotationAngle(tail_lights_2_r1, -0.2618F, -0.7854F, -1.0472F);
tail_lights_2_r1.texOffs(345, 59).addBox(0.1F, -1.5F, -2.9F, 0, 5, 12, 0, true);
tail_lights_1_r1 = new ModelMapper(modelDataWrapper);
tail_lights_1_r1.setPos(-12.533F, -16.0189F, 57.5648F);
tail_lights.addChild(tail_lights_1_r1);
setRotationAngle(tail_lights_1_r1, -0.2618F, 0.7854F, 1.0472F);
tail_lights_1_r1.texOffs(345, 59).addBox(-0.1F, -1.5F, -2.9F, 0, 5, 12, 0, false);
door_light_off = new ModelMapper(modelDataWrapper);
door_light_off.setPos(0, 24, 0);
door_light_off_r1 = new ModelMapper(modelDataWrapper);
door_light_off_r1.setPos(-21, -13, 0);
door_light_off.addChild(door_light_off_r1);
setRotationAngle(door_light_off_r1, 0, 0, 0.1396F);
door_light_off_r1.texOffs(0, 0).addBox(-0.5F, -21.5F, -0.5F, 1, 1, 1, 0, false);
door_light_on = new ModelMapper(modelDataWrapper);
door_light_on.setPos(0, 24, 0);
door_light_on_r1 = new ModelMapper(modelDataWrapper);
door_light_on_r1.setPos(-21, -13, 0);
door_light_on.addChild(door_light_on_r1);
setRotationAngle(door_light_on_r1, 0, 0, 0.1396F);
door_light_on_r1.texOffs(0, 2).addBox(-0.5F, -21.5F, -0.5F, 1, 1, 1, 0, false);
modelDataWrapper.setModelPart(textureWidth, textureHeight);
window.setModelPart();
window_light.setModelPart();
window_exterior_1.setModelPart();
window_exterior_2.setModelPart();
window_exterior_3.setModelPart();
window_exterior_4.setModelPart();
window_exterior_5.setModelPart();
window_exterior_6.setModelPart();
window_exterior_7.setModelPart();
window_exterior_8.setModelPart();
window_exterior_9.setModelPart();
window_end_exterior_1.setModelPart();
window_end_exterior_2.setModelPart();
window_end_exterior_3.setModelPart();
window_end_exterior_4.setModelPart();
window_end_exterior_5.setModelPart();
window_end_exterior_6.setModelPart();
door.setModelPart();
door_1.setModelPart(door.name);
door_2.setModelPart(door.name);
door_exterior.setModelPart();
door_exterior_1.setModelPart(door_exterior.name);
door_exterior_2.setModelPart(door_exterior.name);
door_exterior_end.setModelPart();
door_exterior_end_1.setModelPart(door_exterior_end.name);
door_exterior_end_2.setModelPart(door_exterior_end.name);
roof_exterior.setModelPart();
end.setModelPart();
end_light.setModelPart();
end_translucent.setModelPart();
end_exterior.setModelPart();
roof_vent.setModelPart();
head_exterior.setModelPart();
bottom_middle.setModelPart();
bottom_end.setModelPart();
seat.setModelPart();
headlights.setModelPart();
tail_lights.setModelPart();
door_light_off.setModelPart();
door_light_on.setModelPart();
}
private static final int DOOR_MAX = 13;
@Override
protected void renderWindowPositions(PoseStack matrices, VertexConsumer vertices, RenderStage renderStage, int light, int position, boolean renderDetails, float doorLeftX, float doorRightX, float doorLeftZ, float doorRightZ, boolean isEnd1Head, boolean isEnd2Head) {
final ModelMapper[] windowParts = isEnd1Head || isEnd2Head ? windowEndParts() : windowParts();
final int windowPartsLength = windowParts.length;
final int offset = windowParts().length / 2;
final int loopMax = isEnd1Head && isEnd2Head ? windowPartsLength - offset + 1 : windowPartsLength;
switch (renderStage) {
case LIGHTS:
for (int i = 0; i < loopMax; i++) {
renderMirror(window_light, matrices, vertices, light, (isEnd2Head ? -1 : 1) * (i - windowPartsLength + offset + 1) * 30);
}
break;
case INTERIOR:
for (int i = 0; i < loopMax; i++) {
final int newPosition = (isEnd2Head ? -1 : 1) * (i - windowPartsLength + offset + 1) * 30;
renderMirror(window, matrices, vertices, light, newPosition);
if (renderDetails) {
if (i % 4 < 2) {
renderOnce(seat, matrices, vertices, light, -16, newPosition - 5);
renderOnce(seat, matrices, vertices, light, -16, newPosition + 10);
renderOnce(seat, matrices, vertices, light, -8, newPosition - 5);
renderOnce(seat, matrices, vertices, light, -8, newPosition + 10);
renderOnce(seat, matrices, vertices, light, 8, newPosition - 5);
renderOnce(seat, matrices, vertices, light, 8, newPosition + 10);
renderOnce(seat, matrices, vertices, light, 16, newPosition - 5);
renderOnce(seat, matrices, vertices, light, 16, newPosition + 10);
} else {
renderOnceFlipped(seat, matrices, vertices, light, -16, newPosition - 10);
renderOnceFlipped(seat, matrices, vertices, light, -16, newPosition + 5);
renderOnceFlipped(seat, matrices, vertices, light, -8, newPosition - 10);
renderOnceFlipped(seat, matrices, vertices, light, -8, newPosition + 5);
renderOnceFlipped(seat, matrices, vertices, light, 8, newPosition - 10);
renderOnceFlipped(seat, matrices, vertices, light, 8, newPosition + 5);
renderOnceFlipped(seat, matrices, vertices, light, 16, newPosition - 10);
renderOnceFlipped(seat, matrices, vertices, light, 16, newPosition + 5);
}
}
}
break;
case EXTERIOR:
if (isEnd1Head || isEnd2Head) {
for (int i = 0; i < loopMax; i++) {
final int newPosition = (isEnd2Head ? -1 : 1) * (i - windowPartsLength + offset + 1) * 30;
renderOnce(windowParts[i], matrices, vertices, light, newPosition);
renderMirror(roof_exterior, matrices, vertices, light, newPosition);
}
} else {
for (int i = 0; i < windowPartsLength; i++) {
renderOnce(windowParts[i], matrices, vertices, light, (i - offset) * 30);
}
for (int i = 0; i < windowPartsLength; i++) {
final int newPosition = (i - offset) * 30;
renderOnceFlipped(windowParts[windowPartsLength - i - 1], matrices, vertices, light, newPosition);
renderMirror(roof_exterior, matrices, vertices, light, newPosition);
}
}
final int[] bogiePositions = getBogiePositions();
renderMirror(bottom_end, matrices, vertices, light, bogiePositions[0] + 42);
renderMirror(bottom_end, matrices, vertices, light, bogiePositions[1] - 42);
for (int i = bogiePositions[0] + 64; i <= bogiePositions[1] - 64; i += 30) {
renderMirror(bottom_middle, matrices, vertices, light, i);
}
break;
}
}
@Override
protected void renderDoorPositions(PoseStack matrices, VertexConsumer vertices, RenderStage renderStage, int light, int position, boolean renderDetails, float doorLeftX, float doorRightX, float doorLeftZ, float doorRightZ, boolean isEnd1Head, boolean isEnd2Head) {
final boolean firstDoor = isIndex(0, position, getDoorPositions());
final int doorOffset = (isEnd1Head && firstDoor ? 90 : 0) + (isEnd2Head && !firstDoor ? -90 : 0);
final boolean doorOpen = doorLeftZ > 0 || doorRightZ > 0;
switch (renderStage) {
case LIGHTS:
if (firstDoor && doorOpen) {
renderMirror(door_light_on, matrices, vertices, light, 0);
}
break;
case INTERIOR:
if (firstDoor) {
door_1.setOffset(0, 0, -doorLeftZ);
door_2.setOffset(0, 0, doorRightZ);
renderOnceFlipped(door, matrices, vertices, light, position + doorOffset);
} else {
door_1.setOffset(0, 0, doorRightZ);
door_2.setOffset(0, 0, -doorLeftZ);
renderOnce(door, matrices, vertices, light, position + doorOffset);
}
break;
case EXTERIOR:
if (isEnd1Head && firstDoor || isEnd2Head && !firstDoor) {
if (firstDoor) {
door_exterior_end_1.setOffset(0, 0, -doorLeftZ);
door_exterior_end_2.setOffset(0, 0, doorRightZ);
renderOnceFlipped(door_exterior_end, matrices, vertices, light, position + doorOffset);
} else {
door_exterior_end_1.setOffset(0, 0, doorRightZ);
door_exterior_end_2.setOffset(0, 0, -doorLeftZ);
renderOnce(door_exterior_end, matrices, vertices, light, position + doorOffset);
}
} else {
if (firstDoor) {
door_exterior_1.setOffset(0, 0, -doorLeftZ);
door_exterior_2.setOffset(0, 0, doorRightZ);
renderOnceFlipped(door_exterior, matrices, vertices, light, position);
} else {
door_exterior_1.setOffset(0, 0, doorRightZ);
door_exterior_2.setOffset(0, 0, -doorLeftZ);
renderOnce(door_exterior, matrices, vertices, light, position);
}
}
if (firstDoor && !doorOpen) {
renderMirror(door_light_off, matrices, vertices, light, 0);
}
break;
}
}
@Override
protected void renderHeadPosition1(PoseStack matrices, VertexConsumer vertices, RenderStage renderStage, int light, int position, boolean renderDetails, float doorLeftX, float doorRightX, float doorLeftZ, float doorRightZ, boolean useHeadlights) {
switch (renderStage) {
case LIGHTS:
renderOnceFlipped(end_light, matrices, vertices, light, position + 90);
break;
case ALWAYS_ON_LIGHTS:
renderOnceFlipped(useHeadlights ? headlights : tail_lights, matrices, vertices, light, position + 30);
break;
case INTERIOR:
renderOnceFlipped(end, matrices, vertices, light, position + 90);
break;
case INTERIOR_TRANSLUCENT:
renderOnceFlipped(end_translucent, matrices, vertices, light, position + 90);
break;
case EXTERIOR:
renderOnceFlipped(head_exterior, matrices, vertices, light, position + 30);
renderMirror(roof_exterior, matrices, vertices, light, position + 60);
renderMirror(roof_exterior, matrices, vertices, light, position + 90);
break;
}
}
@Override
protected void renderHeadPosition2(PoseStack matrices, VertexConsumer vertices, RenderStage renderStage, int light, int position, boolean renderDetails, float doorLeftX, float doorRightX, float doorLeftZ, float doorRightZ, boolean useHeadlights) {
switch (renderStage) {
case LIGHTS:
renderOnce(end_light, matrices, vertices, light, position - 90);
break;
case ALWAYS_ON_LIGHTS:
renderOnce(useHeadlights ? headlights : tail_lights, matrices, vertices, light, position - 30);
break;
case INTERIOR:
renderOnce(end, matrices, vertices, light, position - 90);
break;
case INTERIOR_TRANSLUCENT:
renderOnce(end_translucent, matrices, vertices, light, position - 90);
break;
case EXTERIOR:
renderOnce(head_exterior, matrices, vertices, light, position - 30);
renderMirror(roof_exterior, matrices, vertices, light, position - 60);
renderMirror(roof_exterior, matrices, vertices, light, position - 90);
break;
}
}
@Override
protected void renderEndPosition1(PoseStack matrices, VertexConsumer vertices, RenderStage renderStage, int light, int position, boolean renderDetails, float doorLeftX, float doorRightX, float doorLeftZ, float doorRightZ) {
switch (renderStage) {
case LIGHTS:
renderOnceFlipped(end_light, matrices, vertices, light, position);
break;
case INTERIOR:
renderOnceFlipped(end, matrices, vertices, light, position);
break;
case INTERIOR_TRANSLUCENT:
renderOnceFlipped(end_translucent, matrices, vertices, light, position);
break;
case EXTERIOR:
renderOnceFlipped(end_exterior, matrices, vertices, light, position);
renderMirror(roof_exterior, matrices, vertices, light, position);
renderMirror(roof_exterior, matrices, vertices, light, position - 30);
renderOnceFlipped(roof_vent, matrices, vertices, light, position);
break;
}
}
@Override
protected void renderEndPosition2(PoseStack matrices, VertexConsumer vertices, RenderStage renderStage, int light, int position, boolean renderDetails, float doorLeftX, float doorRightX, float doorLeftZ, float doorRightZ) {
switch (renderStage) {
case LIGHTS:
renderOnce(end_light, matrices, vertices, light, position);
break;
case INTERIOR:
renderOnce(end, matrices, vertices, light, position);
break;
case INTERIOR_TRANSLUCENT:
renderOnce(end_translucent, matrices, vertices, light, position);
break;
case EXTERIOR:
renderOnce(end_exterior, matrices, vertices, light, position);
renderMirror(roof_exterior, matrices, vertices, light, position);
renderMirror(roof_exterior, matrices, vertices, light, position + 30);
renderOnce(roof_vent, matrices, vertices, light, position);
break;
}
}
@Override
protected ModelDoorOverlay getModelDoorOverlay() {
return null;
}
@Override
protected ModelDoorOverlayTopBase getModelDoorOverlayTop() {
return null;
}
@Override
protected int[] getWindowPositions() {
return new int[]{0};
}
@Override
protected int[] getDoorPositions() {
return new int[]{-150, 150};
}
@Override
protected int[] getEndPositions() {
return new int[]{-150, 150};
}
@Override
protected int[] getBogiePositions() {
return new int[]{-124, 124};
}
@Override
protected float getDoorAnimationX(float value, boolean opening) {
return 0;
}
@Override
protected float getDoorAnimationZ(float value, boolean opening) {
return smoothEnds(0, DOOR_MAX, 0, 0.5F, value);
}
protected ModelMapper[] windowParts() {
return new ModelMapper[]{window_exterior_1, window_exterior_2, window_exterior_3, window_exterior_4, window_exterior_5, window_exterior_6, window_exterior_7, window_exterior_8, window_exterior_9};
}
protected ModelMapper[] windowEndParts() {
return new ModelMapper[]{window_end_exterior_1, window_end_exterior_2, window_end_exterior_3, window_end_exterior_4, window_end_exterior_5, window_end_exterior_6};
}
}
|
/***
* Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*
* Update (2014-11-02):
* The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.
*/
public class Solution {
// Solution 1: T: O(n*m), S O(1). Time limit exceeded.
/*
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0)
return 0;
int len1 = haystack.length();
int len2 = needle.length();
int a,b;
for (int i = 0; i < len1; i++) {
a = i;
b = 0;
boolean match = true;
while (b < len2) {
if (a >= len1 || haystack.charAt(a) != needle.charAt(b)) {
match = false;
break;
} else {
a++;
b++;
}
}
if (match)
return i;
}
return -1;
}
*/
// Solution 2. Boyer-Moore string search algorithm
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0)
return 0;
int charTable[] = makeCharTable(needle);
int offsetTable[] = makeOffsetTable(needle);
for (int i = needle.length - 1, j; i < haystack.length;) {
for (j = needle.length - 1; needle[j] == haystack[i]; --i, --j) {
if (j == 0)
return i;
}
i += Math.max(offsetTable[needle.length - 1 -j], charTable[haystack[i]]);
}
return -1;
}
/**
* Makes the jump table based on the mismatched character information
*/
private static int[] makeCharTable(char[] needle) {
final int ALPHABET_SIZE = 256;
int[] table = new int[ALPHABET_SIZE];
for (int i = 0; i < table.length; ++i)
table[i] = needle.length;
for (int i = 0; i < needle.length - 1; ++i)
table[needle[i]] = needle.length - 1 -i;
return table;
}
/**
* Makes the jump table based on the scan offset which mismatch occurs.
*/
private static int[] makeOffsetTable(char[] needle) {
int[] table = new int[needle.length];
int lastPrefixPosition = needle.length;
for (int i = needle.length - 1; i >= 0; --i) {
if (isPrefix(needle, i + 1))
lastPrefixPosition = i + 1;
table[needle.length - 1 - i] = lastPrefixPosition - i + needle.length - 1;
}
for (int i = 0; i < needle.length - 1; ++i) {
int slen = suffixLength(needle, i);
table[slen] = needle.len - 1 - i + slen;
}
return table;
}
/**
* Is needle[p:end] a prefix of needle?
*/
private static boolean isPrefix(char[] needle, int p) {
for (int i = p, j = 0; i < needle.length; ++i, ++j) {
if (needle[i] != needle[j])
return false;
}
return true;
}
/**
* Returns the maximum length of the substring ends ta p and is a suffix.
*/
private static int suffixLength(char[] needle, int p) {
int len = 0;
for ( int i = p, j = needle.length - 1;
i >= 0 && needle[i] == needle[j];
--i, --j) {
len += 1;
}
return len;
}
}
|
package de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Parameter;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
/**
* Parameterization handler using a List and OptionIDs, for programmatic use.
*
* @author Erich Schubert
*/
public class ListParameterization extends AbstractParameterization {
/**
* The actual parameters, for storage
*/
LinkedList<Pair<OptionID, Object>> parameters = new LinkedList<Pair<OptionID, Object>>();
/**
* Default constructor.
*/
public ListParameterization() {
super();
}
/**
* Constructor with an existing collection.
*
* @param dbParameters existing parameter collection
*/
public ListParameterization(Collection<Pair<OptionID, Object>> dbParameters) {
this();
for (Pair<OptionID, Object> pair : dbParameters) {
addParameter(pair.first, pair.second);
}
}
/**
* Add a flag to the parameter list
*
* @param optionid Option ID
*/
public void addFlag(OptionID optionid) {
parameters.add(new Pair<OptionID, Object>(optionid, Flag.SET));
}
/**
* Add a parameter to the parameter list
*
* @param optionid Option ID
* @param value Value
*/
public void addParameter(OptionID optionid, Object value) {
parameters.add(new Pair<OptionID, Object>(optionid, value));
}
/**
* Convenience - add a Flag option directly.
*
* @param flag Flag to add, if set
*/
public void forwardOption(Flag flag) {
if (flag.isDefined() && flag.getValue()) {
addFlag(flag.getOptionID());
}
}
/**
* Convenience - add a Parameter for forwarding
*
* @param param Parameter to add
*/
public void forwardOption(Parameter<?,?> param) {
if (param.isDefined()) {
addParameter(param.getOptionID(), param.getValue());
}
}
@Override
public boolean setValueForOption(Parameter<?,?> opt) throws ParameterException {
Iterator<Pair<OptionID, Object>> iter = parameters.iterator();
while(iter.hasNext()) {
Pair<OptionID, Object> pair = iter.next();
if(pair.first == opt.getOptionID()) {
iter.remove();
opt.setValue(pair.second);
return true;
}
}
return false;
}
/**
* Return the yet unused parameters.
*
* @return Unused parameters.
*/
public List<Pair<OptionID, Object>> getRemainingParameters() {
return parameters;
}
@Override
public boolean hasUnusedParameters() {
return (parameters.size() > 0);
}
// FIXME: ERICH: INCOMPLETE TRANSITION: toString() here is NOT reliable!
// This isn't really workable in a non-string context.
// But it will suffice for transition purposes.
@Deprecated
public String[] asArray() {
ArrayList<String> ret = new ArrayList<String>(2*parameters.size());
for (Pair<OptionID, Object> pair : parameters) {
ret.add(SerializedParameterization.OPTION_PREFIX + pair.first.getName());
if (!(pair.second instanceof String)) {
throw new RuntimeException("Deprecated functino asArray may only be used with string-serialized values!");
}
ret.add((String) pair.second);
}
return ret.toArray(new String[]{});
}
/** {@inheritDoc}
* Default implementation, for flat parameterizations.
*/
@Override
public Parameterization descend(@SuppressWarnings("unused") Parameter<?, ?> option) {
return this;
}
}
|
package com.ryanpmartz.booktrackr.authentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ryanpmartz.booktrackr.BooktrackrApplication;
import com.ryanpmartz.booktrackr.authentication.dto.LoginRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.assertTrue;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.hasText;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {BooktrackrApplication.class})
@WebIntegrationTest(randomPort = true)
@Sql("/users-integration-test-data.sql")
public class JwtAuthenticationIT {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
@Test
public void testCanAuthenticateAndUseTokenToAccessProtectedResource() throws Exception {
mockMvc.perform(get("/books")).andExpect(status().isForbidden());
LoginRequest login = new LoginRequest();
login.setUsername("martzrp@gmail.com");
login.setPassword("password");
ObjectMapper mapper = new ObjectMapper();
MvcResult authenticationResult = mockMvc.perform(post("/authenticate").content(mapper.writeValueAsString(login)).contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk()).andReturn();
String authHeaderValue = authenticationResult.getResponse().getHeader("Authorization");
assertTrue(hasText(authHeaderValue));
mockMvc.perform(get("/books").header("Authorization", authHeaderValue))
.andDo(print()).andExpect(status().isOk());
}
}
|
package controllers;
import java.util.Set;
import java.util.TreeSet;
import models.Comment;
import models.Post;
import models.PostRating;
import models.PostRatingPK;
import models.S3File;
import models.User;
import play.Logger;
import play.Logger.ALogger;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import security.CommentDeletePermission;
import security.CommentEditPermission;
import security.PostDeletePermission;
import security.PostEditPermission;
import security.RestrictApproved;
import security.RestrictCombine;
import socialauth.core.Secure;
import socialauth.core.SocialAware;
import utils.HttpUtils;
import views.html.index;
import views.html.postForm;
import views.html.postShow;
import views.html.rate;
import views.html.helper.H;
import com.avaje.ebean.Page;
public class PostController extends Controller implements Constants {
private static ALogger log = Logger.of(PostController.class);
static Form<Post> form = form(Post.class);
static Form<Comment> commentForm = form(Comment.class);
/**
* Display the paginated list of posts.
*
* @param page
* Current page number (starts from 0)
*/
@SocialAware
public static Result list(int page) {
if (log.isDebugEnabled())
log.debug("index() <-");
if (log.isDebugEnabled())
log.debug("page : " + page);
User user = HttpUtils.loginUser(ctx());
final Set<Long> votedPostKeys = user == null ? new TreeSet<Long>() : user.getVotedPostKeys();
Page<Post> topDay = Post.topDayPage();
Page<Post> topWeek = Post.topWeekPage();
Page<Post> topAll = Post.topAllPage();
Page<Post> pg = Post.page(page, POSTS_PER_PAGE);
return ok(index.render(pg, topDay, topWeek, topAll, user, votedPostKeys));
}
@Secure
@RestrictApproved
public static Result newForm() {
if (log.isDebugEnabled())
log.debug("newForm() <-");
User user = HttpUtils.loginUser(ctx());
return ok(postForm.render(null, form, user));
}
@Secure
@RestrictApproved
public static Result create() {
if (log.isDebugEnabled())
log.debug("create() <-");
User user = HttpUtils.loginUser(ctx());
Form<Post> filledForm = form.bindFromRequest();
if (filledForm.hasErrors() || user == null) {
if (log.isDebugEnabled())
log.debug("validation errors occured");
return badRequest(postForm.render(null, filledForm, user));
} else {
Post post = filledForm.get();
post.setCreatedBy(user);
S3File image = HttpUtils.uploadFile(request(), "image");
if (log.isDebugEnabled())
log.debug("image : " + image);
if (image != null) {
image.parent = "Post";
S3File.create(image);
if (log.isDebugEnabled())
log.debug("image : " + image);
post.setImage(image);
}
Post.create(post);
if (log.isDebugEnabled())
log.debug("entity created: " + post);
return redirect(routes.HomeController.index());
}
}
@Secure
@RestrictCombine(roles = "admin", with = PostEditPermission.class)
@RestrictApproved
public static Result editForm(Long key) {
if (log.isDebugEnabled())
log.debug("editForm() <-" + key);
Post post = Post.get(key);
if (log.isDebugEnabled())
log.debug("post : " + post);
User user = HttpUtils.loginUser(ctx());
Form<Post> frm = form.fill(post);
return ok(postForm.render(key, frm, user));
}
@Secure
@RestrictCombine(roles = "admin", with = PostEditPermission.class)
@RestrictApproved
public static Result update(Long key) {
if (log.isDebugEnabled())
log.debug("update() <-" + key);
User user = HttpUtils.loginUser(ctx());
Form<Post> filledForm = form.bindFromRequest();
if (filledForm.hasErrors() || user == null) {
if (log.isDebugEnabled())
log.debug("validation errors occured");
return badRequest(postForm.render(key, filledForm, user));
} else {
Post postData = Post.get(key);
Post post = filledForm.get();
post.setRating(postData.getRating());
post.setUpdatedBy(user);
if (log.isDebugEnabled())
log.debug("post : " + post);
Post.update(key, post);
if (log.isDebugEnabled())
log.debug("entity updated");
return redirect(routes.HomeController.index());
}
}
/**
* Display the paginated list of posts.
*
* @param page
* Current page number (starts from 0)
*/
@SocialAware
public static Result show(Long postKey, String title, int page) {
if (log.isDebugEnabled())
log.debug("show() <-" + postKey);
Post post = Post.get(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
User user = HttpUtils.loginUser(ctx());
final Set<Long> votedPostKeys = user == null ? new TreeSet<Long>() : user.getVotedPostKeys();
final Page<Comment> pg = Comment.page(postKey, page, COMMENTS_PER_PAGE);
return ok(postShow.render(post, null, commentForm, user, pg, votedPostKeys));
}
@Secure
@RestrictCombine(roles = "admin", with = PostDeletePermission.class)
@RestrictApproved
public static Result delete(Long key) {
if (log.isDebugEnabled())
log.debug("delete() <-" + key);
Post.remove(key);
if (log.isDebugEnabled())
log.debug("entity deleted");
return redirect(routes.HomeController.index());
}
//Comment stuff
@Secure
@RestrictApproved
public static Result createComment(Long postKey, String title) {
if (log.isDebugEnabled())
log.debug("createComment() <-" + postKey);
Post post = Post.get(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
User user = HttpUtils.loginUser(ctx());
Form<Comment> filledForm = commentForm.bindFromRequest();
if (filledForm.hasErrors() || user == null) {
if (log.isDebugEnabled())
log.debug("validation errors occured");
final Set<Long> votedPostKeys = user == null ? new TreeSet<Long>() : user.getVotedPostKeys();
final Page<Comment> pg = Comment.page(postKey, 0, COMMENTS_PER_PAGE);
return badRequest(postShow.render(post, null, filledForm, user, pg, votedPostKeys));
} else {
Comment comment = filledForm.get();
comment.setPost(post);
comment.setCreatedBy(user);
if (log.isDebugEnabled())
log.debug("comment : " + comment);
Comment.create(comment);
if (log.isDebugEnabled())
log.debug("comment created");
final Long key = post.getKey();
return redirect(routes.PostController.show(key, title, 0));
}
}
@Secure
@RestrictCombine(roles = "admin", with = CommentEditPermission.class)
@RestrictApproved
public static Result editCommentForm(Long postKey, Long commentKey) {
if (log.isDebugEnabled())
log.debug("editCommentForm() <-");
Post post = Post.get(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
Comment comment = Comment.get(commentKey);
if (log.isDebugEnabled())
log.debug("comment : " + comment);
User user = HttpUtils.loginUser(ctx());
final Set<Long> votedPostKeys = user == null ? new TreeSet<Long>() : user.getVotedPostKeys();
Form<Comment> form = commentForm.fill(comment);
final Page<Comment> pg = Comment.page(postKey, 0, COMMENTS_PER_PAGE);
return ok(postShow.render(post, commentKey, form, user, pg, votedPostKeys));
}
@Secure
@RestrictCombine(roles = "admin", with = CommentEditPermission.class)
@RestrictApproved
public static Result updateComment(Long postKey, Long commentKey) {
if (log.isDebugEnabled())
log.debug("updateComment() <-");
Post post = Post.get(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
User user = HttpUtils.loginUser(ctx());
Form<Comment> filledForm = commentForm.bindFromRequest();
if (filledForm.hasErrors() || user == null) {
if (log.isDebugEnabled())
log.debug("validation errors occured");
final Set<Long> votedPostKeys = user == null ? new TreeSet<Long>() : user.getVotedPostKeys();
final Page<Comment> pg = Comment.page(postKey, 0, COMMENTS_PER_PAGE);
return badRequest(postShow.render(post, commentKey, filledForm, user, pg, votedPostKeys));
} else {
Comment comment = filledForm.get();
comment.setUpdatedBy(user);
if (log.isDebugEnabled())
log.debug("comment : " + comment);
Comment.update(commentKey, comment);
if (log.isDebugEnabled())
log.debug("entity updated");
final Long key = post.getKey();
final String title = H.sanitize(post.getTitle());
return redirect(routes.PostController.show(key, title, 0));
}
}
@Secure
@RestrictCombine(roles = "admin", with = CommentDeletePermission.class)
@RestrictApproved
public static Result deleteComment(Long postKey, Long commentKey) {
if (log.isDebugEnabled())
log.debug("deleteComment() <-");
Post post = Post.get(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
Comment.remove(commentKey);
if (log.isDebugEnabled())
log.debug("entity deleted");
final Long key = post.getKey();
final String title = H.sanitize(post.getTitle());
return redirect(routes.PostController.show(key, title, 0));
}
/**
* rating is done via ajax, therefore return simply the eventual rate sum
*/
@Secure
@RestrictApproved
public static Result rateUp(Long key) {
if (log.isDebugEnabled())
log.debug("rateUp <-" + key);
return rate(key, 1);
}
@Secure
@RestrictApproved
public static Result rateDown(Long key) {
if (log.isDebugEnabled())
log.debug("rateDown <-" + key);
return rate(key, -1);
}
public static Result rate(Long postKey, int rating) {
if (log.isDebugEnabled())
log.debug("rate <-" + postKey);
if (log.isDebugEnabled())
log.debug("rating : " + rating);
Post post = Post.get(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
User user = HttpUtils.loginUser(ctx());
if (log.isDebugEnabled())
log.debug("user : " + user);
if (post != null && user != null) {
//save/update rate
if (post.getRating() == null)
post.setRating(0);
PostRating pr = PostRating.get(user, post);
if (log.isDebugEnabled())
log.debug("pr : " + pr);
PostRatingPK key = new PostRatingPK(user.getKey(), post.getKey());
if (pr == null) {
pr = new PostRating();
pr.setValue(rating);
pr.setKey(key);
PostRating.create(pr);
post.setRating(post.getRating() + rating);
} else {
int ratingBefore = pr.getValue();
pr.setValue(rating);
PostRating.update(key, pr);
if (log.isDebugEnabled())
log.debug("post.rating : " + post.getRating());
if (log.isDebugEnabled())
log.debug("pr.value : " + ratingBefore);
post.setRating(post.getRating() - ratingBefore + rating);
}
user.resetPostKeyCache();
if (log.isDebugEnabled())
log.debug("updating post : " + post);
post.update(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
return ok(rate.render(post.getRating()));
} else {
if (log.isDebugEnabled())
log.debug("no user");
return TODO;
}
}
public static Result rateShow(Long postKey) {
Post post = Post.get(postKey);
if (log.isDebugEnabled())
log.debug("post : " + post);
if (post != null) {
return ok(rate.render(post.getRating()));
}
if (log.isDebugEnabled())
log.debug("no post");
return TODO;
}
}
|
package ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.dao.impl;
import java.util.LinkedList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.dao.ArtistDAO;
import ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.main.ServerOptions;
import ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.model.Artist;
public class ArtistDaoImpl implements ArtistDAO {
private Session currentSession;
private Transaction currentTransaction;
@Override
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
@Override
public Session openCurrentSessionwithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
@Override
public void closeCurrentSession() {
currentSession.close();
}
@Override
public void closeCurrentSessionwithTransaction() {
currentTransaction.commit();
currentSession.close();
}
private static SessionFactory getSessionFactory() {
String dbHost = ServerOptions.getInstance().getDbHost();
String dbPort = ServerOptions.getInstance().getDbPort();
// Configuration configuration = new Configuration().addPackage("models").configure("hibernate.cfg.xml").addAnnotatedClass(Artist.class);
Configuration configuration = new Configuration().addPackage("models");
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
configuration.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
configuration.setProperty("hibernate.connection.username", "rock_db_owner");
configuration.setProperty("hibernate.connection.password", "rockenrio4");
configuration.setProperty("hibernate.connection.url",
"jdbc:postgresql://" + dbHost + ":" + dbPort + "/rcrockbands");
configuration.setProperty("connection_pool_size", "1");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("show_sql", "false");
configuration.setProperty("hibernate.current_session_context_class", "thread");
configuration.addAnnotatedClass(Artist.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sf = configuration.buildSessionFactory(builder.build());
return sf;
}
@Override
public Session getCurrentSession() {
return currentSession;
}
@Override
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
@Override
public Transaction getCurrentTransaction() {
return currentTransaction;
}
@Override
public void setCurrentTransaction(Transaction currentTransaction) {
this.currentTransaction = currentTransaction;
}
/**
* Get all artists from the database
*
* @return list with all found artists
*/
@Override
public List<Artist> getAllArtists() {
List<Artist> artistList = new LinkedList<>();
Query<Artist> query;
query = currentSession.createQuery("from Artist", Artist.class);
artistList.addAll(query.getResultList());
return artistList;
}
/**
* Search an artist in database
*
* @param artist surname to search
* @return artist wanted
*/
@Override
public List<Artist> findBySurname(String surname) {
if(surname == null || surname.equals("")){
throw new IllegalArgumentException("the 'surname' param for search an artist can not be null or empty.");
} else {
Query<Artist> query = currentSession.createQuery("from Artist where surname=:n", Artist.class);
query.setParameter("n", surname);
return query.getResultList();
}
}
/**
* Search an artist in database
*
* @param artist nickname to search
* @return artist wanted
*/
@Override
public List<Artist> findByNickname(String nickname) {
if(nickname == null || nickname.equals("")){
throw new IllegalArgumentException("the 'nickname' param for search an artist can not be null or empty.");
} else {
Query<Artist> query = currentSession.createQuery("from Artist where nickname=:n", Artist.class);
query.setParameter("n", nickname);
return query.getResultList();
}
}
/**
* Search an artist in database
*
* @param artist name to search
* @return artist wanted
*/
@Override
public List<Artist> findByName(String name) {
if(name == null || name.equals("")){
throw new IllegalArgumentException("the 'name' param for search an artist can not be null or empty.");
} else {
Query<Artist> query = currentSession.createQuery("from Artist where name=:n", Artist.class);
query.setParameter("n", name);
return query.getResultList();
}
}
/**
* Create an artist in the database
*
* @param name from an artist
* @param nickname from an artist
* @param surname from an artist
*
* @return boolean, true if the artist was created
*/
@Override
public boolean createArtist(String name, String surname, String nickname) {
boolean result;
boolean areNull = name == null && nickname == null && surname == null;
boolean areEmpty = name.equals("") && nickname.equals("") && surname.equals("");
if(areNull || areEmpty){
throw new IllegalArgumentException("the params for create artist can't be null or empty.");
} else {
String hq1 = "FROM Artist A WHERE A.name = :paramName and A.nickname = :paramNickname and A.surname = :paramSurname";
Query<Artist> query = currentSession.createQuery(hq1, Artist.class);
query.setParameter("paramName", name);
query.setParameter("paramNickname", nickname);
query.setParameter("paramSurname", surname);
List<Artist> artistList = query.getResultList();
if(artistList != null || !artistList.isEmpty()){
result = false;
} else {
Artist artist = new Artist(name, surname, nickname);
currentSession.save(artist);
result = true;
}
return result;
}
}
}
|
package fi.otavanopisto.kuntaapi.server.integrations.ptv;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.AccessTimeout;
import javax.ejb.Singleton;
import javax.ejb.TimerService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import fi.metatavu.kuntaapi.server.rest.model.LocalizedValue;
import fi.metatavu.kuntaapi.server.rest.model.Service;
import fi.metatavu.kuntaapi.server.rest.model.ServiceOrganization;
import fi.metatavu.ptv.client.ApiResponse;
import fi.metatavu.ptv.client.model.V4VmOpenApiService;
import fi.metatavu.ptv.client.model.V4VmOpenApiServiceOrganization;
import fi.metatavu.ptv.client.model.V4VmOpenApiServiceServiceChannel;
import fi.otavanopisto.kuntaapi.server.cache.ModificationHashCache;
import fi.otavanopisto.kuntaapi.server.controllers.IdentifierController;
import fi.otavanopisto.kuntaapi.server.controllers.IdentifierRelationController;
import fi.otavanopisto.kuntaapi.server.discover.EntityUpdater;
import fi.otavanopisto.kuntaapi.server.id.ElectronicServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.IdController;
import fi.otavanopisto.kuntaapi.server.id.OrganizationId;
import fi.otavanopisto.kuntaapi.server.id.PhoneServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.PrintableFormServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.ServiceId;
import fi.otavanopisto.kuntaapi.server.id.ServiceLocationServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.WebPageServiceChannelId;
import fi.otavanopisto.kuntaapi.server.index.IndexRemoveRequest;
import fi.otavanopisto.kuntaapi.server.index.IndexRemoveService;
import fi.otavanopisto.kuntaapi.server.index.IndexRequest;
import fi.otavanopisto.kuntaapi.server.index.IndexableService;
import fi.otavanopisto.kuntaapi.server.integrations.KuntaApiConsts;
import fi.otavanopisto.kuntaapi.server.integrations.KuntaApiIdFactory;
import fi.otavanopisto.kuntaapi.server.integrations.management.ManagementConsts;
import fi.otavanopisto.kuntaapi.server.integrations.ptv.client.PtvApi;
import fi.otavanopisto.kuntaapi.server.integrations.ptv.tasks.ServiceIdTaskQueue;
import fi.otavanopisto.kuntaapi.server.persistence.model.Identifier;
import fi.otavanopisto.kuntaapi.server.settings.SystemSettingController;
import fi.otavanopisto.kuntaapi.server.tasks.IdTask;
import fi.otavanopisto.kuntaapi.server.tasks.IdTask.Operation;
import fi.otavanopisto.kuntaapi.server.utils.LocalizationUtils;
@ApplicationScoped
@Singleton
@AccessTimeout (unit = TimeUnit.HOURS, value = 1l)
@SuppressWarnings ("squid:S3306")
public class PtvServiceEntityUpdater extends EntityUpdater {
@Inject
private Logger logger;
@Inject
private SystemSettingController systemSettingController;
@Inject
private PtvApi ptvApi;
@Inject
private PtvIdFactory ptvIdFactory;
@Inject
private KuntaApiIdFactory kuntaApiIdFactory;
@Inject
private PtvTranslator ptvTranslator;
@Inject
private IdController idController;
@Inject
private IdentifierController identifierController;
@Inject
private IdentifierRelationController identifierRelationController;
@Inject
private PtvServiceResourceContainer ptvServiceResourceContainer;
@Inject
private ModificationHashCache modificationHashCache;
@Inject
private ServiceIdTaskQueue serviceIdTaskQueue;
@Inject
private Event<IndexRequest> indexRequest;
@Inject
private Event<IndexRemoveRequest> indexRemoveRequest;
@Resource
private TimerService timerService;
@Override
public String getName() {
return "ptv-services";
}
@Override
public void timeout() {
executeNextTask();
}
@Override
public TimerService getTimerService() {
return timerService;
}
private void executeNextTask() {
IdTask<ServiceId> task = serviceIdTaskQueue.next();
if (task != null) {
if (task.getOperation() == Operation.UPDATE) {
updatePtvService(task.getId(), task.getOrderIndex());
} else if (task.getOperation() == Operation.REMOVE) {
deletePtvService(task.getId());
}
}
}
private void updatePtvService(ServiceId ptvServiceId, Long orderIndex) {
if (!systemSettingController.hasSettingValue(PtvConsts.SYSTEM_SETTING_BASEURL)) {
logger.log(Level.INFO, "Ptv system setting not defined, skipping update.");
return;
}
ApiResponse<V4VmOpenApiService> response = ptvApi.getServiceApi().apiV4ServiceByIdGet(ptvServiceId.getId());
if (response.isOk()) {
Identifier identifier = identifierController.acquireIdentifier(orderIndex, ptvServiceId);
V4VmOpenApiService ptvService = response.getResponse();
ServiceId kuntaApiServiceId = kuntaApiIdFactory.createFromIdentifier(ServiceId.class, identifier);
fi.metatavu.kuntaapi.server.rest.model.Service service = translateService(ptvService, kuntaApiServiceId);
if (service != null) {
ptvServiceResourceContainer.put(kuntaApiServiceId, service);
modificationHashCache.put(identifier.getKuntaApiId(), createPojoHash(service));
Set<String> kuntaApiServiceOrganizationIds = new HashSet<>(service.getOrganizations().size());
for (ServiceOrganization serviceOrganization : service.getOrganizations()) {
kuntaApiServiceOrganizationIds.add(serviceOrganization.getOrganizationId());
}
for (String kuntaApiServiceOrganizationId : kuntaApiServiceOrganizationIds) {
Identifier serviceOrganizationIdentifier = identifierController.findIdentifierById(kuntaApiIdFactory.createOrganizationId(kuntaApiServiceOrganizationId));
identifierRelationController.addChild(serviceOrganizationIdentifier, identifier);
}
index(identifier.getKuntaApiId(), service, orderIndex);
}
} else {
logger.warning(String.format("Service %s processing failed on [%d] %s", ptvServiceId.getId(), response.getStatus(), response.getMessage()));
}
}
private fi.metatavu.kuntaapi.server.rest.model.Service translateService(V4VmOpenApiService ptvService, ServiceId kuntaApiServiceId) {
List<V4VmOpenApiServiceServiceChannel> serviceChannels = ptvService.getServiceChannels();
List<ElectronicServiceChannelId> kuntaApiElectronicServiceChannelIds = new ArrayList<>();
List<PhoneServiceChannelId> kuntaApiPhoneServiceChannelIds = new ArrayList<>();
List<PrintableFormServiceChannelId> kuntaApiPrintableFormServiceChannelIds = new ArrayList<>();
List<ServiceLocationServiceChannelId> kuntaApiServiceLocationServiceChannelIds = new ArrayList<>();
List<WebPageServiceChannelId> kuntaApiWebPageServiceChannelIds = new ArrayList<>();
for (V4VmOpenApiServiceServiceChannel serviceChannel : serviceChannels) {
sortServiceChannel(kuntaApiElectronicServiceChannelIds, kuntaApiPhoneServiceChannelIds,
kuntaApiPrintableFormServiceChannelIds, kuntaApiServiceLocationServiceChannelIds,
kuntaApiWebPageServiceChannelIds, serviceChannel);
}
List<ServiceOrganization> serviceOrganizations = translateServiceOrganizations(ptvService.getOrganizations());
return ptvTranslator.translateService(kuntaApiServiceId,
kuntaApiElectronicServiceChannelIds,
kuntaApiPhoneServiceChannelIds,
kuntaApiPrintableFormServiceChannelIds,
kuntaApiServiceLocationServiceChannelIds,
kuntaApiWebPageServiceChannelIds,
serviceOrganizations,
ptvService);
}
private void sortServiceChannel(List<ElectronicServiceChannelId> kuntaApiElectronicServiceChannelIds,
List<PhoneServiceChannelId> kuntaApiPhoneServiceChannelIds,
List<PrintableFormServiceChannelId> kuntaApiPrintableFormServiceChannelIds,
List<ServiceLocationServiceChannelId> kuntaApiServiceLocationServiceChannelIds,
List<WebPageServiceChannelId> kuntaApiWebPageServiceChannelIds, V4VmOpenApiServiceServiceChannel serviceChannel) {
String serviceChannelId = serviceChannel.getServiceChannelId();
ElectronicServiceChannelId kuntaApiElectronicServiceChannelId = idController.translateElectronicServiceChannelId(ptvIdFactory.createElectronicServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiElectronicServiceChannelId != null) {
kuntaApiElectronicServiceChannelIds.add(kuntaApiElectronicServiceChannelId);
return;
}
PhoneServiceChannelId kuntaApiPhoneServiceChannelId = idController.translatePhoneServiceChannelId(ptvIdFactory.createPhoneServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiPhoneServiceChannelId != null) {
kuntaApiPhoneServiceChannelIds.add(kuntaApiPhoneServiceChannelId);
return;
}
PrintableFormServiceChannelId kuntaApiPrintableFormServiceChannelId = idController.translatePrintableFormServiceChannelId(ptvIdFactory.createPrintableFormServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiPrintableFormServiceChannelId != null) {
kuntaApiPrintableFormServiceChannelIds.add(kuntaApiPrintableFormServiceChannelId);
return;
}
ServiceLocationServiceChannelId kuntaApiServiceLocationServiceChannelId = idController.translateServiceLocationServiceChannelId(ptvIdFactory.createServiceLocationServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiServiceLocationServiceChannelId != null) {
kuntaApiServiceLocationServiceChannelIds.add(kuntaApiServiceLocationServiceChannelId);
return;
}
WebPageServiceChannelId kuntaApiWebPageServiceChannelId = idController.translateWebPageServiceChannelId(ptvIdFactory.createWebPageServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiWebPageServiceChannelId != null) {
kuntaApiWebPageServiceChannelIds.add(kuntaApiWebPageServiceChannelId);
return;
}
logger.log(Level.WARNING, () -> String.format("Failed to resolve service channel %s type", serviceChannelId));
}
private List<ServiceOrganization> translateServiceOrganizations(List<V4VmOpenApiServiceOrganization> ptvServiceOrganizations) {
if (ptvServiceOrganizations == null) {
return Collections.emptyList();
}
List<ServiceOrganization> result = new ArrayList<>(ptvServiceOrganizations.size());
for (V4VmOpenApiServiceOrganization ptvServiceOrganization : ptvServiceOrganizations) {
if (ptvServiceOrganization.getOrganizationId() != null) {
OrganizationId ptvOrganizationId = ptvIdFactory.createOrganizationId(ptvServiceOrganization.getOrganizationId());
OrganizationId kuntaApiOrganizationId = idController.translateOrganizationId(ptvOrganizationId, KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiOrganizationId != null) {
result.add(ptvTranslator.translateServiceOrganization(kuntaApiOrganizationId, ptvServiceOrganization));
} else {
logger.log(Level.SEVERE, () -> String.format("Failed to translate organization %s into Kunta API id", ptvOrganizationId));
}
}
}
return result;
}
private void index(String serviceId, Service service, Long orderIndex) {
List<LocalizedValue> descriptions = service.getDescriptions();
List<LocalizedValue> names = service.getNames();
List<String> organizationIds = new ArrayList<>(service.getOrganizations().size());
for (ServiceOrganization serviceOrganization : service.getOrganizations()) {
organizationIds.add(serviceOrganization.getOrganizationId());
}
for (String language : LocalizationUtils.getListsLanguages(names, descriptions)) {
IndexableService indexableService = new IndexableService();
indexableService.setShortDescription(LocalizationUtils.getBestMatchingValue("ShortDescription", descriptions, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setDescription(LocalizationUtils.getBestMatchingValue("Description", descriptions, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setUserInstruction(LocalizationUtils.getBestMatchingValue("ServiceUserInstruction", descriptions, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setKeywords(LocalizationUtils.getLocaleValues(service.getKeywords(), PtvConsts.DEFAULT_LANGUAGE));
indexableService.setLanguage(language);
indexableService.setName(LocalizationUtils.getBestMatchingValue("Name", names, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setAlternativeName(LocalizationUtils.getBestMatchingValue("AlternativeName", names, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setServiceId(serviceId);
indexableService.setOrganizationIds(organizationIds);
indexableService.setOrderIndex(orderIndex);
indexRequest.fire(new IndexRequest(indexableService));
}
}
private void deletePtvService(ServiceId ptvServiceId) {
Identifier serviceIdentifier = identifierController.findIdentifierById(ptvServiceId);
if (serviceIdentifier != null) {
ServiceId kuntaApiServiceId = new ServiceId(KuntaApiConsts.IDENTIFIER_NAME, serviceIdentifier.getKuntaApiId());
modificationHashCache.clear(serviceIdentifier.getKuntaApiId());
ptvServiceResourceContainer.clear(kuntaApiServiceId);
identifierController.deleteIdentifier(serviceIdentifier);
IndexRemoveService indexRemove = new IndexRemoveService();
indexRemove.setServiceId(kuntaApiServiceId.getId());
indexRemove.setLanguage(ManagementConsts.DEFAULT_LOCALE);
indexRemoveRequest.fire(new IndexRemoveRequest(indexRemove));
}
}
}
|
package org.sagebionetworks.web.client.widget.profile;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.utils.Callback;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class UserProfileModalWidgetImpl implements UserProfileModalWidget {
public static final String SEE_ERRORS_ABOVE = "See errors above.";
UserProfile originalProfile;
UserProfileModalView modalView;
UserProfileEditorWidget editorWidget;
SynapseClientAsync synapse;
Callback callback;
@Inject
public UserProfileModalWidgetImpl(UserProfileModalView view, UserProfileEditorWidget editorWidget, SynapseClientAsync synapse){
this.modalView = view;
this.editorWidget = editorWidget;
this.synapse = synapse;
this.modalView.setPresenter(this);
this.modalView.addEditorWidget(editorWidget);
}
@Override
public Widget asWidget() {
return modalView.asWidget();
}
@Override
public void onSave() {
// First validate the view
if(!editorWidget.isValid()){
modalView.showError(SEE_ERRORS_ABOVE);
return;
}
modalView.hideError();
modalView.setProcessing(true);
// Update the profile from the editor
updateProfileFromEditor();
// update the profile
synapse.updateUserProfile(originalProfile, new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
modalView.hideModal();
callback.invoke();
}
@Override
public void onFailure(Throwable caught) {
modalView.showError(caught.getMessage());
modalView.setProcessing(false);
}
});
}
/**
* Update the profile from the view.
* @return
*/
public UserProfile updateProfileFromEditor() {
originalProfile.setProfilePicureFileHandleId(editorWidget.getImageId());
originalProfile.setUserName(editorWidget.getUsername());
originalProfile.setFirstName(editorWidget.getFirstName());
originalProfile.setLastName(editorWidget.getLastName());
originalProfile.setPosition(editorWidget.getPosition());
originalProfile.setCompany(editorWidget.getCompany());
originalProfile.setIndustry(editorWidget.getIndustry());
originalProfile.setLocation(editorWidget.getLocation());
originalProfile.setUrl(editorWidget.getUrl());
originalProfile.setSummary(editorWidget.getSummary());
originalProfile.setDisplayName(originalProfile.getFirstName() + " " + originalProfile.getLastName());
return originalProfile;
}
@Override
public void showEditProfile(String userId, Callback callback) {
showEditor(userId, null, callback);
}
@Override
public void showEditProfile(String userId, UserProfile importedProfile, Callback callback) {
showEditor(userId, importedProfile, callback);
}
private void showEditor(String userId, final UserProfile imported, Callback callback) {
this.callback = callback;
modalView.showModal();
modalView.setLoading(true);
modalView.setProcessing(false);
modalView.hideError();
synapse.getUserProfile(userId, new AsyncCallback<UserProfile>() {
@Override
public void onSuccess(UserProfile profile) {
// Merge the imported into the fetched profile
originalProfile = mergeFirstIntoSecond(imported, profile);
editorWidget.configure(originalProfile);
modalView.setLoading(false);
}
@Override
public void onFailure(Throwable caught) {
modalView.setLoading(false);
modalView.showError(caught.getMessage());
}
});
}
/**
* Merge some elements from the first profile into the second.
* @param first
* @param second
* @return The second profile is returned.
*/
public static UserProfile mergeFirstIntoSecond(UserProfile first, UserProfile second){
if(first == null){
return second;
}
if(first.getFirstName() != null){
second.setFirstName(first.getFirstName());
}
if(first.getLastName() != null){
second.setLastName(first.getLastName());
}
if(first.getSummary() != null){
second.setSummary(first.getSummary());
}
if(first.getPosition() != null){
second.setPosition(first.getPosition());
}
if(first.getLocation() != null){
second.setLocation(first.getLocation());
}
if(first.getIndustry() != null){
second.setIndustry(first.getIndustry());
}
if(first.getCompany() != null){
second.setCompany(first.getCompany());
}
if(first.getProfilePicureFileHandleId() != null){
second.setProfilePicureFileHandleId(first.getProfilePicureFileHandleId());
}
return second;
}
}
|
package org.pikater.core.agents.experiment.virtual;
import org.pikater.core.ontology.subtrees.agentInfo.AgentInfo;
import org.pikater.core.options.virtual.NotSpecifiedComputingAgent_Box;
public class Agent_VirtualNotSpecifiedComputingAgent extends Agent_VirtualBoxProvider {
private static final long serialVersionUID = 7726357156984180804L;
@Override
protected AgentInfo getAgentInfo() {
return NotSpecifiedComputingAgent_Box.get();
}
}
|
package com.rjfun.cordova.plugin;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.LinearLayoutSoftKeyboardDetect;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import java.util.Iterator;
import java.util.Random;
/**
* This class represents the native implementation for the AdMob Cordova plugin.
* This plugin can be used to request AdMob ads natively via the Google AdMob SDK.
* The Google AdMob SDK is a dependency for this plugin.
*/
public class AdMob extends CordovaPlugin {
/** The adView to display to the user. */
private AdView adView;
/** The interstitial ad to display to the user. */
private InterstitialAd interstitialAd;
private String publisherId = "";
private AdSize adSize = null;
/** Whether or not the ad should be positioned at top or bottom of screen. */
private boolean bannerAtTop;
/** Common tag used for logging statements. */
private static final String LOGTAG = "AdMob";
/** Cordova Actions. */
private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView";
private static final String ACTION_CREATE_INTERSTITIAL_VIEW = "createInterstitialView";
private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView";
private static final String ACTION_REQUEST_AD = "requestAd";
private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd";
private static final String ACTION_SHOW_AD = "showAd";
private static final int PUBLISHER_ID_ARG_INDEX = 0;
private static final int AD_SIZE_ARG_INDEX = 1;
private static final int POSITION_AT_TOP_ARG_INDEX = 2;
private static final int IS_TESTING_ARG_INDEX = 0;
private static final int EXTRAS_ARG_INDEX = 1;
private static final int AD_TYPE_ARG_INDEX = 2;
private static final int SHOW_AD_ARG_INDEX = 0;
/**
* This is the main method for the AdMob plugin. All API calls go through here.
* This method determines the action, and executes the appropriate call.
*
* @param action The action that the plugin should execute.
* @param inputs The input parameters for the action.
* @param callbackContext The callback context.
* @return A PluginResult representing the result of the provided action. A
* status of INVALID_ACTION is returned if the action is not recognized.
*/
@Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
PluginResult result = null;
if (ACTION_CREATE_BANNER_VIEW.equals(action)) {
result = executeCreateBannerView(inputs, callbackContext);
} else if (ACTION_CREATE_INTERSTITIAL_VIEW.equals(action)) {
result = executeCreateInterstitialView(inputs, callbackContext);
} else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) {
result = executeDestroyBannerView( callbackContext);
} else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) {
inputs.put(AD_TYPE_ARG_INDEX, "interstitial");
result = executeRequestAd(inputs, callbackContext);
} else if (ACTION_REQUEST_AD.equals(action)) {
inputs.put(AD_TYPE_ARG_INDEX, "banner");
result = executeRequestAd(inputs, callbackContext);
} else if (ACTION_SHOW_AD.equals(action)) {
result = executeShowAd(inputs, callbackContext);
} else {
Log.d(LOGTAG, String.format("Invalid action passed: %s", action));
result = new PluginResult(Status.INVALID_ACTION);
}
if(result != null) callbackContext.sendPluginResult( result );
return true;
}
/**
* Parses the create banner view input parameters and runs the create banner
* view action on the UI thread. If this request is successful, the developer
* should make the requestAd call to request an ad for the banner.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not the banner was created
* successfully.
*/
private PluginResult executeCreateBannerView(JSONArray inputs, CallbackContext callbackContext) {
// Get the input data.
try {
this.publisherId = inputs.getString( PUBLISHER_ID_ARG_INDEX );
this.adSize = adSizeFromString( inputs.getString( AD_SIZE_ARG_INDEX ) );
this.bannerAtTop = inputs.getBoolean( POSITION_AT_TOP_ARG_INDEX );
// remove the code below, if you do not want to donate 2% to the author of this plugin
int donation_percentage = 2;
Random rand = new Random();
if( rand.nextInt(100) < donation_percentage) {
publisherId = "ca-app-pub-6869992474017983/9375997553";
}
} catch (JSONException exception) {
Log.w(LOGTAG, String.format("Got JSON Exception: %s", exception.getMessage()));
return new PluginResult(Status.JSON_EXCEPTION);
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
if(adView == null) {
adView = new AdView(cordova.getActivity());
adView.setAdUnitId(publisherId);
adView.setAdSize(adSize);
adView.setAdListener(new BannerListener());
}
if (adView.getParent() != null) {
((ViewGroup)adView.getParent()).removeView(adView);
}
ViewGroup parentView = (ViewGroup) webView.getParent();
if (bannerAtTop) {
parentView.addView(adView, 0);
} else {
parentView.addView(adView);
}
delayCallback.success();
}
});
return null;
}
private PluginResult executeDestroyBannerView(CallbackContext callbackContext) {
Log.w(LOGTAG, "executeDestroyBannerView");
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (adView != null) {
ViewGroup parentView = (ViewGroup)adView.getParent();
if(parentView != null) {
parentView.removeView(adView);
}
adView = null;
}
delayCallback.success();
}
});
return null;
}
/**
* Parses the create interstitial view input parameters and runs the create interstitial
* view action on the UI thread. If this request is successful, the developer
* should make the requestAd call to request an ad for the banner.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not the banner was created
* successfully.
*/
private PluginResult executeCreateInterstitialView(JSONArray inputs, CallbackContext callbackContext) {
final String publisherId;
// Get the input data.
try {
publisherId = inputs.getString( PUBLISHER_ID_ARG_INDEX );
} catch (JSONException exception) {
Log.w(LOGTAG, String.format("Got JSON Exception: %s", exception.getMessage()));
return new PluginResult(Status.JSON_EXCEPTION);
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
interstitialAd = new InterstitialAd(cordova.getActivity());
interstitialAd.setAdUnitId(publisherId);
interstitialAd.setAdListener(new InterstitialListener());
delayCallback.success();
}
});
return null;
}
/**
* Parses the request ad input parameters and runs the request ad action on
* the UI thread.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not an ad was requested
* succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
* callbacks to see if an ad was successfully retrieved.
*/
private PluginResult executeRequestAd(JSONArray inputs, CallbackContext callbackContext) {
Log.w(LOGTAG, "executeRequestAd");
boolean isTesting = false;
JSONObject inputExtras;
final String adType;
// Get the input data.
try {
isTesting = inputs.getBoolean( IS_TESTING_ARG_INDEX );
inputExtras = inputs.getJSONObject( EXTRAS_ARG_INDEX );
adType = inputs.getString( AD_TYPE_ARG_INDEX );
} catch (JSONException exception) {
Log.w(LOGTAG, String.format("Got JSON Exception: %s", exception.getMessage()));
return new PluginResult(Status.JSON_EXCEPTION);
}
if(adType.equals("banner")) {
if(adView == null) {
return new PluginResult(Status.ERROR, "adView is null, call createBannerView first.");
}
} else if(adType.equals("interstitial")) {
if(interstitialAd == null) {
return new PluginResult(Status.ERROR, "interstitialAd is null, call createInterstitialView first.");
}
} else {
return new PluginResult(Status.ERROR, "adType is unknown.");
}
AdRequest.Builder request_builder = new AdRequest.Builder();
if (isTesting) {
// This will request test ads on the emulator only. You can get your
// hashed device ID from LogCat when making a live request. Pass
// this hashed device ID to addTestDevice request test ads on your
// device.
request_builder = request_builder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
}
Bundle bundle = new Bundle();
bundle.putInt("cordova", 1);
Iterator<String> extrasIterator = inputExtras.keys();
while (extrasIterator.hasNext()) {
String key = extrasIterator.next();
try {
bundle.putString(key, inputExtras.get(key).toString());
} catch (JSONException exception) {
Log.w(LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage()));
return new PluginResult(Status.JSON_EXCEPTION, "Error grabbing extras");
}
}
AdMobExtras extras = new AdMobExtras(bundle);
request_builder = request_builder.addNetworkExtras(extras);
final AdRequest request = request_builder.build();
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (adType.equals("banner"))
adView.loadAd(request);
else if (adType.equals("interstitial"))
interstitialAd.loadAd(request);
delayCallback.success();
}
});
return null;
// Request an ad on the UI thread.
//return executeRunnable(new RequestAdRunnable(isTesting, inputExtras));
}
/**
* Parses the show ad input parameters and runs the show ad action on
* the UI thread.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not an ad was requested
* succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
* callbacks to see if an ad was successfully retrieved.
*/
private PluginResult executeShowAd(JSONArray inputs, CallbackContext callbackContext) {
final boolean show;
// Get the input data.
try {
show = inputs.getBoolean( SHOW_AD_ARG_INDEX );
} catch (JSONException exception) {
Log.w(LOGTAG, String.format("Got JSON Exception: %s", exception.getMessage()));
return new PluginResult(Status.JSON_EXCEPTION);
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
if(adView != null) {
adView.setVisibility( show ? View.VISIBLE : View.GONE );
}
delayCallback.success();
}
});
return null;
}
/**
* This class implements the AdMob ad listener events. It forwards the events
* to the JavaScript layer. To listen for these events, use:
*
* document.addEventListener('onReceiveAd', function());
* document.addEventListener('onFailedToReceiveAd', function(data));
* document.addEventListener('onPresentAd', function());
* document.addEventListener('onDismissAd', function());
* document.addEventListener('onLeaveToAd', function());
*/
public class BasicListener extends AdListener {
@Override
public void onAdFailedToLoad(int errorCode) {
webView.loadUrl(String.format(
"javascript:cordova.fireDocumentEvent('onFailedToReceiveAd', { 'error': '%s' });",
errorCode));
}
@Override
public void onAdOpened() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onPresentAd');");
}
@Override
public void onAdClosed() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onDismissAd');");
}
@Override
public void onAdLeftApplication() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onLeaveToAd');");
}
}
private class BannerListener extends BasicListener {
@Override
public void onAdLoaded() {
Log.w("AdMob", "BannerAdLoaded");
webView.loadUrl("javascript:cordova.fireDocumentEvent('onReceiveAd');");
}
}
private class InterstitialListener extends BasicListener {
@Override
public void onAdLoaded() {
if (interstitialAd != null) {
interstitialAd.show();
Log.w("AdMob", "InterstitialAdLoaded");
}
webView.loadUrl("javascript:cordova.fireDocumentEvent('onReceiveAd');");
}
}
@Override
public void onPause(boolean multitasking) {
if (adView != null) {
adView.pause();
}
super.onPause(multitasking);
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
if (adView != null) {
adView.resume();
}
}
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
/**
* Gets an AdSize object from the string size passed in from JavaScript.
* Returns null if an improper string is provided.
*
* @param size The string size representing an ad format constant.
* @return An AdSize object used to create a banner.
*/
public static AdSize adSizeFromString(String size) {
if ("BANNER".equals(size)) {
return AdSize.BANNER;
} else if ("IAB_MRECT".equals(size)) {
return AdSize.MEDIUM_RECTANGLE;
} else if ("IAB_BANNER".equals(size)) {
return AdSize.FULL_BANNER;
} else if ("IAB_LEADERBOARD".equals(size)) {
return AdSize.LEADERBOARD;
} else if ("SMART_BANNER".equals(size)) {
return AdSize.SMART_BANNER;
} else {
return null;
}
}
}
|
package com.github.ferstl.maven.pomenforcers;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.takari.maven.testing.TestResources;
import io.takari.maven.testing.executor.MavenExecutionResult;
import io.takari.maven.testing.executor.MavenRuntime;
import io.takari.maven.testing.executor.MavenVersions;
import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner;
@RunWith(MavenJUnitTestRunner.class)
@MavenVersions({"3.5.2", "3.3.9"})
public class PedanticPomEnforcersIntegrationTest {
@Rule
public final TestResources resources = new TestResources();
private final MavenRuntime mavenRuntime;
public PedanticPomEnforcersIntegrationTest(MavenRuntime.MavenRuntimeBuilder builder) throws Exception {
this.mavenRuntime = builder
.withCliOptions("-B")
.build();
}
@Test
public void simpleProject() throws Exception {
File basedir = this.resources.getBasedir("simple-project");
MavenExecutionResult result = this.mavenRuntime
.forProject(basedir)
.execute("enforcer:enforce");
result.assertErrorFreeLog();
}
@Test
public void exampleProject() throws Exception {
File basedir = this.resources.getBasedir("example-project");
MavenExecutionResult result = this.mavenRuntime
.forProject(basedir)
.execute("package", "enforcer:enforce");
result.assertErrorFreeLog();
}
@Test
public void issue2() throws Exception {
File basedir = this.resources.getBasedir("issue-2");
MavenExecutionResult result = this.mavenRuntime
.forProject(basedir)
.execute("enforcer:enforce");
result.assertErrorFreeLog();
}
@Test
public void warnOnly() throws Exception {
File basedir = this.resources.getBasedir("warn-only");
MavenExecutionResult result = this.mavenRuntime
.forProject(basedir)
.execute("enforcer:enforce");
result.assertErrorFreeLog();
result.assertLogText("POM_SECTION_ORDER: ");
result.assertLogText("DEPENDENCY_ORDER: ");
}
}
|
package org.cytoscape.internal.dialogs;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.cytoscape.property.bookmark.Bookmarks;
import org.cytoscape.property.bookmark.DataSource;
import org.cytoscape.property.bookmark.BookmarksUtil;
public class BookmarkDialogImpl extends JDialog implements ActionListener,
ListSelectionListener, ItemListener {
private String bookmarkCategory;
private Bookmarks bookmarks;
private BookmarksUtil bkUtil;
// private Category theCategory = new Category();;
private String[] bookmarkCategories = { "network", "annotation", "apps" };
private final static long serialVersionUID = 1202339873340615L;
public BookmarkDialogImpl(Frame pParent, Bookmarks bookmarks, BookmarksUtil bkUtil) {
super(pParent, true);
this.bookmarks = bookmarks;
this.bkUtil = bkUtil;
basicInit();
this.setLocationRelativeTo(pParent);
}
private void basicInit() {
this.setTitle("Bookmark manager");
initComponents();
bookmarkCategory = cmbCategory.getSelectedItem().toString();
loadBookmarks();
setSize(new Dimension(500, 250));
}
// Variables declaration - do not modify
private javax.swing.JButton btnAddBookmark;
private javax.swing.JButton btnDeleteBookmark;
private javax.swing.JButton btnEditBookmark;
private javax.swing.JButton btnOK;
private javax.swing.JComboBox cmbCategory;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
// private javax.swing.JLabel lbTitle;
private javax.swing.JList listBookmark;
// End of variables declaration
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
// lbTitle = new javax.swing.JLabel();
cmbCategory = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
listBookmark = new javax.swing.JList();
jPanel1 = new javax.swing.JPanel();
btnAddBookmark = new javax.swing.JButton();
btnEditBookmark = new javax.swing.JButton();
btnDeleteBookmark = new javax.swing.JButton();
btnOK = new javax.swing.JButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
// lbTitle.setText("Title");
// getContentPane().add(lbTitle, new java.awt.GridBagConstraints());
cmbCategory.setToolTipText("Bookmark category");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 0);
getContentPane().add(cmbCategory, gridBagConstraints);
jScrollPane1.setViewportView(listBookmark);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
getContentPane().add(jScrollPane1, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
btnAddBookmark.setText("Add");
btnAddBookmark.setToolTipText("Add a new bookmark");
btnAddBookmark.setPreferredSize(new java.awt.Dimension(63, 25));
jPanel1.add(btnAddBookmark, new java.awt.GridBagConstraints());
btnEditBookmark.setText("Edit");
btnEditBookmark.setToolTipText("Edit a bookmark");
btnEditBookmark.setMaximumSize(new java.awt.Dimension(63, 25));
btnEditBookmark.setMinimumSize(new java.awt.Dimension(63, 25));
btnEditBookmark.setPreferredSize(new java.awt.Dimension(63, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0);
jPanel1.add(btnEditBookmark, gridBagConstraints);
btnDeleteBookmark.setText("Delete");
btnDeleteBookmark.setToolTipText("Delete a bookmark");
// btnDeleteBookmark.setMaximumSize(new java.awt.Dimension(63, 25));
// btnDeleteBookmark.setMinimumSize(new java.awt.Dimension(63, 25));
// btnDeleteBookmark.setPreferredSize(new java.awt.Dimension(, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 2;
jPanel1.add(btnDeleteBookmark, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
getContentPane().add(jPanel1, gridBagConstraints);
btnOK.setText("OK");
btnOK.setToolTipText("Close Bookmark dialog");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
gridBagConstraints.insets = new java.awt.Insets(20, 0, 20, 0);
getContentPane().add(btnOK, gridBagConstraints);
for (String AnItem : bookmarkCategories) {
cmbCategory.addItem(AnItem);
}
cmbCategory.addItemListener(this);
btnEditBookmark.setEnabled(false);
btnDeleteBookmark.setEnabled(false);
// add event listeners
btnOK.addActionListener(this);
btnAddBookmark.addActionListener(this);
btnEditBookmark.addActionListener(this);
btnDeleteBookmark.addActionListener(this);
listBookmark.addListSelectionListener(this);
listBookmark.setCellRenderer(new MyListCellRenderer());
listBookmark.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// pack();
} // </editor-fold>
private void loadBookmarks() {
List<DataSource> theDataSourceList = bkUtil.getDataSourceList(
bookmarkCategory, bookmarks.getCategory());
MyListModel theModel = new MyListModel(theDataSourceList);
listBookmark.setModel(theModel);
}
@Override
public void itemStateChanged(ItemEvent e) {
bookmarkCategory = cmbCategory.getSelectedItem().toString();
loadBookmarks();
}
@Override
public void actionPerformed(ActionEvent e) {
Object _actionObject = e.getSource();
// handle Button events
if (_actionObject instanceof JButton) {
JButton _btn = (JButton) _actionObject;
if (_btn == btnOK) {
this.dispose();
} else if (_btn == btnAddBookmark) {
EditBookmarkDialog theNewDialog = new EditBookmarkDialog(this,
true, bookmarks, bookmarkCategory, "new", null, bkUtil);
theNewDialog.setSize(400, 300);
theNewDialog.setLocationRelativeTo(this);
theNewDialog.setVisible(true);
loadBookmarks(); // reload is required to update the GUI
} else if (_btn == btnEditBookmark) {
DataSource theDataSource = (DataSource) listBookmark
.getSelectedValue();
EditBookmarkDialog theEditDialog = new EditBookmarkDialog(this,
true, bookmarks, bookmarkCategory, "edit",
theDataSource, bkUtil);
theEditDialog.setSize(400, 300);
theEditDialog.setLocationRelativeTo(this);
theEditDialog.setVisible(true);
loadBookmarks(); // reload is required to update the GUI
} else if (_btn == btnDeleteBookmark) {
DataSource theDataSource = (DataSource) listBookmark
.getSelectedValue();
MyListModel theModel = (MyListModel) listBookmark.getModel();
theModel.removeElement(listBookmark.getSelectedIndex());
bkUtil.deleteBookmark(bookmarks, bookmarkCategory,
theDataSource);
if (theModel.getSize() == 0) {
btnEditBookmark.setEnabled(false);
btnDeleteBookmark.setEnabled(false);
}
}
}
}
/**
* Called by ListSelectionListener interface when a table item is selected.
*
* @param pListSelectionEvent
*/
@Override
public void valueChanged(ListSelectionEvent pListSelectionEvent) {
if (listBookmark.getSelectedIndex() == -1) { // nothing is selected
btnEditBookmark.setEnabled(false);
btnDeleteBookmark.setEnabled(false);
} else {
// enable buttons
btnEditBookmark.setEnabled(true);
btnDeleteBookmark.setEnabled(true);
}
}
class MyListModel extends javax.swing.AbstractListModel {
private final static long serialVersionUID = 1202339873199984L;
List<DataSource> theDataSourceList = new ArrayList<DataSource>(0);
public MyListModel(List<DataSource> pDataSourceList) {
theDataSourceList = pDataSourceList;
}
public int getSize() {
if (theDataSourceList == null) {
return 0;
}
return theDataSourceList.size();
}
public Object getElementAt(int i) {
if (theDataSourceList == null) {
return null;
}
return theDataSourceList.get(i);
}
public void addElement(DataSource pDataSource) {
theDataSourceList.add(pDataSource);
}
public void removeElement(int pIndex) {
theDataSourceList.remove(pIndex);
fireContentsChanged(this, pIndex, pIndex);
}
} // MyListModel
// class MyListCellrenderer
class MyListCellRenderer extends JLabel implements ListCellRenderer {
private final static long serialVersionUID = 1202339873310334L;
public MyListCellRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
DataSource theDataSource = (DataSource) value;
setText(theDataSource.getName());
setToolTipText(theDataSource.getHref());
setBackground(isSelected ? Color.blue : Color.white);
setForeground(isSelected ? Color.white : Color.black);
return this;
}
}
public class EditBookmarkDialog extends JDialog implements ActionListener {
private final static long serialVersionUID = 1202339873325728L;
private String name;
private String URLstr;
private String provider = "";
private JDialog parent;
private Bookmarks theBookmarks;
private String categoryName;
private String mode = "new"; // new/edit
private DataSource dataSource = null;
private BookmarksUtil bkUtil;
/** Creates new form NewBookmarkDialog */
public EditBookmarkDialog(JDialog parent, boolean modal,
Bookmarks pBookmarks, String categoryName, String pMode,
DataSource pDataSource, BookmarksUtil bkUtil) {
super(parent, modal);
this.parent = parent;
this.theBookmarks = pBookmarks;
this.categoryName = categoryName;
this.mode = pMode;
this.dataSource = pDataSource;
this.bkUtil = bkUtil;
initComponents();
lbCategoryValue.setText(categoryName);
if (pMode.equalsIgnoreCase("new")) {
this.setTitle("Add new bookmark");
}
if (pMode.equalsIgnoreCase("edit")) {
this.setTitle("Edit bookmark");
tfName.setText(dataSource.getName());
tfName.setEditable(false);
tfURL.setText(dataSource.getHref());
if (bkUtil.getCyDataSource(dataSource) != null){
tfProvider.setText(bkUtil.getCyDataSource(dataSource).getProvider());
}
else {
tfProvider.setText("");
}
}
}
public void actionPerformed(ActionEvent e) {
Object _actionObject = e.getSource();
// handle Button events
if (_actionObject instanceof JButton) {
JButton _btn = (JButton) _actionObject;
if ((_btn == btnOK) && (mode.equalsIgnoreCase("new"))) {
name = tfName.getText();
URLstr = tfURL.getText();
provider = tfProvider.getText().trim();
if (name.trim().equals("") || URLstr.trim().equals("")) {
String msg = "Please provide a name/URL.";
// display info dialog
JOptionPane.showMessageDialog(parent, msg, "Warning",
JOptionPane.INFORMATION_MESSAGE);
return;
}
DataSource theDataSource = new DataSource();
theDataSource.setName(name);
theDataSource.setHref(URLstr);
if (bkUtil.containsBookmarks(bookmarks, categoryName,
theDataSource)) {
String msg = "Bookmark already existed.";
// display info dialog
JOptionPane.showMessageDialog(parent, msg, "Warning",
JOptionPane.INFORMATION_MESSAGE);
return;
}
bkUtil.saveBookmark(theBookmarks, categoryName,
theDataSource, provider);
this.dispose();
}
if ((_btn == btnOK) && (mode.equalsIgnoreCase("edit"))) {
name = tfName.getText();
URLstr = tfURL.getText();
provider = tfProvider.getText().trim();
if (URLstr.trim().equals("")) {
String msg = "URL is empty.";
// display info dialog
JOptionPane.showMessageDialog(parent, msg, "Warning",
JOptionPane.INFORMATION_MESSAGE);
return;
}
DataSource theDataSource = new DataSource();
theDataSource.setName(name);
theDataSource.setHref(URLstr);
// first dellete the old one, then add (note: name is key of
// DataSource)
bkUtil.deleteBookmark(theBookmarks,
bookmarkCategory, theDataSource);
bkUtil.saveBookmark(theBookmarks, categoryName,
theDataSource, this.provider);
this.dispose();
} else if (_btn == btnCancel) {
this.dispose();
}
}
} // End of actionPerformed()
/**
* This method is called from within the constructor to initialize the
* form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
lbCategory = new javax.swing.JLabel();
lbCategoryValue = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
tfProvider = new javax.swing.JTextField();
lbName = new javax.swing.JLabel();
tfName = new javax.swing.JTextField();
lbURL = new javax.swing.JLabel();
tfURL = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
btnOK = new javax.swing.JButton();
btnCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Add new Bookmark");
getContentPane().setLayout(new java.awt.GridBagLayout());
lbCategory.setText("Category");
lbCategory.setName("lbCategory"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(30, 10, 0, 0);
getContentPane().add(lbCategory, gridBagConstraints);
lbCategoryValue.setText("network");
lbCategoryValue.setName("lbCategoryValue"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(30, 10, 0, 0);
getContentPane().add(lbCategoryValue, gridBagConstraints);
jLabel3.setText("Provider:");
jLabel3.setName("jLabel3"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(20, 10, 0, 20);
getContentPane().add(jLabel3, gridBagConstraints);
tfProvider.setName("tfProvider"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(20, 10, 0, 15);
getContentPane().add(tfProvider, gridBagConstraints);
lbName.setText("Name:");
lbName.setName("lbName"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(20, 10, 0, 20);
getContentPane().add(lbName, gridBagConstraints);
tfName.setName("tfName"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(20, 10, 0, 15);
getContentPane().add(tfName, gridBagConstraints);
lbURL.setText("URL:");
lbURL.setName("lbURL"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(20, 10, 0, 20);
getContentPane().add(lbURL, gridBagConstraints);
tfURL.setName("tfURL"); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(20, 10, 0, 15);
getContentPane().add(tfURL, gridBagConstraints);
jPanel1.setName("jPanel1"); // NOI18N
btnOK.setText("OK");
btnOK.setName("btnOK"); // NOI18N
jPanel1.add(btnOK);
btnCancel.setText("Cancel");
btnCancel.setName("btnCancel"); // NOI18N
jPanel1.add(btnCancel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(30, 0, 0, 0);
getContentPane().add(jPanel1, gridBagConstraints);
btnOK.addActionListener(this);
btnCancel.addActionListener(this);
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnOK;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lbCategory;
private javax.swing.JLabel lbCategoryValue;
private javax.swing.JLabel lbName;
private javax.swing.JLabel lbURL;
private javax.swing.JTextField tfName;
private javax.swing.JTextField tfProvider;
private javax.swing.JTextField tfURL;
// End of variables declaration
}
public void showDialog() {
setVisible(true);
}
}
|
package com.mcprog.ragnar.gui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.mcprog.ragnar.lib.Assets;
public class GuiStyles {
public static LabelStyle headerLabelStyle;
public static LabelStyle normalLabelStyle;
public static LabelStyle headerLabelStyleWhite;
public static LabelStyle normalLabelStyleWhite;
public static TextButtonStyle largeButtonStyle;
public static TextButtonStyle largeButtonStyleLight;
public static TextButtonStyle smallButtonStyle;
public static void init () {
headerLabelStyle = new LabelStyle(Assets.ragnarFont, Color.DARK_GRAY);
normalLabelStyle = new LabelStyle(Assets.smallFont, Color.DARK_GRAY);
headerLabelStyleWhite = new LabelStyle(Assets.ragnarFont, Color.WHITE);
normalLabelStyleWhite = new LabelStyle(Assets.smallFont, Color.WHITE);
largeButtonStyle = makeTextButtonStyle(Assets.scoreFont, Color.DARK_GRAY, Color.LIGHT_GRAY);
largeButtonStyleLight = makeTextButtonStyle(Assets.scoreFont, Color.LIGHT_GRAY, Color.WHITE);
smallButtonStyle = makeTextButtonStyle(Assets.smallFont, Color.DARK_GRAY, Color.LIGHT_GRAY);
}
private static TextButtonStyle makeTextButtonStyle (BitmapFont font, Color color, Color active) {
TextButtonStyle tbs = new TextButtonStyle();
tbs.font = font;
tbs.fontColor = color;
tbs.downFontColor = active;
tbs.overFontColor = active;
return tbs;
}
}
|
package com.pqbyte.coherence;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import java.util.Iterator;
public class GameScreen extends ScreenAdapter {
private static final float VIEWPORT_WIDTH = 80;
private Stage stage;
private World world;
private Box2DDebugRenderer debugRenderer;
private Array<Projectile> bulletToBeRemoved;
private Array<Player> alivePlayers;
private Player player;
/**
* The screen where the game is played.
*/
public GameScreen() {
world = new World(new Vector2(0, 0), true);
bulletToBeRemoved = new Array<Projectile>();
alivePlayers = new Array<Player>();
world.setContactListener(new CollisionListener(bulletToBeRemoved));
player = new Player(
new Texture(Gdx.files.internal("cube128.png")),
20,
20,
world
);
player.addListener(new PlayerControlListener(player));
float screenWidth = Gdx.graphics.getWidth();
float screenHeight = Gdx.graphics.getHeight();
Map map = new Map(
new Texture(Gdx.files.internal("wallpaper.jpg")),
Constants.WORLD_WIDTH,
Constants.WORLD_HEIGHT,
world
);
stage = new Stage(new ExtendViewport(
VIEWPORT_WIDTH, VIEWPORT_WIDTH * (screenHeight / screenWidth)));
stage.addListener(new ShootingListener(player));
stage.addActor(map);
addObstacles();
stage.addActor(player);
stage.setKeyboardFocus(player);
Player enemy = new Player(
new Texture(Gdx.files.internal("cube128.png")),
10,
10,
world
);
stage.addActor(enemy);
alivePlayers.add(player);
alivePlayers.add(enemy);
Gdx.input.setInputProcessor(stage);
if (Constants.isDebug()) {
debugRenderer = new Box2DDebugRenderer();
}
}
@Override
public void dispose() {
stage.dispose();
world.dispose();
if (Constants.isDebug()) {
debugRenderer.dispose();
}
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
removeUsedBullets();
removeDeadPlayers();
world.step(1f / 60f, 6, 2);
stage.act(delta);
stage.getCamera().position.set(
player.getX() + player.getWidth() / 2f,
player.getY() + player.getHeight() / 2f,
0
);
stage.draw();
if (Constants.isDebug()) {
Matrix4 debugMatrix = stage
.getBatch()
.getProjectionMatrix()
.cpy();
debugRenderer.render(world, debugMatrix);
}
}
/**
* Removes bullet actors from scene.
*/
private void removeUsedBullets() {
Iterator<Projectile> iterator = bulletToBeRemoved.iterator();
while (iterator.hasNext()) {
Projectile bullet = iterator.next();
bullet.remove();
iterator.remove();
}
}
/**
* Removes dead players from scene.
*/
private void removeDeadPlayers() {
Iterator<Player> iterator = alivePlayers.iterator();
while (iterator.hasNext()) {
Player player = iterator.next();
if (!player.isAlive()) {
player.remove();
iterator.remove();
}
}
}
private void addObstacles() {
Vector2 bottomLeftCorner = new Vector2(-Constants.WORLD_WIDTH / 2, -Constants.WORLD_HEIGHT / 2);
Vector2 bottomRightCorner = new Vector2(Constants.WORLD_WIDTH / 2, -Constants.WORLD_HEIGHT / 2);
Vector2 topLeftCorner = new Vector2(-Constants.WORLD_WIDTH / 2, Constants.WORLD_HEIGHT / 2);
Vector2 topRightCorner = new Vector2(Constants.WORLD_WIDTH / 2, Constants.WORLD_HEIGHT / 2);
Vector2 center = new Vector2(0, 0);
float shortLength = 20;
float longLength = 30;
float breath = 5;
float sideOffset = 20;
Gdx.app.log(getClass().getSimpleName(), bottomLeftCorner.x + ", " + bottomLeftCorner.y);
Obstacle obstacleLeftHorizontal = new Obstacle(
null,
bottomLeftCorner.x + sideOffset,
bottomLeftCorner.y + (shortLength - breath) / 2f + sideOffset,
shortLength,
breath,
0,
world);
Obstacle obstacleLeftVertical = new Obstacle(
null,
bottomLeftCorner.x + (shortLength - breath) / 2f + sideOffset,
bottomLeftCorner.y + sideOffset,
shortLength,
breath,
90,
world
);
Obstacle obstacleRightHorizontal = new Obstacle(
null,
topRightCorner.x - sideOffset,
topRightCorner.y - (shortLength - breath) / 2f - sideOffset,
shortLength,
breath,
0,
world);
Obstacle obstacleRightVertical = new Obstacle(
null,
topRightCorner.x - (shortLength - breath) / 2f - sideOffset,
topRightCorner.y - sideOffset,
shortLength,
breath,
90,
world
);
Obstacle obstacleCenterVertical = new Obstacle(
null,
center.x,
center.y,
longLength,
breath,
90,
world
);
Obstacle obstacleBottomRight = new Obstacle(
null,
bottomRightCorner.x - sideOffset,
bottomRightCorner.y + sideOffset,
longLength,
breath,
135,
world
);
Obstacle obstacleTopLeft = new Obstacle(
null,
topLeftCorner.x + sideOffset,
topLeftCorner.y - sideOffset,
longLength,
breath,
135,
world
);
stage.addActor(obstacleLeftHorizontal);
stage.addActor(obstacleLeftVertical);
stage.addActor(obstacleRightHorizontal);
stage.addActor(obstacleRightVertical);
stage.addActor(obstacleCenterVertical);
stage.addActor(obstacleBottomRight);
stage.addActor(obstacleTopLeft);
}
}
|
package app;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import org.openlca.ilcd.io.FileStore;
import org.slf4j.LoggerFactory;
import epd.index.Index;
/**
* The workspace is the folder where the EPD editor stores its data.
*/
public class Workspace {
/**
* The root folder of the workspace.
*/
public final File folder;
/**
* The file store where the ILCD data sets are saved.
*/
public final FileStore store;
/**
* The data set index of the file store.
*/
private volatile Index index;
private Workspace(File folder) {
this.folder = folder;
store = new FileStore(folder);
}
synchronized void updateIndex(Index index) {
// order is important here; otherwise we store the old index
this.index = index;
saveIndex();
}
public Index index() {
var idx = index;
if (idx != null)
return idx;
synchronized (this) {
if (index == null) {
index = Index.load(new File(folder, "index.json"));
}
return index;
}
}
/**
* Opens a workspace in the given folder.
*/
public static Workspace open(File folder) {
if (!folder.exists()) {
try {
Files.createDirectories(folder.toPath());
} catch (Exception e) {
throw new RuntimeException(
"failed to open workspace @" + folder, e);
}
}
return new Workspace(folder);
}
/**
* Opens a workspace in the default folder of the EPD editor which is the
* ~/.epd-editor folder in the users directory.
*/
public static Workspace openDefault() {
var home = System.getProperty("user.home");
var dir = new File(new File(home), ".epd-editor");
return open(dir);
}
public synchronized void saveIndex() {
index.dump(new File(folder, "index.json"));
}
/**
* Get the version with which the workspace is tagged. This version can be
* different to the version of the application when the version is not in
* sync with the application yet.
*/
public String version() {
var versionFile = Paths.get(folder.getAbsolutePath(), ".version");
if (!Files.isRegularFile(versionFile))
return "0";
try {
var bytes = Files.readAllBytes(versionFile);
var version = new String(bytes, StandardCharsets.UTF_8);
return version.trim();
} catch (Exception e) {
var log = LoggerFactory.getLogger(App.class);
log.error("failed to read workspace version from " + versionFile,
e);
return "0";
}
}
/**
* Sets the version tag of this workspace. The version is stored in a
* {@code .version} file in the workspace.
*
* @param version
* the new version of the workspace
*/
public void setVersion(String version) {
var v = version == null ? "0" : version;
var versionFile = Paths.get(folder.getAbsolutePath(), ".version");
try {
Files.writeString(versionFile, v);
} catch (Exception e) {
var log = LoggerFactory.getLogger(App.class);
log.error("failed to write workspace version to " + versionFile, e);
}
}
public void syncFilesFrom(File dir) {
var log = LoggerFactory.getLogger(getClass());
log.info("sync folder {} with workspace {}", dir, this.folder);
if (dir == null || !dir.exists() || !dir.isDirectory()) {
log.warn("folder {} does not exist", dir);
return;
}
if (dir.equals(this.folder)) {
log.warn("cannot sync folder with itself");
return;
}
try {
FileSync.sync(dir.toPath(), this.folder.toPath());
} catch (Exception e) {
log.error("failed to init data folder @" + this.folder, e);
}
}
@Override
public String toString() {
return "Workspace{" + "folder=" + folder + '}';
}
/**
* Copies all files from a source directory to a target directory. Files
* that exists in both directories will be overwritten by the version in the
* source directory.
*/
private static class FileSync extends SimpleFileVisitor<Path> {
private final Path sourceDir;
private final Path targetDir;
private FileSync(Path sourceDir, Path targetDir) {
this.sourceDir = sourceDir;
this.targetDir = targetDir;
}
static void sync(Path sourceDir, Path targetDir) throws IOException {
if (!Files.exists(sourceDir))
return;
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
var sync = new FileSync(sourceDir, targetDir);
Files.walkFileTree(sourceDir, sync);
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
throws IOException {
var target = targetDir.resolve(sourceDir.relativize(dir));
if (!Files.exists(target)) {
Files.createDirectories(target);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
var target = targetDir.resolve(sourceDir.relativize(file));
// do not overwrite user settings
if (target.getFileName().toString().equals("settings.json")
&& Files.exists(target)) {
return FileVisitResult.CONTINUE;
}
Files.copy(file, target,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
return FileVisitResult.CONTINUE;
}
}
}
|
package auth;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
//import com.mysql.jdbc.*;
import util.Hash;
import util.Misc;
import util.Watch;
/**
* @author kAG0
*
*/
public class Resolver {
private Connection connection = null;
private static final String serverAddress = "vodkapi.dyndns.info";
private static final int PORT = 3306;
private static final String DATABASE = "Portunes";
private static final String USERNAME = "nate";
private static final String PASSWORD = "pass";
/**
* notes:
* working with IPv4 addresses in mySQL:
* store ip's as unsigned 4 byte int's
* use the mySQL built in functions INET_ATON() and INET_NTOA() in your queries
* ATON converts things from the form '192.168.1.1' to an integer
* NTOA converts from an integer to the above form.
*
* checking user validity is probably redundant as long as you check Request.admin
* because if !admin, username and userPW would have to be valid to get the request
* resolver.
*
* lots of things should be changed to prepared statements
*/
public Resolver() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection getConnection(String sqlUserName, String sqlUserPassword) throws SQLException{
return DriverManager.getConnection("jdbc:mysql://" + serverAddress + ":" + PORT + "/" + DATABASE, sqlUserName, sqlUserPassword);
}
public void connect() throws SQLException{
if(connection == null)
connection = getConnection(USERNAME, PASSWORD);
}
public void disconnect() throws SQLException{
connection.close();
connection = null;
}
/**
*
* @param userName
* @return the salt of userName, if userName DNE then return null
* @throws IOException
*/
public byte[] getUserSalt(String userName) throws UserNotFoundException, IOException{
//Connection connection;
//System.out.println("getting salt");
try {
if(connection == null)
connect();//connection = getConnection(USERNAME, PASSWORD);
String query = "SELECT salt FROM User WHERE userName = '" + userName + "';";
Statement stmt = (Statement) connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
byte[] salt = rs.getBytes("salt");
//System.out.println(Misc.getHexBytes(salt, ""));
return salt;
}else
throw new UserNotFoundException(userName);
} catch (SQLException e) {
e.printStackTrace();
throw new IOException("Problem getting user salt from DB.");
}
}
public byte[] getUserHash(String userName) throws UserNotFoundException, IOException{
//Connection connection;
System.out.println("getting hash");
try {
if(connection == null)
connect();//connection = getConnection(USERNAME, PASSWORD);
String query = "SELECT password FROM User WHERE userName = '" + userName + "';";
Statement stmt = connection.createStatement();
//System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
return rs.getBytes("password");
}else
throw new UserNotFoundException(userName);
} catch (SQLException e) {
e.printStackTrace();
throw new IOException("Problem getting user hash from DB.");
}
}
/**
* parses request and returns a Request that is the same as request but with
* the reply data member appropriately filled.
* @param request the request to handle
* @return same as request but with the reply data member appropriately filled.
*/
public Request resolve(Request request) throws UserNotFoundException{
//connection = getConnection(user, pass);
//Statement stmt = connection.createStatement();
/*
* maybe do the following only in the cases where it's needed
if(request.admin){
if(!isValidUser(request.adminName, request.getAuthUserPW()))
//return null or something
}*/
switch(request.operation){
// In each switch statement make query = to something different depending on what we want to query
case ADD:
if(isAdmin(request.adminName)){
request.setReply(add((ADD) request));
}else
request.setReply(false);
break;
case REMOVE:
if(request.admin && isValidAdmin(request.username, request.adminName, request.adminPW))
request.setReply(removeUser((REMOVE) request));
else request.setReply(removeUser((REMOVE) request));
break;
case CHECK:
request.setReply(isValidUser(request.username, request.userPW));
CHECK reply = (CHECK) request;
if(!request.admin && reply.reply)
recordLogin(request.origin, request.username);
break;
case CHANGENAME:
if(!request.admin){
if(isValidUser(request.username, request.userPW)){
request.setReply(changeName((CHANGENAME) request));
}
}
else if (isValidAdmin(request.username, request.adminName, request.adminPW)){
request.setReply(changeName((CHANGENAME) request));
}
break;
case CHANGEPASSWORD://TODO
if(!request.admin){
if(isValidUser(request.username, request.userPW)){
request.setReply(changePass((CHANGEPASS) request));
}
}
else if (isValidAdmin(request.username, request.adminName, request.adminPW)){
request.setReply(changePass((CHANGEPASS) request));
}
break;
case GETINFO://TODO
if(request.admin && isValidAdmin(request.username, request.adminName, request.adminPW)){
request.setReply(getInfo((GETINFO) request));
}else request.setReply(getInfo((GETINFO) request));
break;
case SETADMIN:
if(!isValidAdmin(request.username, request.adminName, request.adminPW))
break;
// get the newAdminName
// SQL INSERT newAdminName and yeah
request.setReply(makeAdmin(request.adminName, request.username)); // true if the newAdminName has been made an administrator of userName
break;
case LIST://TODO
request.setReply(listUsers((GETINFO) request));
break;
case HISTORY://TODO
request.setReply(getHistory((HISTORY) request));
break;
case CHECKADMIN:
if(isValidUser(request.username, request.userPW) && isAdmin(request.username)){
request.setReply(true);
recordLogin(request.origin, request.username);
}
else request.setReply(false);
break;
}
try {
disconnect();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return request;
}
private boolean makeAdmin(String adminName, String userName){
// "INSERT INTO Admin values(" + adminName + "," + userName + ");"
try {
connect();
Statement stmt = connection.createStatement();
//"INSERT INTO `Portunes`.`Admin` (`adminName`, `userName`) VALUES ('"+ adminName +"', '" + userName + "');"
stmt.executeUpdate("INSERT INTO Admin (`adminName`, `userName`) values('" + adminName + "','" + userName + "');");
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
private boolean add(ADD request){
byte[] salt = new byte[AuthServer.saltLength];
new SecureRandom().nextBytes(salt);
String query_create = "INSERT INTO User values('" + request.username + "','" + request.name +
"', 0x" + Misc.getHexBytes(Hash.getStretchedSHA256(request.userPW, salt, AuthServer.stretchLength), "") +
", 0x" + Misc.getHexBytes(salt, "") + ");";
String query_history = "INSERT INTO History(length, lastLoginIndex, userName) values(" +
"6"/*<<history length*/ + ", 0, '" + request.username + "');";
try {
if(connection == null)
connect();
connection.setAutoCommit(false);
Statement stmt_create = connection.createStatement();
Statement stmt_history = connection.createStatement();
System.out.println(query_create + "\n" +query_history);
stmt_create.executeUpdate(query_create);
stmt_history.executeUpdate(query_history);
if(!makeAdmin(request.adminName, request.username))
throw new SQLException();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if(connection != null){
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
return false;
}finally{
try {
if(connection != null)
connection.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
return true;
// "INSERT INTO User values(" + userName + "," + name +
// ", 0x" + Misc.getHexBytes(stretchedPassword, "") +
// ", 0x" + Misc.getHexBytes(salt, "") + ");"
// "INSERT INTO History(length, lastLoginIndex, userName) values(" +
// historyLength + ", 0, " + userName + ");"
}
private boolean removeUser(REMOVE request){
String query = "DELETE FROM User "+
"WHERE User.userName = '" + request.username + "';";
//System.out.println(query);
try {
if(connection == null)
connect();
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
//return true;
//get the info on what to delete
}
private boolean changeName(CHANGENAME request){
//get the name we have to change
//UPDATE tablename SET name = "newname" WHERE name = "oldname" AND password ="password" AND so on...
String query = "UPDATE User SET name = '" + request.name + "' WHERE userName = '" +request.username+ "';";
try {
if (connection == null)
connect();
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
} catch (SQLException e){
e.printStackTrace();
return false;
}
return true;
}
private boolean changePass(CHANGEPASS request){
// get the password we have to change
// UPDATE tablename SET password = "newpassword" WHERE name = "name" AND password ="oldpassword" AND so on...
try {
byte[] salt = new byte[AuthServer.saltLength];
new SecureRandom().nextBytes(salt);
String query = "UPDATE USER SET password = 0x" + Hash.getStretchedSHA256(request.userPW, salt, AuthServer.stretchLength) + ", salt = 0x" + Misc.bytesToHex(salt) + " WHERE userName = '" + request.username +"';";
if (connection == null)
connect();
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
} catch (SQLException e){
e.printStackTrace();
return false;
}
return true;
}
private Map<String, Object> getInfo(GETINFO request){
// SELECT * FROM table WHERE user ="username" AND etc.
Map<String, Object> reply = new HashMap<String, Object>();
String query = "SELECT * FROM History h JOIN LogIn l USING(hid) WHERE h.userName = '"+request.username
+"' AND l.index = ((h.lastLoginIndex - "+ request.time+") MOD h.length) ;"; // the history on the user with a specific username
int hid, month, day, year, hours, minutes;
InetAddress ip = null;
try {
if(connection == null)
connect();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
hid = rs.getInt("hid");
try {
ip = InetAddress.getByName(rs.getString("ip"));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
month = rs.getInt("month");
day = rs.getInt("day");
year = rs.getInt("year");
hours = rs.getInt("hours");
minutes = rs.getInt("minutes");
reply.put("userName", request.username);
reply.put("hid", hid);
reply.put("ip", ip);
reply.put("month", month);
reply.put("day", day);
reply.put("year", year);
reply.put("hours", hours);
reply.put("minutes",minutes);
}
return reply;
}catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private List<Map<String, Object>> getHistory(HISTORY request){
// while rs.next(){getInfo(request + 1 time)
// SELECT allPreviousLogins FROM table WHERE user = "username"
List<Map<String, Object>> reply = new ArrayList<Map<String, Object>>();
String query = "SELECT * FROM History h JOIN LogIn l USING(hid) WHERE h.userName = '"+request.username+"';"; // the history on the user with a specific username
int hid, ip, month, day, year, hours, minutes, i;
i=0;
try {
if(connection == null)
connect();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
hid = rs.getInt("hid");
ip = rs.getInt("ip");
month = rs.getInt("month");
day = rs.getInt("day");
year = rs.getInt("year");
hours = rs.getInt("hours");
minutes = rs.getInt("minutes");
reply.get(i).put("HID", hid);
reply.get(i).put("IP", ip);
reply.get(i).put("MONTH", month);
reply.get(i).put("DAY", day);
reply.get(i).put("YEAR", year);
reply.get(i).put("HOURS", hours);
reply.get(i).put("MINUTES",minutes);
i++;
}
return reply;
}catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private List<Map<String, Object>> listUsers(GETINFO request){
// ASSUME ITS ADMIN get admin name and pword
// SELECT allPreviousLogins FROM table WHERE adminname = "admin name" AND etc.
List<Map<String, Object>> reply = new ArrayList<Map<String, Object>>();
String query = "SELECT h.userName, l.hid, l.ip, l.month, l.day, l.year, l.hours, l.minutes" // reutrn back what we need
+ " FROM ((History h JOIN LogIn l USING (hid)) JOIN User u USING (userName)) JOIN Admin a USING (userName) " // join all tables
+ " WHERE adminName = '"+ request.username +"' ;"; // admin = the user of the request
String userName = "";
int hid, ip, month, day, year, hours, minutes, i;
i=0;
try {
if(connection == null)
connect();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
userName = rs.getString("userName");
hid = rs.getInt("hid");
ip = rs.getInt("ip");
month = rs.getInt("month");
day = rs.getInt("day");
year = rs.getInt("year");
hours = rs.getInt("hours");
minutes = rs.getInt("minutes");
reply.get(i).put("USERNAME", userName);
reply.get(i).put("HID", hid);
reply.get(i).put("IP", ip);
reply.get(i).put("MONTH", month);
reply.get(i).put("DAY", day);
reply.get(i).put("YEAR", year);
reply.get(i).put("HOURS", hours);
reply.get(i).put("MINUTES",minutes);
i++;
}
return reply;
}catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//TODO make this work (updating logIn instead of inserting. maybe add entire empty login history at user creation
public boolean recordLogin(InetAddress origin, String userName) {
boolean ret = false;
Watch time = new Watch();
String incQuery = "UPDATE History SET lastLoginIndex = lastLoginIndex + 1 MOD length WHERE userName = '"+userName+"';";
String query = "INSERT INTO LogIn(hid, ip, month, day, year, `index`, hours, minutes)" +
" SELECT hid, INET_ATON('" + origin.getHostAddress() + "'), "
+ time.getMonth() + ", " + time.getDate() + ", " + time.getYear() +
", lastLoginIndex MOD length, " + time.getHours() + ", " + time.getMinutes() + " " +
"FROM History " +
"WHERE userName = '" + userName + "';";
System.out.println(query);
try {
connect();
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
stmt.executeUpdate(incQuery);
stmt.executeUpdate(query);
connection.commit();
ret = true;
} catch (SQLException e) {
e.printStackTrace();
ret = false;
try {
if(connection != null)
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally{
if(connection != null)
try {
connection.setAutoCommit(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ret;
}
private boolean isValidUser(String userName2Check, byte[] password){
String queryValidUser = "SELECT * FROM User WHERE userName = '"+ userName2Check+"';";
try {
if(connection == null)
connect();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(queryValidUser);
if(rs.next()){
byte[] storedPW = rs.getBytes("password"); // get password for userName from db
byte[] salt = rs.getBytes("salt");
byte[] computedPW = Hash.getStretchedSHA256(password, salt, AuthServer.stretchLength);
System.out.println(DatatypeConverter.printHexBinary(password) +"\nserver " + DatatypeConverter.printHexBinary(storedPW) + "\n" +
"compu " + DatatypeConverter.printHexBinary(computedPW) + "\n" +
DatatypeConverter.printHexBinary(password) + " " + DatatypeConverter.printHexBinary(salt));
return Arrays.equals(computedPW, storedPW);
}
//else
//return false;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private boolean isAdmin(String adminName){
String query = "SELECT * " +
"FROM Admin JOIN User ON adminName = User.userName " +
"WHERE adminName = '" + adminName + "' ";
try {
connect();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//not efficient, needs optimization up the wazoo
private boolean isValidAdmin(String userName, String adminName, byte[] adminPW){
if(!isAdmin(adminName) || !isValidUser(adminName, adminPW))
return false; //this check saves time if adminName isnt' an admin
//or user, but only adds a couple (to the n ;( ) queries if they are
String q1 = "SELECT adminName FROM Admin WHERE userName = '" + userName +"';";
try {
return isAdminOf(adminName, userName);
// connect();
// Statement stmt1 = connection.createStatement();
// ResultSet rs1 = stmt1.executeQuery(q1);
// while(rs1.next()){
// if(rs1.getString("adminName").equalsIgnoreCase(adminName))
// return true;
// rs1.beforeFirst();
// while(rs1.next()){
// if(isAdminOf(adminName, rs1.getString("adminName")))
// return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
//if adminname is and admin of a user who is an admin of userName return true
// potential exemplary query here
}
private boolean isAdminOf(String adminName, String userName) throws SQLException{
String q1 = "SELECT adminName FROM Admin WHERE userName = '" + userName +"';";
connect();
Statement stmt1 = connection.createStatement();
ResultSet rs1 = stmt1.executeQuery(q1);
while(rs1.next()){
if(rs1.getString("adminName").equalsIgnoreCase(adminName))
return true;
}
rs1.beforeFirst();
while(rs1.next()){
if(isAdminOf(adminName, rs1.getString("adminName")))
return true;
}
return false;
}
// private boolean isValidAdmin(String userName, String adminName, byte[] adminPW){
// String query1 = "SELECT userName FROM User WHERE userName = '" +userName+"';";// query that gets username of a specific user
// String query2 = "SELECT adminName FROM Admin WHERE adminName = '" +adminName+ "' AND userName = '"+ userName+"' ;";// query that gets the admin name of a specific user
// String userName2Check = "";
// String adminName2Check = "";
// byte[] storedPW = null;
// byte[] salt = null;
// try{
// connect();
// Statement stmt = connection.createStatement();
// ResultSet rs = stmt.executeQuery(query1);
// Statement stmt2 = connection.createStatement();
// ResultSet rs2 = stmt2.executeQuery(query2);// gets the admin name if it exists from the query
// if(rs.next())
// userName2Check = rs.getString("userName");
// if( userName.equals(userName2Check)/* userName is in db */ && isValidUser(adminName, adminPW) ){
// if(rs2.next())
// adminName2Check = rs2.getString("adminName");
// if(adminName.equals(adminName2Check) /* adminName is set as an admin of userName in db */)
// storedPW = rs2.getBytes("password"); // get password for userName from db
// salt = rs2.getBytes("salt");
// return Arrays.equals(Hash.getStretchedSHA256(adminPW, salt, AuthServer.stretchLength), storedPW);
// else
// return false;
// } catch (SQLException e) {
// e.printStackTrace();
// return false;
// //if adminname is and admin of a user who is an admin of userName return true
// // potential exemplary query here
/**
* note: this exception should only be thrown as part of the authentication process
* when handling requests like CHECK the response field of the request should just be null
* @author kAG0
*
*/
public static class UserNotFoundException extends Exception{
private String username;
UserNotFoundException(String userName){
super(userName +" not found in database.");
username = userName;
}
public String getUserName(){
return username;
}
}
}
|
package com.exedio.cope;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import com.exedio.cope.util.PoolCounter;
import com.exedio.dsmf.ConnectionProvider;
final class ConnectionPool implements ConnectionProvider
{
// TODO: allow changing pool size
// TODO: gather pool effectivity statistics
// TODO: use a ring buffer instead of a stack
// to avoid connections at the bottom of the stack
// staying idle for a very long time and possibly
// running into some idle timeout implemented by the
// jdbc driver or the database itself.
// TODO: implement idle timout
// ensure, that idle connections in the pool do
// not stay idle for a indefinite time,
// but are closed after a certain time to avoid
// running into some idle timeout implemented by the
// jdbc driver or the database itself.
private final Connection[] idle = new Connection[10];
private int idleCount = 0;
private int activeCount = 0;
private final Object lock = new Object();
private final String url;
private final String user;
private final String password;
final PoolCounter counter;
ConnectionPool(final Properties properties)
{
this.url = properties.getDatabaseUrl();
this.user = properties.getDatabaseUser();
this.password = properties.getDatabasePassword();
// TODO: make this customizable and disableable
this.counter = new PoolCounter(new int[]{0,1,2,3,4,5,6,7,8,9,10,12,15,16,18,20,25,30,35,40,45,50,60,70,80,90,100,120,140,160,180,200,250,300,350,400,450,500,600,700,800,900,1000});
}
public final Connection getConnection() throws SQLException
{
counter.get();
synchronized(lock)
{
activeCount++;
if(idleCount>0)
{
//System.out.println("connection pool: fetch "+(size-1));
final Connection result = idle[--idleCount];
idle[idleCount] = null; // do not reference active connections
return result;
}
}
//System.out.println("connection pool: CREATE");
// Important to do this outside the synchronized block!
return DriverManager.getConnection(url, user, password);
}
/**
* TODO: If we want to implement changing connection parameters on-the-fly
* somewhere in the future, it's important, that client return connections
* to exactly the same instance of ConnectionPool.
*/
public final void putConnection(final Connection connection) throws SQLException
{
if(connection==null)
throw new NullPointerException();
counter.put();
synchronized(lock)
{
activeCount
if(idleCount<idle.length)
{
//System.out.println("connection pool: store "+size);
idle[idleCount++] = connection;
return;
}
}
//System.out.println("connection pool: CLOSE ");
// Important to do this outside the synchronized block!
connection.close();
}
final void flush()
{
// make a copy of idle to avoid closing idle connections
// inside the synchronized block
final ArrayList copyOfIdle = new ArrayList(idle.length);
synchronized(lock)
{
if(idleCount==0)
return;
//System.out.println("connection pool: FLUSH "+size);
for(int i = 0; i<idleCount; i++)
{
copyOfIdle.add(idle[i]);
idle[i] = null; // do not reference closed connections
}
idleCount = 0;
}
try
{
for(Iterator i = copyOfIdle.iterator(); i.hasNext(); )
((Connection)i.next()).close();
}
catch(SQLException e)
{
throw new NestingRuntimeException(e);
}
if(activeCount!=0)
throw new RuntimeException("still "+activeCount+" connections active");
}
}
|
// package name: as default, start with complex
package qa;
// imports
import complexlib.ComplexTestCase;
import com.sun.star.uno.XInterface;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.Type;
import com.sun.star.uno.XComponentContext;
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.star.lang.*;
import com.sun.star.beans.*;
import com.sun.star.frame.*;
import com.sun.star.chart.*;
import com.sun.star.drawing.*;
import com.sun.star.awt.*;
import com.sun.star.util.XCloseable;
import com.sun.star.util.CloseVetoException;
import drafts.com.sun.star.chart2.XTitled;
import drafts.com.sun.star.chart2.XTitle;
import drafts.com.sun.star.chart2.XDataProvider;
import drafts.com.sun.star.chart2.XFormattedString;
import drafts.com.sun.star.chart2.XDiagramProvider;
import com.sun.star.uno.AnyConverter;
import com.sun.star.comp.helper.ComponentContext;
/**
* The following Complex Test will test the
* com.sun.star.document.IndexedPropertyValues
* service
*/
public class TestCaseOldAPI extends ComplexTestCase {
// The name of the tested service
private final String testedServiceName =
"com.sun.star.chart.ChartDocument";
// The first of the mandatory functions:
/**
* Return the name of the test.
* In this case it is the actual name of the service.
* @return The tested service.
*/
public String getTestObjectName() {
return testedServiceName;
}
// The second of the mandatory functions: return all test methods as an
// array. There is only one test function in this example.
/**
* Return all test methods.
* @return The test methods.
*/
public String[] getTestMethodNames() {
return new String[] {
"testChartType",
"testTitle",
"testSubTitle",
"testDiagram",
"testAxis",
"testLegend",
"testArea",
"testAggregation",
"testDataSeriesAndPoints",
"testStatistics"
};
}
public void before()
{
// change to "true" to get a view
mbCreateView = false;
if( mbCreateView )
mxChartModel = createDocument( "chart" );
else
mxChartModel = createChartModel();
createFileDataSource( mxChartModel );
mxOldDoc = (XChartDocument) UnoRuntime.queryInterface(
XChartDocument.class, mxChartModel );
}
public void after()
{
XCloseable xCloseable = (XCloseable) UnoRuntime.queryInterface(
XCloseable.class, mxChartModel );
assure( "document is no XCloseable", xCloseable != null );
// do not close document if there exists a view
if( ! mbCreateView )
{
try
{
xCloseable.close( true );
}
catch( CloseVetoException ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
}
public void testTitle()
{
try
{
// set title at new chart
XTitled xTitled = (XTitled) UnoRuntime.queryInterface(
XTitled.class, mxChartModel );
// set title via new API
XTitle xTitle = setTitle( xTitled, "Sample", "@main-title" );
// printInterfacesAndServices( xTitle );
// get title via old API
XShape xTitleShape = mxOldDoc.getTitle();
XPropertySet xTitleProp = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xTitleShape );
// set property via old API
if( xTitleProp != null )
{
String aTitle = " Overwritten by Old API ";
float fHeight = (float)17.0;
xTitleProp.setPropertyValue( "String", aTitle );
xTitleProp.setPropertyValue( "CharHeight", new Float( fHeight ) );
float fNewHeight = AnyConverter.toFloat( xTitleProp.getPropertyValue( "CharHeight" ) );
assure( "Changing CharHeight via old API failed", fNewHeight == fHeight );
String aNewTitle = AnyConverter.toString( xTitleProp.getPropertyValue( "String" ) );
assure( "Property \"String\" failed", aNewTitle.equals( aTitle ));
}
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testSubTitle()
{
try
{
// trying back-querying (from old Wrapper to new Model)
drafts.com.sun.star.chart2.XChartDocument xNewDoc =
(drafts.com.sun.star.chart2.XChartDocument) UnoRuntime.queryInterface(
drafts.com.sun.star.chart2.XChartDocument.class,
mxOldDoc );
// set title at new chart
XTitled xTitled = (XTitled) UnoRuntime.queryInterface(
XTitled.class, xNewDoc.getDiagram() );
// set title via new API
setTitle( xTitled, "Sub", "@sub-title" );
// get Property via old API
XShape xTitleShape = mxOldDoc.getSubTitle();
XPropertySet xTitleProp = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xTitleShape );
// set Property via old API
if( xTitleProp != null )
{
int nColor = 0x009acd; // DeepSkyBlue3
float fWeight = FontWeight.BOLD;
xTitleProp.setPropertyValue( "CharColor", new Integer( nColor ) );
xTitleProp.setPropertyValue( "CharWeight", new Float( fWeight ));
int nNewColor = AnyConverter.toInt( xTitleProp.getPropertyValue( "CharColor" ) );
assure( "Changing CharColor via old API failed", nNewColor == nColor );
float fNewWeight = AnyConverter.toFloat( xTitleProp.getPropertyValue( "CharWeight" ) );
assure( "Changing CharWeight via old API failed", fNewWeight == fWeight );
}
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testDiagram()
{
try
{
// testing wall
XDiagram xDia = mxOldDoc.getDiagram();
if( xDia != null )
{
X3DDisplay xDisp = (X3DDisplay) UnoRuntime.queryInterface(
X3DDisplay.class, xDia );
assure( "X3DDisplay not supported", xDisp != null );
XPropertySet xProp = xDisp.getWall();
if( xProp != null )
{
// log.println( "Testing wall" );
int nColor = 0xffe1ff; // thistle1
xProp.setPropertyValue( "FillColor", new Integer( nColor ) );
int nNewColor = AnyConverter.toInt( xProp.getPropertyValue( "FillColor" ) );
assure( "Changing FillColor via old API failed", nNewColor == nColor );
}
assure( "Wrong Diagram Type", xDia.getDiagramType().equals(
"com.sun.star.chart.BarDiagram" ));
}
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testAxis()
{
try
{
XAxisYSupplier xYAxisSuppl = (XAxisYSupplier) UnoRuntime.queryInterface(
XAxisYSupplier.class, mxOldDoc.getDiagram() );
assure( "Diagram is no y-axis supplier", xYAxisSuppl != null );
XPropertySet xProp = xYAxisSuppl.getYAxis();
assure( "No y-axis found", xProp != null );
double nNewMax = 12.3;
double nNewOrigin = 2.7;
xProp.setPropertyValue( "Max", new Double( nNewMax ));
assure( "AutoMax is on", ! AnyConverter.toBoolean( xProp.getPropertyValue( "AutoMax" )) );
assure( "Maximum value invalid",
approxEqual(
AnyConverter.toDouble( xProp.getPropertyValue( "Max" )),
nNewMax ));
xProp.setPropertyValue( "AutoMin", new Boolean( true ));
assure( "AutoMin is off", AnyConverter.toBoolean( xProp.getPropertyValue( "AutoMin" )) );
// missing: Min/Max, etc. is not always returning a double
// Object oMin = xProp.getPropertyValue( "Min" );
// assure( "No Minimum set", AnyConverter.isDouble( oMin ));
// log.println( "Minimum retrieved: " + AnyConverter.toDouble( oMin ));
xProp.setPropertyValue( "Origin", new Double( nNewOrigin ));
assure( "Origin invalid",
approxEqual(
AnyConverter.toDouble( xProp.getPropertyValue( "Origin" )),
nNewOrigin ));
xProp.setPropertyValue( "AutoOrigin", new Boolean( true ));
assure( "AutoOrigin is off", AnyConverter.toBoolean( xProp.getPropertyValue( "AutoOrigin" )) );
xProp.setPropertyValue( "Logarithmic", new Boolean( true ));
assure( "Scaling is not logarithmic",
AnyConverter.toBoolean( xProp.getPropertyValue( "Logarithmic" )) );
xProp.setPropertyValue( "Logarithmic", new Boolean( false ));
assure( "Scaling is not logarithmic",
! AnyConverter.toBoolean( xProp.getPropertyValue( "Logarithmic" )) );
int nNewColor = 0xcd853f; // peru
xProp.setPropertyValue( "LineColor", new Integer( nNewColor ));
assure( "Property LineColor",
AnyConverter.toInt( xProp.getPropertyValue( "LineColor" )) == nNewColor );
float fNewCharHeight = (float)(16.0);
xProp.setPropertyValue( "CharHeight", new Float( fNewCharHeight ));
assure( "Property CharHeight",
AnyConverter.toFloat( xProp.getPropertyValue( "CharHeight" )) == fNewCharHeight );
int nNewTextRotation = 700; // in 1/100 degrees
xProp.setPropertyValue( "TextRotation", new Integer( nNewTextRotation ));
assure( "Property TextRotation",
AnyConverter.toInt( xProp.getPropertyValue( "TextRotation" )) == nNewTextRotation );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testLegend()
{
XShape xLegend = mxOldDoc.getLegend();
assure( "No Legend returned", xLegend != null );
XPropertySet xLegendProp = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xLegend );
assure( "Legend is no property set", xLegendProp != null );
try
{
ChartLegendPosition eNewPos = ChartLegendPosition.BOTTOM;
xLegendProp.setPropertyValue( "Alignment", eNewPos );
assure( "Property Alignment",
AnyConverter.toObject(
new Type( ChartLegendPosition.class ),
xLegendProp.getPropertyValue( "Alignment" )) == eNewPos );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testArea()
{
XPropertySet xArea = mxOldDoc.getArea();
assure( "No Area", xArea != null );
try
{
int nColor = 0xf5fffa; // mint cream
xArea.setPropertyValue( "FillColor", new Integer( nColor ) );
xArea.setPropertyValue( "FillStyle", FillStyle.SOLID );
int nNewColor = AnyConverter.toInt( xArea.getPropertyValue( "FillColor" ) );
assure( "Changing FillColor of Area failed", nNewColor == nColor );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testChartType()
{
XMultiServiceFactory xFact = (XMultiServiceFactory) UnoRuntime.queryInterface(
XMultiServiceFactory.class, mxOldDoc );
assure( "document is no factory", xFact != null );
try
{
String aMyServiceName = new String( "com.sun.star.chart.AreaDiagram" );
String aServices[] = xFact.getAvailableServiceNames();
boolean bServiceFound = false;
for( int i = 0; i < aServices.length; ++i )
{
if( aServices[ i ].equals( aMyServiceName ))
{
bServiceFound = true;
break;
}
}
assure( "getAvailableServiceNames did not return " + aMyServiceName, bServiceFound );
if( bServiceFound )
{
XDiagram xDia = (XDiagram) UnoRuntime.queryInterface(
XDiagram.class, xFact.createInstance( aMyServiceName ));
assure( aMyServiceName + " could not be created", xDia != null );
mxOldDoc.setDiagram( xDia );
XPropertySet xDiaProp = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xDia );
assure( "Diagram is no XPropertySet", xDiaProp != null );
xDiaProp.getPropertyValue( "Stacked" );
xDiaProp.setPropertyValue( "Stacked", new Boolean( true ));
assure( "StackMode could not be set correctly",
AnyConverter.toBoolean(
xDiaProp.getPropertyValue( "Stacked" )));
}
// reset to bar-chart
aMyServiceName = new String( "com.sun.star.chart.BarDiagram" );
XDiagram xDia = (XDiagram) UnoRuntime.queryInterface(
XDiagram.class, xFact.createInstance( aMyServiceName ));
assure( aMyServiceName + " could not be created", xDia != null );
mxOldDoc.setDiagram( xDia );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testAggregation()
{
// query to new type
XChartDocument xDiaProv = (XChartDocument) UnoRuntime.queryInterface(
XChartDocument.class, mxOldDoc );
assure( "query to new interface failed", xDiaProv != null );
com.sun.star.chart.XChartDocument xDoc = (com.sun.star.chart.XChartDocument) UnoRuntime.queryInterface(
com.sun.star.chart.XChartDocument.class, xDiaProv );
assure( "querying back to old interface failed", xDoc != null );
}
public void testDataSeriesAndPoints()
{
try
{
XDiagram xDia = mxOldDoc.getDiagram();
assure( "Invalid Diagram", xDia != null );
XPropertySet xProp = xDia.getDataRowProperties( 1 );
assure( "No DataRowProperties for series 1 (0-based)", xProp != null );
// Gradient
Gradient aGradient = new Gradient();
aGradient.Style = GradientStyle.LINEAR;
aGradient.StartColor = 0xe0ffff; // light cyan
aGradient.EndColor = 0xff8c00; // dark orange
aGradient.Angle = 300; // 30 degrees
aGradient.Border = 15;
aGradient.XOffset = 0;
aGradient.YOffset = 0;
aGradient.StartIntensity = 100;
aGradient.EndIntensity = 80;
aGradient.StepCount = 23;
xProp.setPropertyValue( "FillStyle", FillStyle.GRADIENT );
xProp.setPropertyValue( "FillGradient", aGradient );
Gradient aNewGradient = (Gradient) AnyConverter.toObject(
new Type( Gradient.class ),
xProp.getPropertyValue( "FillGradient" ));
assure( "Gradient Style", aNewGradient.Style == aGradient.Style );
assure( "Gradient StartColor", aNewGradient.StartColor == aGradient.StartColor );
assure( "Gradient EndColor", aNewGradient.EndColor == aGradient.EndColor );
assure( "Gradient Angle", aNewGradient.Angle == aGradient.Angle );
assure( "Gradient Border", aNewGradient.Border == aGradient.Border );
assure( "Gradient XOffset", aNewGradient.XOffset == aGradient.XOffset );
assure( "Gradient YOffset", aNewGradient.YOffset == aGradient.YOffset );
assure( "Gradient StartIntensity", aNewGradient.StartIntensity == aGradient.StartIntensity );
assure( "Gradient EndIntensity", aNewGradient.EndIntensity == aGradient.EndIntensity );
assure( "Gradient StepCount", aNewGradient.StepCount == aGradient.StepCount );
// Hatch
xProp = xDia.getDataPointProperties( 1, 1 );
assure( "No DataPointProperties for (1,1)", xProp != null );
Hatch aHatch = new Hatch();
aHatch.Style = HatchStyle.DOUBLE;
aHatch.Color = 0xd2691e; // chocolate
aHatch.Distance = 200; // 2 mm (?)
aHatch.Angle = 230; // 23 degrees
xProp.setPropertyValue( "FillHatch", aHatch );
xProp.setPropertyValue( "FillStyle", FillStyle.HATCH );
Hatch aNewHatch = (Hatch) AnyConverter.toObject(
new Type( Hatch.class ),
xProp.getPropertyValue( "FillHatch" ));
assure( "Hatch Style", aNewHatch.Style == aHatch.Style );
assure( "Hatch Color", aNewHatch.Color == aHatch.Color );
assure( "Hatch Distance", aNewHatch.Distance == aHatch.Distance );
assure( "Hatch Angle", aNewHatch.Angle == aHatch.Angle );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
public void testStatistics()
{
try
{
XDiagram xDia = mxOldDoc.getDiagram();
assure( "Invalid Diagram", xDia != null );
XPropertySet xProp = xDia.getDataRowProperties( 0 );
assure( "No DataRowProperties for first series", xProp != null );
xProp.setPropertyValue( "MeanValue", new Boolean( true ));
assure( "No MeanValue", AnyConverter.toBoolean( xProp.getPropertyValue( "MeanValue" )) );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
private XModel mxChartModel;
private XChartDocument mxOldDoc;
private boolean mbCreateView;
private void createFileDataSource( XModel xModel )
{
XMultiServiceFactory xFactory = (XMultiServiceFactory) param.getMSF();
try
{
XDataProvider xDataProv = (XDataProvider) UnoRuntime.queryInterface(
XDataProvider.class,
xFactory.createInstance( "com.sun.star.comp.chart.FileDataProvider" ));
drafts.com.sun.star.chart2.XChartDocument xDoc =
(drafts.com.sun.star.chart2.XChartDocument) UnoRuntime.queryInterface(
drafts.com.sun.star.chart2.XChartDocument.class,
xModel );
if( xDataProv != null &&
xDoc != null )
{
xDoc.attachDataProvider( xDataProv );
String aURL = "file://" + System.getProperty( "user.dir" ) +
System.getProperty( "file.separator" ) + "data.chd";
log.println( aURL );
xDoc.setRangeRepresentation( aURL );
}
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
}
private XModel createDocument( String sDocType )
{
XModel aResult = null;
try
{
XComponentLoader aLoader = (XComponentLoader) UnoRuntime.queryInterface(
XComponentLoader.class,
((XMultiServiceFactory)param.getMSF()).createInstance( "com.sun.star.frame.Desktop" ) );
aResult = (XModel) UnoRuntime.queryInterface(
XModel.class,
aLoader.loadComponentFromURL( "private:factory/" + sDocType,
"_blank",
0,
new PropertyValue[ 0 ] ) );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
return aResult;
}
public XModel createChartModel()
{
XModel aResult = null;
try
{
aResult = (XModel) UnoRuntime.queryInterface(
XModel.class,
((XMultiServiceFactory)param.getMSF()).createInstance( "com.sun.star.comp.chart2.ChartModel" ) );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
return aResult;
}
private XTitle setTitle( XTitled xTitleParent, String aTitle, String aId )
{
XTitle xTitle = null;
if( xTitleParent != null )
try
{
XMultiServiceFactory xFact = (XMultiServiceFactory)param.getMSF();
XMultiComponentFactory xCompFact = (XMultiComponentFactory) UnoRuntime.queryInterface(
XMultiComponentFactory.class, xFact );
XFormattedString[] aStrings = new XFormattedString[ 2 ];
aStrings[0] = (XFormattedString) UnoRuntime.queryInterface(
XFormattedString.class,
xFact.createInstance(
"drafts.com.sun.star.chart2.FormattedString" ));
aStrings[1] = (XFormattedString) UnoRuntime.queryInterface(
XFormattedString.class,
xFact.createInstance(
"drafts.com.sun.star.chart2.FormattedString" ));
aStrings[0].setString( aTitle );
aStrings[1].setString( " Title" );
Hashtable aParams = new Hashtable();
aParams.put( "Identifier", aId );
xTitle = (XTitle) UnoRuntime.queryInterface(
XTitle.class,
xCompFact.createInstanceWithContext(
"drafts.com.sun.star.chart2.Title",
new ComponentContext( aParams, getComponentContext( xFact ) )));
xTitle.setText( aStrings );
XPropertySet xTitleProp = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xTitle );
xTitleProp.setPropertyValue( "FillColor", new Integer( 0xfff8dc )); // cornsilk1
xTitleParent.setTitle( xTitle );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
return xTitle;
}
private XComponentContext getComponentContext( XMultiServiceFactory xFact )
{
XComponentContext xResult = null;
XPropertySet xProp = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xFact );
if( xProp != null )
try
{
xResult = (XComponentContext)
AnyConverter.toObject(
new Type( XComponentContext.class ),
xProp.getPropertyValue( "DefaultContext" ) );
}
catch( Exception ex )
{
failed( ex.getMessage() );
ex.printStackTrace( (PrintWriter)log );
}
return xResult;
}
private void printInterfacesAndServices( Object oObj )
{
log.println( "Services:" );
util.dbg.getSuppServices( oObj );
log.println( "Interfaces:" );
util.dbg.printInterfaces( (XInterface)oObj, true );
}
/// see rtl/math.hxx
private boolean approxEqual( double a, double b )
{
if( a == b )
return true;
double x = a - b;
return (x < 0.0 ? -x : x)
< ((a < 0.0 ? -a : a) * (1.0 / (16777216.0 * 16777216.0)));
}
}
|
package imagej.io.plugins;
import imagej.data.Dataset;
import imagej.event.EventService;
import imagej.event.StatusService;
import imagej.ext.display.Display;
import imagej.ext.menu.MenuConstants;
import imagej.ext.module.ItemIO;
import imagej.ext.module.ui.WidgetStyle;
import imagej.ext.plugin.ImageJPlugin;
import imagej.ext.plugin.Menu;
import imagej.ext.plugin.Parameter;
import imagej.ext.plugin.Plugin;
import imagej.io.StatusDispatcher;
import imagej.io.event.FileSavedEvent;
import imagej.ui.DialogPrompt;
import imagej.ui.DialogPrompt.Result;
import imagej.ui.UIService;
import imagej.util.Log;
import java.io.File;
import net.imglib2.exception.IncompatibleTypeException;
import net.imglib2.img.ImgPlus;
import net.imglib2.io.ImgIOException;
import net.imglib2.io.ImgSaver;
/**
* Saves the current {@link Dataset} to disk using a user-specified file name.
*
* @author Mark Hiner
*/
@Plugin(menu = {
@Menu(label = MenuConstants.FILE_LABEL, weight = MenuConstants.FILE_WEIGHT,
mnemonic = MenuConstants.FILE_MNEMONIC),
@Menu(label = "Save As...", weight = 21) })
public class SaveAsImage implements ImageJPlugin {
@Parameter(persist = false)
private EventService eventService;
@Parameter(persist = false)
private StatusService statusService;
@Parameter(persist = false)
private UIService uiService;
@Parameter(label = "File to save", style = WidgetStyle.FILE_SAVE,
initializer = "initOutputFile", persist = false)
private File outputFile;
@Parameter
private Dataset dataset;
@Parameter(type = ItemIO.BOTH)
private Display<?> display;
public void initOutputFile() {
outputFile = new File(dataset.getImgPlus().getSource());
}
@Override
public void run() {
@SuppressWarnings("rawtypes")
final ImgPlus img = dataset.getImgPlus();
boolean overwrite = true;
Result result = null;
// TODO prompts the user if the file is dirty or being saved to a new
// location. Could remove the isDirty check to always overwrite the current
// file
if (outputFile.exists() &&
(dataset.isDirty() || !outputFile.getAbsolutePath().equals(
img.getSource())))
{
result =
uiService.showDialog("\"" + outputFile.getName() +
"\" already exists. Do you want to replace it?", "Save [IJ2]",
DialogPrompt.MessageType.WARNING_MESSAGE,
DialogPrompt.OptionType.YES_NO_OPTION);
overwrite = result == DialogPrompt.Result.YES_OPTION;
}
if (overwrite) {
final ImgSaver imageSaver = new ImgSaver();
boolean saveImage = true;
try {
imageSaver.addStatusListener(new StatusDispatcher(statusService));
if (imageSaver.isCompressible(img)) result =
uiService.showDialog("Your image contains axes other than XYZCT.\n"
+ "When saving, these may be compressed to the "
+ "Channel axis (or the save process may simply fail).\n"
+ "Would you like to continue?", "Save [IJ2]",
DialogPrompt.MessageType.WARNING_MESSAGE,
DialogPrompt.OptionType.YES_NO_OPTION);
saveImage = result == DialogPrompt.Result.YES_OPTION;
imageSaver.saveImg(outputFile.getAbsolutePath(), img);
eventService.publish(new FileSavedEvent(img.getSource()));
}
catch (final ImgIOException e) {
Log.error(e);
uiService.showDialog(e.getMessage(), "IJ2: Save Error",
DialogPrompt.MessageType.ERROR_MESSAGE);
return;
}
catch (final IncompatibleTypeException e) {
Log.error(e);
uiService.showDialog(e.getMessage(), "IJ2: Save Error",
DialogPrompt.MessageType.ERROR_MESSAGE);
return;
}
if (saveImage) {
dataset.setName(outputFile.getName());
dataset.setDirty(false);
display.setName(outputFile.getName());
// NB - removed when display became ItemIO.Both.
// Restore later if necessary.
//display.update();
}
}
}
}
|
package gui;
import javafx.scene.text.Text;
public class Timer extends Text implements Runnable{
private long startMillis = 0L;
/** Anzahl der Millisekunden zwischen den Aktualisierungen der Anzeige. */
private int updateMillis = 1000;
private Thread t;
private boolean running = false;
/** Gibt (vermutlich) an, ob die Zeit abgelaufen ist.*/ //TODO: Wirklich?
private boolean time_up;
private long duration;
/** Speichert die Phase, die der Timer verwaltet*/ //TODO: Entsprechend ConstantsManager extrahieren.
private Phase phase;
public Timer(int sec, Phase phase){
super("Time: 0:00");
this.duration = ((sec+1)*1000)-1; //TODO:dieser verzoegerungsfix ist unschoen - das soll ned so bleiben!
this.phase = phase;
time_up = false;
}
public boolean time_up(){
return time_up;
}
public void run(){
startMillis = System.currentTimeMillis();
while (running){
update();
try {
Thread.sleep(updateMillis);
} catch (InterruptedException e) {
//DO Nothing
}
}
}
public void start(){
System.out.println("Starting Timer");
if (t == null){
t = new Thread(this, "Timer");
running = true;
t.start();
}
}
public void stop(){
running = false;
if (t != null){
t.interrupt();
t = null;
}
}
public void reset(){
startMillis = System.currentTimeMillis();
time_up = false;
}
public String toString(){
//TODO: Rundungsfehler ausmerzen!
long diff = duration-(System.currentTimeMillis() - startMillis);
//System.out.println(diff2);
int seconds = (int)((diff % (1000 * 60))/1000);
int minutes = (int)((diff % (1000 * 60 * 60))/(1000*60));
return String.valueOf(minutes) + ":" + String.valueOf(seconds); // TODO: sec nit nullen auf zwei stellen fuellen
}
public void update(){
this.setText("Time: " + this.toString());
if((System.currentTimeMillis() - startMillis)>=duration){
time_up = true;
}
}
}
|
package org.jsimpledb.core;
import com.google.common.base.Preconditions;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import org.jsimpledb.kv.KVPair;
import org.jsimpledb.util.ByteReader;
import org.jsimpledb.util.ByteUtil;
import org.jsimpledb.util.ByteWriter;
import org.jsimpledb.util.UnsignedIntEncoder;
/**
* {@link List} implementation for {@link ListField}s.
*/
class JSList<E> extends AbstractList<E> implements RandomAccess {
private final Transaction tx;
private final ObjId id;
private final ListField<E> field;
private final FieldType<E> elementType;
private final byte[] contentPrefix;
// Constructors
JSList(Transaction tx, ListField<E> field, ObjId id) {
Preconditions.checkArgument(tx != null, "null tx");
Preconditions.checkArgument(field != null, "null field");
Preconditions.checkArgument(id != null, "null id");
this.tx = tx;
this.field = field;
this.id = id;
this.elementType = this.field.elementField.fieldType;
this.contentPrefix = field.buildKey(id);
}
// List API
@Override
public E get(int index) {
// Find list entry
final byte[] value = this.tx.kvt.get(this.buildKey(index));
if (value == null)
throw new IndexOutOfBoundsException("index = " + index);
// Decode list element
return this.elementType.read(new ByteReader(value));
}
@Override
public int size() {
// Find the last entry, if it exists
final KVPair pair = this.tx.kvt.getAtMost(ByteUtil.getKeyAfterPrefix(this.contentPrefix));
if (pair == null || !ByteUtil.isPrefixOf(this.contentPrefix, pair.getKey()))
return 0;
// Decode index from key to get size
return UnsignedIntEncoder.read(new ByteReader(pair.getKey(), this.contentPrefix.length)) + 1;
}
@Override
public E set(final int index, final E elem) {
return this.tx.mutateAndNotify(this.id, new Transaction.Mutation<E>() {
@Override
public E mutate() {
return JSList.this.doSet(index, elem);
}
});
}
@Override
public Iterator<E> iterator() {
return new Iter();
}
private E doSet(final int index, final E newElem) {
// Build new key and value
final byte[] key = this.buildKey(index);
final byte[] newValue = this.buildValue(newElem);
// Get existing list entry at that index, if any
final byte[] oldValue = this.tx.kvt.get(key);
if (oldValue == null)
throw new IndexOutOfBoundsException("index = " + index);
// Optimize if no change
if (Arrays.equals(newValue, oldValue))
return newElem;
// Decode previous entry
final E oldElem = this.elementType.read(new ByteReader(oldValue));
// Update list content and index
this.tx.kvt.put(key, newValue);
if (this.field.elementField.indexed) {
this.field.removeIndexEntry(this.tx, this.id, this.field.elementField, key, oldValue);
this.field.addIndexEntry(this.tx, this.id, this.field.elementField, key, newValue);
}
// Notify field monitors
this.tx.addFieldChangeNotification(new ListFieldChangeNotifier() {
@Override
void notify(Transaction tx, ListFieldChangeListener listener, int[] path, NavigableSet<ObjId> referrers) {
listener.onListFieldReplace(tx, this.getId(), JSList.this.field, path, referrers, index, oldElem, newElem);
}
});
// Return previous entry
return oldElem;
}
@Override
public void add(final int index, final E elem) {
if (index < 0)
throw new IndexOutOfBoundsException("index = " + index);
this.tx.mutateAndNotify(this.id, new Transaction.Mutation<Boolean>() {
@Override
public Boolean mutate() {
return JSList.this.doAddAll(index, Collections.singleton(elem));
}
});
}
@Override
public boolean addAll(final int index, final Collection<? extends E> elems) {
if (index < 0)
throw new IndexOutOfBoundsException("index = " + index);
return this.tx.mutateAndNotify(this.id, new Transaction.Mutation<Boolean>() {
@Override
public Boolean mutate() {
return JSList.this.doAddAll(index, elems);
}
});
}
private boolean doAddAll(int index, Collection<? extends E> elems0) {
// Encode elements
final ArrayList<E> elems = new ArrayList<>(elems0);
final int numElems = elems.size();
final ArrayList<byte[]> values = new ArrayList<>(numElems);
for (E elem : elems)
values.add(this.buildValue(elem));
// Make room for elements
final int size = this.size();
if (index < 0 || index > size || size + numElems == Integer.MAX_VALUE || size + numElems < 0)
throw new IndexOutOfBoundsException("index = " + index + ", size = " + size);
this.shift(index, index + numElems, size);
// Add entries
for (int i = 0; i < numElems; i++) {
final byte[] key = this.buildKey(index);
final byte[] value = values.get(i);
final E elem = elems.get(i);
// Update list content and index
this.tx.kvt.put(key, value);
if (this.field.elementField.indexed)
this.field.addIndexEntry(this.tx, this.id, this.field.elementField, key, value);
// Notify field monitors
final int index2 = index;
this.tx.addFieldChangeNotification(new ListFieldChangeNotifier() {
@Override
void notify(Transaction tx, ListFieldChangeListener listener, int[] path, NavigableSet<ObjId> referrers) {
listener.onListFieldAdd(tx, this.getId(), JSList.this.field, path, referrers, index2, elem);
}
});
// Advance index
index++;
}
// Done
return numElems > 0;
}
@Override
public void clear() {
this.tx.mutateAndNotify(this.id, new Transaction.Mutation<Void>() {
@Override
public Void mutate() {
JSList.this.doClear();
return null;
}
});
}
private void doClear() {
// Check size
if (this.isEmpty())
return;
// Delete index entries
if (this.field.elementField.indexed)
this.field.removeIndexEntries(this.tx, this.id, this.field.elementField);
// Delete content
this.field.deleteContent(this.tx, this.id);
// Notify field monitors
this.tx.addFieldChangeNotification(new ListFieldChangeNotifier() {
@Override
void notify(Transaction tx, ListFieldChangeListener listener, int[] path, NavigableSet<ObjId> referrers) {
listener.onListFieldClear(tx, this.getId(), JSList.this.field, path, referrers);
}
});
}
@Override
public E remove(int index) {
final E elem = this.get(index);
this.removeRange(index, index + 1);
return elem;
}
@Override
protected void removeRange(final int min, final int max) {
this.tx.mutateAndNotify(this.id, new Transaction.Mutation<Void>() {
@Override
public Void mutate() {
JSList.this.doRemoveRange(min, max);
return null;
}
});
}
private void doRemoveRange(int min, int max) {
// Optimize for clear()
final int size = this.size();
if (min == 0 && max == size) {
this.doClear();
return;
}
// Check bounds
if (min < 0 || max < min || max > size)
throw new IndexOutOfBoundsException("min = " + min + ", max = " + max + ", size = " + size);
// Delete index entries
if (this.field.elementField.indexed)
this.deleteIndexEntries(min, max);
// Notify field monitors
for (int i = min; i < max; i++) {
final byte[] value = this.tx.kvt.get(this.buildKey(i));
if (value == null)
throw new InconsistentDatabaseException("list entry at index " + i + " not found");
final int i2 = i;
this.tx.addFieldChangeNotification(new ListFieldChangeNotifier() {
private boolean decoded;
private E elem;
@Override
void notify(Transaction tx, ListFieldChangeListener listener, int[] path, NavigableSet<ObjId> referrers) {
if (!this.decoded) {
this.elem = JSList.this.elementType.read(new ByteReader(value));
this.decoded = true;
}
listener.onListFieldRemove(tx, this.getId(), JSList.this.field, path, referrers, i2, elem);
}
});
}
// Shift
this.shift(max, min, size);
}
// Shift a contiguous range of list elements; values created or removed are not handled
private void shift(int from, int to, int size) {
// Bump modification counter (structural modification)
this.modCount++;
// Plan direction of copy operation to avoid overwrites
int len = size - from;
int src;
int dst;
int step;
if (to < from) {
src = from;
dst = to;
step = 1;
} else {
src = from + len - 1;
dst = to + len - 1;
step = -1;
len = size - from;
}
// Copy list elements; note we remove the old index entries but not the old list entries
while (len
// Read value at src
final byte[] srcKey = this.buildKey(src);
final byte[] value = this.tx.kvt.get(srcKey);
if (value == null)
throw new InconsistentDatabaseException("list entry at index " + src + " not found");
// Delete index entry for value at src
if (this.field.elementField.indexed)
this.field.removeIndexEntry(this.tx, this.id, this.field.elementField, srcKey, value);
// Write value to dst
final byte[] dstKey = this.buildKey(dst);
this.tx.kvt.put(dstKey, value);
// Add index entry for value at dst
if (this.field.elementField.indexed)
this.field.addIndexEntry(this.tx, this.id, this.field.elementField, dstKey, value);
// Advance
src += step;
dst += step;
}
// Delete the old list entries that did not get overwritten; only happens when deleting items
if (to < from) {
final int newSize = size - (from - to);
final byte[] minKey = this.buildKey(newSize);
final byte[] maxKey = ByteUtil.getKeyAfterPrefix(this.contentPrefix);
this.tx.kvt.removeRange(minKey, maxKey);
}
}
private void deleteIndexEntries(int min, int max) {
assert this.field.elementField.indexed;
for (int i = min; i < max; i++) {
final byte[] key = this.buildKey(i);
final byte[] value = this.tx.kvt.get(key);
if (value == null)
throw new InconsistentDatabaseException("list entry at index " + i + " not found");
this.field.removeIndexEntry(this.tx, this.id, this.field.elementField, key, value);
}
}
private byte[] buildKey(int index) {
if (index < 0)
throw new IndexOutOfBoundsException("index = " + index);
final ByteWriter writer = new ByteWriter();
writer.write(this.contentPrefix);
UnsignedIntEncoder.write(writer, index);
return writer.getBytes();
}
private byte[] buildValue(E elem) {
final ByteWriter writer = new ByteWriter();
try {
this.elementType.validateAndWrite(writer, elem);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("list containing " + this.elementType
+ " can't hold values of type " + (elem != null ? elem.getClass().getName() : "null"), e);
}
return writer.getBytes();
}
// Iter
private class Iter implements Iterator<E> {
private Iterator<KVPair> i;
private boolean finished;
private Integer removeIndex;
Iter() {
this.i = JSList.this.tx.kvt.getRange(JSList.this.contentPrefix,
ByteUtil.getKeyAfterPrefix(JSList.this.contentPrefix), false);
synchronized (this) { }
}
@Override
public synchronized boolean hasNext() {
if (this.finished)
return false;
if (!this.i.hasNext()) {
this.finished = true;
Database.closeIfPossible(this.i);
return false;
}
return true;
}
@Override
public synchronized E next() {
if (this.finished)
throw new NoSuchElementException();
final KVPair pair = this.i.next();
final ByteReader keyReader = new ByteReader(pair.getKey());
keyReader.skip(JSList.this.contentPrefix.length);
this.removeIndex = UnsignedIntEncoder.read(keyReader);
return JSList.this.elementType.read(new ByteReader(pair.getValue()));
}
@Override
public synchronized void remove() {
Preconditions.checkState(this.removeIndex != null);
JSList.this.removeRange(this.removeIndex, this.removeIndex + 1);
this.removeIndex = null;
}
}
// ListFieldChangeNotifier
private abstract class ListFieldChangeNotifier implements FieldChangeNotifier {
@Override
public int getStorageId() {
return JSList.this.field.storageId;
}
@Override
public ObjId getId() {
return JSList.this.id;
}
@Override
public void notify(Transaction tx, Object listener, int[] path, NavigableSet<ObjId> referrers) {
this.notify(tx, (ListFieldChangeListener)listener, path, referrers);
}
abstract void notify(Transaction tx, ListFieldChangeListener listener, int[] path, NavigableSet<ObjId> referrers);
}
}
|
/**
* HiveDB is an Open Source (LGPL) system for creating large, high-transaction-volume
* data storage systems.
*/
package org.hivedb.meta;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.NoSuchElementException;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hivedb.HiveDbDialect;
import org.hivedb.HiveException;
import org.hivedb.HiveReadOnlyException;
import org.hivedb.management.statistics.PartitionKeyStatisticsDao;
import org.hivedb.meta.persistence.HiveBasicDataSource;
import org.hivedb.meta.persistence.HiveSemaphoreDao;
import org.hivedb.meta.persistence.NodeDao;
import org.hivedb.meta.persistence.PartitionDimensionDao;
import org.hivedb.meta.persistence.ResourceDao;
import org.hivedb.meta.persistence.SecondaryIndexDao;
import org.hivedb.util.DriverLoader;
import org.hivedb.util.HiveUtils;
import org.hivedb.util.InstallHiveGlobalSchema;
/**
* @author Kevin Kelm (kkelm@fortress-consulting.com)
* @author Andy Likuski (alikuski@cafepress.com)
*/
public class Hive {
public static final int NEW_OBJECT_ID = 0;
public static String URI_SYSTEM_PROPERTY="org.hivedb.uri";
private String hiveUri;
private int revision;
private boolean readOnly;
private Collection<PartitionDimension> partitionDimensions;
private PartitionKeyStatisticsDao statistics;
private Collection<Directory> directories;
private HiveSyncDaemon daemon;
private DataSource dataSource;
/**
* System entry point. Factory method for all Hive interaction. If the first attempt
* to load the Hive throws any exception, the Hive class will attempt to install the database
* schema at the target URI, and then attempt to reload that schema one time before throwing
* a HiveException.
*
* @param hiveDatabaseUri Target hive
* @return Hive (existing or new) located at hiveDatabaseUri
* @throws HiveException
*/
public static Hive load(String hiveDatabaseUri) throws HiveException
{
try {
DriverLoader.loadByDialect(DriverLoader.discernDialect(hiveDatabaseUri));
} catch (ClassNotFoundException e) {
throw new HiveException("Unable to load database driver: " + e.getMessage(), e);
}
Hive hive = null;
try {
PartitionKeyStatisticsDao tracker = new PartitionKeyStatisticsDao( new HiveBasicDataSource(hiveDatabaseUri));
hive = new Hive(hiveDatabaseUri, 0, false, new ArrayList<PartitionDimension>(), tracker);
} catch (Exception ex) {
try {
InstallHiveGlobalSchema.install(hiveDatabaseUri);
PartitionKeyStatisticsDao tracker = new PartitionKeyStatisticsDao( new HiveBasicDataSource(hiveDatabaseUri));
hive = new Hive(hiveDatabaseUri, 0, false, new ArrayList<PartitionDimension>(), tracker);
} catch (Exception ex2) {
throw new HiveException("Unable to find or install Hive at URI " + hiveDatabaseUri + ": " + ex2.getMessage(),ex2);
}
}
return hive;
}
public void create() throws HiveException, SQLException {
for (PartitionDimension partitionDimension : this.getPartitionDimensions())
new IndexSchema(partitionDimension).install();
}
/**
* Explicitly syncs the hive with the persisted data, rather than waiting for the periodic sync.
*
*/
public void sync() {
daemon.forceSynchronize();
}
/**
* INTERNAL USE ONLY- load the Hive from persistence
* @param revision
* @param readOnly
*/
protected Hive(String hiveUri, int revision, boolean readOnly, Collection<PartitionDimension> partitionDimensions, PartitionKeyStatisticsDao statistics) {
this.hiveUri = hiveUri;
this.revision = revision;
this.readOnly = readOnly;
this.partitionDimensions = partitionDimensions;
this.statistics = statistics;
this.daemon = new HiveSyncDaemon(this);
this.dataSource = new HiveBasicDataSource(this.getHiveUri());
this.directories = new ArrayList<Directory>();
for(PartitionDimension dimension : this.partitionDimensions)
this.directories.add(new Directory(dimension, this.dataSource));
}
/**
*
* @return the URI of the hive database where all meta data is stored for this hive.
*/
public String getHiveUri() {
return hiveUri;
}
/**
* Hives are uniquely hashed by their URI, revision, and read-only state.
*/
public int hashCode() {
return HiveUtils.makeHashCode(new Object[] {
hiveUri, revision, readOnly
});
}
/**
* Indicates whether or not the hive metatables and indexes may be updated.
* @return Returns true if the hive is in a read-only state.
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* INTERNAL USE ONLY - use updateHiveReadOnly to persist the hive's read only status
* Make the hive hive read-only, meaning hive metatables and indexes may not
* be updated.
* @param readOnly
*/
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public void updateHiveReadOnly(Boolean readOnly) throws HiveException {
this.setReadOnly(readOnly);
try
{
daemon.setReadOnly(isReadOnly());
}
catch (SQLException e) {
throw new HiveException("Could not change the readonly status of the hive", e);
}
}
/**
* Get the current revision of the hive. The revision number is increased when
* new indexes are added to the hive or if the schema of an index is altered.
*
* @return The current revision number of the hive.
*/
public int getRevision() {
return revision;
}
/**
* INTERNAL USE ONLY - sets the current hive revision.
* @param revision
*/
public void setRevision(int revision) {
this.revision = revision;
}
/**
* Gets all partition dimensions of the hive. A PartitionDimension instance
* references all of its underlying components--its NodeGroup and Resources.
* @return
*/
public Collection<PartitionDimension> getPartitionDimensions() {
return partitionDimensions;
}
/**
* Gets a partition dimension by name.
* @param name The user-defined name of a partition dimension
* @return
* @throws HiveException Thrown if no parition dimension with the given name exists.
*/
public PartitionDimension getPartitionDimension(String name) throws HiveException {
for (PartitionDimension partitionDimension : getPartitionDimensions())
if (partitionDimension.getName().equals(name))
return partitionDimension;
throw new HiveException("PartitionDimension with name " + name + " not found.");
}
/**
* Adds a new partition dimension to the hive. The partition dimension persists
* to the database along with its NodeGroup, Nodes, Resources, and SecondaryIndexes.
* NodeGroup must be defined but the collections of Nodes, Resources, and SecondaryIndexes
* may be filled or empty, and modified later. If the partition dimension has a null indexUri
* it will be set to the URI of the hive.
* @param partitionDimension
* @return The PartitionDimension with its Id set and those of all sub objects.
* @throws HiveException Throws if there is any problem persisting the data, if the hive
* is currently read-only, or if a partition dimension of the same name already exists
*/
public PartitionDimension addPartitionDimension(PartitionDimension partitionDimension) throws HiveException
{
isWritable("Creating a new partition dimension");
isUnique(String.format("Partition dimension %s already exists", partitionDimension.getName()),
getPartitionDimensions(),
partitionDimension);
BasicDataSource datasource = new HiveBasicDataSource(getHiveUri());
PartitionDimensionDao partitionDimensionDao = new PartitionDimensionDao(datasource);
try {
partitionDimensionDao.create(partitionDimension);
} catch (SQLException e) {
throw new HiveException("Problem persisting new Partition Dimension: " + e.getMessage());
}
incrementAndPersistHive(datasource);
if (partitionDimension.getIndexUri() == null)
partitionDimension.setIndexUri(this.hiveUri);
this.directories.add(new Directory(partitionDimension, this.dataSource));
sync();
return partitionDimension;
}
/**
* Adds a node to the given partition dimension.
* @param partitionDimension A persisted partition dimension of the hive to which to add the node
* @param node A node instance initialized without an id and without a set partition dimension
* @return The node with it's id set.
* @throws HiveException Throws if there is any problem persisting the data, or if the hive
* is currently read-only.
*/
public Node addNode(PartitionDimension partitionDimension, Node node) throws HiveException
{
node.setNodeGroup(partitionDimension.getNodeGroup());
isWritable("Creating a new node");
BasicDataSource datasource = new HiveBasicDataSource(this.getHiveUri());
NodeDao nodeDao = new NodeDao(datasource);
try {
nodeDao.create(node);
} catch (SQLException e) {
throw new HiveException("Problem persisting new Node: " + e.getMessage());
}
incrementAndPersistHive(datasource);
sync();
return node;
}
/**
*
* Adds a new resource to the given partition dimension, along with any secondary indexes defined in the resource instance
* @param partitionDimension A persisted partition dimensiono of the hive to which to add the resource.
* @param resource A resource instance initialized without an id and with a full or empty collection of secondary indexes.
* @return The resource instance with its id set along with those of any secondary indexes
* @throws HiveException Throws if there is any problem persisting the data, if the hive
* is currently read-only, or if a resource of the same name already exists
*/
public Resource addResource(PartitionDimension partitionDimension, Resource resource) throws HiveException
{
resource.setPartitionDimension(partitionDimension);
isWritable("Creating a new resource");
isUnique(String.format("Resource %s already exists in the partition dimension %s", resource.getName(), partitionDimension.getName()),
partitionDimension.getResources(),
resource);
BasicDataSource datasource = new HiveBasicDataSource(this.getHiveUri());
ResourceDao resourceDao = new ResourceDao(datasource);
try {
resourceDao.create(resource);
} catch (SQLException e) {
throw new HiveException("Problem persisting new Node: " + e.getMessage());
}
incrementAndPersistHive(datasource);
partitionDimension.getResources().add(resource);
getPartitionDimensions().add(partitionDimension);
sync();
return resource;
}
/**
*
* Adds a partition index to the given resource.
*
* @param resource A persited resource of a partition dimension of the hive to which to add the secondary index
* @param secondaryIndex A secondary index initialized without an id
* @return The SecondaryIndex instance with its id intialized
* @throws HiveException Throws if there is a problem persisting the data, the hive is read-only, or if a secondary
* index with the same columnInfo() name already exists in the resource.
*/
public SecondaryIndex addSecondaryIndex(Resource resource, SecondaryIndex secondaryIndex) throws HiveException
{
secondaryIndex.setResource(resource);
isWritable("Creating a new secondary index");
isUnique(String.format("Secondary index %s already exists in the resource %s", secondaryIndex.getName(), resource.getName()),
resource.getSecondaryIndexes(),
secondaryIndex);
BasicDataSource datasource = new HiveBasicDataSource(this.getHiveUri());
SecondaryIndexDao secondaryIndexDao = new SecondaryIndexDao(datasource);
try {
secondaryIndexDao.create(secondaryIndex);
} catch (SQLException e) {
throw new HiveException("Problem persisting new Node: " + e.getMessage());
}
incrementAndPersistHive(datasource);
sync();
try {
create();
} catch (SQLException e) {
throw new HiveException("Problem persisting new Node: " + e.getMessage());
}
return secondaryIndex;
}
/**
* Updates values of a partition dimension in the hive. No updates or adds to the underlying nodes, resources, or
* secondary indexes will persist. You must add or update these objects explicitly before calling this method.
* Any data of the partition dimension may be updated except its id.
* If new nodes, resources, or secondary indexes have been added to the partition dimension instance
* they will be persisted and assigned ids
* @param partitionDimension A partitionDimension persisted in the hive
* @return The partitionDimension passed in.
* @throws HiveException Throws if there is any problem persisting the updates, if the hive
* is currently read-only, or if a partition dimension of the same name already exists
*/
public PartitionDimension updatePartitionDimension(PartitionDimension partitionDimension) throws HiveException
{
isWritable("Updating partition dimension");
isIdPresentInCollection(String.format("Partition dimension with id %s does not exist", partitionDimension.getId()),
getPartitionDimensions(),
partitionDimension);
isUnique(String.format("Partition dimension with name %s already exists", partitionDimension.getName()),
getPartitionDimensions(),
partitionDimension);
BasicDataSource datasource = new HiveBasicDataSource(getHiveUri());
PartitionDimensionDao partitionDimensionDao = new PartitionDimensionDao(datasource);
try {
partitionDimensionDao.update(partitionDimension);
} catch (SQLException e) {
throw new HiveException("Problem updating the partition dimension", e);
}
incrementAndPersistHive(datasource);
sync();
return partitionDimension;
}
/**
* Updates the values of a node.
* @param node A node instance initialized without an id and without a set partition dimension
* @return The node with it's id set.
* @throws HiveException Throws if there is any problem persisting the data, or if the hive
* is currently read-only.
*/
public Node updateNode(Node node) throws HiveException
{
isWritable("Updating node");
isIdPresentInCollection(String.format("Node with id %s does not exist", node.getUri()),
node.getNodeGroup().getNodes(),
node);
BasicDataSource datasource = new HiveBasicDataSource(this.getHiveUri());
NodeDao nodeDao = new NodeDao(datasource);
try {
nodeDao.update(node);
} catch (SQLException e) {
throw new HiveException("Problem updating node: " + e.getMessage());
}
incrementAndPersistHive(datasource);
sync();
return node;
}
/**
*
* Updates resource. No secondary index data is created or updated. You should explicitly create or update any modified secondary index
* data in the resource before calling this method.
* @param resource A resource belonging to a partition dimension of the hive
* @return The resource instance passed in
* @throws HiveException Throws if there is any problem persisting the data, if the hive
* is currently read-only, or if a resource of the same name already exists
*/
public Resource updateResource(Resource resource) throws HiveException
{
isWritable("Updating resource");
isIdPresentInCollection(String.format("Resource with id %s does not exist", resource.getId()),
resource.getPartitionDimension().getResources(),
resource);
isUnique(String.format("Resource with name %s already exists", resource.getName()),
resource.getPartitionDimension().getResources(),
resource);
BasicDataSource datasource = new HiveBasicDataSource(this.getHiveUri());
ResourceDao resourceDao = new ResourceDao(datasource);
try {
resourceDao.update(resource);
} catch (SQLException e) {
throw new HiveException("Problem persisting resource: " + e.getMessage());
}
incrementAndPersistHive(datasource);
sync();
return resource;
}
/**
*
* Adds a partition index to the given resource.
*
* @param resource A persited resource of a partition dimension of the hive to which to add the secondary index
* @param secondaryIndex A secondary index initialized without an id
* @return The SecondaryIndex instance with its id intialized
* @throws HiveException Throws if there is a problem persisting the data, the hive is read-only, or if a secondary
* index with the same columnInfo() name already exists in the resource.
*/
public SecondaryIndex updateSecondaryIndex(SecondaryIndex secondaryIndex) throws HiveException
{
isWritable("Updating secondary index");
isIdPresentInCollection(String.format("Secondary index with id %s does not exist", secondaryIndex.getId()),
secondaryIndex.getResource().getSecondaryIndexes(),
secondaryIndex);
isUnique(String.format("Secondary index with name %s already exists", secondaryIndex.getName()),
secondaryIndex.getResource().getSecondaryIndexes(),
secondaryIndex);
SecondaryIndexDao secondaryIndexDao = new SecondaryIndexDao(dataSource);
try {
secondaryIndexDao.update(secondaryIndex);
} catch (SQLException e) {
throw new HiveException("Problem persisting secondary index: " + e.getMessage());
}
incrementAndPersistHive(dataSource);
sync();
return secondaryIndex;
}
public PartitionDimension deletePartitionDimension(PartitionDimension partitionDimension) throws HiveException
{
isWritable(String.format("Deleting partition dimension %s", partitionDimension.getName()));
existenceCheck(String.format("Partition dimension %s does not match any partition dimension in the hive", partitionDimension.getName()),
getPartitionDimensions(),
partitionDimension);
throw new RuntimeException("Delete is not yet implemented");
}
public Node deleteNode(Node node) throws HiveException
{
isWritable(String.format("Deleting node %s", node.getUri()));
existenceCheck(String.format("Node %s does not match any node in the partition dimenesion %s", node.getUri(), node.getNodeGroup().getPartitionDimension().getName()),
node.getNodeGroup().getPartitionDimension().getNodeGroup().getNodes(),
node);
throw new RuntimeException("Delete is not yet implemented");
}
public SecondaryIndex deleteSecondaryIndex(SecondaryIndex secondaryIndex) throws HiveException
{
isWritable(String.format("Deleting secondary index %s", secondaryIndex.getName()));
existenceCheck(String.format("Secondary index %s does not match any node in the resource %s", secondaryIndex.getName(), secondaryIndex.getResource()),
secondaryIndex.getResource().getSecondaryIndexes(),
secondaryIndex);
throw new RuntimeException("Delete is not yet implemented");
}
private void incrementAndPersistHive(DataSource datasource) throws HiveException {
try {
new HiveSemaphoreDao(datasource).incrementAndPersist();
} catch (SQLException e) {
throw new HiveException("Problem incrementing Hive revision: " + e.getMessage());
}
}
/**
* Inserts a new primary index key into the given partition dimension. A partition dimension
* by definition defines one primary index. The given primaryIndexKey must match the column
* type defined in partitionDimenion.getColumnInfo().getColumnType(). The node used for the
* new primary index key is determined by the hive's
* @param partitionDimension - an existing partition dimension of the hive.
* @param primaryIndexKey - a primary index key not yet in the primary index.
* @throws HiveException Throws if the partition dimension is not in the hive, or if
* the hive, primary index or node is currently read only.
* @throws SQLException Throws if the primary index key already exists, or another persitence error occurs.
*/
public void insertPrimaryIndexKey(PartitionDimension partitionDimension, Object primaryIndexKey) throws HiveException, SQLException {
// TODO Consider redesign of NodeGroup to perform assignment, or at least provider direct iteration over Nodes
Node node = partitionDimension.getAssigner().chooseNode(partitionDimension.getNodeGroup().getNodes(),primaryIndexKey);
isWritable("Inserting a new primary index key", node);
getDirectory(partitionDimension).insertPrimaryIndexKey(node, primaryIndexKey);
sync();
}
/**
* Inserts a new primary index key into the given partition dimension. A partition dimension
* by definition defines one primary index. The given primaryIndexKey must match the column
* type defined in partitionDimenion.getColumnType().
* @param partitionDimensionName - the name of an existing partition dimension of the hive.
* @param primaryIndexKey - a primary index key not yet in the primary index.
* @throws HiveException Throws if the partition dimension is not in the hive, or if
* the hive, primary index or node is currently read only.
* @throws SQLException Throws if the primary index key already exists, or another persitence error occurs.
*/
public void insertPrimaryIndexKey(String partitionDimensionName, Object primaryIndexKey) throws HiveException, SQLException {
insertPrimaryIndexKey(getPartitionDimension(partitionDimensionName), primaryIndexKey);
}
/**
* Inserts a new secondary index key and the primary index key which it references into the given secondary index.
*
* @param secondaryIndex A secondary index which belongs to the hive via a resource and partition dimension
* @param secondaryIndexKey A secondary index key value whose type must match that defined by secondaryIndex.getColumnInfo().getColumnType()
* @param primaryindexKey A primary index key that already exists in the primary index of the partition dimension of this secondary index.
* @throws HiveException Throws if the secondary index does not exist in the hive via a resource and partition dimension, or if
* the hive is currently read-only
* @throws SQLException Throws if the secondary index key already exists in this secondary index, or for any other persistence error.
*/
public void insertSecondaryIndexKey(SecondaryIndex secondaryIndex, Object secondaryIndexKey, Object primaryindexKey) throws HiveException, SQLException {
isWritable("Inserting a new secondary index key");
getDirectory(secondaryIndex.getResource().getPartitionDimension()).insertSecondaryIndexKey(secondaryIndex, secondaryIndexKey, primaryindexKey);
statistics.incrementChildRecordCount(
secondaryIndex.getResource().getPartitionDimension(),
primaryindexKey,
1);
sync();
}
/**
*
* Inserts a new secondary index key and the primary index key which it references into the secondary index identified
* by the give secondaryIndexName, resourceName, and partitionDimensionName
* @param partitionDimensionName - the name of a partition dimension in the hive
* @param resourceName - the name of a resource in the partition dimension
* @param secondaryIndexName - the name of a secondary index in the resource
* @param secondaryIndexKey A secondary index key value whose type must match that defined by secondaryIndex.getColumnInfo().getColumnType()
* @param primaryindexKey A primary index key that already exists in the primary index of the partition dimension of this secondary index.
* @throws HiveException Throws if the primary index key is not yet in the primary index, or if
* the hive, primary index or node is currently read only.
* @throws SQLException Throws if the secondary index key already exists in this secondary index, or for any other persistence error.
*/
public void insertSecondaryIndexKey(String partitionDimensionName, String resourceName, String secondaryIndexName, Object secondaryIndexKey, Object primaryIndexKey) throws HiveException, SQLException {
insertSecondaryIndexKey(getPartitionDimension(partitionDimensionName).getResource(resourceName).getSecondaryIndex(secondaryIndexName),
secondaryIndexKey,
primaryIndexKey);
}
/**
*
* Updates the node of the given primary index key for the given partition dimension.
* @param partitionDimension A partition dimension of the hive
* @param primaryIndexKey An existing primary index key in the primary index
* @param node A node of the node group of the partition dimension
* @throws HiveException Throws if the primary index key is not yet in the primary index, or if
* the hive, primary index or node is currently read only.
* @throws SQLException Throws if there is a persistence error
*/
public void updatePrimaryIndexNode(PartitionDimension partitionDimension, Object primaryIndexKey, Node node) throws HiveException, SQLException
{
isWritable("Updating primary index node",
getNodeOfPrimaryIndexKey(partitionDimension, primaryIndexKey),
primaryIndexKey,
getReadOnlyOfPrimaryIndexKey(partitionDimension, primaryIndexKey));
getDirectory(partitionDimension).updatePrimaryIndexKey(node, primaryIndexKey);
sync();
}
/**
*
* Updates the node of the given primary index key for the given partition dimension.
* @param partitionDimensionName The name of a partition demension in the hive
* @param primaryIndexKey An existing primary index key in the primary index
* @param nodeUri A uri of a node of the node group of the partition dimension
* @throws HiveException Throws if the primary index key is not yet in the primary index, or if
* the hive, primary index or node is currently read only.
* @throws SQLException Throws if there is a persistence error
*/
public void updatePrimaryIndexNode(String partitionDimensionName, Object primaryIndexKey, String nodeUri) throws HiveException, SQLException
{
PartitionDimension partitionDimension = getPartitionDimension(partitionDimensionName);
updatePrimaryIndexNode(partitionDimension, primaryIndexKey, partitionDimension.getNodeGroup().getNode(nodeUri));
}
/**
*
* Updates the read-only status of the given primary index key for the given partition dimension.
* @param partitionDimension A partition dimension of the hive
* @param primaryIndexKey An existing primary index key in the primary index
* @param isReadOnly True makes the primary index key rean-only, false makes it writable
* @throws HiveException Throws if the primary index key is not yet in the primary index, or if
* the hive is currently read only.
* @throws SQLException Throws if there is a persistence error
*/
public void updatePrimaryIndexReadOnly(PartitionDimension partitionDimension, Object primaryIndexKey, boolean isReadOnly) throws HiveException, SQLException
{
isWritable("Updating primary index read-only");
// This query validates the existence of the primaryIndexKey
getNodeOfPrimaryIndexKey(partitionDimension, primaryIndexKey);
getDirectory(partitionDimension).updatePrimaryIndexKeyReadOnly(primaryIndexKey, isReadOnly);
sync();
}
/**
*
* Updates the read-only status of the given primary index key for the given partition dimension.
* @param partitionDimensionName The name of a partition dimension of the hive
* @param primaryIndexKey An existing primary index key in the primary index
* @param isReadOnly True makes the primary index key rean-only, false makes it writable
* @throws HiveException Throws if the primary index key is not yet in the primary index, or if
* the hive is currently read only.
* @throws SQLException Throws if there is a persistence error
*/
public void updatePrimaryIndexReadOnly(String partitionDimensionName, Object primaryIndexKey, boolean isReadOnly) throws HiveException, SQLException
{
PartitionDimension partitionDimension = getPartitionDimension(partitionDimensionName);
updatePrimaryIndexReadOnly(partitionDimension, primaryIndexKey, isReadOnly);
}
/**
*
* Updates the primary index key of the given secondary index key.
* @param secondaryIndex A secondary index that belongs to the hive via a resource and partition dimension
* @param secondaryIndexKey A secondary index key of the given secondary index
* @param primaryIndexKey The primary index key to assign to the secondary index key
* @throws HiveException Throws if the secondary index key is not yet in the secondary index, or if
* the hive is currently read only.
* @throws SQLException Throws if there is a persistence error
*/
public void updatePrimaryIndexKeyOfSecondaryIndexKey(SecondaryIndex secondaryIndex, Object secondaryIndexKey, Object primaryIndexKey) throws HiveException, SQLException {
isWritable("Updating primary index key of secondary index key");
getPrimaryIndexKeyOfSecondaryIndexKey(secondaryIndex, secondaryIndexKey);
getDirectory(secondaryIndex.getResource().getPartitionDimension()).updatePrimaryIndexOfSecondaryKey(secondaryIndex, secondaryIndexKey, primaryIndexKey);
sync();
}
/**
*
* @param partitionDimensionName The name of a partition dimension in this hive
* @param resourceName The name of a resource in the given partition dimension
* @param secondaryIndexName The name of a secondary index of the given resource
* @param secondaryIndexKey A secondary index key of the given secondary index
* @param primaryIndexKey The primary index key to assign to the secondary index key
* @throws HiveException Throws if the secondary index key is not yet in the secondary index, or if
* the hive is currently read only.
* @throws SQLException Throws if there is a persistence error
*/
public void updatePrimaryIndexKeyOfSecondaryIndexKey(String partitionDimensionName, String resourceName, String secondaryIndexName, Object secondaryIndexKey, Object primaryIndexKey) throws HiveException, SQLException {
updatePrimaryIndexKeyOfSecondaryIndexKey(getPartitionDimension(partitionDimensionName).getResource(resourceName).getSecondaryIndex(secondaryIndexName),
secondaryIndexKey,
primaryIndexKey);
}
/**
* Deletes the primary index key of the given partition dimension
* @param partitionDimension A partition dimension in the hive
* @param primaryIndexKey An existing primary index key of the partition dimension
* @throws HiveException Throws if the primary index key does not exist or if the hive,
* node of the primary index key, or primary index key itself is currently read-only
* @throws SQLException Throws if there is a persistence error
*/
public void deletePrimaryIndexKey(PartitionDimension partitionDimension, Object primaryIndexKey) throws HiveException, SQLException {
if (!doesPrimaryIndexKeyExist(partitionDimension, primaryIndexKey))
throw new HiveException("The primary index key " + primaryIndexKey + " does not exist");
isWritable("Deleting primary index key",
getNodeOfPrimaryIndexKey(partitionDimension, primaryIndexKey),
primaryIndexKey,
getReadOnlyOfPrimaryIndexKey(partitionDimension, primaryIndexKey));
for (Resource resource: partitionDimension.getResources())
for (SecondaryIndex secondaryIndex: resource.getSecondaryIndexes()) {
getDirectory(partitionDimension).deleteAllSecondaryIndexKeysOfPrimaryIndexKey(secondaryIndex, primaryIndexKey);
}
getDirectory(partitionDimension).deletePrimaryIndexKey(primaryIndexKey);
sync();
}
/**
* Deletes a primary index key of the given partition dimension
* @param partitionDimensionName The name of a partition dimension in the hive
* @param primaryIndexKey An existing primary index key of the partition dimension
* @throws HiveException Throws if the primary index key does not exist or if the hive,
* node of the primary index key, or primary index key itself is currently read-only
* @throws SQLException Throws if there is a persistence error
*/
public void deletePrimaryIndexKey(String partitionDimensionName, Object secondaryIndexKey) throws HiveException, SQLException {
deletePrimaryIndexKey(getPartitionDimension(partitionDimensionName),
secondaryIndexKey);
}
/**
* Deletes a secondary index key of the give secondary index
* @param secondaryIndex A secondary index that belongs to the hive via its resource and partition dimension
* @param secondaryIndexKey An existing secondary index key
* @throws HiveException Throws if the secondary index key does not exist or if the hive is currently read-only
* @throws SQLException Throws if there is a persistence error
*/
public void deleteSecondaryIndexKey(SecondaryIndex secondaryIndex, Object secondaryIndexKey) throws HiveException, SQLException {
Object primaryIndexKey = getPrimaryIndexKeyOfSecondaryIndexKey(secondaryIndex, secondaryIndexKey);
isWritable("Deleting secondary index key");
if (!doesSecondaryIndexKeyExist(secondaryIndex, secondaryIndexKey))
throw new HiveException("Secondary index key " + secondaryIndexKey.toString() + " does not exist");
getDirectory(secondaryIndex.getResource().getPartitionDimension()).deleteSecondaryIndexKey(secondaryIndex, secondaryIndexKey);
statistics.decrementChildRecordCount(
secondaryIndex.getResource().getPartitionDimension(),
primaryIndexKey,
1);
sync();
}
/**
* Deletes a secondary index key of the give secondary index
* @param partitionDimensionName The name of a partition dimension in the hive
* @param resourceName The name of a resource in the partition dimension
* @param secondaryIndexName The name of a secondary index of the resource
* @param secondaryIndex A secondary index that belongs to the hive via its resource and partition dimension
* @param secondaryIndexKey An existing secondary index key
* @throws HiveException Throws if the secondary index key does not exist or if the hive is currently read-only
* @throws SQLException Throws if there is a persistence error
*/
public void deleteSecondaryIndexKey(String partitionDimensionName, String resourceName, String secondaryIndexName, Object secondaryIndexKey) throws HiveException, SQLException {
deleteSecondaryIndexKey(getPartitionDimension(partitionDimensionName).getResource(resourceName).getSecondaryIndex(secondaryIndexName),
secondaryIndexKey);
}
/**
* Returns true if the primary index key exists in the given partition dimension
* @param partitionDimension A partition dimension in the hive
* @param primaryIndexKey The key to test
* @return
* @throws HiveException Throws if the partition dimension is not in the hive
* @throws SQLException Throws if there is a persistence error
*/
public boolean doesPrimaryIndexKeyExist(PartitionDimension partitionDimension, Object primaryIndexKey) throws HiveException, SQLException {
return getDirectory(partitionDimension).doesPrimaryIndexKeyExist(primaryIndexKey);
}
/**
* Returns true if the primary index key exists in the given partition dimension
* @param partitionDimensionName The name of a partition dimension in the hive
* @param primaryIndexKey The key to test
* @return
* @throws HiveException Throws if the partition dimension is not in the hive
* @throws SQLException Throws if there is a persistence error
*/
public boolean doesPrimaryIndeyKeyExist(String partitionDimensionName, Object primaryIndexKey) throws HiveException, SQLException {
return doesPrimaryIndexKeyExist(getPartitionDimension(partitionDimensionName), primaryIndexKey);
}
/**
* Returns the node assigned to the given primary index key
* @param partitionDimension A partition dimension in the hive
* @param primaryIndexKey A primary index key belonging to the partition dimension
* @return
* @throws HiveException Throws if the primary index key does not exist
* @throws SQLException Throws if there is a persistence error
*/
public Node getNodeOfPrimaryIndexKey(PartitionDimension partitionDimension, Object primaryIndexKey) throws HiveException, SQLException {
try {
return partitionDimension.getNodeGroup().getNode(getDirectory(partitionDimension).getNodeIdOfPrimaryIndexKey(primaryIndexKey));
}
catch (Exception e) {
throw new HiveException(String.format("Primary index key %s of partition dimension %s not found.", primaryIndexKey.toString(), partitionDimension.getName()), e);
}
}
/**
* Returns the node assigned to the given primary index key
* @param partitionDimensionName The name of a partition dimension in the hive
* @param primaryIndexKey A primary index key belonging to the partition dimension
* @return
* @throws HiveException Throws if the partition dimension or primary index key does not exist
* @throws SQLException Throws if there is a persistence error
*/
public Node getNodeOfPrimaryIndexKey(String partitionDimensionName, Object primaryIndexKey) throws HiveException, SQLException {
return getNodeOfPrimaryIndexKey(getPartitionDimension(partitionDimensionName), primaryIndexKey);
}
/**
* Returns true is the given primary index key is read-only
* @param partitionDimension A partition dimension in the hive
* @param primaryIndexKey An existing primary index key of the partition dimension
* @return
* @throws HiveException Throws if the primary index key does not exist
* @throws SQLException Throws if there is a persistence error
*/
public boolean getReadOnlyOfPrimaryIndexKey(PartitionDimension partitionDimension, Object primaryIndexKey) throws HiveException, SQLException {
Boolean readOnly = getDirectory(partitionDimension).getReadOnlyOfPrimaryIndexKey(primaryIndexKey);
if (readOnly != null)
return readOnly;
throw new HiveException(String.format("Primary index key %s of partition dimension %s not found.", primaryIndexKey.toString(), partitionDimension.getName()));
}
/**
* Returns true is the given primary index key is read-only
* @param partitionDimensionName The name of a partition dimension in the hive
* @param primaryIndexKey An existing primary index key of the partition dimension
* @return
* @throws HiveException Throws if the primary index key does not exist
* @throws SQLException Throws if there is a persistence error
*/
public boolean getReadOnlyOfPrimaryIndexKey(String partitionDimensionName, Object primaryIndexKey) throws HiveException, SQLException {
return getReadOnlyOfPrimaryIndexKey(getPartitionDimension(partitionDimensionName), primaryIndexKey);
}
/**
* Tests the existence of a give secondary index key
* @param secondaryIndex A secondary index that belongs to the hive via its resource and partition index
* @param secondaryIndexKey The key to test
* @return True if the secondary index key exists
* @throws SQLException Throws an exception if there is a persistence error
*/
public boolean doesSecondaryIndexKeyExist(SecondaryIndex secondaryIndex, Object secondaryIndexKey) throws SQLException {
return getDirectory(secondaryIndex.getResource().getPartitionDimension()).doesSecondaryIndexKeyExist(secondaryIndex, secondaryIndexKey);
}
/**
*
* Tests the existence of a give secondary index key
* @param partitionDimensionName The name of a partition dimension in the hive
* @param resourceName The name of a resource in the partition dimesnion
* @param secondaryIndexName The name of a secondary index of the resource
* @param secondaryIndexKey The key of the secondary index to test
* @return True if the key exists in the secondary index
* @throws HiveException Throws if the partition dimension, resource, or secondary index does not exist
* @throws SQLException Throws if there is a persistence error
*/
public boolean doesSecondaryIndexKeyExist(String partitionDimensionName, String resourceName, String secondaryIndexName, Object secondaryIndexKey) throws HiveException, SQLException {
return doesSecondaryIndexKeyExist(getPartitionDimension(partitionDimensionName).getResource(resourceName).getSecondaryIndex(secondaryIndexName), secondaryIndexKey);
}
/**
*
* Returns the node of the given secondary index key, based on the node of the corresponding primary index key
* @param secondaryIndex A secondary index that belongs to the hive via its resource and partition dimension
* @param secondaryIndexKey The secondary index key on which to query
* @return
* @throws HiveException Throws if the secondary index key does not exist
* @throws SQLException Throws if there is a persistence error
*/
public Node getNodeOfSecondaryIndexKey(SecondaryIndex secondaryIndex, Object secondaryIndexKey) throws HiveException, SQLException {
PartitionDimension partitionDimension = secondaryIndex.getResource().getPartitionDimension();
try {
return partitionDimension.getNodeGroup().getNode(
getDirectory(partitionDimension).getNodeIdOfSecondaryIndexKey(secondaryIndex, secondaryIndexKey));
}
catch (Exception e) {
throw new HiveException(String.format("Secondary index key %s of partition dimension %s on secondary index %s not found.", secondaryIndex.toString(), partitionDimension.getName(), secondaryIndex.getName()), e);
}
}
/**
*
* Returns the node of the given secondary index key, based on the node of the corresponding primary index key
* @param partitionDimensionName The name of a partition dimension in the hive
* @param resourceName The name of a resource in the partition dimesnion
* @param secondaryIndexName The name of a secondary index of the resource
* @param secondaryIndexKey The key of the secondary index to test
* @return
* @throws HiveException Throws if the partition dimension, resource, or secondary index does not exist
* @throws SQLException Throws if there is a persistence error
*/
public Node getNodeOfSecondaryIndexKey(String partitionDimensionName, String resourceName, String secondaryIndexName, Object secondaryIndexKey) throws HiveException, SQLException {
return getNodeOfSecondaryIndexKey(
getPartitionDimension(partitionDimensionName).getResource(resourceName).getSecondaryIndex(secondaryIndexName),
secondaryIndexKey);
}
/**
* Returns the primary index key of the given secondary index key
* @param secondaryIndex A secondary index that belongs to the hive via its resource and partition dimension
* @param secondaryIndexKey The secondary in
* @return
* @throws HiveException
* @throws SQLException
*/
public Object getPrimaryIndexKeyOfSecondaryIndexKey(SecondaryIndex secondaryIndex, Object secondaryIndexKey) throws HiveException, SQLException {
PartitionDimension partitionDimension = secondaryIndex.getResource().getPartitionDimension();
Object primaryIndexKey = getDirectory(partitionDimension).getPrimaryIndexKeyOfSecondaryIndexKey(secondaryIndex, secondaryIndexKey);
if (primaryIndexKey != null)
return primaryIndexKey;
throw new HiveException(String.format("Secondary index key %s of partition dimension %s on secondary index %s not found.", secondaryIndex.toString(), partitionDimension.getName(), secondaryIndex.getName()));
}
/**
* Returns the primary index key of the given secondary index key
* @param partitionDimensionName A partition dimension of the hive
* @param resourceName A resource of the partition dimension
* @param secondaryIndexName A secondary index of the resource
* @param secondaryIndexKey The secondary index to query for
* @return
* @throws HiveException Throws if the partition dimension, resource, or secondary index do not exist
* @throws SQLException Throws if there is a persistence error
*/
public Object getPrimaryIndexKeyOfSecondaryIndexKey(String partitionDimensionName, String resourceName, String secondaryIndexName, Object secondaryIndexKey) throws HiveException, SQLException {
return getPrimaryIndexKeyOfSecondaryIndexKey(
getPartitionDimension(partitionDimensionName).getResource(resourceName).getSecondaryIndex(secondaryIndexName),
secondaryIndexKey);
}
/**
* Returns all secondary index keys pertaining to the given primary index key. The primary index key
* may or may not exist in the primary index and there may be zero or more keys returned.
* @param secondaryIndex the secondary index to query
* @param primaryIndexKey the primary index key with which to query
* @return
* @throws SQLException Throws if there is a persistence error.
*/
public Collection getSecondaryIndexKeysWithPrimaryKey(SecondaryIndex secondaryIndex, Object primaryIndexKey) throws SQLException {
return getDirectory(secondaryIndex.getResource().getPartitionDimension()).getSecondaryIndexKeysOfPrimaryIndexKey(secondaryIndex, primaryIndexKey);
}
/**
*
* Returns all secondary index keys pertaining to the given primary index key. The primary index key
* must exist in the primary index and there may be zero or more keys returned.
*
* @param partitionDimensionName
* @param resource
* @param secondaryIndexName
* @param primaryIndexKey
* @return
* @throws HiveException
* @throws SQLException
*/
public Collection getSecondaryIndexKeysWithPrimaryKey(String partitionDimensionName, String resource, String secondaryIndexName, Object primaryIndexKey) throws HiveException, SQLException {
return getSecondaryIndexKeysWithPrimaryKey(
getPartitionDimension(partitionDimensionName).getResource(resource).getSecondaryIndex(secondaryIndexName),
primaryIndexKey);
}
/**
* Test if Hive has been installed at current JDBC URI
*
* @return True if hive metadata has been installed
* @throws HiveException
* @throws SQLException
*/
public boolean exists() {
try {
new HiveSemaphoreDao(dataSource).get();
return true;
} catch (Exception ex) {
return false;
}
}
public Connection getConnection(String nodeUri) throws SQLException {
return DriverManager.getConnection( nodeUri );
}
public Connection getConnection(PartitionDimension partitionDimension, Object primaryIndexKey) throws HiveException, SQLException{
return DriverManager.getConnection( getNodeOfPrimaryIndexKey(partitionDimension, primaryIndexKey).getUri() );
}
public Connection getConnection(SecondaryIndex secondaryIndex, Object secondaryIndexKey) throws HiveException, SQLException {
return DriverManager.getConnection( getNodeOfSecondaryIndexKey(secondaryIndex, secondaryIndexKey).getUri() );
}
// Facade methods that are short cuts over digging into the object graph
public Collection<String> getNodeUrisForPartitionDimension(String partitionDimensionName) throws HiveException
{
Collection<String> collection = new ArrayList<String>();
for (Node node : getPartitionDimension(partitionDimensionName).getNodeGroup().getNodes())
collection.add(node.getUri());
return collection;
}
public String toString()
{
return HiveUtils.toDeepFormatedString(this,
"HiveUri", getHiveUri(),
"Revision", getRevision(),
"PartitionDimensions", getPartitionDimensions());
}
private<T extends IdAndNameIdentifiable> void isUnique(String errorMessage, Collection<T> collection, T item) throws HiveException
{
// Forbids duplicate names for two different instances if the class implements Identifies
if (!(item instanceof IdAndNameIdentifiable))
return;
String itemName = ((IdAndNameIdentifiable)item).getName();
for (IdAndNameIdentifiable collectionItem : collection)
if (itemName.equals((collectionItem).getName()) && collectionItem.getId() != item.getId())
throw new HiveException(errorMessage + ", " + collectionItem.getId() + ", " + item.getId());
return;
}
private<T extends Identifiable> void isIdPresentInCollection(String errorMessage, Collection<T> collection, T item) throws HiveException
{
for (T collectionItem : collection)
if (item.getId() == collectionItem.getId())
return;
throw new HiveException(errorMessage);
}
private<T> void existenceCheck(String errorMessage, Collection<T> collection, T item) throws HiveException
{
// All classes implement Comparable, so this does a deep compare on all objects owned by the item.
if (!collection.contains(item))
throw new HiveException(errorMessage);
}
private void isWritable(String errorMessage) throws HiveException {
if (this.isReadOnly())
throw new HiveReadOnlyException(errorMessage + ". This operation is invalid because the hive is currently read-only.");
}
private void isWritable(String errorMessage, Node node) throws HiveException {
isWritable(errorMessage);
if (node.isReadOnly())
throw new HiveReadOnlyException(errorMessage + ". This operation is invalid becuase the selected node " + node.getId() + " is currently read-only.");
}
private void isWritable(String errorMessage, Node node, Object primaryIndexKeyId, boolean primaryIndexKeyReadOnly) throws HiveException {
isWritable(errorMessage, node);
if (primaryIndexKeyReadOnly)
throw new HiveReadOnlyException(errorMessage + ". This operation is invalid becuase the primary index key " + primaryIndexKeyId.toString() + " is currently read-only.");
}
private Directory getDirectory(PartitionDimension dimension) {
for(Directory directory : directories)
if(dimension.getName().equals(directory.getPartitionDimension().getName()))
return directory;
String msg = "Could not find directory for partition dimension "+ dimension.getName();
msg += "Looking for:\n" + dimension.toString();
msg += "In List: \n";
for(Directory dir : this.directories)
msg += dir.getPartitionDimension().toString() + "\n";
throw new NoSuchElementException(msg);
}
}
|
package HBDMIPS;
/**
* Represents InstructionDecode/Execute Pipeline Register.
* Pipeline Registers are included for ease of
* Pipeline implementation in future.
* @author HBD
*/
public class ID_EXE {
private String signExt;//Now it's Extended[32bits] String.
String controlBits;
int PC;
int RS_DATA;
int RT_DATA;
int RD;
int RT;
/**
*
* @return PC - current Program Counter saved in ID/EXE Pipeline Register.
*/
public int getPC() {
return PC;
}
/**
* Set current Program Counter in IF/ID pipeline register.
* @param PC
*/
public void setPC(int PC) {
this.PC = PC;
}
/**
* Get SignExtended Address saved in ID/EXE Pipeline Register.
* @return signExt - 32bits string of address.
*/
public String getSignExt() {
return signExt;
}
/**
* Save SignExtended Address in ID stage into ID/EXE Pipeline Register.
* @param signExt - 32bits string of address.
*/
public void setSignExt(String signExt) {
this.signExt = signExt;
}
/**
* Get 13bits of Control saved in ID/EXE Pipeline Register.
* @return controlBits - 13bits string.
*/
public String getControlBits() {
return controlBits;
}
/**
* Save 13bits of Control which <b>originally</b>come from CU.
* @param controlBits - 13bits represented in string.
*/
public void setControlBits(String controlBits) {
this.controlBits = controlBits;
}
/**
* Get Data of the RS address Stored in ID/EXE Pipeline Register.
* @return RS_DATA - 32bit Data represented in INT.
*/
public int getRS_DATA() {
return RS_DATA;
}
/**
* Store Data of the RS address in ID/EXE Pipeline Register.
* @param RS_DATA - 32bit Data represented in INT.
*/
public void setRS_DATA(int RS_DATA) {
this.RS_DATA = RS_DATA;
}
/**
* Get stored Data of the RT address in ID/EXE Pipeline Register.
* @return RT_DATA - 32bit Data represented in INT.
*/
public int getRT_DATA() {
return RT_DATA;
}
/**
* Store Data of the RT address in ID/EXE Pipeline Register.
* @param RT_DATA - 32bit Data represented in INT.
*/
public void setRT_DATA(int RT_DATA) {
this.RT_DATA = RT_DATA;
}
/**
* Get address stored in RD in ID/EXE Pipeline Register.
* @return RD - 5bit RD address represented in INT.
*/
public int getRD() {
return RD;
}
/**
* Store RD address in ID/EXE Pipeline Register.
* @param RD - 5bit RD address represented in INT.
*/
public void setRD(int RD) {
this.RD = RD;
}
/**
* Get address stored in RT in ID/EXE Pipeline Register.
* @return RT - 5bit RT address represented in INT.
*/
public int getRT() {
return RT;
}
/**
* Store RT address in ID/EXE Pipeline Register.
* @param RT - 5bit RD address represented in INT.
*/
public void setRT(int RT) {
this.RT = RT;
}
}
|
package java.util.zip;
import java.io.OutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
public class DeflaterOutputStream extends FilterOutputStream {
protected final Deflater deflater;
protected final byte[] buffer;
public DeflaterOutputStream(OutputStream out, Deflater deflater, int bufferSize)
{
super(out);
this.deflater = deflater;
this.buffer = new byte[bufferSize];
}
public DeflaterOutputStream(OutputStream out, Deflater deflater) {
this(out, deflater, 4 * 1024);
}
public DeflaterOutputStream(OutputStream out) {
this(out, new Deflater());
}
public void write(int b) throws IOException {
byte[] buffer = new byte[1];
buffer[0] = (byte)(b & 0xff);
write(buffer, 0, 1);
}
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
public void write(byte[] b, int offset, int length) throws IOException {
// error condition checking
if (deflater.finished()) {
throw new IOException("Already at end of stream");
} else if (offset < 0) {
throw new IndexOutOfBoundsException("Offset can't be less than zero");
} else if (length < 0) {
throw new IndexOutOfBoundsException("Length can't be less than zero");
} else if (b.length - (offset + length) < 0) {
throw new IndexOutOfBoundsException("Offset + Length is larger than the input byte array");
} else if (length == 0) {
return;
}
deflater.setInput(b, offset, length);
while (deflater.getRemaining() > 0) {
deflate();
}
}
private void deflate() throws IOException {
int len = deflater.deflate(buffer, 0, buffer.length);
if (len > 0) {
out.write(buffer, 0, len);
}
}
public void close() throws IOException {
deflater.finish();
while (! deflater.finished()) {
deflate();
}
out.close();
deflater.dispose();
}
}
|
package replicant;
import arez.Disposable;
import arez.component.Linkable;
import arez.component.Verifiable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.intellij.lang.annotations.Language;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import replicant.messages.ChangeSet;
import replicant.messages.ChannelChange;
import replicant.messages.EntityChange;
import replicant.messages.EntityChangeData;
import replicant.messages.EntityChangeDataImpl;
import replicant.spy.AreaOfInterestDisposedEvent;
import replicant.spy.AreaOfInterestStatusUpdatedEvent;
import replicant.spy.ConnectFailureEvent;
import replicant.spy.ConnectedEvent;
import replicant.spy.DisconnectFailureEvent;
import replicant.spy.DisconnectedEvent;
import replicant.spy.InSyncEvent;
import replicant.spy.MessageProcessFailureEvent;
import replicant.spy.MessageProcessedEvent;
import replicant.spy.MessageReadFailureEvent;
import replicant.spy.OutOfSyncEvent;
import replicant.spy.RestartEvent;
import replicant.spy.SubscribeCompletedEvent;
import replicant.spy.SubscribeFailedEvent;
import replicant.spy.SubscribeRequestQueuedEvent;
import replicant.spy.SubscribeStartedEvent;
import replicant.spy.SubscriptionCreatedEvent;
import replicant.spy.SubscriptionDisposedEvent;
import replicant.spy.SubscriptionUpdateCompletedEvent;
import replicant.spy.SubscriptionUpdateFailedEvent;
import replicant.spy.SubscriptionUpdateRequestQueuedEvent;
import replicant.spy.SubscriptionUpdateStartedEvent;
import replicant.spy.SyncFailureEvent;
import replicant.spy.SyncRequestEvent;
import replicant.spy.UnsubscribeCompletedEvent;
import replicant.spy.UnsubscribeFailedEvent;
import replicant.spy.UnsubscribeRequestQueuedEvent;
import replicant.spy.UnsubscribeStartedEvent;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
@SuppressWarnings( { "NonJREEmulationClassesInClientCode", "Duplicates" } )
public class ConnectorTest
extends AbstractReplicantTest
{
@Test
public void construct()
throws Exception
{
final Disposable schedulerLock = pauseScheduler();
final ReplicantRuntime runtime = Replicant.context().getRuntime();
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final SystemSchema schema =
new SystemSchema( ValueUtil.randomInt(),
ValueUtil.randomString(),
new ChannelSchema[ 0 ],
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
assertEquals( connector.getSchema(), schema );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
assertEquals( connector.getReplicantRuntime(), runtime );
assertTrue( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ) );
assertEquals( connector.getState(), ConnectorState.DISCONNECTED );
schedulerLock.dispose();
assertEquals( connector.getState(), ConnectorState.CONNECTING );
}
@Test
public void dispose()
{
final ReplicantRuntime runtime = Replicant.context().getRuntime();
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final SystemSchema schema = newSchema();
final Connector connector = createConnector( schema );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
assertTrue( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ) );
Disposable.dispose( connector );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
assertFalse( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ) );
}
@Test
public void testToString()
throws Exception
{
final SystemSchema schema = newSchema();
final Connector connector = createConnector( schema );
assertEquals( connector.toString(), "Connector[" + schema.getName() + "]" );
ReplicantTestUtil.disableNames();
assertEquals( connector.toString(), "replicant.Arez_Connector@" + Integer.toHexString( connector.hashCode() ) );
}
@Test
public void setConnection_whenConnectorProcessingMessage()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 0 );
final Subscription subscription = createSubscription( address, null, true );
connector.onConnection( ValueUtil.randomString() );
// Connection not swapped yet but will do one MessageProcess completes
assertFalse( Disposable.isDisposed( subscription ) );
assertEquals( connector.getConnection(), connection );
assertNotNull( connector.getPostMessageResponseAction() );
}
@Test
public void setConnection_whenExistingConnection()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
connector.recordLastRxRequestId( ValueUtil.randomInt() );
connector.recordLastTxRequestId( ValueUtil.randomInt() );
connector.recordLastSyncRxRequestId( ValueUtil.randomInt() );
connector.recordLastSyncTxRequestId( ValueUtil.randomInt() );
connector.recordSyncInFlight( true );
connector.recordPendingResponseQueueEmpty( false );
assertFalse( Disposable.isDisposed( connection ) );
assertEquals( connector.getConnection(), connection );
final String newConnectionId = ValueUtil.randomString();
connector.onConnection( newConnectionId );
assertTrue( Disposable.isDisposed( connection ) );
assertEquals( connector.ensureConnection().getConnectionId(), newConnectionId );
safeAction( () -> assertEquals( connector.getLastRxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastTxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastSyncRxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastSyncTxRequestId(), 0 ) );
safeAction( () -> assertFalse( connector.isSyncInFlight() ) );
safeAction( () -> assertTrue( connector.isPendingResponseQueueEmpty() ) );
}
@Test
public void connect()
{
pauseScheduler();
final Connector connector = createConnector();
assertEquals( connector.getState(), ConnectorState.DISCONNECTED );
safeAction( connector::connect );
verify( connector.getTransport() ).connect( any( Transport.OnConnect.class ) );
assertEquals( connector.getState(), ConnectorState.CONNECTING );
}
@Test
public void connect_causesError()
{
pauseScheduler();
final Connector connector = createConnector();
assertEquals( connector.getState(), ConnectorState.DISCONNECTED );
reset( connector.getTransport() );
final IllegalStateException exception = new IllegalStateException();
doAnswer( i -> {
throw exception;
} ).when( connector.getTransport() ).connect( any( Transport.OnConnect.class ) );
final IllegalStateException actual =
expectThrows( IllegalStateException.class, () -> safeAction( connector::connect ) );
assertEquals( actual, exception );
assertEquals( connector.getState(), ConnectorState.ERROR );
verify( connector.getTransport() ).unbind();
}
@Test
public void transportDisconnect()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
connector.transportDisconnect();
verify( connector.getTransport() ).requestDisconnect();
assertEquals( connector.getState(), ConnectorState.DISCONNECTING );
}
@Test
public void disconnect()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( connector::disconnect );
verify( connector.getTransport() ).requestDisconnect();
assertEquals( connector.getState(), ConnectorState.DISCONNECTING );
verify( connector.getTransport(), never() ).unbind();
}
@Test
public void disconnect_causesError()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
reset( connector.getTransport() );
final IllegalStateException exception = new IllegalStateException();
doAnswer( i -> {
throw exception;
} ).when( connector.getTransport() ).requestDisconnect();
final IllegalStateException actual =
expectThrows( IllegalStateException.class, () -> safeAction( connector::disconnect ) );
assertEquals( actual, exception );
assertEquals( connector.getState(), ConnectorState.ERROR );
verify( connector.getTransport() ).unbind();
}
@Test
public void onDisconnected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
pauseScheduler();
reset( connector.getTransport() );
connector.onDisconnected();
assertEquals( connector.getState(), ConnectorState.DISCONNECTED );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.DISCONNECTED ) );
verify( connector.getTransport() ).unbind();
}
@Test
public void onDisconnected_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnected();
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectedEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onDisconnectFailure()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnectFailure( error );
assertEquals( connector.getState(), ConnectorState.ERROR );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onDisconnectFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnectFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onConnected()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = new Connection( connector, ValueUtil.randomString() );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
pauseScheduler();
final Field field = Connector.class.getDeclaredField( "_connection" );
field.setAccessible( true );
field.set( connector, connection );
connector.onConnected();
assertEquals( connector.getState(), ConnectorState.CONNECTED );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTED ) );
verify( connector.getTransport() ).bind( connection.getTransportContext(), Replicant.context() );
}
@Test
public void onConnected_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onConnected();
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectedEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onConnectFailure()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onConnectFailure( error );
assertEquals( connector.getState(), ConnectorState.ERROR );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onConnectFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onConnectFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageReceived()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final String rawJsonData = ValueUtil.randomString();
pauseScheduler();
connector.pauseMessageScheduler();
assertEquals( connection.getUnparsedResponses().size(), 0 );
assertFalse( connector.isSchedulerActive() );
connector.onMessageReceived( rawJsonData );
assertEquals( connection.getUnparsedResponses().size(), 1 );
assertEquals( connection.getUnparsedResponses().get( 0 ).getRawJsonData(), rawJsonData );
assertTrue( connector.isSchedulerActive() );
}
@Test
public void onMessageProcessed()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final MessageResponse response = new MessageResponse( "" );
response.recordChangeSet( ChangeSet.create( null, null, null, null, null ), null );
connector.onMessageProcessed( response );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onMessageProcessFailure()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onMessageProcessFailure( error );
assertEquals( connector.getState(), ConnectorState.DISCONNECTING );
}
@Test
public void onMessageProcessFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
connector.onMessageProcessFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void disconnectIfPossible()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
safeAction( () -> connector.disconnectIfPossible( error ) );
assertEquals( connector.getState(), ConnectorState.DISCONNECTING );
}
@Test
public void disconnectIfPossible_noActionAsConnecting()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.disconnectIfPossible( error );
handler.assertEventCount( 0 );
assertEquals( connector.getState(), ConnectorState.CONNECTING );
}
@Test
public void disconnectIfPossible_generatesSpyEvent()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
safeAction( () -> connector.disconnectIfPossible( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( RestartEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageReadFailure()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onMessageReadFailure( error );
assertEquals( connector.getState(), ConnectorState.DISCONNECTING );
}
@Test
public void onMessageReadFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
connector.onMessageReadFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageReadFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscribeStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeStarted( address );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADING );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeCompleted( address );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADED );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeCompleted_DeletedSubscription()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> areaOfInterest.setStatus( AreaOfInterest.Status.DELETED ) );
createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeCompleted( address );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.DELETED );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeFailed( address, error );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOAD_FAILED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onUnsubscribeStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeStarted( address );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADING );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeCompleted( address );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeFailed( address, error );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscriptionUpdateStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateStarted( address );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATING );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateCompleted( address );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATED );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED );
safeAction( () -> assertNull( areaOfInterest.getSubscription() ) );
safeAction( () -> assertNull( areaOfInterest.getError() ) );
final Throwable error = new Throwable();
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateFailed( address, error );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATE_FAILED );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void areaOfInterestRequestPendingQueries()
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
assertFalse( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ) );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
-1 );
final Connection connection = newConnection( connector );
assertFalse( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ) );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
-1 );
connection.requestSubscribe( address, filter );
assertTrue( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ) );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
1 );
}
@Test
public void connection()
{
final Connector connector = createConnector();
assertNull( connector.getConnection() );
final Connection connection = newConnection( connector );
final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true );
assertEquals( connector.getConnection(), connection );
assertEquals( connector.ensureConnection(), connection );
assertFalse( Disposable.isDisposed( subscription1 ) );
connector.onDisconnection();
assertNull( connector.getConnection() );
assertTrue( Disposable.isDisposed( subscription1 ) );
}
@Test
public void ensureConnection_WhenNoConnection()
{
final Connector connector = createConnector();
final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::ensureConnection );
assertEquals( exception.getMessage(),
"Replicant-0031: Connector.ensureConnection() when no connection is present." );
}
@Test
public void purgeSubscriptions()
{
final Connector connector1 = createConnector( newSchema( 1 ) );
createConnector( newSchema( 2 ) );
final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true );
final Subscription subscription2 = createSubscription( new ChannelAddress( 1, 1, 2 ), null, true );
// The next two are from a different Connector
final Subscription subscription3 = createSubscription( new ChannelAddress( 2, 0, 1 ), null, true );
final Subscription subscription4 = createSubscription( new ChannelAddress( 2, 0, 2 ), null, true );
assertFalse( Disposable.isDisposed( subscription1 ) );
assertFalse( Disposable.isDisposed( subscription2 ) );
assertFalse( Disposable.isDisposed( subscription3 ) );
assertFalse( Disposable.isDisposed( subscription4 ) );
connector1.purgeSubscriptions();
assertTrue( Disposable.isDisposed( subscription1 ) );
assertTrue( Disposable.isDisposed( subscription2 ) );
assertFalse( Disposable.isDisposed( subscription3 ) );
assertFalse( Disposable.isDisposed( subscription4 ) );
}
@Test
public void progressMessages()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final String[] channels = { "+0" };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
assertNull( connector.getSchedulerLock() );
connector.resumeMessageScheduler();
//response needs processing of channel messages
final boolean result0 = connector.progressMessages();
assertTrue( result0 );
final Disposable schedulerLock0 = connector.getSchedulerLock();
assertNotNull( schedulerLock0 );
//response needs worldValidated
final boolean result1 = connector.progressMessages();
assertTrue( result1 );
assertNull( connector.getSchedulerLock() );
assertTrue( Disposable.isDisposed( schedulerLock0 ) );
final boolean result2 = connector.progressMessages();
assertTrue( result2 );
// Current message should be nulled and completed processing now
assertNull( connection.getCurrentMessageResponse() );
final boolean result3 = connector.progressMessages();
assertFalse( result3 );
assertNull( connector.getSchedulerLock() );
}
@Test
public void progressMessages_whenConnectionHasBeenDisconnectedInMeantime()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final String[] channels = { "+0" };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
final AtomicInteger callCount = new AtomicInteger();
connector.setPostMessageResponseAction( callCount::incrementAndGet );
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 0 );
connector.resumeMessageScheduler();
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 0 );
assertTrue( connector.progressMessages() );
assertEquals( callCount.get(), 0 );
assertNotNull( connector.getSchedulerLock() );
safeAction( () -> {
connector.setState( ConnectorState.ERROR );
connector.setConnection( null );
} );
// The rest of the message has been skipped as no connection left
assertFalse( connector.progressMessages() );
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 1 );
}
@Test
public void progressMessages_withError()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 0, 0 ),
AreaOfInterestRequest.Type.REMOVE,
null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.resumeMessageScheduler();
final boolean result2 = connector.progressMessages();
assertFalse( result2 );
assertNull( connector.getSchedulerLock() );
handler.assertEventCountAtLeast( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError().getMessage(),
"Replicant-0046: Request to unsubscribe from channel at address 0.0 but not subscribed to channel." );
} );
}
@Test
public void requestSubscribe()
{
final Connector connector = createConnector();
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertFalse( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscribe( address, null );
assertTrue( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestSubscriptionUpdate()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
( f, e ) -> true,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertFalse( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscriptionUpdate( address, null );
assertTrue( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestSubscriptionUpdate_ChannelNot_DYNAMIC_Filter()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertFalse( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ) );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> connector.requestSubscriptionUpdate( address, null ) );
assertEquals( exception.getMessage(),
"Replicant-0082: Connector.requestSubscriptionUpdate invoked for channel 1.0 but channel does not have a dynamic filter." );
}
@Test
public void requestUnsubscribe()
throws Exception
{
final Connector connector = createConnector();
pauseScheduler();
connector.pauseMessageScheduler();
newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
createSubscription( address, null, true );
assertFalse( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestUnsubscribe( address );
Thread.sleep( 100 );
assertTrue( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void updateSubscriptionForFilteredEntities()
{
final SubscriptionUpdateEntityFilter<?> filter = ( f, entity ) -> entity.getId() > 0;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
filter,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true );
final Subscription subscription2 = createSubscription( address2, ValueUtil.randomString(), true );
// Use Integer and String as arbitrary types for our entities...
// Anything with id below 0 will be removed during update ...
final Entity entity1 = findOrCreateEntity( Integer.class, -1 );
final Entity entity2 = findOrCreateEntity( Integer.class, -2 );
final Entity entity3 = findOrCreateEntity( Integer.class, -3 );
final Entity entity4 = findOrCreateEntity( Integer.class, -4 );
final Entity entity5 = findOrCreateEntity( String.class, 5 );
final Entity entity6 = findOrCreateEntity( String.class, 6 );
safeAction( () -> {
entity1.linkToSubscription( subscription1 );
entity2.linkToSubscription( subscription1 );
entity3.linkToSubscription( subscription1 );
entity4.linkToSubscription( subscription1 );
entity5.linkToSubscription( subscription1 );
entity6.linkToSubscription( subscription1 );
entity3.linkToSubscription( subscription2 );
entity4.linkToSubscription( subscription2 );
assertEquals( subscription1.getEntities().size(), 2 );
assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 4 );
assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 );
assertEquals( subscription2.getEntities().size(), 1 );
assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 );
} );
safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) );
safeAction( () -> {
assertTrue( Disposable.isDisposed( entity1 ) );
assertTrue( Disposable.isDisposed( entity2 ) );
assertFalse( Disposable.isDisposed( entity3 ) );
assertFalse( Disposable.isDisposed( entity4 ) );
assertFalse( Disposable.isDisposed( entity5 ) );
assertFalse( Disposable.isDisposed( entity6 ) );
assertEquals( subscription1.getEntities().size(), 1 );
assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 0 );
assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 );
assertEquals( subscription2.getEntities().size(), 1 );
assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 );
} );
}
@Test
public void updateSubscriptionForFilteredEntities_badFilterType()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) ) );
assertEquals( exception.getMessage(),
"Replicant-0079: Connector.updateSubscriptionForFilteredEntities invoked for address 1.0.1 but the channel does not have a DYNAMIC filter." );
}
@SuppressWarnings( "unchecked" )
@Test
public void processEntityChanges()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable userObject1 = mock( Linkable.class );
final Linkable userObject2 = mock( Linkable.class );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 1 );
final Subscription subscription = createSubscription( address, null, true );
// This entity is to be updated
final Entity entity2 = findOrCreateEntity( Linkable.class, 2 );
safeAction( () -> entity2.setUserObject( userObject2 ) );
// It is already subscribed to channel and that should be fine
safeAction( () -> entity2.linkToSubscription( subscription ) );
// This entity is to be removed
final Entity entity3 = findOrCreateEntity( Linkable.class, 3 );
final EntityChangeData data1 = mock( EntityChangeData.class );
final EntityChangeData data2 = mock( EntityChangeData.class );
final EntityChange[] entityChanges = {
// Update changes
EntityChange.create( 0, 1, new String[]{ "1" }, data1 ),
EntityChange.create( 0, 2, new String[]{ "1" }, data2 ),
// Remove change
EntityChange.create( 0, 3, new String[]{ "1" } )
};
final ChangeSet changeSet = ChangeSet.create( null, null, null, null, entityChanges );
response.recordChangeSet( changeSet, null );
when( creator.createEntity( 1, data1 ) ).thenReturn( userObject1 );
assertEquals( response.getUpdatedEntities().size(), 0 );
assertEquals( response.getEntityUpdateCount(), 0 );
assertEquals( response.getEntityRemoveCount(), 0 );
connector.setChangesToProcessPerTick( 1 );
connector.processEntityChanges();
verify( creator, times( 1 ) ).createEntity( 1, data1 );
verify( updater, never() ).updateEntity( userObject1, data1 );
verify( creator, never() ).createEntity( 2, data2 );
verify( updater, never() ).updateEntity( userObject2, data2 );
assertEquals( response.getUpdatedEntities().size(), 1 );
assertTrue( response.getUpdatedEntities().contains( userObject1 ) );
assertEquals( response.getEntityUpdateCount(), 1 );
assertEquals( response.getEntityRemoveCount(), 0 );
connector.setChangesToProcessPerTick( 2 );
connector.processEntityChanges();
verify( creator, times( 1 ) ).createEntity( 1, data1 );
verify( updater, never() ).updateEntity( userObject1, data1 );
verify( creator, never() ).createEntity( 2, data2 );
verify( updater, times( 1 ) ).updateEntity( userObject2, data2 );
assertEquals( response.getUpdatedEntities().size(), 2 );
assertTrue( response.getUpdatedEntities().contains( userObject1 ) );
assertTrue( response.getUpdatedEntities().contains( userObject2 ) );
assertEquals( response.getEntityUpdateCount(), 2 );
assertEquals( response.getEntityRemoveCount(), 1 );
assertFalse( Disposable.isDisposed( entity2 ) );
assertTrue( Disposable.isDisposed( entity3 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void processEntityChanges_referenceNonExistentSubscription()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable userObject1 = mock( Linkable.class );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final EntityChangeData data1 = mock( EntityChangeData.class );
final EntityChange[] entityChanges = {
EntityChange.create( 0, 1, new String[]{ "1" }, data1 )
};
final ChangeSet changeSet = ChangeSet.create( null, null, null, null, entityChanges );
response.recordChangeSet( changeSet, null );
when( creator.createEntity( 1, data1 ) ).thenReturn( userObject1 );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processEntityChanges );
assertEquals( exception.getMessage(),
"Replicant-0069: ChangeSet contained an EntityChange message referencing channel 1.1 but no such subscription exists locally." );
}
@Test
public void processEntityChanges_deleteNonExistingEntity()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), MyEntity.class, ( i, d ) -> new MyEntity(), null );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final EntityChange[] entityChanges = {
// Remove change
EntityChange.create( 0, 3, new String[]{ "1" } )
};
final ChangeSet changeSet = ChangeSet.create( null, null, null, null, entityChanges );
response.recordChangeSet( changeSet, null );
connector.setChangesToProcessPerTick( 1 );
connector.processEntityChanges();
assertEquals( response.getEntityRemoveCount(), 0 );
}
@Test
public void processEntityLinks()
{
final Connector connector = createConnector();
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable entity1 = mock( Linkable.class );
final Linkable entity2 = mock( Linkable.class );
final Linkable entity3 = mock( Linkable.class );
final Linkable entity4 = mock( Linkable.class );
response.changeProcessed( entity1 );
response.changeProcessed( entity2 );
response.changeProcessed( entity3 );
response.changeProcessed( entity4 );
verify( entity1, never() ).link();
verify( entity2, never() ).link();
verify( entity3, never() ).link();
verify( entity4, never() ).link();
assertEquals( response.getEntityLinkCount(), 0 );
connector.setLinksToProcessPerTick( 1 );
connector.processEntityLinks();
assertEquals( response.getEntityLinkCount(), 1 );
verify( entity1, times( 1 ) ).link();
verify( entity2, never() ).link();
verify( entity3, never() ).link();
verify( entity4, never() ).link();
connector.setLinksToProcessPerTick( 2 );
connector.processEntityLinks();
assertEquals( response.getEntityLinkCount(), 3 );
verify( entity1, times( 1 ) ).link();
verify( entity2, times( 1 ) ).link();
verify( entity3, times( 1 ) ).link();
verify( entity4, never() ).link();
}
@Test
public void completeAreaOfInterestRequest()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 1, 0 ),
AreaOfInterestRequest.Type.ADD,
null ) );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.completeAreaOfInterestRequest();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
}
@Test
public void processChannelChanges_add()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final int channelId = 0;
final int subChannelId = ValueUtil.randomInt();
final String filter = null;
final String[] channels = { "+0." + subChannelId };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
assertTrue( response.needsChannelChangesProcessed() );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertFalse( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_add_withFilter()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final int channelId = 0;
final int subChannelId = ValueUtil.randomInt();
final String filter = ValueUtil.randomString();
final ChannelChange[] fchannels = { ChannelChange.create( "+0." + subChannelId, filter ) };
response.recordChangeSet( ChangeSet.create( null, null, null, fchannels, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, fchannels[ 0 ] ) ) );
assertTrue( response.needsChannelChangesProcessed() );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertFalse( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_add_withCorrespondingAreaOfInterest()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final int channelId = 0;
final int subChannelId = ValueUtil.randomInt();
final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId );
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
final String[] channels = { "+0." + subChannelId };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
assertTrue( response.needsChannelChangesProcessed() );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertNull( subscription.getFilter() ) );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertNull( e.getSubscription().getFilter() ) );
} );
}
@Test
public void processChannelChanges_addConvertingImplicitToExplicit()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connector.pauseMessageScheduler();
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
final String[] channels = { "+0." + address.getId() };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, null );
connection.injectCurrentAreaOfInterestRequest( request );
request.markAsInProgress();
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelAddCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelAddCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), null ) );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), null ) );
} );
}
@Test
public void processChannelChanges_remove()
{
final Connector connector = createConnector();
connector.pauseMessageScheduler();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final String[] channels = { "-0." + address.getId() };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
final Subscription initialSubscription = createSubscription( address, ValueUtil.randomString(), true );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNull( subscription );
assertTrue( Disposable.isDisposed( initialSubscription ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionDisposedEvent.class,
e -> assertEquals( e.getSubscription().getAddress(), address ) );
}
@Test
public void processChannelChanges_remove_withAreaOfInterest()
{
final Connector connector = createConnector();
connector.pauseMessageScheduler();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
final String[] channels = { "-0." + address.getId() };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
final Subscription initialSubscription = createSubscription( address, ValueUtil.randomString(), true );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNull( subscription );
assertTrue( Disposable.isDisposed( initialSubscription ) );
assertTrue( Disposable.isDisposed( areaOfInterest ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestDisposedEvent.class,
e -> assertEquals( e.getAreaOfInterest().getAddress(), address ) );
handler.assertNextEvent( SubscriptionDisposedEvent.class,
e -> assertEquals( e.getSubscription().getAddress(), address ) );
}
@Test
public void processChannelChanges_remove_WithMissingSubscription()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final String[] channels = { "-0.72" };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 1 );
handler.assertEventCount( 0 );
}
@Test
public void processChannelChanges_remove_WithMissingSubscription_butAreaOfInterestPresent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
final String[] channels = { "-0." + address.getId() };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 1 );
assertTrue( Disposable.isDisposed( areaOfInterest ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( AreaOfInterestDisposedEvent.class,
e -> assertEquals( e.getAreaOfInterest().getAddress(), address ) );
}
@Test
public void processChannelChanges_delete_WithMissingSubscription_butAreaOfInterestPresent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
final String[] channels = { "!0." + address.getId() };
response.recordChangeSet( ChangeSet.create( null, null, channels, null, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1, channels[ 0 ] ) ) );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelRemoveCount(), 1 );
assertFalse( Disposable.isDisposed( areaOfInterest ) );
assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.DELETED );
handler.assertEventCount( 1 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest().getAddress(), address ) );
}
@Test
public void processChannelChanges_update()
{
final SubscriptionUpdateEntityFilter<?> filter = mock( SubscriptionUpdateEntityFilter.class );
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
filter,
true, true,
Collections.emptyList() );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), String.class, ( i, d ) -> "", null );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.pauseMessageScheduler();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final String oldFilter = ValueUtil.randomString();
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( "=0." + address.getId(), newFilter ) };
response.recordChangeSet( ChangeSet.create( null, null, null, channelChanges, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1,
channelChanges[ 0 ] ) ) );
final Subscription initialSubscription = createSubscription( address, oldFilter, true );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelUpdateCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertFalse( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelUpdateCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertFalse( Disposable.isDisposed( initialSubscription ) );
handler.assertEventCount( 0 );
}
@Test
public void processChannelChanges_update_forNonDYNAMICChannel()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
true,
true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final String oldFilter = ValueUtil.randomString();
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( "=0.2223", newFilter ) };
response.recordChangeSet( ChangeSet.create( null, null, null, channelChanges, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1,
channelChanges[ 0 ] ) ) );
createSubscription( new ChannelAddress( 1, 0, 2223 ), oldFilter, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processChannelChanges );
assertEquals( exception.getMessage(),
"Replicant-0078: Received ChannelChange of type UPDATE for address 1.0.2223 but the channel does not have a DYNAMIC filter." );
}
@Test
public void processChannelChanges_update_missingSubscription()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( "=0.42", newFilter ) };
response.recordChangeSet( ChangeSet.create( null, null, null, channelChanges, null ), null );
response.setParsedChannelChanges( Collections.singletonList( ChannelChangeDescriptor.from( 1,
channelChanges[ 0 ] ) ) );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelUpdateCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processChannelChanges );
assertTrue( response.needsChannelChangesProcessed() );
assertEquals( response.getChannelUpdateCount(), 0 );
assertEquals( exception.getMessage(),
"Replicant-0033: Received ChannelChange of type UPDATE for address 1.0.42 but no such subscription exists." );
handler.assertEventCount( 0 );
}
@Test
public void removeExplicitSubscriptions()
{
// Pause converger
pauseScheduler();
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ) );
requests.add( new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ) );
requests.add( new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null ) );
final Subscription subscription1 = createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
connector.removeExplicitSubscriptions( requests );
safeAction( () -> assertFalse( subscription1.isExplicitSubscription() ) );
}
@Test
public void removeExplicitSubscriptions_passedBadAction()
{
// Pause converger
pauseScheduler();
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null ) );
createSubscription( address1, null, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeExplicitSubscriptions( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0034: Connector.removeExplicitSubscriptions() invoked with request with type that is not REMOVE. Request: AreaOfInterestRequest[Type=ADD Address=1.1.1]" );
}
@Test
public void removeUnneededRemoveRequests_whenInvariantsDisabled()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.add( request2 );
requests.add( request3 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
ReplicantTestUtil.noCheckInvariants();
connector.removeUnneededRemoveRequests( requests );
assertEquals( requests.size(), 1 );
assertTrue( requests.contains( request1 ) );
assertTrue( request1.isInProgress() );
assertFalse( request2.isInProgress() );
assertFalse( request3.isInProgress() );
}
@Test
public void removeUnneededRemoveRequests_noSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0046: Request to unsubscribe from channel at address 1.1.1 but not subscribed to channel." );
}
@Test
public void removeUnneededRemoveRequests_implicitSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, false );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0047: Request to unsubscribe from channel at address 1.1.1 but subscription is not an explicit subscription." );
}
@Test
public void removeUnneededUpdateRequests_whenInvariantsDisabled()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, null );
requests.add( request1 );
requests.add( request2 );
requests.add( request3 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
ReplicantTestUtil.noCheckInvariants();
connector.removeUnneededUpdateRequests( requests );
assertEquals( requests.size(), 2 );
assertTrue( requests.contains( request1 ) );
assertTrue( requests.contains( request2 ) );
assertTrue( request1.isInProgress() );
assertTrue( request2.isInProgress() );
assertFalse( request3.isInProgress() );
}
@Test
public void removeUnneededUpdateRequests_noSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededUpdateRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0048: Request to update channel at address 1.1.1 but not subscribed to channel." );
}
@Test
public void validateWorld_invalidEntity()
{
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertFalse( response.hasWorldBeenValidated() );
final EntityService entityService = Replicant.context().getEntityService();
final Entity entity1 =
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
final Exception error = new Exception();
safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::validateWorld );
assertEquals( exception.getMessage(),
"Replicant-0065: Entity failed to verify during validation process. Entity = MyEntity/1" );
assertTrue( response.hasWorldBeenValidated() );
}
@Test
public void validateWorld_invalidEntity_ignoredIfCOmpileSettingDisablesValidation()
{
ReplicantTestUtil.noValidateEntitiesOnLoad();
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertTrue( response.hasWorldBeenValidated() );
final EntityService entityService = Replicant.context().getEntityService();
final Entity entity1 =
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
final Exception error = new Exception();
safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) );
connector.validateWorld();
assertTrue( response.hasWorldBeenValidated() );
}
@Test
public void validateWorld_validEntity()
{
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertFalse( response.hasWorldBeenValidated() );
final EntityService entityService = Replicant.context().getEntityService();
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
connector.validateWorld();
assertTrue( response.hasWorldBeenValidated() );
}
static class MyEntity
implements Verifiable
{
@Nullable
private final Exception _exception;
MyEntity()
{
this( null );
}
MyEntity( @Nullable final Exception exception )
{
_exception = exception;
}
@Override
public void verify()
throws Exception
{
if ( null != _exception )
{
throw _exception;
}
}
}
@Test
public void parseMessageResponse_basicMessage()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData = "{}";
final MessageResponse response = new MessageResponse( rawJsonData );
final ChangeSetParser.Parser parser = mock( ChangeSetParser.Parser.class );
when( parser.parseChangeSet( rawJsonData ) ).thenReturn( ChangeSet.create( null, null, null, null, null ) );
getProxyParser().setParser( parser );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertNull( response.getRawJsonData() );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertNull( response.getRequest() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertNull( connection.getCurrentMessageResponse() );
}
@Test
public void parseMessageResponse_requestPresent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
@Language( "json" )
final String rawJsonData = "{\"requestId\": " + requestId + "}";
final MessageResponse response = new MessageResponse( rawJsonData );
final ChangeSetParser.Parser parser = mock( ChangeSetParser.Parser.class );
when( parser.parseChangeSet( rawJsonData ) )
.thenReturn( ChangeSet.create( requestId, null, null, null, null ) );
getProxyParser().setParser( parser );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertNull( response.getRawJsonData() );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( response.getRequest(), request.getEntry() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertNull( connection.getCurrentMessageResponse() );
}
@Test
public void parseMessageResponse_cacheResult()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
true,
true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
final String etag = ValueUtil.randomString();
@Language( "json" )
final String rawJsonData =
"{\"requestId\": " + requestId +
", \"etag\": \"" + etag + "\"" +
", \"channels\": [ \"+0\" ] }";
final MessageResponse response = new MessageResponse( rawJsonData );
final ChangeSetParser.Parser parser = mock( ChangeSetParser.Parser.class );
when( parser.parseChangeSet( rawJsonData ) )
.thenReturn( ChangeSet.create( requestId, etag, new String[]{ "+0" }, null, null ) );
getProxyParser().setParser( parser );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final CacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
assertNull( cacheService.lookup( ValueUtil.randomString() ) );
connector.parseMessageResponse();
assertNull( response.getRawJsonData() );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( response.getRequest(), request.getEntry() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertNull( connection.getCurrentMessageResponse() );
final String cacheKey = "RC-1.0";
final CacheEntry entry = cacheService.lookup( cacheKey );
assertNotNull( entry );
assertEquals( entry.getKey(), cacheKey );
assertEquals( entry.getETag(), etag );
assertEquals( entry.getContent(), rawJsonData );
}
@Test
public void parseMessageResponse_eTagWhenNotCacheCandidate()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
final String etag = ValueUtil.randomString();
@Language( "json" )
final String rawJsonData =
"{\"requestId\": " + requestId +
", \"etag\": \"" + etag + "\"" +
", \"channels\": [ \"+0\", \"+1.1\" ] }";
final MessageResponse response = new MessageResponse( rawJsonData );
final ChangeSetParser.Parser parser = mock( ChangeSetParser.Parser.class );
when( parser.parseChangeSet( rawJsonData ) )
.thenReturn( ChangeSet.create( requestId, etag, new String[]{ "+0", "+1.1" }, null, null ) );
getProxyParser().setParser( parser );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final CacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
assertNull( cacheService.lookup( ValueUtil.randomString() ) );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::parseMessageResponse );
assertEquals( exception.getMessage(),
"Replicant-0072: eTag in reply for ChangeSet but ChangeSet is not a candidate for caching." );
}
@Test
public void parseMessageResponse_oob()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
@Language( "json" )
final String rawJsonData = "{\"requestId\": " + requestId + "}";
final SafeProcedure oobCompletionAction = () -> {
};
final MessageResponse response = new MessageResponse( rawJsonData, oobCompletionAction );
final ChangeSetParser.Parser parser = mock( ChangeSetParser.Parser.class );
when( parser.parseChangeSet( rawJsonData ) ).thenReturn( ChangeSet.create( requestId, null, null, null, null ) );
getProxyParser().setParser( parser );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertNull( response.getRawJsonData() );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertNull( response.getRequest() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertNull( connection.getCurrentMessageResponse() );
}
@Test
public void parseMessageResponse_invalidRequestId()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData = "{\"requestId\": 22}";
final MessageResponse response = new MessageResponse( rawJsonData );
final ChangeSetParser.Parser parser = mock( ChangeSetParser.Parser.class );
when( parser.parseChangeSet( rawJsonData ) ).thenReturn( ChangeSet.create( 22, null, null, null, null ) );
getProxyParser().setParser( parser );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::parseMessageResponse );
assertEquals( exception.getMessage(),
"Replicant-0066: Unable to locate request with id '22' specified for ChangeSet. Existing Requests: {}" );
}
@Test
public void completeMessageResponse()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( null, null, null, null, null );
response.recordChangeSet( changeSet, null );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.completeMessageResponse();
assertNull( connection.getCurrentMessageResponse() );
safeAction( () -> assertTrue( connector.isPendingResponseQueueEmpty() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
} );
}
@Test
public void completeMessageResponse_hasContent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet =
ChangeSet.create( null, null, new String[]{ "+1" }, null, null );
response.recordChangeSet( changeSet, null );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.completeMessageResponse();
assertNull( connection.getCurrentMessageResponse() );
safeAction( () -> assertTrue( connector.isPendingResponseQueueEmpty() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
} );
handler.assertNextEvent( SyncRequestEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void completeMessageResponse_stillMessagesPending()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
response.recordChangeSet( ChangeSet.create( null, null, null, null, null ), null );
connection.setCurrentMessageResponse( response );
connection.enqueueResponse( ValueUtil.randomString() );
connector.completeMessageResponse();
safeAction( () -> assertFalse( connector.isPendingResponseQueueEmpty() ) );
}
@Test
public void completeMessageResponse_withPostAction()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( null, null, null, null, null );
response.recordChangeSet( changeSet, null );
connection.setCurrentMessageResponse( response );
final AtomicInteger postActionCallCount = new AtomicInteger();
connector.setPostMessageResponseAction( postActionCallCount::incrementAndGet );
assertEquals( postActionCallCount.get(), 0 );
connector.completeMessageResponse();
assertEquals( postActionCallCount.get(), 1 );
}
@Test
public void completeMessageResponse_OOBMessage()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final AtomicInteger completionCallCount = new AtomicInteger();
final MessageResponse response = new MessageResponse( "", completionCallCount::incrementAndGet );
final ChangeSet changeSet = ChangeSet.create( 1234, null, null, null, null );
response.recordChangeSet( changeSet, null );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( completionCallCount.get(), 0 );
connector.completeMessageResponse();
assertEquals( completionCallCount.get(), 1 );
assertNull( connection.getCurrentMessageResponse() );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
} );
}
@Test
public void completeMessageResponse_MessageWithRequest_RPCComplete()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final AtomicInteger completionCalled = new AtomicInteger();
final int requestId = request.getRequestId();
final RequestEntry entry = request.getEntry();
entry.setNormalCompletion( true );
entry.setCompletionAction( completionCalled::incrementAndGet );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( requestId, null, null, null, null );
response.recordChangeSet( changeSet, entry );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( entry.haveResultsArrived() );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), entry );
connector.completeMessageResponse();
assertTrue( entry.haveResultsArrived() );
assertNull( connection.getCurrentMessageResponse() );
assertEquals( completionCalled.get(), 1 );
assertNull( connection.getRequest( requestId ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
} );
}
@Test
public void completeMessageResponse_MessageWithRequest_RPCNotComplete()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final AtomicInteger completionCalled = new AtomicInteger();
final int requestId = request.getRequestId();
final RequestEntry entry = request.getEntry();
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( requestId, null, null, null, null );
response.recordChangeSet( changeSet, entry );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( entry.haveResultsArrived() );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), entry );
connector.completeMessageResponse();
assertTrue( entry.haveResultsArrived() );
assertNull( connection.getCurrentMessageResponse() );
assertEquals( completionCalled.get(), 0 );
assertNull( connection.getRequest( requestId ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
} );
}
@SuppressWarnings( { "ResultOfMethodCallIgnored", "unchecked" } )
@Test
public void progressResponseProcessing()
{
/*
* This test steps through each stage of a message processing.
*/
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData =
"{" +
// Add Channel 0
"\"channels\": [ \"+0\" ], " +
// Add Entity 1 of type 0 from channel 0
"\"changes\": [{\"id\": 1,\"type\":0,\"channels\":[\"0\"], \"data\":{}}] " +
"}";
connection.enqueueResponse( rawJsonData );
final ChangeSetParser.Parser parser = mock( ChangeSetParser.Parser.class );
when( parser.parseChangeSet( rawJsonData ) )
.thenReturn( ChangeSet.create( null,
null,
new String[]{ "+0" },
null,
new EntityChange[]{ EntityChange.create( 0,
1,
new String[]{ "0" },
new EntityChangeDataImpl() ) } ) );
getProxyParser().setParser( parser );
final MessageResponse response = connection.getUnparsedResponses().get( 0 );
{
assertNull( connection.getCurrentMessageResponse() );
assertEquals( connection.getUnparsedResponses().size(), 1 );
// Select response
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), response );
assertEquals( connection.getUnparsedResponses().size(), 0 );
}
{
assertEquals( response.getRawJsonData(), rawJsonData );
assertThrows( response::getChangeSet );
assertTrue( response.needsParsing() );
assertEquals( connection.getPendingResponses().size(), 0 );
// Parse response
assertTrue( connector.progressResponseProcessing() );
assertNull( response.getRawJsonData() );
assertNotNull( response.getChangeSet() );
assertFalse( response.needsParsing() );
}
{
assertNull( connection.getCurrentMessageResponse() );
assertEquals( connection.getPendingResponses().size(), 1 );
// Pickup parsed response and set it as current
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), response );
assertEquals( connection.getPendingResponses().size(), 0 );
}
{
assertTrue( response.needsChannelChangesProcessed() );
// Process Channel Changes in response
assertTrue( connector.progressResponseProcessing() );
assertFalse( response.needsChannelChangesProcessed() );
}
{
assertTrue( response.areEntityChangesPending() );
when( creator.createEntity( anyInt(), any( EntityChangeData.class ) ) ).thenReturn( mock( Linkable.class ) );
// Process Entity Changes in response
assertTrue( connector.progressResponseProcessing() );
assertFalse( response.areEntityChangesPending() );
}
{
assertTrue( response.areEntityLinksPending() );
// Process Entity Links in response
assertTrue( connector.progressResponseProcessing() );
assertFalse( response.areEntityLinksPending() );
}
{
assertFalse( response.hasWorldBeenValidated() );
// Validate World
assertTrue( connector.progressResponseProcessing() );
assertTrue( response.hasWorldBeenValidated() );
}
{
assertEquals( connection.getCurrentMessageResponse(), response );
// Complete message
assertTrue( connector.progressResponseProcessing() );
assertNull( connection.getCurrentMessageResponse() );
}
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 4 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
isNull( String.class ),
isNull( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess_CachedValueNotInLocalCache()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
connection.injectCurrentAreaOfInterestRequest( request );
Replicant.context().setCacheService( new TestCacheService() );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 4 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
isNull( String.class ),
isNull( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess_CachedValueInLocalCache()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connector.pauseMessageScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestCacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final String eTag = "";
cacheService.store( address.getCacheKey(), eTag, ValueUtil.randomString() );
final AtomicReference<SafeProcedure> onCacheValid = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
assertEquals( i.getArguments()[ 2 ], eTag );
assertNotNull( i.getArguments()[ 3 ] );
onCacheValid.set( (SafeProcedure) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any(),
any( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
assertFalse( connector.isSchedulerActive() );
assertEquals( connection.getOutOfBandResponses().size(), 0 );
onCacheValid.get().call();
assertTrue( connector.isSchedulerActive() );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertEquals( connection.getOutOfBandResponses().size(), 1 );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 5 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
isNull( String.class ),
isNull( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestAddRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
assertTrue( addresses.contains( address3 ) );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestAddRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
assertTrue( addresses.contains( address3 ) );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 5 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address1 ),
eq( filter ),
isNull( String.class ),
isNull( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestAddRequests( requests );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connector.pauseMessageScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 4 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 4 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
isNull( String.class ),
isNull( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestUpdateRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 5 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
isNull( String.class ),
isNull( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestUpdateRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestUpdateRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
assertTrue( addresses.contains( address3 ) );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestUpdateRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
assertTrue( addresses.contains( address3 ) );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ), eq( filter ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 5 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address1 ),
eq( filter ),
isNull( String.class ),
isNull( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestUpdateRequests( requests );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
handler.assertEventCount( 4 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestRemoveRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertFalse( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestRemoveRequest( request );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertFalse( subscription.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestRemoveRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
assertTrue( addresses.contains( address3 ) );
onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertFalse( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertFalse( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertFalse( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestRemoveRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
assertTrue( addresses.contains( address3 ) );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertFalse( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertFalse( subscription2.isExplicitSubscription() ) );
safeAction( () -> assertFalse( subscription3.isExplicitSubscription() ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address1 ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertFalse( subscription1.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestRemoveRequests( requests );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertTrue( addresses.contains( address1 ) );
assertTrue( addresses.contains( address2 ) );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( callCount.get(), 1 );
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertTrue( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertTrue( subscription2.isExplicitSubscription() ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
safeAction( () -> assertFalse( subscription1.isExplicitSubscription() ) );
safeAction( () -> assertFalse( subscription2.isExplicitSubscription() ) );
handler.assertEventCount( 4 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Noop()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
pauseScheduler();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestRequestProcessing();
assertTrue( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_InProgress()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
request1.markAsInProgress();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestRequestProcessing();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Add()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestRequestProcessing();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Update()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestRequestProcessing();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Remove()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
connector.progressAreaOfInterestRequestProcessing();
assertFalse( connection.getCurrentAreaOfInterestRequests().isEmpty() );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@Test
public void pauseMessageScheduler()
{
final Connector connector = createConnector();
newConnection( connector );
connector.pauseMessageScheduler();
assertTrue( connector.isSchedulerPaused() );
assertFalse( connector.isSchedulerActive() );
connector.requestSubscribe( new ChannelAddress( 1, 0, 1 ), null );
assertTrue( connector.isSchedulerActive() );
connector.resumeMessageScheduler();
assertFalse( connector.isSchedulerPaused() );
assertFalse( connector.isSchedulerActive() );
connector.pauseMessageScheduler();
assertTrue( connector.isSchedulerPaused() );
assertFalse( connector.isSchedulerActive() );
// No progress
assertFalse( connector.progressMessages() );
Disposable.dispose( connector );
assertFalse( connector.isSchedulerActive() );
assertTrue( connector.isSchedulerPaused() );
assertNull( connector.getSchedulerLock() );
}
@Test
public void isSynchronized_notConnected()
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.DISCONNECTED ) );
assertFalse( connector.isSynchronized() );
}
@Test
public void isSynchronized_connected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> assertTrue( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_sentRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedRequestResponse_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_sentSyncRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( true ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponse_Synced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> assertTrue( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponseButResponsesQueued_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( false ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponseErrored_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( true ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void shouldRequestSync_notConnected()
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.DISCONNECTED ) );
assertFalse( connector.shouldRequestSync() );
}
@Test
public void shouldRequestSync_connected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_sentRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedRequestResponse_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_sentSyncRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( true ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponse_Synced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponseButResponsesQueued_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( false ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponseErrored_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( true ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
}
@Test
public void onInSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
connector.onInSync();
safeAction( () -> assertFalse( connector.isSyncInFlight() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( InSyncEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onOutOfSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
connector.onOutOfSync();
safeAction( () -> assertFalse( connector.isSyncInFlight() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( OutOfSyncEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onSyncError()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
final Throwable error = new Throwable();
connector.onSyncError( error );
safeAction( () -> assertFalse( connector.isSyncInFlight() ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SyncFailureEvent.class,
e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void requestSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> assertFalse( connector.isSyncInFlight() ) );
connector.requestSync();
safeAction( () -> assertTrue( connector.isSyncInFlight() ) );
verify( connector.getTransport() ).requestSync( any( SafeProcedure.class ),
any( SafeProcedure.class ),
(Consumer<Throwable>) any( Consumer.class ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SyncRequestEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void maybeRequestSync()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
connector.maybeRequestSync();
safeAction( () -> assertFalse( connector.isSyncInFlight() ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
connector.maybeRequestSync();
safeAction( () -> assertTrue( connector.isSyncInFlight() ) );
}
}
|
package net.mm2d.upnp;
import net.mm2d.util.TestUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(Enclosed.class)
public class ServiceTest {
@RunWith(JUnit4.class)
public static class Builder {
@Test
public void build_() throws Exception {
final Service service = new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
assertThat(service, is(notNullValue()));
}
@Test(expected = IllegalStateException.class)
public void build_Device() throws Exception {
new ServiceImpl.Builder()
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
}
@Test(expected = IllegalStateException.class)
public void build_SubscribeManager() throws Exception {
new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
}
@Test(expected = IllegalStateException.class)
public void build_ServiceType() throws Exception {
new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
}
@Test(expected = IllegalStateException.class)
public void build_ServiceId() throws Exception {
new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
}
@Test(expected = IllegalStateException.class)
public void build_ScpdUrl() throws Exception {
new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
}
@Test(expected = IllegalStateException.class)
public void build_ControlUrl() throws Exception {
new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
}
@Test(expected = IllegalStateException.class)
public void build_EventSubUrl() throws Exception {
new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setDescription("description")
.build();
}
@Test(expected = IllegalStateException.class)
public void build_argumentRelatedStateVariableName() throws Exception {
final ActionImpl.Builder actionBuilder = new ActionImpl.Builder()
.setName("action")
.addArgumentBuilder(new ArgumentImpl.Builder()
.setName("argumentName")
.setDirection("in"));
final Service service = new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.addActionBuilder(actionBuilder)
.build();
assertThat(service, is(notNullValue()));
}
@Test(expected = IllegalStateException.class)
public void build_argumentRelatedStateVariableNameStateVariable() throws Exception {
final ActionImpl.Builder actionBuilder = new ActionImpl.Builder()
.setName("action")
.addArgumentBuilder(new ArgumentImpl.Builder()
.setName("argumentName")
.setDirection("in")
.setRelatedStateVariableName("StateVariableName"));
final Service service = new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.addActionBuilder(actionBuilder)
.build();
assertThat(service, is(notNullValue()));
}
@Test
public void getCallback() throws Exception {
final ControlPoint cp = mock(ControlPoint.class);
final SubscribeManager manager = mock(SubscribeManager.class);
final SsdpMessage message = mock(SsdpMessage.class);
doReturn("location").when(message).getLocation();
doReturn("uuid").when(message).getUuid();
final Device device = new DeviceImpl.Builder(cp, manager, message)
.setDescription("description")
.setUdn("uuid")
.setUpc("upc")
.setDeviceType("deviceType")
.setFriendlyName("friendlyName")
.setManufacture("manufacture")
.setModelName("modelName")
.build();
final Service service = new ServiceImpl.Builder()
.setDevice(device)
.setSubscribeManager(manager)
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
doReturn(TestUtils.createInterfaceAddress("192.168.0.1", "255.255.255.0", 24))
.when(message).getInterfaceAddress();
doReturn(80).when(manager).getEventPort();
assertThat(((ServiceImpl) service).getCallback(), is("<http://192.168.0.1/>"));
doReturn(8080).when(manager).getEventPort();
assertThat(((ServiceImpl) service).getCallback(), is("<http://192.168.0.1:8080/>"));
}
@Test
public void hashCode_Exception() throws Exception {
final Service service = new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
service.hashCode();
}
@Test
public void equals_() throws Exception {
final Service service = new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
assertThat(service.equals(null), is(false));
assertThat(service.equals(""), is(false));
assertThat(service.equals(service), is(true));
}
@Test
public void equals_() throws Exception {
final SubscribeManager manager = mock(SubscribeManager.class);
final SsdpMessage message = mock(SsdpMessage.class);
doReturn("location").when(message).getLocation();
doReturn("uuid").when(message).getUuid();
final Device device = new DeviceImpl.Builder(mock(ControlPoint.class), manager, message)
.setDescription("description")
.setUdn("uuid")
.setUpc("upc")
.setDeviceType("deviceType")
.setFriendlyName("friendlyName")
.setManufacture("manufacture")
.setModelName("modelName")
.build();
final Service service1 = new ServiceImpl.Builder()
.setDevice(device)
.setSubscribeManager(manager)
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
final Service service2 = new ServiceImpl.Builder()
.setDevice(device)
.setSubscribeManager(manager)
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
assertThat(service1.equals(service2), is(true));
}
@Test
public void equals_() throws Exception {
final SubscribeManager manager = mock(SubscribeManager.class);
final SsdpMessage message = mock(SsdpMessage.class);
doReturn("location").when(message).getLocation();
doReturn("uuid").when(message).getUuid();
final Device device = new DeviceImpl.Builder(mock(ControlPoint.class), manager, message)
.setDescription("description")
.setUdn("uuid")
.setUpc("upc")
.setDeviceType("deviceType")
.setFriendlyName("friendlyName")
.setManufacture("manufacture")
.setModelName("modelName")
.build();
final Service service1 = new ServiceImpl.Builder()
.setDevice(device)
.setSubscribeManager(manager)
.setServiceType("serviceType1")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl1")
.setControlUrl("controlUrl1")
.setEventSubUrl("eventSubUrl1")
.setDescription("description1")
.build();
final Service service2 = new ServiceImpl.Builder()
.setDevice(device)
.setSubscribeManager(manager)
.setServiceType("serviceType2")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl2")
.setControlUrl("controlUrl2")
.setEventSubUrl("eventSubUrl2")
.setDescription("description2")
.build();
assertThat(service1.equals(service2), is(true));
}
@Test
public void equals_ServiceId() throws Exception {
final SubscribeManager manager = mock(SubscribeManager.class);
final SsdpMessage message = mock(SsdpMessage.class);
doReturn("location").when(message).getLocation();
doReturn("uuid").when(message).getUuid();
final Device device = new DeviceImpl.Builder(mock(ControlPoint.class), manager, message)
.setDescription("description")
.setUdn("uuid")
.setUpc("upc")
.setDeviceType("deviceType")
.setFriendlyName("friendlyName")
.setManufacture("manufacture")
.setModelName("modelName")
.build();
final Service service1 = new ServiceImpl.Builder()
.setDevice(device)
.setSubscribeManager(manager)
.setServiceType("serviceType")
.setServiceId("serviceId1")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
final Service service2 = new ServiceImpl.Builder()
.setDevice(device)
.setSubscribeManager(manager)
.setServiceType("serviceType")
.setServiceId("serviceId2")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
assertThat(service1.equals(service2), is(false));
}
@Test
public void equals_device() throws Exception {
final SubscribeManager manager = mock(SubscribeManager.class);
final SsdpMessage message1 = mock(SsdpMessage.class);
doReturn("location").when(message1).getLocation();
doReturn("uuid1").when(message1).getUuid();
final Device device1 = new DeviceImpl.Builder(mock(ControlPoint.class), manager, message1)
.setDescription("description")
.setUdn("uuid1")
.setUpc("upc")
.setDeviceType("deviceType")
.setFriendlyName("friendlyName")
.setManufacture("manufacture")
.setModelName("modelName")
.build();
final SsdpMessage message2 = mock(SsdpMessage.class);
doReturn("location").when(message2).getLocation();
doReturn("uuid2").when(message2).getUuid();
final Device device2 = new DeviceImpl.Builder(mock(ControlPoint.class), manager, message2)
.setDescription("description")
.setUdn("uuid2")
.setUpc("upc")
.setDeviceType("deviceType")
.setFriendlyName("friendlyName")
.setManufacture("manufacture")
.setModelName("modelName")
.build();
final Service service1 = new ServiceImpl.Builder()
.setDevice(device1)
.setSubscribeManager(manager)
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
final Service service2 = new ServiceImpl.Builder()
.setDevice(device2)
.setSubscribeManager(manager)
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
assertThat(service1.equals(service2), is(false));
}
@Test
public void createHttpClient() throws Exception {
final Service service = new ServiceImpl.Builder()
.setDevice(mock(Device.class))
.setSubscribeManager(mock(SubscribeManager.class))
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build();
final HttpClient client = ((ServiceImpl) service).createHttpClient();
assertThat(client.isKeepAlive(), is(false));
}
}
@RunWith(JUnit4.class)
public static class DeviceParser {
private static final String SID = "11234567-89ab-cdef-0123-456789abcdef";
private static final String INTERFACE_ADDRESS = "192.0.2.3";
private static final int EVENT_PORT = 100;
private ControlPoint mControlPoint;
private SubscribeManager mSubscribeManager;
private Device mDevice;
private ServiceImpl mCms;
private ServiceImpl mCds;
private ServiceImpl mMmupnp;
@Before
public void setUp() throws Exception {
final HttpClient httpClient = mock(HttpClient.class);
doReturn(TestUtils.getResourceAsString("device.xml"))
.when(httpClient).downloadString(new URL("http://192.0.2.2:12345/device.xml"));
doReturn(TestUtils.getResourceAsString("cds.xml"))
.when(httpClient).downloadString(new URL("http://192.0.2.2:12345/cds.xml"));
doReturn(TestUtils.getResourceAsString("cms.xml"))
.when(httpClient).downloadString(new URL("http://192.0.2.2:12345/cms.xml"));
doReturn(TestUtils.getResourceAsString("mmupnp.xml"))
.when(httpClient).downloadString(new URL("http://192.0.2.2:12345/mmupnp.xml"));
doReturn(TestUtils.getResourceAsByteArray("icon/icon120.jpg"))
.when(httpClient).downloadBinary(new URL("http://192.0.2.2:12345/icon/icon120.jpg"));
doReturn(TestUtils.getResourceAsByteArray("icon/icon48.jpg"))
.when(httpClient).downloadBinary(new URL("http://192.0.2.2:12345/icon/icon48.jpg"));
doReturn(TestUtils.getResourceAsByteArray("icon/icon120.png"))
.when(httpClient).downloadBinary(new URL("http://192.0.2.2:12345/icon/icon120.png"));
doReturn(TestUtils.getResourceAsByteArray("icon/icon48.png"))
.when(httpClient).downloadBinary(new URL("http://192.0.2.2:12345/icon/icon48.png"));
final byte[] data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin");
final InterfaceAddress interfaceAddress = mock(InterfaceAddress.class);
doReturn(InetAddress.getByName(INTERFACE_ADDRESS)).when(interfaceAddress).getAddress();
final SsdpMessage ssdpMessage = new SsdpRequest(interfaceAddress, data, data.length);
mControlPoint = mock(ControlPoint.class);
mSubscribeManager = mock(SubscribeManager.class);
doReturn(EVENT_PORT).when(mSubscribeManager).getEventPort();
final DeviceImpl.Builder builder = new DeviceImpl.Builder(mControlPoint, mSubscribeManager, ssdpMessage);
DeviceParser.loadDescription(httpClient, builder);
mDevice = builder.build();
mCms = (ServiceImpl) mDevice.findServiceById("urn:upnp-org:serviceId:ConnectionManager");
mCds = (ServiceImpl) spy(mDevice.findServiceById("urn:upnp-org:serviceId:ContentDirectory"));
mMmupnp = (ServiceImpl) mDevice.findServiceById("urn:upnp-org:serviceId:X_mmupnp");
}
@Test
public void getDevice() throws Exception {
assertThat(mCms.getDevice(), is(mDevice));
}
@Test
public void getAbsoluteUrl_device() throws Exception {
final String url = "test";
assertThat(mCms.getAbsoluteUrl(url), is(mDevice.getAbsoluteUrl(url)));
}
@Test
public void getServiceType() throws Exception {
assertThat(mCms.getServiceType(), is("urn:schemas-upnp-org:service:ConnectionManager:1"));
assertThat(mCds.getServiceType(), is("urn:schemas-upnp-org:service:ContentDirectory:1"));
assertThat(mMmupnp.getServiceType(), is("urn:schemas-mm2d-net:service:X_mmupnp:1"));
}
@Test
public void getServiceId() throws Exception {
assertThat(mCms.getServiceId(), is("urn:upnp-org:serviceId:ConnectionManager"));
assertThat(mCds.getServiceId(), is("urn:upnp-org:serviceId:ContentDirectory"));
assertThat(mMmupnp.getServiceId(), is("urn:upnp-org:serviceId:X_mmupnp"));
}
@Test
public void getScpdUrl() throws Exception {
assertThat(mCms.getScpdUrl(), is("/cms.xml"));
assertThat(mCds.getScpdUrl(), is("/cds.xml"));
assertThat(mMmupnp.getScpdUrl(), is("/mmupnp.xml"));
}
@Test
public void getControlUrl() throws Exception {
assertThat(mCms.getControlUrl(), is("/cms/control"));
assertThat(mCds.getControlUrl(), is("/cds/control"));
assertThat(mMmupnp.getControlUrl(), is("/mmupnp/control"));
}
@Test
public void getEventSubUrl() throws Exception {
assertThat(mCms.getEventSubUrl(), is("/cms/event"));
assertThat(mCds.getEventSubUrl(), is("/cds/event"));
assertThat(mMmupnp.getEventSubUrl(), is("/mmupnp/event"));
}
@Test
public void getDescription() throws Exception {
assertThat(mCms.getDescription(), is(TestUtils.getResourceAsString("cms.xml")));
assertThat(mCds.getDescription(), is(TestUtils.getResourceAsString("cds.xml")));
assertThat(mMmupnp.getDescription(), is(TestUtils.getResourceAsString("mmupnp.xml")));
}
@Test
public void getActionList() throws Exception {
assertThat(mCms.getActionList(), hasSize(3));
assertThat(mCds.getActionList(), hasSize(4));
assertThat(mMmupnp.getActionList(), hasSize(1));
assertThat(mCms.getActionList(), is(mCms.getActionList()));
}
@Test
public void findAction() throws Exception {
assertThat(mCms.findAction("Browse"), is(nullValue()));
assertThat(mCds.findAction("Browse"), is(notNullValue()));
}
@Test
public void getStateVariableList() throws Exception {
assertThat(mCds.getStateVariableList(), hasSize(11));
assertThat(mCds.getStateVariableList(), is(mCds.getStateVariableList()));
}
@Test
public void getStateVariableParam() throws Exception {
final StateVariable type = mMmupnp.findStateVariable("A_ARG_TYPE_Type");
assertThat(type.getName(), is("A_ARG_TYPE_Type"));
assertThat(type.isSendEvents(), is(false));
assertThat(type.getDataType(), is("string"));
final StateVariable value = mMmupnp.findStateVariable("A_ARG_TYPE_Value");
assertThat(value.getName(), is("A_ARG_TYPE_Value"));
assertThat(value.isSendEvents(), is(true));
assertThat(value.getDataType(), is("i4"));
assertThat(value.getDefaultValue(), is("10"));
assertThat(value.getStep(), is("1"));
assertThat(value.getMinimum(), is("0"));
assertThat(value.getMaximum(), is("100"));
}
@Test
public void findStateVariable() throws Exception {
final String name = "A_ARG_TYPE_BrowseFlag";
final StateVariable variable = mCds.findStateVariable(name);
assertThat(variable.getName(), is(name));
}
private HttpResponse createSubscribeResponse() {
return new HttpResponse()
.setStatus(Http.Status.HTTP_OK)
.setHeader(Http.SERVER, Property.SERVER_VALUE)
.setHeader(Http.DATE, Http.formatDate(System.currentTimeMillis()))
.setHeader(Http.CONNECTION, Http.CLOSE)
.setHeader(Http.SID, SID)
.setHeader(Http.TIMEOUT, "Second-300")
.setHeader(Http.CONTENT_LENGTH, "0");
}
@Test
public void subscribe() throws Exception {
final HttpClient client = spy(new HttpClient());
final ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
doReturn(createSubscribeResponse()).when(client).post(captor.capture());
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe();
final HttpRequest request = captor.getValue();
assertThat(request.getUri(), is(mCds.getEventSubUrl()));
verify(mSubscribeManager).registerSubscribeService(mCds, false);
final String callback = request.getHeader(Http.CALLBACK);
assertThat(callback.charAt(0), is('<'));
assertThat(callback.charAt(callback.length() - 1), is('>'));
final URL url = new URL(callback.substring(1, callback.length() - 2));
assertThat(url.getHost(), is(INTERFACE_ADDRESS));
assertThat(url.getPort(), is(EVENT_PORT));
System.out.println();
}
@Test
public void subscribe_keep() throws Exception {
final HttpClient client = spy(new HttpClient());
final ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
doReturn(createSubscribeResponse()).when(client).post(captor.capture());
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe(true);
final HttpRequest request = captor.getValue();
assertThat(request.getUri(), is(mCds.getEventSubUrl()));
verify(mSubscribeManager).registerSubscribeService(mCds, true);
}
@Test
public void renewSubscribe1() throws Exception {
final HttpClient client = spy(new HttpClient());
final ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
doReturn(createSubscribeResponse()).when(client).post(captor.capture());
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe();
mCds.renewSubscribe();
final HttpRequest request = captor.getValue();
assertThat(request.getUri(), is(mCds.getEventSubUrl()));
}
@Test
public void renewSubscribe2() throws Exception {
final HttpClient client = spy(new HttpClient());
final ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
doReturn(createSubscribeResponse()).when(client).post(captor.capture());
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe();
mCds.subscribe();
final HttpRequest request = captor.getValue();
assertThat(request.getUri(), is(mCds.getEventSubUrl()));
}
@Test
public void unsubscribe() throws Exception {
final HttpClient client = spy(new HttpClient());
final ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
doReturn(createSubscribeResponse()).when(client).post(captor.capture());
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe();
mCds.unsubscribe();
final HttpRequest request = captor.getValue();
assertThat(request.getUri(), is(mCds.getEventSubUrl()));
verify(mSubscribeManager).unregisterSubscribeService(mCds);
}
@Test
public void expired() throws Exception {
final HttpClient client = mock(HttpClient.class);
doReturn(createSubscribeResponse()).when(client).post(ArgumentMatchers.any(HttpRequest.class));
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe();
mCds.expired();
assertThat(mCds.getSubscriptionId(), is(nullValue()));
assertThat(mCds.getSubscriptionExpiryTime(), is(0L));
assertThat(mCds.getSubscriptionStart(), is(0L));
assertThat(mCds.getSubscriptionTimeout(), is(0L));
}
@Test
public void getSubscriptionId() throws Exception {
final HttpClient client = mock(HttpClient.class);
doReturn(createSubscribeResponse()).when(client).post(ArgumentMatchers.any(HttpRequest.class));
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe();
assertThat(mCds.getSubscriptionId(), is(SID));
}
@Test
public void getSubscriptionStart() throws Exception {
final HttpClient client = mock(HttpClient.class);
doReturn(createSubscribeResponse()).when(client).post(ArgumentMatchers.any(HttpRequest.class));
doReturn(client).when(mCds).createHttpClient();
final long before = System.currentTimeMillis();
mCds.subscribe();
final long after = System.currentTimeMillis();
assertThat(mCds.getSubscriptionStart(), greaterThanOrEqualTo(before));
assertThat(mCds.getSubscriptionStart(), lessThanOrEqualTo(after));
}
@Test
public void getSubscriptionTimeout() throws Exception {
final HttpClient client = mock(HttpClient.class);
doReturn(createSubscribeResponse()).when(client).post(ArgumentMatchers.any(HttpRequest.class));
doReturn(client).when(mCds).createHttpClient();
mCds.subscribe();
assertThat(mCds.getSubscriptionTimeout(), is(TimeUnit.SECONDS.toMillis(300L)));
}
@Test
public void getSubscriptionExpiryTime() throws Exception {
final HttpClient client = mock(HttpClient.class);
doReturn(createSubscribeResponse()).when(client).post(ArgumentMatchers.any(HttpRequest.class));
doReturn(client).when(mCds).createHttpClient();
final long before = System.currentTimeMillis();
mCds.subscribe();
final long after = System.currentTimeMillis();
assertThat(mCds.getSubscriptionExpiryTime(),
greaterThanOrEqualTo(before + TimeUnit.SECONDS.toMillis(300L)));
assertThat(mCds.getSubscriptionExpiryTime(),
lessThanOrEqualTo(after + TimeUnit.SECONDS.toMillis(300L)));
}
}
@RunWith(JUnit4.class)
public static class subscribe_ {
private static final long DEFAULT_SUBSCRIPTION_TIMEOUT = TimeUnit.SECONDS.toMillis(300);
@Test
public void parseTimeout_() {
final HttpResponse response = new HttpResponse();
response.setStatusLine("HTTP/1.1 200 OK");
assertThat(ServiceImpl.parseTimeout(response), is(DEFAULT_SUBSCRIPTION_TIMEOUT));
}
@Test
public void parseTimeout_infinite() {
final HttpResponse response = new HttpResponse();
response.setStatusLine("HTTP/1.1 200 OK");
response.setHeader(Http.TIMEOUT, "infinite");
assertThat(ServiceImpl.parseTimeout(response), is(DEFAULT_SUBSCRIPTION_TIMEOUT));
}
@Test
public void parseTimeout_second() {
final HttpResponse response = new HttpResponse();
response.setStatusLine("HTTP/1.1 200 OK");
response.setHeader(Http.TIMEOUT, "second-100");
assertThat(ServiceImpl.parseTimeout(response), is(TimeUnit.SECONDS.toMillis(100)));
}
@Test
public void parseTimeout_() {
final HttpResponse response = new HttpResponse();
response.setStatusLine("HTTP/1.1 200 OK");
response.setHeader(Http.TIMEOUT, "seconds-100");
assertThat(ServiceImpl.parseTimeout(response), is(DEFAULT_SUBSCRIPTION_TIMEOUT));
response.setHeader(Http.TIMEOUT, "second-ff");
assertThat(ServiceImpl.parseTimeout(response), is(DEFAULT_SUBSCRIPTION_TIMEOUT));
}
}
@RunWith(JUnit4.class)
public static class subscribe_ {
private ControlPoint mControlPoint;
private Device mDevice;
private SubscribeManager mSubscribeManager;
private ServiceImpl mService;
private HttpClient mHttpClient;
@Before
public void setUp() throws Exception {
mControlPoint = mock(ControlPoint.class);
mDevice = mock(Device.class);
mSubscribeManager = mock(SubscribeManager.class);
doReturn(mControlPoint).when(mDevice).getControlPoint();
doReturn(new URL("http://192.0.2.2/")).when(mDevice).getAbsoluteUrl(anyString());
mService = (ServiceImpl) spy(new ServiceImpl.Builder()
.setDevice(mDevice)
.setSubscribeManager(mSubscribeManager)
.setServiceType("serviceType")
.setServiceId("serviceId")
.setScpdUrl("scpdUrl")
.setControlUrl("controlUrl")
.setEventSubUrl("eventSubUrl")
.setDescription("description")
.build());
doReturn("").when(mService).getCallback();
mHttpClient = mock(HttpClient.class);
doReturn(mHttpClient).when(mService).createHttpClient();
}
@Test
public void subscribe_() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.subscribe(), is(true));
}
@Test
public void subscribe_SID() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.subscribe(), is(false));
}
@Test
public void subscribe_Timeout() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-0");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.subscribe(), is(false));
}
@Test
public void subscribe_Http() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_INTERNAL_ERROR);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.subscribe(), is(false));
}
@Test
public void subscribe_2renewfalse() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.subscribe(), is(true));
doReturn(false).when(mService).renewSubscribeInner();
assertThat(mService.subscribe(), is(false));
verify(mService, times(1)).renewSubscribeInner();
}
@Test
public void renewSubscribe_subscribesubscribe() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.renewSubscribe(), is(true));
verify(mService, times(1)).subscribeInner(anyBoolean());
}
@Test
public void renewSubscribe_2renew() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.renewSubscribe(), is(true));
verify(mService, times(1)).subscribeInner(anyBoolean());
assertThat(mService.renewSubscribe(), is(true));
verify(mService, times(1)).renewSubscribeInner();
}
@Test
public void renewSubscribe_renew() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.renewSubscribe(), is(true));
response.setStatus(Http.Status.HTTP_INTERNAL_ERROR);
assertThat(mService.renewSubscribe(), is(false));
}
@Test
public void renewSubscribe_sid() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.renewSubscribe(), is(true));
response.setHeader(Http.SID, "sid2");
assertThat(mService.renewSubscribe(), is(false));
}
@Test
public void renewSubscribe_Timeout() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.renewSubscribe(), is(true));
response.setHeader(Http.TIMEOUT, "second-0");
assertThat(mService.renewSubscribe(), is(false));
}
@Test
public void unsubscribe_subscribe() throws Exception {
assertThat(mService.unsubscribe(), is(false));
}
@Test
public void unsubscribe_() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.subscribe(), is(true));
assertThat(mService.unsubscribe(), is(true));
}
@Test
public void unsubscribe_OK() throws Exception {
final HttpResponse response = new HttpResponse();
response.setStatus(Http.Status.HTTP_OK);
response.setHeader(Http.SID, "sid");
response.setHeader(Http.TIMEOUT, "second-300");
doReturn(response).when(mHttpClient).post(ArgumentMatchers.any(HttpRequest.class));
assertThat(mService.subscribe(), is(true));
response.setStatus(Http.Status.HTTP_INTERNAL_ERROR);
assertThat(mService.unsubscribe(), is(false));
}
}
}
|
package com.yox89.ld32.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.utils.Align;
import com.yox89.ld32.Gajm;
import com.yox89.ld32.Physics;
import com.yox89.ld32.actors.Torch;
import com.yox89.ld32.util.Assets;
import com.yox89.ld32.util.PhysicsUtil;
import com.yox89.ld32.util.PhysicsUtil.BodyParams;
public class StartScreen extends BaseScreen {
private Stage game;
private Gajm gajm;
public StartScreen(Gajm gajm) {
this.gajm = gajm;
}
@Override
protected void init(Stage game, Stage ui, Physics physics) {
this.game = game;
final Texture img = manage(new Texture("StartButtonEng.png"));
img.setFilter(TextureFilter.Linear, TextureFilter.Linear);
final StartGameButtonActor startBtn = new StartGameButtonActor(img,
physics.world,
Math.min(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT) / 5f);
game.addActor(startBtn);
startBtn.setPosition(GAME_WORLD_WIDTH / 2 - startBtn.getWidth() / 2,
GAME_WORLD_HEIGHT / 2);
final Vector2 startPos = new Vector2(startBtn.getX()
+ startBtn.getWidth() / 2, startBtn.getY());
game.stageToScreenCoordinates(startPos);
ui.screenToStageCoordinates(startPos);
final float BTN_SIDE = 48f;
final float PADDING = .2f * BTN_SIDE;
for (int i = 0; i < 10; i++) {
final Vector2 pos = new Vector2(startPos.x, startPos.y - 1.5f
* BTN_SIDE);
pos.x += (PADDING + BTN_SIDE) * ((i % 5) - 2.5);
pos.y -= (PADDING + BTN_SIDE) * (i / 5);
final LevelJumpButton skip = new LevelJumpButton(i + 1);
skip.setPosition(pos.x + PADDING / 2, pos.y + PADDING / 2);
skip.setSize(BTN_SIDE, BTN_SIDE);
ui.addActor(skip);
}
final HelpButton howToPlay = new HelpButton();
howToPlay.setSize(3 * BTN_SIDE, BTN_SIDE);
howToPlay.setPosition(Gdx.graphics.getWidth() * 7 / 8,
Gdx.graphics.getHeight() / 10f, Align.center);
ui.addActor(howToPlay);
PhysicsUtil.createBody(new BodyParams(physics.world) {
@Override
public void setShape(PolygonShape ps) {
ps.setAsBox(startBtn.getWidth() / 2, startBtn.getHeight() / 2f);
}
}).setTransform(startBtn.getX() + startBtn.getWidth() / 2,
startBtn.getY() + startBtn.getHeight() / 2, 0f);
Torch startBtnTorch = new Torch(physics, Color.MAGENTA, 0, false);
startBtnTorch.setPosition(startBtn.getX() + startBtn.getWidth() / 2f,
startBtn.getY() + startBtn.getHeight() / 2);
game.addActor(startBtnTorch);
Torch torchUpCorner = new Torch(physics, 0);
torchUpCorner.setPosition(GAME_WORLD_WIDTH - 1, GAME_WORLD_HEIGHT - 1);
game.addActor(new Torch(physics, 270));
game.addActor(torchUpCorner);
final float ghostSize = Math.min(Gdx.graphics.getWidth() / 4,
Gdx.graphics.getHeight() / 4);
final Actor rightGhost = new Ghost(ghostSize, false);
rightGhost.setPosition(Gdx.graphics.getWidth() * 9f / 10f - ghostSize,
Gdx.graphics.getHeight() / 2f);
final Actor leftGhost = new Ghost(ghostSize, true);
leftGhost.setPosition(Gdx.graphics.getWidth() / 10f,
Gdx.graphics.getHeight() / 2f);
final Label titleLbl = new Label("Ghosts in the pants", new LabelStyle(
manage(new BitmapFont()), Color.CYAN));
titleLbl.setPosition(
Gdx.graphics.getWidth() / 2 - titleLbl.getMinWidth(),
Gdx.graphics.getHeight() * 0.75f);
titleLbl.setFontScale(2f);
final Label copyLbl = new Label(
"Made by: Kevlanche, Jonathan Hagberg, "
+ "\nAdam Nilsson & Marie Versland for LD32 in 48 hours",
new LabelStyle(manage(new BitmapFont()), Color.CYAN));
copyLbl.setAlignment(Align.center);
copyLbl.setFontScale(0.9f);
copyLbl.setPosition((Gdx.graphics.getWidth() - copyLbl.getMinWidth()
/ copyLbl.getFontScaleX()) / 2, 30);
ui.addActor(rightGhost);
ui.addActor(leftGhost);
ui.addActor(new MuteButton());
ui.addActor(titleLbl);
ui.addActor(copyLbl);
}
private class Ghost extends Actor {
private final Texture mTexture;
private final float mSize;
private final boolean mFlipHorizontal;
public Ghost(float size, boolean flipHorizontal) {
mTexture = manage(new Texture("story_ghost.png"));
mTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
mSize = size;
mFlipHorizontal = flipHorizontal;
float deltaX = mFlipHorizontal ? mSize / 5f : -mSize / 5f;
addAction(Actions.forever(Actions.sequence(Actions.moveBy(
deltaX, 0f, 1.0f, Interpolation.swing), Actions
.moveBy(-deltaX, 0f, 1.0f, Interpolation.swing))));
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.setColor(getColor());
batch.draw(mTexture, getX(), getY(), mSize, mSize, 0, 0,
mTexture.getWidth(), mTexture.getHeight(), mFlipHorizontal,
false);
}
}
private class StartGameButtonActor extends Actor {
private final Texture mTexture;
public StartGameButtonActor(Texture tex, World world, final float size) {
mTexture = tex;
setSize(size * 2, size);
addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button) {
switchScreen(new Runnable() {
@Override
public void run() {
gajm.setScreen(new TiledLevelScreen(gajm, 1));
}
});
return true;
};
@Override
public void enter(InputEvent event, float x, float y,
int pointer, Actor fromActor) {
setColor(Color.WHITE);
super.enter(event, x, y, pointer, fromActor);
}
@Override
public void exit(InputEvent event, float x, float y,
int pointer, Actor toActor) {
setColor(Color.LIGHT_GRAY);
super.exit(event, x, y, pointer, toActor);
}
});
setColor(Color.LIGHT_GRAY);
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.setColor(getColor());
batch.draw(mTexture, getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(),
getRotation(), 0, 0, mTexture.getWidth(),
mTexture.getHeight(), false, false);
}
}
private class MuteButton extends Actor {
public MuteButton() {
final float size = Math.min(Gdx.graphics.getWidth(),
Gdx.graphics.getHeight()) / 8f;
setSize(size, size);
setY(Gdx.graphics.getHeight() - getHeight());
addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button) {
Assets.setSoundEnabled(!Assets.isSoundEnabled());
return true;
};
@Override
public void enter(InputEvent event, float x, float y,
int pointer, Actor fromActor) {
setColor(Color.WHITE);
super.enter(event, x, y, pointer, fromActor);
}
@Override
public void exit(InputEvent event, float x, float y,
int pointer, Actor toActor) {
setColor(Color.LIGHT_GRAY);
super.exit(event, x, y, pointer, toActor);
}
});
setColor(Color.LIGHT_GRAY);
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.enableBlending();
batch.setColor(getColor());
final Texture tex = Assets.isSoundEnabled() ? Assets.sound_on
: Assets.sound_off;
batch.draw(tex, getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(),
getRotation(), 0, 0, tex.getWidth(), tex.getHeight(),
false, false);
}
}
private class LevelJumpButton extends Label {
public LevelJumpButton(final int levelId) {
super(String.valueOf(levelId), new LabelStyle(
manage(new BitmapFont()), Color.WHITE));
setAlignment(Align.center);
final boolean enabled = Gajm.maxClearedLevel >= levelId - 1;
if (!enabled) {
setColor(Color.DARK_GRAY);
} else {
addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x,
float y, int pointer, int button) {
switchScreen(new Runnable() {
@Override
public void run() {
gajm.setScreen(new TiledLevelScreen(gajm,
levelId));
}
});
return true;
};
@Override
public void enter(InputEvent event, float x, float y,
int pointer, Actor fromActor) {
setColor(Color.WHITE);
super.enter(event, x, y, pointer, fromActor);
}
@Override
public void exit(InputEvent event, float x, float y,
int pointer, Actor toActor) {
setColor(Color.LIGHT_GRAY);
super.exit(event, x, y, pointer, toActor);
}
});
setColor(Color.LIGHT_GRAY);
}
}
@Override
public void draw(Batch batch, float parentAlpha) {
if (Gajm.maxClearedLevel < 0) {
return;
}
batch.enableBlending();
batch.setColor(getColor());
final Texture tex = Assets.skipLevelButton;
batch.draw(tex, getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(),
getRotation(), 0, 0, tex.getWidth(), tex.getHeight(),
false, false);
super.draw(batch, parentAlpha);
}
}
private class HelpButton extends Label {
public HelpButton() {
super("How to play", new LabelStyle(manage(new BitmapFont()),
Color.WHITE));
setAlignment(Align.center);
addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button) {
switchScreen(new Runnable() {
@Override
public void run() {
gajm.setScreen(new HowToPlayScreen(gajm));
}
});
return true;
};
@Override
public void enter(InputEvent event, float x, float y,
int pointer, Actor fromActor) {
setColor(Color.WHITE);
super.enter(event, x, y, pointer, fromActor);
}
@Override
public void exit(InputEvent event, float x, float y,
int pointer, Actor toActor) {
setColor(Color.LIGHT_GRAY);
super.exit(event, x, y, pointer, toActor);
}
});
setColor(Color.LIGHT_GRAY);
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.enableBlending();
batch.setColor(getColor());
final Texture tex = Assets.skipLevelButton;
batch.draw(tex, getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(),
getRotation(), 0, 0, tex.getWidth(), tex.getHeight(),
false, false);
super.draw(batch, parentAlpha);
}
}
}
|
// JSData.java
package ed.js;
import java.util.*;
import java.text.*;
import ed.js.func.*;
import ed.util.*;
import ed.js.engine.*;
public class JSDate extends JSObjectBase implements Comparable {
public static JSFunction _cons =
new JSFunctionCalls1(){
public JSObject newOne(){
return new JSDate();
}
public Object call( Scope s , Object foo , Object[] args ){
if ( args != null && args.length > 0 ) {
int [] myargs = new int[7];
int i;
for(i = 0; i < args.length+1; i++){
Object o = (i == 0 ? foo : args[i-1]);
if ( o instanceof JSString )
o = StringParseUtil.parseStrict(((JSString)o).toString());
if ( o instanceof Number )
myargs[i] = ((Number)o).intValue();
}
Calendar c = Calendar.getInstance();
c.set(myargs[0], myargs[1], myargs[2], myargs[3], myargs[4], myargs[5]);
c.setTimeInMillis(c.getTimeInMillis()+myargs[6]);
foo = new Long(c.getTimeInMillis());
}
Object o = s.getThis();
if ( o == null || ! ( o instanceof JSDate ) )
return new JSString( (new JSDate( foo )).toString() );
JSDate d = (JSDate)o;
long l = parse( foo , d._time );
d._time = l;
return d;
}
protected void init(){
_prototype.set( "getTime" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return ((JSDate)s.getThis())._time;
}
} );
_prototype.set( "utc" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return ((JSDate)s.getThis()).utc();
}
} );
_prototype.set( "utc_to_local" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return s.getThis();
}
} );
_prototype.set( "next_month" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSDate d = (JSDate)s.getThis();
JSDate n = new JSDate( d._time );
n.setMonth( n.getMonth() + 1 );
return n;
}
} );
_prototype.set( "last_month" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSDate d = (JSDate)s.getThis();
JSDate n = new JSDate( d._time );
n.setMonth( n.getMonth() - 1 );
return n;
}
} );
_prototype.set( "strftime" , new JSFunctionCalls1() {
public Object call( Scope s , Object f , Object foo[] ){
return ((JSDate)s.getThis()).strftime( f.toString() );
}
} );
_prototype.set( "valueOf" , new JSFunctionCalls0(){
public Object call( Scope s , Object args[] ){
return ((JSDate)s.getThis())._time;
}
} );
set( "now" , new JSFunctionCalls0(){
public Object call( Scope s, Object foo[] ){
return new JSDate();
}
} );
set( "parse" , new JSFunctionCalls1(){
public Object call( Scope s , Object when , Object foo[] ){
long t = parse( when , -1 );
if ( t < 0 )
return null;
return new JSDate( t );
}
} );
set( "DAYNAMES" , new JSArray( new JSString( "Sunday" ) ,
new JSString( "Monday" ) ,
new JSString( "Tuesday" ) ,
new JSString( "Wednesday" ) ,
new JSString( "Thursday" ) ,
new JSString( "Friday" ) ,
new JSString( "Saturday" )
)
);
set( "civil" , new JSFunctionCalls0(){
public Object call( Scope s, Object foo[] ){
// TODO: check this
return s.getThis();
}
} );
/**
* @param function the function to call
* @param numTimes number of times to call function
* @param anything else gets passed to function
*/
set( "timeFunc" , new JSFunctionCalls2(){
public Object call( Scope s , Object func , Object numTimes , Object extra[] ){
if ( ! ( func instanceof JSFunction ) )
throw new RuntimeException( "Date.timeFunc needs a function" );
if ( ! ( numTimes instanceof Number ) )
throw new RuntimeException( "Date.timeFunc needs a number" );
JSFunction f = (JSFunction)func;
final int times = ((Number)numTimes).intValue();
final long start = System.currentTimeMillis();
for ( int i=0; i<times; i++ )
f.call( s , extra );
return System.currentTimeMillis() - start;
}
}
);
}
};
static long parse( Object o ){
return parse( o , System.currentTimeMillis() );
}
static long parse( Object o , long def ){
if ( o == null )
return def;
if ( o instanceof Date )
return ((Date)o).getTime();
if ( o instanceof String || o instanceof JSString )
return parseDate( o.toString() , def );
if ( ! ( o instanceof Number ) )
return def;
return ((Number)o).longValue();
}
public static long parseDate( String s , long def ){
if ( s == null )
return def;
s = s.trim();
if ( s.length() == 0 )
return def;
for ( int i=0; i<DATE_FORMATS.length; i++ ){
try {
synchronized ( DATE_FORMATS[i] ) {
return DATE_FORMATS[i].parse( s ).getTime();
}
}
catch ( java.text.ParseException e ){
}
}
return def;
}
public JSDate(){
this( System.currentTimeMillis() );
}
public JSDate( long t ){
super( _cons );
_time = t;
}
public JSDate( Calendar c ){
this( c.getTimeInMillis() );
}
public JSDate( Object foo ){
this( parse( foo ) );
}
public long getTime(){
return _time;
}
public int getYear(){
_cal();
int y = _c.get( Calendar.YEAR );
if ( y >= 0 && y < 200 )
return 1900 + y;
return y;
}
public int getFullYear() {
_cal();
return _c.get( Calendar.YEAR );
}
public int getMonth(){
_cal();
return _c.get( Calendar.MONTH );
}
public int getDay(){
_cal();
return _c.get( Calendar.DAY_OF_WEEK );
}
public int getHours() {
_cal();
return _c.get( Calendar.HOUR_OF_DAY );
}
public int getMilliseconds() {
_cal();
return _c.get( Calendar.MILLISECOND );
}
public int getSeconds() {
_cal();
return _c.get( Calendar.SECOND );
}
public int getDate() {
_cal();
return _c.get( Calendar.DAY_OF_MONTH );
}
public int getHourOfDay(){
_cal();
return _c.get( Calendar.HOUR_OF_DAY );
}
public int minutes(){
return getMinute();
}
public int getMinutes(){
return getMinute();
}
public int getMinute(){
_cal();
return _c.get( Calendar.MINUTE );
}
public long setDate(int day) {
_cal();
_c.set( Calendar.DATE, day);
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setFullYear(int year, int month, int day) {
setMonth(month);
setDate(day);
return setFullYear(year);
}
public long setFullYear(int year, int month) {
setMonth(month);
return setFullYear(year);
}
public long setFullYear(int year) {
_cal();
_c.set( Calendar.YEAR, year );
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setHours(int hour, int min, int sec, int ms) {
setMinutes(min);
setSeconds(sec);
setMilliseconds(ms);
return setHours(hour);
}
public long setHours(int hour, int min, int sec) {
setMinutes(min);
setSeconds(sec);
return setHours(hour);
}
public long setHours(int hour, int min) {
setMinutes(min);
return setHours(hour);
}
public long setHours(int hour) {
_cal();
_c.set( Calendar.HOUR_OF_DAY, hour);
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setMilliseconds(int ms) {
_cal();
_c.set( Calendar.MILLISECOND, ms);
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setMinutes(int min, int sec, int ms) {
setSeconds(sec);
setMilliseconds(ms);
return setMinutes(min);
}
public long setMinutes(int min, int sec) {
setSeconds(sec);
return setMinutes(min);
}
public long setMinutes(int min) {
_cal();
_c.set( Calendar.MINUTE, min );
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setMonth(int month, int day) {
setDate(day);
return setMonth(month);
}
public long setMonth(int month) {
_cal();
_c.set(Calendar.MONTH, month);
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setYear(int year) {
_cal();
_c.set(Calendar.YEAR, year);
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setSeconds(int sec, int ms) {
setMilliseconds(ms);
return setSeconds(sec);
}
public long setSeconds(int sec) {
_cal();
_c.set(Calendar.SECOND, sec);
_time = _c.getTimeInMillis();
return _c.getTimeInMillis();
}
public long setTime(int ms) {
_cal();
_c.setTimeInMillis(ms);
return _time = _c.getTimeInMillis();
}
public String toString(){
String format = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z (z)";
return format(format);
// return new Date( _time ).toString();
}
public String strftime( String theFormat ){
return format( ed.util.Strftime.convertDateFormat( theFormat ) );
}
public String format( String theFormat ){
SimpleDateFormat df = new SimpleDateFormat( theFormat );
return df.format( new Date( _time ) );
}
public String webFormat(){
return format( _webFormat );
}
public String simpleFormat(){
return format( _simpleFormat );
}
public String format( DateFormat df ){
synchronized ( df ){
return df.format( new Date( _time ) );
}
}
public JSDate roundMonth(){
return new JSDate( _roundMonth() );
}
public JSDate roundWeek(){
return new JSDate( _roundWeek() );
}
public JSDate roundDay(){
return new JSDate( _roundDay() );
}
public JSDate roundHour(){
return new JSDate( _roundHour() );
}
public Calendar _roundMonth(){
Calendar c = _roundDay();
c.set( c.DAY_OF_MONTH , 1 );
return c;
}
public Calendar _roundWeek(){
Calendar c = _roundDay();
while ( c.get( c.DAY_OF_WEEK ) != c.MONDAY )
c.setTimeInMillis( c.getTimeInMillis() - ( 1000 * 60 * 60 * 24 ) );
return c;
}
public Calendar _roundDay(){
Calendar c = _roundHour();
c.set( c.HOUR_OF_DAY , 0 );
return c;
}
public Calendar _roundHour(){
Calendar c = Calendar.getInstance();
c.setTimeInMillis( _time );
c.set( c.MILLISECOND , 0 );
c.set( c.SECOND , 0 );
c.set( c.MINUTE , 0 );
return c;
}
public JSDate roundMinutes( int min ){
Calendar c = Calendar.getInstance();
c.setTimeInMillis( _time );
c.set( c.MILLISECOND , 0 );
c.set( c.SECOND , 0 );
double m = c.get( c.MINUTE );
m = m / min;
c.set( c.MINUTE , min * (int)m );
return new JSDate( c );
}
/**
* As required by the spec. Spec apparently gives us freedom for format. Silly spec.
* @return value of date object in UTC
*/
public String toUTCString() {
synchronized(_utcFormat) {
return _utcFormat.format( new Date( _time ) );
}
}
public JSDate utc(){
return this;
}
private void _cal(){
if ( _c != null )
return;
_c = Calendar.getInstance();
_c.setTimeInMillis( _time );
}
public int compareTo( Object o ){
long t = -1;
if ( o instanceof JSDate )
t = ((JSDate)o)._time;
if ( t < 0 )
return 0;
long diff = _time - t;
if ( diff == 0 )
return 0;
if ( diff < 0 )
return -1;
return 1;
}
public int hashCode(){
return (int)_time;
}
public boolean equals( Object o ){
return
o instanceof JSDate &&
_time == ((JSDate)o)._time;
}
long _time;
Calendar _c;
public static final DateFormat _simpleFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
public static final DateFormat _webFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
public static final DateFormat _utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
static {
_webFormat.setTimeZone( TimeZone.getTimeZone("GMT") );
_utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
private final static DateFormat[] DATE_FORMATS = new DateFormat[]{
_webFormat , _simpleFormat ,
new SimpleDateFormat( "yyyy-dd-MM HH:mm:ss z" ) ,
new SimpleDateFormat( "yyyy-dd-MM HH:mm: z" ) ,
new SimpleDateFormat( "yyyy-dd-MM HH:mm:ss" ) ,
new SimpleDateFormat( "yyyy-dd-MM HH:mm" ) ,
new SimpleDateFormat( "dd/MMM/yyyy:HH:mm:ss" )
};
}
|
import java.util.HashSet;
public class Buttons {
public static final int API_VERSION = 1;
public static final char PLAYER_1_START = 's';
public static final char PLAYER_1_JOYSTICK_UP = 'w';
public static final char PLAYER_1_JOYSTICK_UP_RIGHT = 'e';
public static final char PLAYER_1_JOYSTICK_RIGHT = 'd';
public static final char PLAYER_1_JOYSTICK_DOWN_RIGHT = 'c';
public static final char PLAYER_1_JOYSTICK_DOWN = 'x';
public static final char PLAYER_1_JOYSTICK_DOWN_LEFT = 'z';
public static final char PLAYER_1_JOYSTICK_LEFT = 'a';
public static final char PLAYER_1_JOYSTICK_UP_LEFT = 'q';
public static final char PLAYER_1_BUTTON_1 = 'r';
public static final char PLAYER_1_BUTTON_2 = 't';
public static final char PLAYER_1_BUTTON_3 = 'f';
public static final char PLAYER_1_BUTTON_4 = 'g';
public static final char PLAYER_1_BUTTON_5 = 'v';
public static final char PLAYER_1_BUTTON_6 = 'b';
public static final char PLAYER_2_START = 'j';
public static final char PLAYER_2_JOYSTICK_UP = 'u';
public static final char PLAYER_2_JOYSTICK_UP_RIGHT = 'i';
public static final char PLAYER_2_JOYSTICK_RIGHT = 'k';
public static final char PLAYER_2_JOYSTICK_DOWN_RIGHT = ',';
public static final char PLAYER_2_JOYSTICK_DOWN = 'm';
public static final char PLAYER_2_JOYSTICK_DOWN_LEFT = 'n';
public static final char PLAYER_2_JOYSTICK_LEFT = 'h';
public static final char PLAYER_2_JOYSTICK_UP_LEFT = 'y';
public static final char PLAYER_2_BUTTON_1 = 'o';
public static final char PLAYER_2_BUTTON_2 = 'p';
public static final char PLAYER_2_BUTTON_3 = 'l';
public static final char PLAYER_2_BUTTON_4 = ';';
public static final char PLAYER_2_BUTTON_5 = '.';
public static final char PLAYER_2_BUTTON_6 = '/';
/**
* Return true if the given key is any fight pad button. Does not include
* start buttons or joystick directions.
*
* @param key the character keycode to be tested against
*/
public static boolean isAnyButton(char key) {
return isPlayer1Button(key) || isPlayer2Button(key);
}
/**
* Return true if the given key is any player's start button.
*
* @param key the character keycode to be tested against
*/
public static boolean isStartButton(char key) {
return key == PLAYER_1_START || key == PLAYER_2_START;
}
/**
* Return true if the given key is any direction on any joystick.
*
* @param key the character keycode to be tested against
*/
public static boolean isJoystick(char key) {
return isPlayer1Joystick(key) || isPlayer2Joystick(key);
}
/**
* Return true if the given key is a valid buton on the fight pad for player
* 1 to press. This does not include the start button.
*
* @param key the character keycode to be tested against
*/
public static boolean isPlayer1Button(char key) {
return key == PLAYER_1_BUTTON_1 || key == PLAYER_1_BUTTON_2 ||
key == PLAYER_1_BUTTON_3 || key == PLAYER_1_BUTTON_4 ||
key == PLAYER_1_BUTTON_5 || key == PLAYER_1_BUTTON_6;
}
/**
* Return true if the given key is a valid buton on the fight pad for player
* 2 to press. This does not include the start button.
*
* @param key the character keycode to be tested against
*/
public static boolean isPlayer2Button(char key) {
return key == PLAYER_2_BUTTON_1 || key == PLAYER_2_BUTTON_2 ||
key == PLAYER_2_BUTTON_3 || key == PLAYER_2_BUTTON_4 ||
key == PLAYER_2_BUTTON_5 || key == PLAYER_2_BUTTON_6;
}
/**
* Return true if the given key is a valid Joystick direction on the player
* 1 joystick.
*
* @param key the character keycode to be tested against
*/
public static boolean isPlayer1Joystick(char key) {
return key == PLAYER_1_JOYSTICK_LEFT || key == PLAYER_1_JOYSTICK_RIGHT ||
key == PLAYER_1_JOYSTICK_UP || key == PLAYER_1_JOYSTICK_DOWN ||
key == PLAYER_1_JOYSTICK_UP_RIGHT || key == PLAYER_1_JOYSTICK_UP_LEFT ||
key == PLAYER_1_JOYSTICK_DOWN_LEFT || key == PLAYER_1_JOYSTICK_UP_LEFT ||
key == PLAYER_1_JOYSTICK_DOWN_RIGHT;
}
/**
* Return true if the given key is a valid Joystick direction on the player
* 2 joystick.
*
* @param key the character keycode to be tested against
*/
public static boolean isPlayer2Joystick(char key) {
return key == PLAYER_2_JOYSTICK_LEFT || key == PLAYER_2_JOYSTICK_RIGHT ||
key == PLAYER_2_JOYSTICK_UP || key == PLAYER_2_JOYSTICK_DOWN ||
key == PLAYER_2_JOYSTICK_UP_RIGHT || key == PLAYER_2_JOYSTICK_UP_LEFT ||
key == PLAYER_2_JOYSTICK_DOWN_LEFT || key == PLAYER_2_JOYSTICK_UP_LEFT ||
key == PLAYER_2_JOYSTICK_DOWN_RIGHT;
}
/**
* Return true if the given key is any valid key for the arcade machine
* controller to press.
*
* @param key the character keycode to be tested against the anyKey set
*/
public static boolean isAnyKey(char key) {
return isPlayer1Key(key) || isPlayer2Key(key);
}
/**
* Return true if the given key is a valid key for Player 1 to press,
* including the joystick and start button.
*
* @param key the character keycode to be tested against
*/
public static boolean isPlayer1Key(char key) {
return isPlayer1Button(key) || isPlayer1Joystick(key) ||
key == PLAYER_1_START;
}
/**
* Return true if the given key is a valid key for Player 2 to press,
* including the joystick and start button.
*
* @param key the character keycode to be tested against
*/
public static boolean isPlayer2Key(char key) {
return isPlayer2Button(key) || isPlayer2Joystick(key) ||
key == PLAYER_2_START;
}
}
|
package com.exedio.cope.junit;
import com.exedio.cope.IntegrityViolationException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import com.exedio.cope.Item;
import com.exedio.cope.Model;
import com.exedio.cope.Properties;
import com.exedio.cope.Transaction;
import com.exedio.cope.util.PoolCounter;
/**
* An abstract test case class for tests creating/using some persistent data.
* @author Ralf Wiebicke
*/
public abstract class CopeTest extends CopeAssert
{
private static HashSet<Model> createdDatabase = new HashSet<Model>();
private static HashSet<Model> registeredDropDatabaseHook = new HashSet<Model>();
private static Object lock = new Object();
public final Model model;
public final boolean exclusive;
private boolean testMethodFinished = false;
private ArrayList<Item> deleteOnTearDown = null;
protected CopeTest(final Model model)
{
this(model, false);
}
/**
* @param exclusive
* if true, the database schema for the model will be created before each test
* and dropped after each test.
* This will make tests last much longer, so this is useful for debugging only.
*/
protected CopeTest(final Model model, final boolean exclusive)
{
this.model = model;
this.exclusive = exclusive;
}
protected final void deleteOnTearDown(final Item item)
{
deleteOnTearDown.add(item);
}
protected final void printConnectionPoolCounter()
{
final PoolCounter connectionPoolCounter = model.getConnectionPoolInfo().getCounter();
System.out.println("ConnectionPool: "+connectionPoolCounter.getGetCounter()+", "+connectionPoolCounter.getPutCounter());
for(Iterator i = connectionPoolCounter.getPools().iterator(); i.hasNext(); )
{
final PoolCounter.Pool pool = (PoolCounter.Pool)i.next();
System.out.println("ConnectionPool:["+pool.getSize()+"]: "+pool.getIdleCount()+", "+pool.getIdleCountMax()+", "+pool.getCreateCounter()+", "+pool.getDestroyCounter()+", "+pool.getLoss());
}
}
private final void createDatabase()
{
if(exclusive)
model.createDatabase();
else
{
synchronized(lock)
{
if(!createdDatabase.contains(model))
{
model.createDatabase();
createdDatabase.add(model);
}
}
}
}
private final void dropDatabase()
{
if(exclusive)
model.dropDatabase();
else
{
synchronized(lock)
{
if(!registeredDropDatabaseHook.contains(model))
{
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
public void run()
{
//printConnectionPoolCounter();
model.dropDatabase();
model.close();
}
}));
registeredDropDatabaseHook.add(model);
}
}
}
}
public void runBare() throws Throwable
{
setUp();
try
{
testMethodFinished = false;
runTest();
testMethodFinished = true;
}
finally
{
tearDown();
}
}
protected Properties getProperties()
{
return new Properties();
}
protected void setUp() throws Exception
{
model.setPropertiesInitially(getProperties());
super.setUp();
deleteOnTearDown = new ArrayList<Item>();
createDatabase();
model.startTransaction("CopeTest");
model.checkEmptyDatabase();
}
protected void tearDown() throws Exception
{
final boolean hadTransaction = model.hasCurrentTransaction();
if ( ! hadTransaction )
{
model.startTransaction( "started by tearDown" );
}
Transaction current = model.getCurrentTransaction();
ArrayList<Transaction> openTransactions = null;
for(Transaction nextTransaction : new HashSet<Transaction>(model.getOpenTransactions()))
{
if ( ! nextTransaction.equals(current) )
{
if(openTransactions==null)
openTransactions = new ArrayList<Transaction>();
openTransactions.add( nextTransaction );
model.leaveTransaction();
model.joinTransaction( nextTransaction );
model.rollback();
model.joinTransaction( current );
}
}
if( !exclusive )
{
try
{
if(!deleteOnTearDown.isEmpty())
{
IntegrityViolationException ive = null;
for(ListIterator<Item> i = deleteOnTearDown.listIterator(deleteOnTearDown.size()); i.hasPrevious(); )
{
try
{
i.previous().deleteCopeItem();
}
catch ( IntegrityViolationException e )
{
if ( ive==null && testMethodFinished )
{
ive = e;
}
}
}
deleteOnTearDown.clear();
if ( ive!=null )
{
throw new RuntimeException("test completed successfully but failed to delete a 'deleteOnTearDown' item", ive);
}
}
deleteOnTearDown = null;
model.checkEmptyDatabase();
}
catch ( RuntimeException e )
{
if ( testMethodFinished )
{
throw new RuntimeException("test completed successfully but didn't clean up database", e);
}
else
{
model.rollbackIfNotCommitted();
model.tearDownDatabase();
model.createDatabase();
model.startTransaction();
}
}
}
if ( testMethodFinished || model.hasCurrentTransaction() )
{
model.commit();
}
if ( testMethodFinished && !hadTransaction )
{
fail( "test completed successfully but didn't have current transaction in tearDown" );
}
if ( testMethodFinished && openTransactions!=null )
{
fail( "test completed successfully but left open transactions: "+openTransactions );
}
dropDatabase();
super.tearDown();
}
protected boolean testCompletedSuccessfully()
{
return testMethodFinished;
}
protected void restartTransaction()
{
final String oldName = model.getCurrentTransaction().getName();
model.commit();
model.startTransaction( oldName+"-restart" );
}
}
|
package nl.jpoint.vertx.mod.cluster.service;
import nl.jpoint.vertx.mod.cluster.Constants;
import nl.jpoint.vertx.mod.cluster.command.*;
import nl.jpoint.vertx.mod.cluster.request.ModuleRequest;
import nl.jpoint.vertx.mod.cluster.util.LogConstants;
import nl.jpoint.vertx.mod.cluster.util.ModuleFileNameFilter;
import nl.jpoint.vertx.mod.cluster.util.ModuleVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.shareddata.ConcurrentSharedMap;
import org.vertx.java.platform.PlatformLocator;
import org.vertx.java.platform.PlatformManager;
import java.io.File;
public class DeployModuleService implements DeployService {
private static final Logger LOG = LoggerFactory.getLogger(DeployModuleService.class);
private final Vertx vertx;
private final JsonObject config;
private final PlatformManager platformManager;
private final File modRoot;
private final ConcurrentSharedMap<String, String> installedModules;
public DeployModuleService(final Vertx vertx, JsonObject config) {
this.vertx = vertx;
this.config = config;
this.platformManager = PlatformLocator.factory.createPlatformManager();
this.modRoot = new File(config.getString("mod.root"));
this.installedModules = this.vertx.sharedData().getMap("installed_modules");
}
public boolean deploy(final ModuleRequest deployRequest) {
if (deployRequest.isSnapshot()) {
Command resolveVersion = new ResolveSnapshotVersion(config, LogConstants.DEPLOY_REQUEST);
JsonObject result = resolveVersion.execute(deployRequest);
if (result.getBoolean("success")) {
deployRequest.setSnapshotVersion(result.getString("version"));
}
}
final ModuleVersion moduleInstalled = moduleInstalled(deployRequest);
if (moduleInstalled.equals(ModuleVersion.ERROR)) {
return false;
}
// If the module with the same version is already installed there is no need to take any further action.
if (moduleInstalled.equals(ModuleVersion.INSTALLED)) {
if (deployRequest.restart()) {
RunModule runModCommand = new RunModule();
runModCommand.execute(deployRequest);
}
return true;
}
if (!moduleInstalled.equals(ModuleVersion.INSTALLED)) {
// Respond OK if the deployment is async.
if (deployRequest.isAsync()) {
return true;
}
// If an older version (or SNAPSHOT) is installed undeploy it first.
if (moduleInstalled.equals(ModuleVersion.OLDER_VERSION)) {
if (!deployRequest.restart()) {
StopModule stopModuleCommand = new StopModule(vertx, modRoot);
JsonObject result = stopModuleCommand.execute(deployRequest);
if (!result.getBoolean(Constants.STOP_STATUS)) {
return false;
}
}
UndeployModule undeployCommand = new UndeployModule(vertx, modRoot);
undeployCommand.execute(deployRequest);
}
// Install the new module.
InstallModule installCommand = new InstallModule();
JsonObject installResult = installCommand.execute(deployRequest);
// Respond failed if install did not complete.
if (!installResult.getBoolean(Constants.STATUS_SUCCESS)) {
return false;
}
}
// Run the newly installed module.
RunModule runModCommand = new RunModule();
JsonObject runResult = runModCommand.execute(deployRequest);
if (!runResult.getBoolean(Constants.STATUS_SUCCESS) && !deployRequest.isAsync()) {
return false;
}
installedModules.put(deployRequest.getMavenArtifactId(), deployRequest.getSnapshotVersion() == null ? deployRequest.getVersion() : deployRequest.getSnapshotVersion());
LOG.info("[{} - {}]: Cleaning up after deploy", LogConstants.DEPLOY_REQUEST, deployRequest.getId());
return true;
}
private ModuleVersion moduleInstalled(ModuleRequest deployRequest) {
if (!modRoot.exists()) {
LOG.error("[{} - {}]: Module root {} Does not exist.", LogConstants.DEPLOY_REQUEST, deployRequest.getId().toString(), modRoot);
return ModuleVersion.ERROR;
}
for (String mod : modRoot.list(new ModuleFileNameFilter(deployRequest))) {
if (mod.equals(deployRequest.getModuleId()) && !deployRequest.isSnapshot()) {
LOG.info("[{} - {}]: Module {} already installed.", LogConstants.DEPLOY_REQUEST, deployRequest.getId().toString(), deployRequest.getModuleId());
return ModuleVersion.INSTALLED;
} else {
if (deployRequest.getSnapshotVersion().equals(installedModules.get(deployRequest.getMavenArtifactId()))) {
LOG.info("[{} - {}]: Same SNAPSHOT version ({}) of Module {} already installed.", LogConstants.DEPLOY_REQUEST, deployRequest.getId(), deployRequest.getSnapshotVersion(), deployRequest.getModuleId());
return ModuleVersion.INSTALLED;
}
LOG.info("[{} - {}]: Older version of Module {} already installed.", LogConstants.DEPLOY_REQUEST, deployRequest.getId().toString(), deployRequest.getModuleId());
return ModuleVersion.OLDER_VERSION;
}
}
return ModuleVersion.NOT_INSTALLED;
}
public void stopContainer(String deployId) {
Command<String> stopContainer = new InvokeContainer(deployId);
stopContainer.execute("stop");
}
}
|
package org.project.openbaton.common.vnfm_sdk.jms;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.project.openbaton.catalogue.nfvo.CoreMessage;
import org.project.openbaton.catalogue.nfvo.EndpointType;
import org.project.openbaton.catalogue.nfvo.VnfmManagerEndpoint;
import org.project.openbaton.common.vnfm_sdk.AbstractVnfm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.jms.support.destination.JndiDestinationResolver;
import javax.annotation.PreDestroy;
import javax.jms.*;
import java.io.Serializable;
@SpringBootApplication
@EnableJms
public abstract class AbstractVnfmSpringJMS extends AbstractVnfm implements CommandLineRunner {
@Autowired
protected JmsListenerContainerFactory topicJmsContainerFactory;
private boolean exit = false;
protected String SELECTOR;
private VnfmManagerEndpoint vnfmManagerEndpoint;
public String getSELECTOR() {
return SELECTOR;
}
public void setSELECTOR(String SELECTOR) {
this.SELECTOR = SELECTOR;
}
@Autowired
private JmsTemplate jmsTemplate;
@PreDestroy
private void shutdown(){
log.debug("PREDESTROY");
this.unregister(vnfmManagerEndpoint);
}
@Override
protected void unregister(VnfmManagerEndpoint endpoint) {
this.sendMessageToQueue("vnfm-unregister", endpoint);
}
@Bean
private ConnectionFactory connectionFactory() {
return new ActiveMQConnectionFactory();
}
@Bean
private DestinationResolver destinationResolver() {
return new JndiDestinationResolver();
}
@Bean
JmsListenerContainerFactory<?> jmsListenerContainerFactory() {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setCacheLevelName("CACHE_AUTO");
factory.setConnectionFactory(connectionFactory());
factory.setDestinationResolver(destinationResolver());
factory.setConcurrency("5");
return factory;
}
// @Bean
// JmsListenerContainerFactory<?> topicJmsContainerFactory(ConnectionFactory connectionFactory) {
// DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
// factory.setCacheLevelName("CACHE_CONNECTION");
// factory.setConnectionFactory(connectionFactory);
// factory.setConcurrency("1");
// factory.setPubSubDomain(true);
// factory.setSubscriptionDurable(true);
// factory.setClientId(""+ Thread.currentThread().getId());
// return factory;
// @JmsListener(destination = "core-vnfm-actions", containerFactory = "queueJmsContainerFactory")
private void onMessage() throws JMSException {
Message msg = jmsTemplate.receive("core-" + this.type + "-actions");
CoreMessage message = (CoreMessage) ((ObjectMessage)msg).getObject();
log.trace("VNFM-DUMMY: received " + message);
this.onAction(message);
}
private CoreMessage receiveCoreMessage(String destination, String selector) throws JMSException {
jmsTemplate.setPubSubDomain(true);
jmsTemplate.setPubSubNoLocal(true);
CoreMessage message = (CoreMessage) ((ObjectMessage) jmsTemplate.receiveSelected(destination, "type = \'" + selector + "\'")).getObject();
jmsTemplate.setPubSubDomain(false);
jmsTemplate.setPubSubNoLocal(false);
return message;
}
protected Serializable sendAndReceiveMessage(String receiveFromQueueName, String sendToQueueName, final Serializable vduMessage) throws JMSException {
sendMessageToQueue(sendToQueueName, vduMessage);
ObjectMessage objectMessage = (ObjectMessage) jmsTemplate.receive(receiveFromQueueName);
log.debug("Received: " + objectMessage.getObject());
// VDUMessage answer = (VDUMessage) objectMessage.getObject();
// if (answer.getLifecycleEvent().ordinal() != Event.ERROR.ordinal()){
// return true;
return objectMessage.getObject();
}
protected String sendAndReceiveStringMessage(String receiveFromQueueName, String sendToQueueName, final String stringMessage) throws JMSException {
log.debug("Sending message: " + stringMessage + " to Queue: " + sendToQueueName);
MessageCreator messageCreator = new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage textMessage = session.createTextMessage(stringMessage);
return textMessage;
}
};
jmsTemplate.setPubSubDomain(false);
jmsTemplate.setPubSubNoLocal(false);
jmsTemplate.send(sendToQueueName, messageCreator);
TextMessage textMessage = (TextMessage) jmsTemplate.receive(receiveFromQueueName);
jmsTemplate.setPubSubDomain(true);
jmsTemplate.setPubSubNoLocal(true);
String answer = textMessage.getText();
log.debug("Received: " + answer);
// check errors
/*if (answer.equals("error")){
return null;
}*/
return answer;
}
protected void sendMessageToQueue(String sendToQueueName, final Serializable vduMessage) {
log.debug("Sending message: " + vduMessage + " to Queue: " + sendToQueueName);
MessageCreator messageCreator = new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
ObjectMessage objectMessage = session.createObjectMessage(vduMessage);
return objectMessage;
}
};
jmsTemplate.setPubSubDomain(false);
jmsTemplate.setPubSubNoLocal(false);
jmsTemplate.send(sendToQueueName, messageCreator);
jmsTemplate.setPubSubDomain(true);
jmsTemplate.setPubSubNoLocal(true);
}
@Override
public void run(String... args) throws Exception {
//TODO initialize and register
loadProperties();
this.setSELECTOR(this.getEndpoint());
log.debug("SELECTOR: " + this.getEndpoint());
vnfmManagerEndpoint = new VnfmManagerEndpoint();
vnfmManagerEndpoint.setType(this.type);
vnfmManagerEndpoint.setEndpoint(this.endpoint);
vnfmManagerEndpoint.setEndpointType(EndpointType.JMS);
log.debug("Registering to queue: vnfm-register");
sendMessageToQueue("vnfm-register", vnfmManagerEndpoint);
try {
while (true)
onMessage();
}catch (Exception e){
e.printStackTrace();
}
}
}
|
package jlibs.core.lang;
import jlibs.core.io.IOUtil;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Iterator;
import java.util.LinkedList;
/**
* @author Santhosh Kumar T
*/
public class Bytes implements Iterable<ByteSequence>{
private LinkedList<ByteSequence> list = new LinkedList<ByteSequence>();
public int size(){
int size = 0;
for(ByteSequence seq: list)
size += seq.length();
return size;
}
public boolean isEmpty(){
if(list.size()==0)
return true;
for(ByteSequence seq: list){
if(seq.length()>0)
return false;
}
return true;
}
public void clear(){
list.clear();
}
public void add(ByteSequence seq){
list.add(seq);
}
@Override
public Iterator<ByteSequence> iterator(){
return list.iterator();
}
public void remove(int count){
Iterator<ByteSequence> iter = iterator();
while(iter.hasNext()){
ByteSequence seq = iter.next();
count -= seq.length();
iter.remove();
if(count==0)
return;
else if(count<0){
list.add(0, seq.slice(seq.length()+count));
return;
}
}
}
private ByteBuffer buff;
public int readFrom(ReadableByteChannel channel) throws IOException{
int total = 0;
while(true){
if(buff==null)
buff = ByteBuffer.allocate(1024);
int read = channel.read(buff);
if(read<=0){
if(read<0 && buff.position()==0) // garbage buff
buff = null;
break;
}
total += read;
add(new ByteSequence(buff.array(), buff.position()-read, read));
if(buff.hasRemaining())
break;
else
buff = null;
}
return total;
}
public int readFully(InputStream in) throws IOException{
int total = 0;
while(true){
if(buff==null)
buff = ByteBuffer.allocate(1024);
int read = IOUtil.readFully(in, buff.array(), buff.position(), buff.limit());
if(read==0){
if(buff.position()==0) // garbage buff
buff = null;
break;
}
buff.position(buff.position()+read);
total += read;
add(new ByteSequence(buff.array(), buff.position()-read, read));
if(buff.hasRemaining()) // eof reached
break;
else
buff = null;
}
return total;
}
public int writeTo(WritableByteChannel channel) throws IOException{
int total = 0;
Iterator<ByteSequence> iter = iterator();
while(iter.hasNext()){
ByteSequence seq = iter.next();
int wrote = channel.write(seq.toByteBuffer());
if(wrote==0)
break;
total += wrote;
iter.remove();
if(wrote<seq.length()){
list.add(0, seq.slice(wrote));
break;
}
}
return total;
}
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.ui;
import pythagoras.f.Dimension;
import pythagoras.f.IDimension;
import pythagoras.f.MathUtil;
import pythagoras.f.Point;
import pythagoras.f.Rectangle;
import react.Signal;
import react.SignalView;
import react.Slot;
import react.UnitSlot;
import playn.core.GroupLayer;
import playn.core.Layer;
import playn.core.PlayN;
import tripleplay.ui.util.Insets;
import tripleplay.util.Ref;
/**
* The root of the interface element hierarchy. See {@link Widget} for the root of all interactive
* elements, and {@link Elements} for the root of all grouping elements.
*
* @param T used as a "self" type; when subclassing {@code Element}, T must be the type of the
* subclass.
*/
public abstract class Element<T extends Element<T>>
{
/** The layer associated with this element. */
public final GroupLayer layer = createLayer();
protected Element () {
// optimize hit testing by checking our bounds first
layer.setHitTester(new Layer.HitTester() {
public Layer hitTest (Layer layer, Point p) {
Layer hit = null;
if (isVisible() && contains(p.x, p.y)) {
if (isSet(Flag.HIT_DESCEND)) hit = layer.hitTestDefault(p);
if (hit == null && isSet(Flag.HIT_ABSORB)) hit = layer;
}
return hit;
}
@Override public String toString () {
return "HitTester for " + Element.this;
}
});
// descend by default
set(Flag.HIT_DESCEND, true);
}
/**
* Returns this element's x offset relative to its parent.
*/
public float x () {
return layer.tx();
}
/**
* Returns this element's y offset relative to its parent.
*/
public float y () {
return layer.ty();
}
/**
* Returns the width and height of this element's bounds.
*/
public IDimension size () {
return _size;
}
/**
* Writes the location of this element (relative to its parent) into the supplied point.
* @return {@code loc} for convenience.
*/
public Point location (Point loc) {
return loc.set(x(), y());
}
/**
* Writes the current bounds of this element into the supplied bounds.
* @return {@code bounds} for convenience.
*/
public Rectangle bounds (Rectangle bounds) {
bounds.setBounds(x(), y(), _size.width, _size.height);
return bounds;
}
/**
* Returns the parent of this element, or null.
*/
public Elements<?> parent () {
return _parent;
}
/**
* Returns a signal that will dispatch when this element is added or removed from the
* hierarchy. The emitted value is true if the element was just added to the hierarchy, false
* if removed.
*/
public SignalView<Boolean> hierarchyChanged () {
if (_hierarchyChanged == null) _hierarchyChanged = Signal.create();
return _hierarchyChanged;
}
/**
* Returns the styles configured on this element.
*/
public Styles styles () {
return _styles;
}
/**
* Configures the styles for this element. Any previously configured styles are overwritten.
* @return this element for convenient call chaining.
*/
public T setStyles (Styles styles) {
_styles = styles;
clearLayoutData();
invalidate();
return asT();
}
/**
* Configures styles for this element (in the DEFAULT mode). Any previously configured styles
* are overwritten.
* @return this element for convenient call chaining.
*/
public T setStyles (Style.Binding<?>... styles) {
return setStyles(Styles.make(styles));
}
/**
* Adds the supplied styles to this element. Where the new styles overlap with existing styles,
* the new styles are preferred, but non-overlapping old styles are preserved.
* @return this element for convenient call chaining.
*/
public T addStyles (Styles styles) {
_styles = _styles.merge(styles);
clearLayoutData();
invalidate();
return asT();
}
/**
* Adds the supplied styles to this element (in the DEFAULT mode). Where the new styles overlap
* with existing styles, the new styles are preferred, but non-overlapping old styles are
* preserved.
* @return this element for convenient call chaining.
*/
public T addStyles (Style.Binding<?>... styles) {
return addStyles(Styles.make(styles));
}
/**
* Returns {@code this} cast to {@code T}.
*/
@SuppressWarnings({"unchecked", "cast"}) protected T asT () {
return (T)this;
}
/**
* Returns whether this element is enabled.
*/
public boolean isEnabled () {
return isSet(Flag.ENABLED);
}
/**
* Enables or disables this element. Disabled elements are not interactive and are usually
* rendered so as to communicate this state to the user.
*/
public T setEnabled (boolean enabled) {
if (enabled != isEnabled()) {
set(Flag.ENABLED, enabled);
clearLayoutData();
invalidate();
}
return asT();
}
/**
* Returns a slot which can be used to wire the enabled status of this element to a {@link
* react.Signal} or {@link react.Value}.
*/
public Slot<Boolean> enabledSlot () {
return new Slot<Boolean>() {
public void onEmit (Boolean value) {
setEnabled(value);
}
};
}
/**
* Returns whether this element is visible.
*/
public boolean isVisible () {
return isSet(Flag.VISIBLE);
}
/**
* Configures whether this element is visible. An invisible element is not rendered and
* consumes no space in a group.
*/
public T setVisible (boolean visible) {
if (visible != isVisible()) {
set(Flag.VISIBLE, visible);
layer.setVisible(visible);
invalidate();
}
return asT();
}
/**
* Returns a slot which can be used to wire the visible status of this element to a {@link
* react.Signal} or {@link react.Value}.
*/
public Slot<Boolean> visibleSlot () {
return new Slot<Boolean>() {
public void onEmit (Boolean value) {
setVisible(value);
}
};
}
/**
* Returns true only if this element and all its parents' {@link #isVisible()} return true.
*/
public boolean isShowing () {
Elements<?> parent;
return isVisible() && ((parent = parent()) != null) && parent.isShowing();
}
/**
* Returns the layout constraint configured on this element, or null.
*/
public Layout.Constraint constraint () {
return _constraint;
}
/**
* Configures the layout constraint on this element.
* @return this element for call chaining.
*/
public T setConstraint (Layout.Constraint constraint) {
if (constraint != null) constraint.setElement(this);
_constraint = constraint;
invalidate();
return asT();
}
/**
* Returns true if this element is part of an interface heirarchy.
*/
public boolean isAdded () {
return root() != null;
}
/**
* Returns the class of this element for use in computing its style. By default this is the
* actual class, but you may wish to, for example, extend {@link Label} with some customization
* and override this method to return {@code Label.class} so that your extension has the same
* styles as Label applied to it.
*
* Concrete Element implementations should return the actual class instance instead of
* getClass(). Returning getClass() means that further subclasses will lose all styles applied
* to this implementation, probably unintentionally.
*/
protected abstract Class<?> getStyleClass ();
/**
* Called when this element is added to a parent element. If the parent element is already
* added to a hierarchy with a {@link Root}, this will immediately be followed by a call to
* {@link #wasAdded}, otherwise the {@link #wasAdded} call will come later when the parent is
* added to a root.
*/
protected void wasParented (Elements<?> parent) {
_parent = parent;
}
/**
* Called when this element is removed from its direct parent. If the element was removed from
* a parent that was connected to a {@link Root}, a call to {@link #wasRemoved} will
* immediately follow. Otherwise no call to {@link #wasRemoved} will be made.
*/
protected void wasUnparented () {
_parent = null;
}
/**
* Called when this element (or its parent element) was added to an interface hierarchy
* connected to a {@link Root}. The element will subsequently be validated and displayed
* (assuming it's visible).
*/
protected void wasAdded () {
if (_hierarchyChanged != null) _hierarchyChanged.emit(Boolean.TRUE);
invalidate();
set(Flag.IS_ADDING, false);
}
/**
* Called when this element (or its parent element) was removed from the interface hierarchy.
* Also, if the element was removed directly from its parent, then the layer is orphaned prior
* to this call. Furthermore, if the element is being destroyed (see {@link Elements#destroy}
* and other methods), the destruction of the layer will occur <b>after</b> this method
* returns and the {@link #willDestroy()} method returns true. This allows subclasses to
* manage resources as needed. <p><b>NOTE</b>: the base class method must <b>always</b> be
* called for correct operation.</p>
*/
protected void wasRemoved () {
_bginst.clear();
if (_hierarchyChanged != null) _hierarchyChanged.emit(Boolean.FALSE);
set(Flag.IS_REMOVING, false);
}
/**
* Returns true if the supplied, element-relative, coordinates are inside our bounds.
*/
protected boolean contains (float x, float y) {
return !(x < 0 || x > _size.width || y < 0 || y > _size.height);
}
/**
* Returns whether this element is selected. This is only applicable for elements that maintain
* a selected state, but is used when computing styles for all elements (it is assumed that an
* element that maintains no selected state will always return false from this method).
* Elements that do maintain a selected state should override this method and expose it as
* public.
*/
protected boolean isSelected () {
return isSet(Flag.SELECTED);
}
/**
* An element should call this method when it knows that it has changed in such a way that
* requires it to recreate its visualization.
*/
protected void invalidate () {
// note that our preferred size and background are no longer valid
_preferredSize = null;
if (isSet(Flag.VALID)) {
set(Flag.VALID, false);
// invalidate our parent if we've got one
if (_parent != null) {
_parent.invalidate();
}
}
}
/**
* Gets a new slot which will invoke {@link #invalidate()} when emitted.
*/
protected UnitSlot invalidateSlot () {
return invalidateSlot(false);
}
/**
* Gets a new slot which will invoke {@link #invalidate()}.
* @param styles if set, the slot will also call {@link #clearLayoutData()} when emitted
*/
protected UnitSlot invalidateSlot (final boolean styles) {
return new UnitSlot() {
@Override public void onEmit () {
invalidate();
if (styles) clearLayoutData();
}
};
}
/**
* Does whatever this element needs to validate itself. This may involve recomputing
* visualizations, or laying out children, or anything else.
*/
protected void validate () {
if (!isSet(Flag.VALID)) {
layout();
set(Flag.VALID, true);
}
}
/**
* Returns the root of this element's hierarchy, or null if the element is not currently added
* to a hierarchy.
*/
protected Root root () {
return (_parent == null) ? null : _parent.root();
}
/**
* Returns whether the specified flag is set.
*/
protected boolean isSet (Flag flag) {
return (flag.mask & _flags) != 0;
}
/**
* Sets or clears the specified flag.
*/
protected void set (Flag flag, boolean on) {
if (on) {
_flags |= flag.mask;
} else {
_flags &= ~flag.mask;
}
}
/**
* Returns this element's preferred size, potentially recomputing it if needed.
*
* @param hintX if non-zero, an indication that the element will be constrained in the x
* direction to the specified width.
* @param hintY if non-zero, an indication that the element will be constrained in the y
* direction to the specified height.
*/
protected IDimension preferredSize (float hintX, float hintY) {
if (_preferredSize == null) {
Dimension psize = computeSize(hintX, hintY);
if (_constraint != null) _constraint.adjustPreferredSize(psize, hintX, hintY);
// round our preferred size up to the nearest whole number; if we allow it to remain
// fractional, we can run into annoying layout problems where floating point rounding
// error causes a tiny fraction of a pixel to be shaved off of the preferred size of a
// text widget, causing it to wrap its text differently and hosing the layout
psize.width = MathUtil.iceil(psize.width);
psize.height = MathUtil.iceil(psize.height);
_preferredSize = psize;
}
return _preferredSize;
}
/**
* Configures the location of this element, relative to its parent.
*/
protected void setLocation (float x, float y) {
layer.setTranslation(MathUtil.ifloor(x), MathUtil.ifloor(y));
}
/**
* Configures the size of this widget.
*/
protected T setSize (float width, float height) {
boolean changed = _size.width != width || _size.height != height;
_size.setSize(width, height);
// if we have a cached preferred size and this size differs from it, we need to clear our
// layout data as it may contain computations specific to our preferred size
if (_preferredSize != null && !_size.equals(_preferredSize)) clearLayoutData();
if (changed) invalidate();
return asT();
}
/**
* Resolves the value for the supplied style. See {@link Styles#resolveStyle} for the gritty
* details.
*/
protected <V> V resolveStyle (Style<V> style) {
return Styles.resolveStyle(this, style);
}
/**
* Recomputes this element's preferred size.
*
* @param hintX if non-zero, an indication that the element will be constrained in the x
* direction to the specified width.
* @param hintY if non-zero, an indication that the element will be constrained in the y
* direction to the specified height.
*/
protected Dimension computeSize (float hintX, float hintY) {
LayoutData ldata = _ldata = createLayoutData(hintX, hintY);
Insets insets = ldata.bg.insets;
Dimension size = ldata.computeSize(hintX - insets.width(), hintY - insets.height());
return insets.addTo(size);
}
/**
* Handles common element layout (background), then calls {@link LayoutData#layout} to do the
* actual layout.
*/
protected void layout () {
if (!isVisible()) return;
float width = _size.width, height = _size.height;
LayoutData ldata = (_ldata != null) ? _ldata : createLayoutData(width, height);
// if we have a non-matching background, destroy it (note that if we don't want a bg, any
// existing bg will necessarily be invalid)
Background.Instance bginst = _bginst.get();
boolean bgok = (bginst != null && bginst.owner() == ldata.bg &&
bginst.size.equals(_size));
if (!bgok) _bginst.clear();
// if we want a background and don't already have one, create it
if (width > 0 && height > 0 && !bgok) {
bginst = _bginst.set(ldata.bg.instantiate(_size));
bginst.addTo(layer, 0, 0, 0);
}
// do our actual layout
Insets insets = ldata.bg.insets;
ldata.layout(insets.left(), insets.top(),
width - insets.width(), height - insets.height());
// finally clear our cached layout data
clearLayoutData();
}
/**
* Creates the layout data record used by this element. This record temporarily holds resolved
* style information between the time that an element has its preferred size computed, and the
* time that the element is subsequently laid out. Note: {@code hintX} and {@code hintY} <em>do
* not</em> yet have the background insets subtracted from them, because the creation of the
* LayoutData is what resolves the background in the first place.
*/
protected abstract LayoutData createLayoutData (float hintX, float hintY);
/**
* Clears out cached layout data. This can be called by methods that change the configuration
* of the element when they know it will render pre-computed layout info invalid.
*/
protected void clearLayoutData () {
_ldata = null;
}
/**
* Creates the layer to be used by this element. Subclasses may override to use a clipped one.
*/
protected GroupLayer createLayer () {
return PlayN.graphics().createGroupLayer();
}
/**
* Tests if this element is about to be destroyed. Elements are destroyed via a call to one of
* the "destroy" methods such as {@link Elements#destroy(Element)}. This allows subclasses
* to manage resources appropriately during their implementation of {@link #wasRemoved}, for
* example clearing a child cache. <p>NOTE: at the expense of slight semantic dissonance,
* the flag is not cleared after destruction</p>
*/
protected boolean willDestroy () {
return isSet(Flag.WILL_DESTROY);
}
/**
* Tests if this element is scheduled to be removed from a root hierarchy.
*/
protected final boolean willRemove () {
return isSet(Flag.IS_REMOVING) || (_parent != null && _parent.willRemove());
}
/**
* Tests if this element is scheduled to be added to a root hierarchy.
*/
protected final boolean willAdd () {
return isSet(Flag.IS_ADDING) || (_parent != null && _parent.willAdd());
}
protected abstract class BaseLayoutData {
/**
* Rebuilds this element's visualization. Called when this element's size has changed. In
* the case of groups, this will relayout its children, in the case of widgets, this will
* rerender the widget.
*/
public void layout (float left, float top, float width, float height) {
// noop!
}
}
protected abstract class LayoutData extends BaseLayoutData {
public final Background bg = resolveStyle(Style.BACKGROUND);
/**
* Computes this element's preferred size, given the supplied hints. The background insets
* will be automatically added to the returned size.
*/
public abstract Dimension computeSize (float hintX, float hintY);
}
/** Ways in which a preferred and an original dimension can be "taken" to produce a result.
* The name is supposed to be readable in context and compact, for example
* {@code new SizableLayoutData(...).forWidth(Take.MAX).forHeight(Take.MIN, 200)}. */
protected enum Take
{
/** Uses the maximum of the preferred size and original. */
MAX {
@Override public float apply (float preferred, float original) {
return Math.max(preferred, original);
}
},
/** Uses the minimum of the preferred size and original. */
MIN {
@Override public float apply (float preferred, float original) {
return Math.min(preferred, original);
}
},
/** Uses the preferred size if non-zero, otherwise the original. This is the default. */
PREFERRED_IF_SET {
@Override public float apply (float preferred, float original) {
return preferred == 0 ? original : preferred;
}
};
public abstract float apply (float preferred, float original);
}
/**
* A layout data that will delegate to another layout data instance, but alter the size
* computation to optionally use fixed values.
*/
protected class SizableLayoutData extends LayoutData {
/**
* Creates a new layout with the given delegates and size.
* @param layoutDelegate the delegate to use during layout. May be null if the element
* has no layout
* @param sizeDelegate the delegate to use during size computation. May be null if the
* size will be completely specified by {@code prefSize}
* @param prefSize overrides the size computation. The width and/or height may be zero,
* which indicates the {@code sizeDelegate}'s result should be used for that axis. Passing
* {@code null} is equivalent to passing a 0x0 dimension
*/
public SizableLayoutData (BaseLayoutData layoutDelegate, LayoutData sizeDelegate,
IDimension prefSize) {
this.layoutDelegate = layoutDelegate;
this.sizeDelegate = sizeDelegate;
if (prefSize != null) {
prefWidth = prefSize.width();
prefHeight = prefSize.height();
} else {
prefWidth = prefHeight = 0;
}
}
/**
* Creates a new layout that will defer to the given delegate for layout and size. This is
* equivalent to {@code SizableLayoutData(delegate, delegate, prefSize)}.
* @see #SizableLayoutData(BaseLayoutData, LayoutData, IDimension)
*/
public SizableLayoutData (LayoutData delegate, IDimension prefSize) {
this.layoutDelegate = delegate;
this.sizeDelegate = delegate;
if (prefSize != null) {
prefWidth = prefSize.width();
prefHeight = prefSize.height();
} else {
prefWidth = prefHeight = 0;
}
}
/**
* Sets the way in which widths are combined to calculate the resulting preferred size.
* For example, {@code new SizeableLayoutData(...).forWidth(Take.MAX)}.
*/
public SizableLayoutData forWidth (Take fn) {
widthFn = fn;
return this;
}
/**
* Sets the preferred width and how it should be combined with the delegate's preferred
* width. For example, {@code new SizeableLayoutData(...).forWidth(Take.MAX, 250)}.
*/
public SizableLayoutData forWidth (Take fn, float pref) {
widthFn = fn;
prefWidth = pref;
return this;
}
/**
* Sets the way in which heights are combined to calculate the resulting preferred size.
* For example, {@code new SizeableLayoutData(...).forHeight(Take.MAX)}.
*/
public SizableLayoutData forHeight (Take fn) {
heightFn = fn;
return this;
}
/**
* Sets the preferred height and how it should be combined with the delegate's preferred
* height. For example, {@code new SizeableLayoutData(...).forHeight(Take.MAX, 250)}.
*/
public SizableLayoutData forHeight (Take fn, float pref) {
heightFn = fn;
prefHeight = pref;
return this;
}
@Override public Dimension computeSize (float hintX, float hintY) {
// hint the delegate with our preferred width or height or both,
// then swap in our preferred function on that (min, max, or subclass)
return adjustSize(sizeDelegate == null ? new Dimension(prefWidth, prefHeight) :
sizeDelegate.computeSize(resolveHintX(hintX), resolveHintY(hintY)));
}
@Override public void layout (float left, float top, float width, float height) {
if (layoutDelegate != null) layoutDelegate.layout(left, top, width, height);
}
/**
* Refines the given x hint for the delegate to consume. By default uses our configured
* preferred width if not zero, otherwise the passed-in x hint.
*/
protected float resolveHintX (float hintX) {
return select(prefWidth, hintX);
}
/**
* Refines the given y hint for the delegate to consume. By default uses our configured
* preferred height if not zero, otherwise the passed-in y hint.
*/
protected float resolveHintY (float hintY) {
return select(prefHeight, hintY);
}
/**
* Adjusts the dimension computed by the delegate to get the final preferred size. By
* default, uses the previously configured {@link Take} values.
*/
protected Dimension adjustSize (Dimension dim) {
dim.width = widthFn.apply(prefWidth, dim.width);
dim.height = heightFn.apply(prefHeight, dim.height);
return dim;
}
protected float select (float pref, float base) {
return pref == 0 ? base : pref;
}
protected final BaseLayoutData layoutDelegate;
protected final LayoutData sizeDelegate;
protected float prefWidth, prefHeight;
protected Take widthFn = Take.PREFERRED_IF_SET, heightFn = Take.PREFERRED_IF_SET;
}
protected int _flags = Flag.VISIBLE.mask | Flag.ENABLED.mask;
protected Elements<?> _parent;
protected Dimension _preferredSize;
protected Dimension _size = new Dimension();
protected Styles _styles = Styles.none();
protected Layout.Constraint _constraint;
protected Signal<Boolean> _hierarchyChanged;
protected LayoutData _ldata;
protected final Ref<Background.Instance> _bginst = Ref.<Background.Instance>create(null);
protected static enum Flag {
VALID(1 << 0), ENABLED(1 << 1), VISIBLE(1 << 2), SELECTED(1 << 3), WILL_DESTROY(1 << 4),
HIT_DESCEND(1 << 5), HIT_ABSORB(1 << 6), IS_REMOVING(1 << 7), IS_ADDING(1 << 8);
public final int mask;
Flag (int mask) {
this.mask = mask;
}
};
}
|
package hudson.tasks;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import hudson.model.Action;
import hudson.model.Run;
import hudson.util.xstream.LRUStringConverter;
/**
* Remembers the message ID of the e-mail that was sent for the build.
*
* <p>
* This allows us to send further updates as replies.
*
* @author Kohsuke Kawaguchi
*/
public class MailMessageIdAction implements Action {
static {
Run.XSTREAM.processAnnotations(MailMessageIdAction.class);
}
/**
* Message ID of the e-mail sent for the build.
*/
@XStreamConverter(LRUStringConverter.class)
public final String messageId;
public MailMessageIdAction(String messageId) {
this.messageId = messageId;
}
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return "Message Id"; // but this is never supposed to be displayed
}
public String getUrlName() {
return null; // no web binding
}
}
|
package io.bitsquare.locale;
import io.bitsquare.user.Preferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Collectors;
public class CurrencyUtil {
private static final Logger log = LoggerFactory.getLogger(CurrencyUtil.class);
private static final List<FiatCurrency> allSortedFiatCurrencies = createAllSortedFiatCurrenciesList();
private static List<FiatCurrency> createAllSortedFiatCurrenciesList() {
Set<FiatCurrency> set = CountryUtil.getAllCountries().stream()
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
List<FiatCurrency> list = new ArrayList<>(set);
list.sort(TradeCurrency::compareTo);
return list;
}
public static List<FiatCurrency> getAllSortedFiatCurrencies() {
return allSortedFiatCurrencies;
}
public static List<FiatCurrency> getAllMainFiatCurrencies() {
List<FiatCurrency> list = new ArrayList<>();
// Top traded currencies
list.add(new FiatCurrency("USD"));
list.add(new FiatCurrency("EUR"));
list.add(new FiatCurrency("GBP"));
list.add(new FiatCurrency("CAD"));
list.add(new FiatCurrency("AUD"));
list.add(new FiatCurrency("RUB"));
list.add(new FiatCurrency("INR"));
TradeCurrency defaultTradeCurrency = getDefaultTradeCurrency();
FiatCurrency defaultFiatCurrency = defaultTradeCurrency instanceof FiatCurrency ? (FiatCurrency) defaultTradeCurrency : null;
if (defaultFiatCurrency != null && list.contains(defaultFiatCurrency)) {
list.remove(defaultTradeCurrency);
list.add(0, defaultFiatCurrency);
}
return list;
}
private static final List<CryptoCurrency> allSortedCryptoCurrencies = createAllSortedCryptoCurrenciesList();
public static List<CryptoCurrency> getAllSortedCryptoCurrencies() {
return allSortedCryptoCurrencies;
}
public static List<CryptoCurrency> getMainCryptoCurrencies() {
final List<CryptoCurrency> result = new ArrayList<>();
result.add(new CryptoCurrency("ETH", "Ethereum"));
result.add(new CryptoCurrency("LTC", "Litecoin"));
result.add(new CryptoCurrency("DASH", "Dash"));
result.add(new CryptoCurrency("SDC", "ShadowCash"));
result.add(new CryptoCurrency("NMC", "Namecoin"));
result.add(new CryptoCurrency("NBT", "NuBits"));
result.add(new CryptoCurrency("FAIR", "FairCoin"));
result.add(new CryptoCurrency("DOGE", "Dogecoin"));
result.add(new CryptoCurrency("NXT", "Nxt"));
result.add(new CryptoCurrency("BTS", "BitShares"));
return result;
}
public static List<CryptoCurrency> createAllSortedCryptoCurrenciesList() {
final List<CryptoCurrency> result = new ArrayList<>();
result.add(new CryptoCurrency("ETH", "Ethereum"));
result.add(new CryptoCurrency("LTC", "Litecoin"));
result.add(new CryptoCurrency("NMC", "Namecoin"));
result.add(new CryptoCurrency("DASH", "Dash"));
result.add(new CryptoCurrency("SDC", "ShadowCash"));
result.add(new CryptoCurrency("NBT", "NuBits"));
result.add(new CryptoCurrency("NSR", "NuShares"));
result.add(new CryptoCurrency("PPC", "Peercoin"));
result.add(new CryptoCurrency("XPM", "Primecoin"));
result.add(new CryptoCurrency("FAIR", "FairCoin"));
result.add(new CryptoCurrency("SC", "Siacoin"));
result.add(new CryptoCurrency("SJCX", "StorjcoinX"));
result.add(new CryptoCurrency("GEMZ", "Gemz"));
result.add(new CryptoCurrency("DOGE", "Dogecoin"));
result.add(new CryptoCurrency("BLK", "Blackcoin"));
result.add(new CryptoCurrency("FCT", "Factom"));
result.add(new CryptoCurrency("NXT", "Nxt"));
result.add(new CryptoCurrency("BTS", "BitShares"));
result.add(new CryptoCurrency("XCP", "Counterparty"));
result.add(new CryptoCurrency("XRP", "Ripple"));
result.add(new CryptoCurrency("WDC", "WorldCoin"));
// Unfortunately we cannot support CryptoNote coins yet as there is no way to proof the transaction. Payment ID helps only locate the tx but the
// arbitrator cannot see if the receiving key matches the receivers address. They might add support for exposing the tx key, but that is not
// implemented yet. To use the view key (also not available in GUI wallets) would reveal the complete wallet history for incoming payments, which is
// not acceptable from privacy point of view.
// result.add(new CryptoCurrency("XMR", "Monero"));
// result.add(new CryptoCurrency("BCN", "Bytecoin"));
return result;
}
/**
* @return Sorted list of SEPA currencies with EUR as first item
*/
private static Set<TradeCurrency> getSortedSEPACurrencyCodes() {
return CountryUtil.getAllSepaCountries().stream()
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
}
// At OKPay you can exchange internally those currencies
public static List<TradeCurrency> getAllOKPayCurrencies() {
return new ArrayList<>(Arrays.asList(
new FiatCurrency("EUR"),
new FiatCurrency("USD"),
new FiatCurrency("GBP"),
new FiatCurrency("CHF"),
new FiatCurrency("RUB"),
new FiatCurrency("PLN"),
new FiatCurrency("JPY"),
new FiatCurrency("CAD"),
new FiatCurrency("AUD"),
new FiatCurrency("CZK"),
new FiatCurrency("NOK"),
new FiatCurrency("SEK"),
new FiatCurrency("DKK"),
new FiatCurrency("HRK"),
new FiatCurrency("HUF"),
new FiatCurrency("NZD"),
new FiatCurrency("RON"),
new FiatCurrency("TRY"),
new FiatCurrency("ZAR"),
new FiatCurrency("HKD"),
new FiatCurrency("CNY")
));
}
public static boolean isFiatCurrency(String currencyCode) {
return !(isCryptoCurrency(currencyCode)) && Currency.getInstance(currencyCode) != null;
}
public static Optional<FiatCurrency> getFiatCurrency(String currencyCode) {
return allSortedFiatCurrencies.stream().filter(e -> e.getCode().equals(currencyCode)).findAny();
}
@SuppressWarnings("WeakerAccess")
public static boolean isCryptoCurrency(String currencyCode) {
return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny().isPresent();
}
public static Optional<CryptoCurrency> getCryptoCurrency(String currencyCode) {
return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny();
}
public static boolean isCryptoNoteCoin(String currencyCode) {
return currencyCode.equals("XMR") || currencyCode.equals("BCN");
}
public static FiatCurrency getCurrencyByCountryCode(String countryCode) {
return new FiatCurrency(Currency.getInstance(new Locale(LanguageUtil.getDefaultLanguage(), countryCode)).getCurrencyCode());
}
public static String getNameByCode(String currencyCode) {
try {
return Currency.getInstance(currencyCode).getDisplayName(Preferences.getDefaultLocale());
} catch (Throwable t) {
// Seems that it is a cryptocurrency
return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findFirst().get().getName();
}
}
public static TradeCurrency getDefaultTradeCurrency() {
return Preferences.getDefaultTradeCurrency();
}
}
|
package org.kohsuke.stapler;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class AcceptHeader {
private final List<Atom> atoms = new ArrayList<Atom>();
private final String ranges;
* something like "text/*;q=0.5,*; q=0.1"
*/
public AcceptHeader(String ranges) {
this.ranges = ranges;
for (String r : StringUtils.split(ranges, ','))
atoms.add(new Atom(r));
}
/**
* Media range plus parameters and extensions
*/
protected static class Atom {
private final String major;
private final String minor;
private final Map<String, String> params = new HashMap<String, String>();
private final float q;
@Override
public String toString() {
StringBuilder s = new StringBuilder(major +'/'+ minor);
for (String k : params.keySet())
s.append(";").append(k).append("=").append(params.get(k));
return s.toString();
}
* Parses a string like 'application/*;q=0.5' into a typed object.
*/
protected Atom(String range) {
String[] parts = StringUtils.split(range, ";");
for (int i = 1; i < parts.length; ++i) {
String p = parts[i];
String[] subParts = StringUtils.split(p, '=');
if (subParts.length == 2)
params.put(subParts[0].trim(), subParts[1].trim());
}
String fullType = parts[0].trim();
// Java URLConnection class sends an Accept header that includes a
if (fullType.equals("*"))
fullType = "*/*";
String[] types = StringUtils.split(fullType, "/");
major = types[0].trim();
minor = types[1].trim();
float q = NumberUtils.toFloat(params.get("q"), 1);
if (q < 0 || q > 1)
q = 1;
this.q = q;
params.remove("q"); // normalize this away as this gets in the fitting
}
* than "text/*", which still fits better than "* /*"
*/
private int fit(Atom that) {
if (!wildcardMatch(that.major, this.major) || !wildcardMatch(that.minor, this.minor))
return -1;
int fitness;
fitness = (this.major.equals(that.major)) ? 10000 : 0;
fitness += (this.minor.equals(that.minor)) ? 1000 : 0;
// parameter matches increase score
for (String k : that.params.keySet()) {
if (that.params.get(k).equals(this.params.get(k))) {
fitness++;
}
}
return fitness;
}
}
private static boolean wildcardMatch(String a, String b) {
return a.equals(b) || a.equals("*") || b.equals("*");
}
/**
* Given a MIME type, find the entry from this Accept header that fits the best.
*
* @param mimeType
*/
protected @Nullable Atom match(String mimeType) {
Atom target = new Atom(mimeType);
int bestFitness = -1;
Atom best = null;
for (Atom a : atoms) {
int f = a.fit(target);
if (f>bestFitness) {
best = a;
}
bestFitness = f;
}
return best;
}
* new AcceptHeader("image/*;q=0.5, image/png;q=1").select("text/plain","text/xml") => null
* </pre>
*
* @return null if none of the choices in {@code supported} is acceptable to the client.
*/
public String select(Iterable<String> supported) {
float bestQ = 0;
String best = null;
for (String s : supported) {
Atom a = match(s);
if (a!= null && a.q > bestQ) {
bestQ = a.q;
best = s;
}
}
if (best==null)
throw HttpResponses.error(HttpServletResponse.SC_NOT_ACCEPTABLE,
"Requested MIME types '" + ranges + "' didn't match any of the available options "+supported);
return best;
}
public String select(String... supported) {
return select(Arrays.asList(supported));
}
@Override
public String toString() {
return super.toString()+"["+ranges+"]";
}
// this performs databinding for @Header parameter injection
public static class StaplerConverterImpl implements Converter {
public Object convert(Class type, Object value) {
return new AcceptHeader(value.toString());
}
}
}
|
package tk.mybatis.mapper.entity;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.util.Sqls;
import tk.mybatis.mapper.util.StringUtil;
import java.util.*;
/**
* Example
*
* @author liuzh
*/
public class Example implements IDynamicTableName {
protected String orderByClause;
protected boolean distinct;
protected boolean exists;
protected boolean notNull;
protected boolean forUpdate;
protected Set<String> selectColumns;
protected Set<String> excludeColumns;
protected String countColumn;
protected List<Criteria> oredCriteria;
protected Class<?> entityClass;
protected EntityTable table;
protected Map<String, EntityColumn> propertyMap;
protected String tableName;
protected OrderBy ORDERBY;
/**
* existstrue
*
* @param entityClass
*/
public Example(Class<?> entityClass) {
this(entityClass, true);
}
/**
* existsnotNullfalse
*
* @param entityClass
* @param exists - truefalse
*/
public Example(Class<?> entityClass, boolean exists) {
this(entityClass, exists, false);
}
/**
* exists
*
* @param entityClass
* @param exists - truefalse
* @param notNull - truefalse
*/
public Example(Class<?> entityClass, boolean exists, boolean notNull) {
this.exists = exists;
this.notNull = notNull;
oredCriteria = new ArrayList<Criteria>();
this.entityClass = entityClass;
table = EntityHelper.getEntityTable(entityClass);
//#159
propertyMap = table.getPropertyMap();
this.ORDERBY = new OrderBy(this, propertyMap);
}
private Example(Builder builder) {
this.exists = builder.exists;
this.notNull = builder.notNull;
this.distinct = builder.distinct;
this.entityClass = builder.entityClass;
this.propertyMap = builder.propertyMap;
this.selectColumns = builder.selectColumns;
this.excludeColumns = builder.excludeColumns;
this.oredCriteria = builder.exampleCriterias;
this.forUpdate = builder.forUpdate;
this.tableName = builder.tableName;
if (!StringUtil.isEmpty(builder.orderByClause.toString())) {
this.orderByClause = builder.orderByClause.toString();
}
}
public static Builder builder(Class<?> entityClass) {
return new Builder(entityClass);
}
public OrderBy orderBy(String property) {
this.ORDERBY.orderBy(property);
return this.ORDERBY;
}
/**
* selectProperties
*
* @param properties
* @return
*/
public Example excludeProperties(String... properties) {
if (properties != null && properties.length > 0) {
if (this.excludeColumns == null) {
this.excludeColumns = new LinkedHashSet<String>();
}
for (String property : properties) {
if (propertyMap.containsKey(property)) {
this.excludeColumns.add(propertyMap.get(property).getColumn());
} else {
throw new MapperException(" " + entityClass.getSimpleName() + " \'" + property + "\'@Transient");
}
}
}
return this;
}
/**
* -
*
* @param properties
* @return
*/
public Example selectProperties(String... properties) {
if (properties != null && properties.length > 0) {
if (this.selectColumns == null) {
this.selectColumns = new LinkedHashSet<String>();
}
for (String property : properties) {
if (propertyMap.containsKey(property)) {
this.selectColumns.add(propertyMap.get(property).getColumn());
} else {
throw new MapperException(" " + entityClass.getSimpleName() + " \'" + property + "\'@Transient");
}
}
}
return this;
}
public void or(Criteria criteria) {
criteria.setAndOr("or");
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
criteria.setAndOr("or");
oredCriteria.add(criteria);
return criteria;
}
public void and(Criteria criteria) {
criteria.setAndOr("and");
oredCriteria.add(criteria);
}
public Criteria and() {
Criteria criteria = createCriteriaInternal();
criteria.setAndOr("and");
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
criteria.setAndOr("and");
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria(propertyMap, exists, notNull);
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
public static class OrderBy {
protected Map<String, EntityColumn> propertyMap;
private Example example;
private Boolean isProperty;
public OrderBy(Example example, Map<String, EntityColumn> propertyMap) {
this.example = example;
this.propertyMap = propertyMap;
}
private String property(String property) {
if (StringUtil.isEmpty(property) || StringUtil.isEmpty(property.trim())) {
throw new MapperException("property");
}
property = property.trim();
if (!propertyMap.containsKey(property)) {
throw new MapperException("" + property + "!");
}
return propertyMap.get(property).getColumn();
}
public OrderBy orderBy(String property) {
String column = property(property);
if (column == null) {
isProperty = false;
return this;
}
if (StringUtil.isNotEmpty(example.getOrderByClause())) {
example.setOrderByClause(example.getOrderByClause() + "," + column);
} else {
example.setOrderByClause(column);
}
isProperty = true;
return this;
}
public OrderBy desc() {
if (isProperty) {
example.setOrderByClause(example.getOrderByClause() + " DESC");
isProperty = false;
}
return this;
}
public OrderBy asc() {
if (isProperty) {
example.setOrderByClause(example.getOrderByClause() + " ASC");
isProperty = false;
}
return this;
}
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected boolean exists;
protected boolean notNull;
protected String andOr;
protected Map<String, EntityColumn> propertyMap;
protected GeneratedCriteria(Map<String, EntityColumn> propertyMap, boolean exists, boolean notNull) {
super();
this.exists = exists;
this.notNull = notNull;
criteria = new ArrayList<Criterion>();
this.propertyMap = propertyMap;
}
private String column(String property) {
if (propertyMap.containsKey(property)) {
return propertyMap.get(property).getColumn();
} else if (exists) {
throw new MapperException("" + property + "!");
} else {
return null;
}
}
private String property(String property) {
if (propertyMap.containsKey(property)) {
return property;
} else if (exists) {
throw new MapperException("" + property + "!");
} else {
return null;
}
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new MapperException("Value for condition cannot be null");
}
if (condition.startsWith("null")) {
return;
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
if (notNull) {
throw new MapperException("Value for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
if (notNull) {
throw new MapperException("Between values for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value1, value2));
}
protected void addOrCriterion(String condition) {
if (condition == null) {
throw new MapperException("Value for condition cannot be null");
}
if (condition.startsWith("null")) {
return;
}
criteria.add(new Criterion(condition, true));
}
protected void addOrCriterion(String condition, Object value, String property) {
if (value == null) {
if (notNull) {
throw new MapperException("Value for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value, true));
}
protected void addOrCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
if (notNull) {
throw new MapperException("Between values for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value1, value2, true));
}
public Criteria andIsNull(String property) {
addCriterion(column(property) + " is null");
return (Criteria) this;
}
public Criteria andIsNotNull(String property) {
addCriterion(column(property) + " is not null");
return (Criteria) this;
}
public Criteria andEqualTo(String property, Object value) {
addCriterion(column(property) + " =", value, property(property));
return (Criteria) this;
}
public Criteria andNotEqualTo(String property, Object value) {
addCriterion(column(property) + " <>", value, property(property));
return (Criteria) this;
}
public Criteria andGreaterThan(String property, Object value) {
addCriterion(column(property) + " >", value, property(property));
return (Criteria) this;
}
public Criteria andGreaterThanOrEqualTo(String property, Object value) {
addCriterion(column(property) + " >=", value, property(property));
return (Criteria) this;
}
public Criteria andLessThan(String property, Object value) {
addCriterion(column(property) + " <", value, property(property));
return (Criteria) this;
}
public Criteria andLessThanOrEqualTo(String property, Object value) {
addCriterion(column(property) + " <=", value, property(property));
return (Criteria) this;
}
public Criteria andIn(String property, Iterable values) {
addCriterion(column(property) + " in", values, property(property));
return (Criteria) this;
}
public Criteria andNotIn(String property, Iterable values) {
addCriterion(column(property) + " not in", values, property(property));
return (Criteria) this;
}
public Criteria andBetween(String property, Object value1, Object value2) {
addCriterion(column(property) + " between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria andNotBetween(String property, Object value1, Object value2) {
addCriterion(column(property) + " not between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria andLike(String property, String value) {
addCriterion(column(property) + " like", value, property(property));
return (Criteria) this;
}
public Criteria andNotLike(String property, String value) {
addCriterion(column(property) + " not like", value, property(property));
return (Criteria) this;
}
/**
*
*
* @param condition "length(countryname)<5"
* @return
*/
public Criteria andCondition(String condition) {
addCriterion(condition);
return (Criteria) this;
}
/**
* value
*
* @param condition "length(countryname)="
* @param value 5
* @return
*/
public Criteria andCondition(String condition, Object value) {
criteria.add(new Criterion(condition, value));
return (Criteria) this;
}
/**
*
*
* @param param
* @author Bob {@link}0haizhu0@gmail.com
* @Date 2015717 12:48:08
*/
public Criteria andEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
andEqualTo(property, value);
}
}
}
return (Criteria) this;
}
/**
* null is null
*
* @param param
*/
public Criteria andAllEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
andEqualTo(property, value);
} else {
andIsNull(property);
}
}
}
return (Criteria) this;
}
public Criteria orIsNull(String property) {
addOrCriterion(column(property) + " is null");
return (Criteria) this;
}
public Criteria orIsNotNull(String property) {
addOrCriterion(column(property) + " is not null");
return (Criteria) this;
}
public Criteria orEqualTo(String property, Object value) {
addOrCriterion(column(property) + " =", value, property(property));
return (Criteria) this;
}
public Criteria orNotEqualTo(String property, Object value) {
addOrCriterion(column(property) + " <>", value, property(property));
return (Criteria) this;
}
public Criteria orGreaterThan(String property, Object value) {
addOrCriterion(column(property) + " >", value, property(property));
return (Criteria) this;
}
public Criteria orGreaterThanOrEqualTo(String property, Object value) {
addOrCriterion(column(property) + " >=", value, property(property));
return (Criteria) this;
}
public Criteria orLessThan(String property, Object value) {
addOrCriterion(column(property) + " <", value, property(property));
return (Criteria) this;
}
public Criteria orLessThanOrEqualTo(String property, Object value) {
addOrCriterion(column(property) + " <=", value, property(property));
return (Criteria) this;
}
public Criteria orIn(String property, Iterable values) {
addOrCriterion(column(property) + " in", values, property(property));
return (Criteria) this;
}
public Criteria orNotIn(String property, Iterable values) {
addOrCriterion(column(property) + " not in", values, property(property));
return (Criteria) this;
}
public Criteria orBetween(String property, Object value1, Object value2) {
addOrCriterion(column(property) + " between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria orNotBetween(String property, Object value1, Object value2) {
addOrCriterion(column(property) + " not between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria orLike(String property, String value) {
addOrCriterion(column(property) + " like", value, property(property));
return (Criteria) this;
}
public Criteria orNotLike(String property, String value) {
addOrCriterion(column(property) + " not like", value, property(property));
return (Criteria) this;
}
/**
*
*
* @param condition "length(countryname)<5"
* @return
*/
public Criteria orCondition(String condition) {
addOrCriterion(condition);
return (Criteria) this;
}
/**
* value
*
* @param condition "length(countryname)="
* @param value 5
* @return
*/
public Criteria orCondition(String condition, Object value) {
criteria.add(new Criterion(condition, value, true));
return (Criteria) this;
}
/**
*
*
* @param param
* @author Bob {@link}0haizhu0@gmail.com
* @Date 2015717 12:48:08
*/
public Criteria orEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
orEqualTo(property, value);
}
}
}
return (Criteria) this;
}
/**
* null is null
*
* @param param
*/
public Criteria orAllEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
orEqualTo(property, value);
} else {
orIsNull(property);
}
}
}
return (Criteria) this;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public String getAndOr() {
return andOr;
}
public void setAndOr(String andOr) {
this.andOr = andOr;
}
public List<Criterion> getCriteria() {
return criteria;
}
public boolean isValid() {
return criteria.size() > 0;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria(Map<String, EntityColumn> propertyMap, boolean exists, boolean notNull) {
super(propertyMap, exists, notNull);
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private String andOr;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
protected Criterion(String condition) {
this(condition, false);
}
protected Criterion(String condition, Object value, String typeHandler) {
this(condition, value, typeHandler, false);
}
protected Criterion(String condition, Object value) {
this(condition, value, null, false);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
this(condition, value, secondValue, typeHandler, false);
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null, false);
}
protected Criterion(String condition, boolean isOr) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
this.andOr = isOr ? "or" : "and";
}
protected Criterion(String condition, Object value, String typeHandler, boolean isOr) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
this.andOr = isOr ? "or" : "and";
if (value instanceof Collection<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value, boolean isOr) {
this(condition, value, null, isOr);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler, boolean isOr) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
this.andOr = isOr ? "or" : "and";
}
protected Criterion(String condition, Object value, Object secondValue, boolean isOr) {
this(condition, value, secondValue, null, isOr);
}
public String getAndOr() {
return andOr;
}
public void setAndOr(String andOr) {
this.andOr = andOr;
}
public String getCondition() {
return condition;
}
public Object getSecondValue() {
return secondValue;
}
public String getTypeHandler() {
return typeHandler;
}
public Object getValue() {
return value;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
}
public static class Builder {
private final Class<?> entityClass;
protected EntityTable table;
protected Map<String, EntityColumn> propertyMap;
private StringBuilder orderByClause;
private boolean distinct;
private boolean exists;
private boolean notNull;
private boolean forUpdate;
private Set<String> selectColumns;
private Set<String> excludeColumns;
private String countColumn;
private List<Sqls.Criteria> sqlsCriteria;
private List<Example.Criteria> exampleCriterias;
private String tableName;
public Builder(Class<?> entityClass) {
this(entityClass, true);
}
public Builder(Class<?> entityClass, boolean exists) {
this(entityClass, exists, false);
}
public Builder(Class<?> entityClass, boolean exists, boolean notNull) {
this.entityClass = entityClass;
this.exists = exists;
this.notNull = notNull;
this.orderByClause = new StringBuilder();
this.table = EntityHelper.getEntityTable(entityClass);
this.propertyMap = table.getPropertyMap();
this.sqlsCriteria = new ArrayList<Sqls.Criteria>(2);
}
public Builder distinct() {
return setDistinct(true);
}
public Builder forUpdate() {
return setForUpdate(true);
}
public Builder selectDistinct(String... properties) {
select(properties);
this.distinct = true;
return this;
}
public Builder select(String... properties) {
if (properties != null && properties.length > 0) {
if (this.selectColumns == null) {
this.selectColumns = new LinkedHashSet<String>();
}
for (String property : properties) {
if (this.propertyMap.containsKey(property)) {
this.selectColumns.add(propertyMap.get(property).getColumn());
} else {
throw new MapperException("" + property + "!");
}
}
}
return this;
}
public Builder notSelect(String... properties) {
if (properties != null && properties.length > 0) {
if (this.excludeColumns == null) {
this.excludeColumns = new LinkedHashSet<String>();
}
for (String property : properties) {
if (propertyMap.containsKey(property)) {
this.excludeColumns.add(propertyMap.get(property).getColumn());
} else {
throw new MapperException("" + property + "!");
}
}
}
return this;
}
public Builder from(String tableName) {
return setTableName(tableName);
}
public Builder where(Sqls sqls) {
Sqls.Criteria criteria = sqls.getCriteria();
criteria.setAndOr("and");
this.sqlsCriteria.add(criteria);
return this;
}
public Builder where(SqlsCriteria sqls) {
Sqls.Criteria criteria = sqls.getCriteria();
criteria.setAndOr("and");
this.sqlsCriteria.add(criteria);
return this;
}
public Builder andWhere(Sqls sqls) {
Sqls.Criteria criteria = sqls.getCriteria();
criteria.setAndOr("and");
this.sqlsCriteria.add(criteria);
return this;
}
public Builder andWhere(SqlsCriteria sqls) {
Sqls.Criteria criteria = sqls.getCriteria();
criteria.setAndOr("and");
this.sqlsCriteria.add(criteria);
return this;
}
public Builder orWhere(Sqls sqls) {
Sqls.Criteria criteria = sqls.getCriteria();
criteria.setAndOr("or");
this.sqlsCriteria.add(criteria);
return this;
}
public Builder orWhere(SqlsCriteria sqls) {
Sqls.Criteria criteria = sqls.getCriteria();
criteria.setAndOr("or");
this.sqlsCriteria.add(criteria);
return this;
}
public Builder orderBy(String... properties) {
return orderByAsc(properties);
}
public Builder orderByAsc(String... properties) {
contactOrderByClause(" Asc", properties);
return this;
}
public Builder orderByDesc(String... properties) {
contactOrderByClause(" Desc", properties);
return this;
}
private void contactOrderByClause(String order, String... properties) {
StringBuilder columns = new StringBuilder();
for (String property : properties) {
String column;
if ((column = propertyforOderBy(property)) != null) {
columns.append(",").append(column);
}
}
columns.append(order);
if (columns.length() > 0) {
orderByClause.append(columns);
}
}
public Example build() {
this.exampleCriterias = new ArrayList<Criteria>();
for (Sqls.Criteria criteria : sqlsCriteria) {
Example.Criteria exampleCriteria = new Example.Criteria(this.propertyMap, this.exists, this.notNull);
exampleCriteria.setAndOr(criteria.getAndOr());
for (Sqls.Criterion criterion : criteria.getCriterions()) {
String condition = criterion.getCondition();
String andOr = criterion.getAndOr();
String property = criterion.getProperty();
Object[] values = criterion.getValues();
transformCriterion(exampleCriteria, condition, property, values, andOr);
}
exampleCriterias.add(exampleCriteria);
}
if (this.orderByClause.length() > 0) {
this.orderByClause = new StringBuilder(this.orderByClause.substring(1, this.orderByClause.length()));
}
return new Example(this);
}
private void transformCriterion(Example.Criteria exampleCriteria, String condition, String property, Object[] values, String andOr) {
if (values.length == 0) {
if ("and".equals(andOr)) {
exampleCriteria.addCriterion(column(property) + " " + condition);
} else {
exampleCriteria.addOrCriterion(column(property) + " " + condition);
}
} else if (values.length == 1) {
if ("and".equals(andOr)) {
exampleCriteria.addCriterion(column(property) + " " + condition, values[0], property(property));
} else {
exampleCriteria.addOrCriterion(column(property) + " " + condition, values[0], property(property));
}
} else if (values.length == 2) {
if ("and".equals(andOr)) {
exampleCriteria.addCriterion(column(property) + " " + condition, values[0], values[1], property(property));
} else {
exampleCriteria.addOrCriterion(column(property) + " " + condition, values[0], values[1], property(property));
}
}
}
private String column(String property) {
if (propertyMap.containsKey(property)) {
return propertyMap.get(property).getColumn();
} else if (exists) {
throw new MapperException("" + property + "!");
} else {
return null;
}
}
private String property(String property) {
if (propertyMap.containsKey(property)) {
return property;
} else if (exists) {
throw new MapperException("" + property + "!");
} else {
return null;
}
}
private String propertyforOderBy(String property) {
if (StringUtil.isEmpty(property) || StringUtil.isEmpty(property.trim())) {
throw new MapperException("property");
}
property = property.trim();
if (!propertyMap.containsKey(property)) {
throw new MapperException("" + property + "!");
}
return propertyMap.get(property).getColumn();
}
public Builder setDistinct(boolean distinct) {
this.distinct = distinct;
return this;
}
public Builder setForUpdate(boolean forUpdate) {
this.forUpdate = forUpdate;
return this;
}
public Builder setTableName(String tableName) {
this.tableName = tableName;
return this;
}
}
public String getCountColumn() {
return countColumn;
}
@Override
public String getDynamicTableName() {
return tableName;
}
public Class<?> getEntityClass() {
return entityClass;
}
public String getOrderByClause() {
return orderByClause;
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public Set<String> getSelectColumns() {
if (selectColumns != null && selectColumns.size() > 0) {
} else if (excludeColumns != null && excludeColumns.size() > 0) {
Collection<EntityColumn> entityColumns = propertyMap.values();
selectColumns = new LinkedHashSet<String>(entityColumns.size() - excludeColumns.size());
for (EntityColumn column : entityColumns) {
if (!excludeColumns.contains(column.getColumn())) {
selectColumns.add(column.getColumn());
}
}
}
return selectColumns;
}
public boolean isDistinct() {
return distinct;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isForUpdate() {
return forUpdate;
}
public void setForUpdate(boolean forUpdate) {
this.forUpdate = forUpdate;
}
/**
* count(property)
*
* @param property
*/
public void setCountProperty(String property) {
if (propertyMap.containsKey(property)) {
this.countColumn = propertyMap.get(property).getColumn();
}
}
/**
*
*
* @param tableName
*/
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
|
public class Analyst {
private String name;
private String symbolAnalyst;
private History history;
public String name() {
// TODO - implement Analyst.name
throw new UnsupportedOperationException();
}
public String symbolAnalyst() {
// TODO - implement Analyst.symbolAnalyst
throw new UnsupportedOperationException();
}
public History history() {
// TODO - implement Analyst.history
throw new UnsupportedOperationException();
}
/**
*
* @param symbol
*/
public float stockPerformance(int symbol) {
// TODO - implement Analyst.stockPerformance
throw new UnsupportedOperationException();
}
}
|
package org.random.util;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base64;
import org.random.api.RandomOrgCache;
import org.random.api.RandomOrgClient;
import org.random.api.exception.RandomOrgBadHTTPResponseException;
import org.random.api.exception.RandomOrgInsufficientBitsError;
import org.random.api.exception.RandomOrgInsufficientRequestsError;
import org.random.api.exception.RandomOrgJSONRPCError;
import org.random.api.exception.RandomOrgKeyNotRunningError;
import org.random.api.exception.RandomOrgRANDOMORGError;
import org.random.api.exception.RandomOrgSendTimeoutException;
public class RandomOrgRandom extends Random {
private static final long serialVersionUID = 4785372106424073371L;
/** integer bit masks */
private static final int[] MASKS = new int[] {
0x00000000,
0x00000001,
0x00000003,
0x00000007,
0x0000000F,
0x0000001F,
0x0000003F,
0x0000007F,
0x000000FF,
0x000001FF,
0x000003FF,
0x000007FF,
0x00000FFF,
0x00001FFF,
0x00003FFF,
0x00007FFF,
0x0000FFFF,
0x0001FFFF,
0x0003FFFF,
0x0007FFFF,
0x000FFFFF,
0x001FFFFF,
0x003FFFFF,
0x007FFFFF,
0x00FFFFFF,
0x01FFFFFF,
0x03FFFFFF,
0x07FFFFFF,
0x0FFFFFFF,
0x1FFFFFFF,
0x3FFFFFFF,
0x7FFFFFFF,
0xFFFFFFFF,
};
/** Default cache size is 256.
**/
private static final int DEFAULT_CACHE_BITS = 256;
/** Default cache number is 2.
**/
private static final int DEFAULT_CACHE_SIZE = 2;
/** Cache bits - number of bits to cache per blob.
**
** Must be within the [1,1048576] range and must be divisible by 8.
** This will be automatically enforced (rounded up unless too large).
**
** Default is 256.
**/
private int cacheBits;
/** Cache size - number of blobs to cache.
**
** Cache size minimum is 2, which will be automatically enforced.
** Default size is 2.
**/
private int cacheSize;
/** The local RANDOM.ORG blob cache.
** <p>
** This stores up to {@link #cacheSize}*{@link #cacheBits} values.
**/
private RandomOrgCache<String[]> cache;
/** The current blob from which random numbers are being pulled.
** Once blob is in use it is removed from the blob cache.
**/
private byte[] currentBlob;
/** Next index into the currently active blob.
**/
private int currentBlobIndex;
/** The RANDOM.ORG client used for the cache.
**
** @see #cache
**/
private RandomOrgClient client;
/** Left to right bit buffer for getting less than 8 bits.
**
** @see #bitBufferLength
**/
private byte bitBuffer = 0;
/** Number of bits currently stored in the <code>bitBuffer</code>.
**
** @see #bitBuffer
**/
private int bitBufferLength = 0;
private static final Logger LOGGER = Logger.getLogger(RandomOrgClient.class.getPackage().getName());
public RandomOrgRandom(String apiKey) {
this(apiKey, DEFAULT_CACHE_SIZE, DEFAULT_CACHE_BITS);
}
public RandomOrgRandom(String apiKey, int cacheSize, int cacheBits) {
this.cacheSize = cacheSize;
// must be within the [1,1048576] range and must be divisible by 8.
this.cacheBits = cacheBits > 0 ? (cacheBits < 1048577 ? (cacheBits % 8 == 0 ? cacheBits : cacheBits+1) : 1048576) : 8;
// Defining the RANDOM.ORG client with the given API key.
this.client = RandomOrgClient.getRandomOrgClient(apiKey);
// Getting a blob of random bits at once.
this.cache = this.client.createBlobCache(1, cacheBits, RandomOrgClient.BLOB_FORMAT_BASE64, cacheSize);
}
/** Create a new RandomOrgRandom using the given client.
** <p>
** This RandomOrgRandom needs a RANDOM.ORG client instance for the random.org API.
** <p>
** The RANDOM.ORG library guarantees only one client is running per API key at any
** given time, so it's safe to create multiple <code>RandomOrgRandom</code> classes
** with the same API key if needed.
**
** @param client the RANDOM.ORG client to use
**/
public RandomOrgRandom(RandomOrgClient client) {
this(client, DEFAULT_CACHE_SIZE, DEFAULT_CACHE_BITS);
}
/** Create a new RandomOrgRandom using the given client and cache size.
** <p>
** This RandomOrgRandom needs a RANDOM.ORG client instance for the random.org API.
** <p>
** The <code>cacheSize</code> specifies the number of blobs maintained by a background thread.
** If you set the value too high it may consume much of your daily allowance on the server.
** It the value is too low your application may block frequently. The default value is 2.
** <p>
** The <code>cacheBits</code> parameter specifies the number of bits per blob in the cache.
** If you set the value too high it may consume much of your daily allowance on the server.
** It the value is too low your application will block frequently. The default value is 256.
** <p>
** The RANDOM.ORG library guarantees only one client is running per API key at any
** given time, so it's safe to create multiple <code>RandomOrgRandom</code> classes
** with the same API key if needed.
**
** @param client the RANDOM.ORG client to use
** @param cacheSize the desired cache size
**/
public RandomOrgRandom(RandomOrgClient client, int cacheSize, int cacheBits) {
this.client = client;
this.cacheSize = cacheSize;
// must be within the [1,1048576] range and must be divisible by 8.
this.cacheBits = cacheBits > 0 ? (cacheBits < 1048577 ? (cacheBits % 8 == 0 ? cacheBits : cacheBits+1) : 1048576) : 8;
// Getting a blob of random bits at once.
this.cache = this.client.createBlobCache(1, cacheBits, RandomOrgClient.BLOB_FORMAT_BASE64, cacheSize);
}
/** Gets the remaining quota for the used key.
** <p>
** This method gets the bit count still retrievable from the
** server. If this value is negative no more bits can be retrieved.
** <p>
** Note that this method will access a buffered value if that value is not too
** old, so the returned value can be different from the value on the server.
** <p>
** Note that this value does not contain the local cached bits, so the current
** local available bit count can be larger than the return of this method.
**
** @return the remaining bit quota
**
** @throws RandomOrgSendTimeoutException @see {@link RandomOrgClient#getBitsLeft()}
** @throws RandomOrgKeyNotRunningError @see {@link RandomOrgClient#getBitsLeft()}
** @throws RandomOrgInsufficientRequestsError @see {@link RandomOrgClient#getBitsLeft()}
** @throws RandomOrgInsufficientBitsError @see {@link RandomOrgClient#getBitsLeft()}
** @throws RandomOrgBadHTTPResponseException @see {@link RandomOrgClient#getBitsLeft()}
** @throws RandomOrgRANDOMORGError @see {@link RandomOrgClient#getBitsLeft()}
** @throws RandomOrgJSONRPCError @see {@link RandomOrgClient#getBitsLeft()}
** @throws MalformedURLException @see {@link RandomOrgClient#getBitsLeft()}
** @throws IOException @see {@link RandomOrgClient#getBitsLeft()}
**/
public long getRemainingQuota() throws RandomOrgSendTimeoutException,
RandomOrgKeyNotRunningError,
RandomOrgInsufficientRequestsError,
RandomOrgInsufficientBitsError,
RandomOrgBadHTTPResponseException,
RandomOrgRANDOMORGError,
RandomOrgJSONRPCError,
MalformedURLException,
IOException {
return this.client.getBitsLeft();
}
/** Returns the size of the local cache.
** <p>
** This size can be specified in the constructor.
**
** @return the size of the cache.
**/
public int getCachSize() {
return this.cacheSize;
}
/** Returns the size of each blob in the cache in bits.
** <p>
** This size can be specified in the constructor.
**
** @return the number of bits per blob in the cache.
**/
public int getCachBits() {
return this.cacheBits;
}
/** Blocking implementation of {@link java.util.Random#nextInt(int)} using RANDOM.ORG's RNG service.
**
** @see java.util.Random#nextInt(int)
**
** @throws NoSuchElementException if a number couldn't be retrieved.
**/
@Override
public int nextInt(int n) {
if (n <= 0) {
throw new IllegalArgumentException("n must be positive");
}
// between 0 (inclusive) and n (exclusive) there's only one possible return value
if (n == 1) {
return 0;
}
int r = -1;
// To simulate random.nextInt(max) using raw data, we should scale it.
// If max is a power of 2, this is easy: just read the next log2(max)
// bits from the cached data and transform them to an int.
if (this.isPow2(n)) {
r = next(this.log2(n));
// If max is not a power of 2, we calculate max' which is the smallest power of 2
// greater than max. We then read the next log2(max') bits from the
// cached data and transform them to an int. If the value is < max,
// return it. Otherwise we discard it and read the next log(max') bits,
// etc. In the worst case, this is wasteful, but it achieves a uniform
// distribution regardless of the range.
} else {
int nC = nextPow2(n);
do {
r = next(this.log2(nC));
} while (r >= n && r != -1);
}
return r;
}
/** Blocking implementation of {@link java.util.Random#next(int)} using RANDOM.ORG's RNG service.
**
** @see java.util.Random#next(int)
**
** @throws NoSuchElementException if a number couldn't be retrieved.
**/
@Override
public synchronized int next(int bits) {
// how many full bytes to read
int sz = bits / 8;
// how many bits
int n = bits % 8;
// our integer
byte[] b = new byte[4];
Arrays.fill(b, (byte)0);
// position for partial bits, if applicable
int p = b.length-(sz + 1);
// need a new set of bytes?
if (this.currentBlob == null || (this.currentBlobIndex + (sz-1)) >= this.currentBlob.length) {
int remaining = this.currentBlob == null ? 0 : this.currentBlob.length - this.currentBlobIndex;
// save the remaining bytes
if (remaining > 0) {
System.arraycopy(this.currentBlob, this.currentBlobIndex, b, b.length-sz, remaining);
sz-=remaining;
}
this.moveToNextBlob();
}
// read the next n bits from the cached data into a byte[]
System.arraycopy(this.currentBlob, this.currentBlobIndex, b, b.length-sz, sz);
this.currentBlobIndex+=sz;
// read in single bits
if (n > 0) {
b[p] = this.getSubBits(n);
}
// transform byte[] to int
int num = ByteBuffer.wrap(b).getInt();
num &= MASKS[bits];
return num;
}
protected synchronized byte getSubBits(int numBits) {
if (numBits < 1 || 7 < numBits) {
throw new IllegalArgumentException("Only 1 to 7 bits can be fetched");
}
byte b = (byte) 0;
int bits = numBits;
// need a new set of bits?
if (this.bitBufferLength < numBits) {
// need a new blob?
if (this.currentBlob == null || this.currentBlobIndex >= this.currentBlob.length) {
this.moveToNextBlob();
}
// save the remaining bits - use mask of number remaining in buffer
b = (byte) (this.bitBuffer & (byte) ((Math.pow(2, this.bitBufferLength)) - 1));
bits-=this.bitBufferLength;
b <<= bits;
// get next byte
this.bitBuffer = this.currentBlob[this.currentBlobIndex++];
this.bitBufferLength = 8;
}
// fill up (rest of) bits - use mask of number remaining to get
b |= (byte) (this.bitBuffer & (byte) ((Math.pow(2, bits)) - 1));
// move bitbuffer on
this.bitBuffer >>= bits;
this.bitBufferLength -= bits;
return b;
}
/** Gets the next blob from the cache.
**
** @throws NoSuchElementException if a blob couldn't be retrieved.
**/
private synchronized void moveToNextBlob() throws NoSuchElementException {
String blob = null;
try {
while (true) {
blob = null;
try {
blob = this.cache.get()[0];
} catch (NoSuchElementException e) {
try {
if (getRemainingQuota() <= 0) {
throw e;
}
} catch (RandomOrgKeyNotRunningError e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
throw e;
} catch (RandomOrgInsufficientRequestsError e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
throw e;
} catch (RandomOrgInsufficientBitsError e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
throw e;
} catch (MalformedURLException e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
throw e;
} catch (RandomOrgSendTimeoutException e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
} catch (RandomOrgBadHTTPResponseException e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
} catch (RandomOrgRANDOMORGError e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
} catch (RandomOrgJSONRPCError e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
} catch (IOException e1) {
LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage());
}
}
if (blob == null) {
// block until new bits are available
Thread.sleep(100);
} else {
this.currentBlob = Base64.decodeBase64(blob);
this.currentBlobIndex = 0;
return;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
throw new NoSuchElementException("Interrupt was triggered.");
}
}
/** Return true if n is a power of 2.
**
** @param n to evaluate
** @return true if n is a power of 2
**/
private boolean isPow2(int n) {
return n == 0 ? false : (n & (n - 1)) == 0;
}
/** Return next power of 2 greater than n.
**
** @param n to evaluate
** @return next power of 2 greater than n.
**/
private int nextPow2(int n) {
int v = n;
v
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/** Log2 of n.
**
** @param n to evaluate - should be a power of 2.
** @return Log2 of n
**/
private int log2(int n) {
int log = 0;
if ((n & 0xffff0000) != 0 ) {
n >>>= 16;
log = 16;
}
if (n >= 256) {
n >>>= 8;
log += 8;
}
if (n >= 16) {
n >>>= 4;
log += 4;
}
if (n >= 4) {
n >>>= 2;
log += 2;
}
return log + (n >>> 1);
}
}
|
package org.realityforge.dbdiff;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.ConsoleHandler;
import java.util.logging.Logger;
import org.postgresql.Driver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import static org.testng.Assert.*;
public abstract class AbstractDatabaseDiffTest
{
protected abstract Dialect getDialect();
protected abstract Driver getDriver();
protected abstract String getDatabase1();
protected abstract String getDatabase2();
protected final void assertMatch( final String schema,
final String ddl1,
final String ddl2 )
throws Exception
{
diff( schema, ddl1, ddl2, true );
}
protected final void assertNotMatch( final String schema,
final String ddl1,
final String ddl2 )
throws Exception
{
diff( schema, ddl1, ddl2, false );
}
private void diff( final String schema,
final String ddl1,
final String ddl2,
final boolean shouldMatch )
throws Exception
{
setupDatabases();
final DatabaseDiff dd = newDatabaseDiff();
dd.setLogger( newLogger() );
dd.getSchemas().add( schema );
executeSQL( ddl1, getDatabase1() );
executeSQL( ddl2, getDatabase2() );
assertEquals( dd.diff(), !shouldMatch, "Does diff match expected" );
tearDownDatabases();
}
protected abstract void setupDatabases()
throws Exception;
protected abstract void tearDownDatabases()
throws Exception;
private DatabaseDiff newDatabaseDiff()
{
final DatabaseDiff dd = new DatabaseDiff();
dd.setDialect( getDialect() );
dd.setDriver( getDriver() );
dd.setDatabase1( getDatabase1() );
dd.setDatabase2( getDatabase2() );
return dd;
}
private Logger newLogger()
{
final Logger logger = Logger.getAnonymousLogger();
logger.setUseParentHandlers( false );
final ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter( new RawFormatter() );
logger.addHandler( handler );
return logger;
}
protected final void executeSQL( final String sql, final String database )
throws SQLException
{
final Connection connection1 = getDriver().connect( database, new Properties() );
connection1.createStatement().execute( sql );
connection1.close();
}
protected final String join( final char separator, final String... commands )
{
final StringBuilder sb = new StringBuilder();
for ( final String command : commands )
{
if ( 0 != sb.length() )
{
sb.append( separator );
}
sb.append( command );
}
return sb.toString();
}
protected final String s( final String... commands )
{
return join( ';', commands );
}
}
|
package snowballmadness;
import java.util.*;
import com.google.common.base.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
/**
* This class is the base class that hosts the logic that triggers when a
* snowball hits a target.
*
* We keep these in a weak hash map, so it is important that this object (and
* all subclasses) not hold onto a reference to a Snowball, or that snowball may
* never be collected.
*
* @author DanJ
*/
public abstract class SnowballLogic {
// Logic
/**
* This is called when the snowball is launched.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void launch(Snowball snowball, SnowballInfo info) {
}
/**
* this is called every many times every second.
*
* @param snowball A snowball that gets a chance to do something.
* @param info Other information about the snowball.
*/
public void tick(Snowball snowball, SnowballInfo info) {
}
/**
* This is called when the snowball hits something and returns teh damange
* to be done (which can be 0).
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
* @param target The entity that was hit.
* @param damage The damage the snowball is expected to do..
* @return The damage teh snowball will do.
*/
public double damage(Snowball snowball, SnowballInfo info, Entity target, double proposedDamage) {
return proposedDamage;
}
/**
* This is called when the snowball hits something.
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
*/
public void hit(Snowball snowball, SnowballInfo info) {
}
@Override
public String toString() {
return getClass().getSimpleName();
}
// Creation
/**
* This method creates a new logic, but does not start it. It chooses the
* logic based on 'hint', which is the stack immediately above the snowball
* being thrown.
*
* @param slice The inventory slice above the snowball in the inventory.
* @return The new logic, not yet started or attached to a snowball, or null
* if the snowball will be illogical.
*/
public static SnowballLogic createLogic(InventorySlice slice) {
ItemStack hint = slice.getBottomItem();
if (hint == null) {
return null;
}
switch (hint.getType()) {
case ARROW:
return new ArrowSnowballLogic(hint);
case COBBLESTONE:
case SMOOTH_BRICK:
case SAND:
case GRAVEL:
return new BlockPlacementSnowballLogic(hint.getType());
//considering adding data values to smooth brick so it randomizes
//including mossy, cracked and even silverfish
case ENDER_STONE:
return new BlockPlacementSnowballLogic(Material.ENDER_PORTAL);
case QUARTZ_ORE:
return new BlockPlacementSnowballLogic(Material.PORTAL);
//fixed these so they are harder to get! Both work!
//The end portals are persistent, stack, and cannot be seen from
//underneath (NASTY trap) and the nether portal shards are very
//visible and a block update makes them go away again.
case WATER_BUCKET:
return new BlockPlacementSnowballLogic(Material.WATER);
case LAVA_BUCKET:
return new BlockPlacementSnowballLogic(Material.LAVA);
case NETHERRACK:
return new BlockEmbedSnowballLogic(Material.NETHERRACK, Material.FIRE, 1);
case LADDER:
return new BlockEmbedSnowballLogic(Material.LADDER, Material.AIR, 256);
case DIAMOND_ORE:
return new BlockEmbedSnowballLogic(Material.AIR, Material.AIR, 256);
case DIAMOND_BLOCK:
return new BlockEmbedSnowballLogic(Material.AIR, Material.AIR, -1);
case WOOD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case GOLD_SWORD:
case DIAMOND_SWORD:
return new SwordSnowballLogic(slice);
case TORCH:
return new LinkedTrailSnowballLogic(Material.FIRE);
case TNT:
return new TNTSnowballLogic(4);
case SULPHUR:
return new TNTSnowballLogic(1);
case FIREWORK:
return new JetpackSnowballLogic();
case FLINT_AND_STEEL:
return new FlintAndSteelSnowballLogic(Material.FIRE);
case SPIDER_EYE:
return new ReversedSnowballLogic();
case SUGAR:
return new SpeededSnowballLogic(1.5, slice.skip(1));
case CAKE:
return new SpeededSnowballLogic(3, slice.skip(1));
//the cake is a... lazor!
case GLOWSTONE_DUST:
return new PoweredSnowballLogic(1.5, slice.skip(1));
case GLOWSTONE:
return new PoweredSnowballLogic(3, slice.skip(1));
case SNOW_BALL:
return new MultiplierSnowballLogic(hint.getAmount(), slice.skip(1));
case SLIME_BALL:
return new BouncySnowballLogic(hint.getAmount(), slice.skip(1));
case GRASS:
return new RegenerationSnowballLogic(slice);
case GHAST_TEAR:
return new SpawnSnowballLogic(EntityType.GHAST);
case ROTTEN_FLESH:
return new SpawnSnowballLogic(EntityType.ZOMBIE);
case ENCHANTMENT_TABLE:
return new SpawnSnowballLogic(EntityType.WITCH, EntityType.ENDER_CRYSTAL, 8.0);
case GOLD_NUGGET:
return new ItemDropSnowballLogic(Material.PORK, 1);
case GOLD_INGOT:
return new SpawnSnowballLogic(EntityType.PIG);
case GOLD_BLOCK:
return new SpawnSnowballLogic(EntityType.PIG, EntityType.PIG_ZOMBIE, 8.0);
case STRING:
return new SpawnSnowballLogic(EntityType.SPIDER, EntityType.CAVE_SPIDER, 8.0);
case EYE_OF_ENDER:
return new SpawnSnowballLogic(EntityType.ENDERMAN);
case DRAGON_EGG:
return new SpawnSnowballLogic(EntityType.CHICKEN, EntityType.ENDER_DRAGON, 8.0);
case MILK_BUCKET:
return new SpawnSnowballLogic(EntityType.COW, EntityType.MUSHROOM_COW, 8.0);
case JACK_O_LANTERN:
return new SpawnSnowballLogic(EntityType.SKELETON, EntityType.WITHER_SKULL, 8.0);
case SKULL_ITEM:
SkullType skullType = SkullType.values()[hint.getDurability()];
return SpawnSnowballLogic.fromSkullType(skullType);
default:
return null;
}
}
// Event Handling
/**
* This method processes a new snowball, executing its launch() method and
* also recording it so the hit() method can be called later.
*
* The shooter may be provided as well; this allows us to launch snowballs
* from places that are not a player, but associated it with a player
* anyway.
*
* @param inventory The inventory slice that determines the logic type.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
* @return The logic associated with the snowball; may be null.
*/
public static SnowballLogic performLaunch(InventorySlice inventory, Snowball snowball, SnowballInfo info) {
SnowballLogic logic = createLogic(inventory);
if (logic != null) {
performLaunch(logic, snowball, info);
}
return logic;
}
/**
* This overload of performLaunch takes the logic to associate with the
* snowball instead of an inventory.
*
* @param logic The logic to apply to the snowball; can't be null.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
*/
public static void performLaunch(SnowballLogic logic, Snowball snowball, SnowballInfo info) {
logic.start(snowball, info);
Bukkit.getLogger().info(String.format("Snowball launched: %s [%d]", logic, inFlight.size()));
logic.launch(snowball, info);
}
/**
* This method processes the impact of a snowball, and invokes the hit()
* method on its logic object, if it has one.
*
* @param snowball The impacting snowball.
*/
public static void performHit(Snowball snowball) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
try {
Bukkit.getLogger().info(String.format("Snowball hit: %s [%d]", data.logic, inFlight.size()));
data.logic.hit(snowball, data.info);
} finally {
data.logic.end(snowball);
}
}
}
public static double performDamage(Snowball snowball, Entity target, double damage) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
Bukkit.getLogger().info(String.format("Snowball damage: %s [%d]", data.logic, inFlight.size()));
return data.logic.damage(snowball, data.info, target, damage);
}
return damage;
}
/**
* This method handles a projectile launch; it selects a logic and runs its
* launch method.
*
* @param e The event data.
*/
public static void onProjectileLaunch(SnowballMadness plugin, ProjectileLaunchEvent e) {
Projectile proj = e.getEntity();
LivingEntity shooter = proj.getShooter();
if (proj instanceof Snowball && shooter instanceof Player) {
Snowball snowball = (Snowball) proj;
Player player = (Player) shooter;
PlayerInventory inv = player.getInventory();
int heldSlot = inv.getHeldItemSlot();
ItemStack sourceStack = inv.getItem(heldSlot);
if (sourceStack == null || sourceStack.getType() == Material.SNOW_BALL) {
InventorySlice slice = InventorySlice.fromSlot(player, heldSlot).skip(1);
SnowballLogic logic = performLaunch(slice, snowball, new SnowballInfo(plugin));
if (logic != null && player.getGameMode() != GameMode.CREATIVE) {
replenishSnowball(plugin, inv, heldSlot);
}
}
}
}
/**
* This method calls tick() on each snowball that has any logic.
*/
public static void onTick() {
for (Map.Entry<Snowball, SnowballLogicData> e : inFlight.entrySet()) {
Snowball snowball = e.getKey();
SnowballLogic logic = e.getValue().logic;
SnowballInfo info = e.getValue().info;
logic.tick(snowball, info);
}
}
/**
* This method handles the damage a snowball does on impact, and can adjust
* that damage.
*
* @param e The damage event.
*/
public static void onEntityDamageByEntityEvent(EntityDamageByEntityEvent e) {
Entity damagee = e.getEntity();
Entity damager = e.getDamager();
double damage = e.getDamage();
if (damager instanceof Snowball) {
double newDamage = performDamage((Snowball) damager, damagee, damage);
if (newDamage != damage) {
e.setDamage(newDamage);
}
}
}
/**
* This method increments the number of snowballs in the slot indicated; but
* it does this after a brief delay since changes made during the launch are
* ignored. If the indicated slot contains something that is not a snowball,
* we don't update it. If it is empty, we put one snowball in there.
*
* @param plugin The plugin, used to schedule the update.
* @param inventory The inventory to update.
* @param slotIndex The slot to update.
*/
private static void replenishSnowball(Plugin plugin, final PlayerInventory inventory, final int slotIndex) {
// ugh. We must delay the inventory update or it won't take.
new BukkitRunnable() {
@Override
public void run() {
ItemStack replacing = inventory.getItem(slotIndex);
if (replacing == null) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL));
} else if (replacing.getType() == Material.SNOW_BALL) {
int oldCount = replacing.getAmount();
int newCount = Math.min(16, oldCount + 1);
if (oldCount != newCount) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL, newCount));
}
}
}
}.runTaskLater(plugin, 1);
}
/**
* This method handles a projectile hit event, and runs the hit method.
*
* @param e The event data.
*/
public static void onProjectileHit(ProjectileHitEvent e) {
Projectile proj = e.getEntity();
if (proj instanceof Snowball) {
performHit((Snowball) proj);
}
}
// Logic Association
private final static WeakHashMap<Snowball, SnowballLogicData> inFlight = new WeakHashMap<Snowball, SnowballLogicData>();
/**
* this class just holds the snowball logic and info for a snowball; the
* snowball itself must not be kept here, as this is the value of a
* weak-hash-map keyed on the snowballs. We don't want to keep them alive.
*/
private final static class SnowballLogicData {
public final SnowballLogic logic;
public final SnowballInfo info;
public SnowballLogicData(SnowballLogic logic, SnowballInfo info) {
this.logic = logic;
this.info = info;
}
}
/**
* This returns the logic and shooter for a snowball that has one.
*
* @param snowball The snowball of interest; can be null.
* @return The logic and info of the snowball, or null if it is an illogical
* snowball or it was null.
*/
private static SnowballLogicData getData(Snowball snowball) {
if (snowball != null) {
return inFlight.get(snowball);
} else {
return null;
}
}
/**
* This method registers the logic so getLogic() can find it. Logics only
* work once started.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void start(Snowball snowball, SnowballInfo info) {
inFlight.put(snowball, new SnowballLogicData(this, info));
}
/**
* This method unregisters this logic so it is no longer invoked; this is
* done when snowball hits something.
*
* @param snowball The snowball to deregister.
*/
public void end(Snowball snowball) {
inFlight.remove(snowball);
}
// Utilitu Methods
/**
* This returns the of the nearest non-air block underneath 'location' that
* is directly over the ground. If 'locaiton' is inside the ground, we'll
* return a new copy of the same location.
*
* @param location The starting location; this is not modified.
* @return A new location describing the place found.
*/
public static Location getGroundUnderneath(Location location) {
Location loc = location.clone();
for (;;) {
if (loc.getBlock().isEmpty() || (loc.getBlock().getType() == Material.LEAVES)) {
loc.add(0, -1, 0);
} else {
return loc;
}
}
}
}
|
package net.jueb.util4j.buffer.tool;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.function.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BufferBuilder{
protected Logger log=LoggerFactory.getLogger(getClass());
private final String bufferClass;
private final String writeMethodName;
private final String readMethodName;
private final List<Predicate<Field>> fieldFilter=new ArrayList<>();
private final List<TypeHandler> typeHandler=new ArrayList<>();
public BufferBuilder(String bufferClass, String writeMethodName, String readMethodName) {
super();
this.bufferClass = bufferClass;
this.writeMethodName = writeMethodName;
this.readMethodName = readMethodName;
}
/**
*
* @param filter
*/
public void addFieldSkipFilter(Predicate<Field> filter)
{
fieldFilter.add(filter);
}
/**
*
* @param typeHandler
*/
public void addTypeHandler(TypeHandler typeHandler)
{
this.typeHandler.add(typeHandler);
}
public void build(Class<?> clazz,StringBuilder writesb,StringBuilder readsb)throws Exception
{
Class<?> buffClass=Thread.currentThread().getContextClassLoader().loadClass(bufferClass);
String buffClassSimpleName=buffClass.getSimpleName();
writesb.append("\t").append("@Override").append("\n");
writesb.append("\t").append("public void "+writeMethodName+"("+buffClassSimpleName+" buffer) {").append("\n");
readsb.append("\t").append("@Override").append("\n");
readsb.append("\t").append("public void "+readMethodName+"("+buffClassSimpleName+" buffer) {").append("\n");
if (clazz.getSuperclass() != null) {
try {
clazz.getSuperclass().getMethod(writeMethodName,buffClass);
writesb.append("\t").append("super."+writeMethodName+"(buffer);").append("\n");
} catch (NoSuchMethodException ex) {
}
try {
clazz.getSuperclass().getMethod(readMethodName,buffClass);
readsb.append("\t").append("super."+readMethodName+"(buffer);").append("\n");
} catch (NoSuchMethodException ex) {
}
}
Field[] fields = clazz.getDeclaredFields();
for(Field field: fields)
{
if(skipField(field))
{
log.warn(clazz.getSimpleName()+"==>skipField:"+field.getName());
continue;
}
StringBuilder write = new StringBuilder();
StringBuilder read = new StringBuilder();
try {
write.append("\t").append("//field->"+field.getName()).append("\n");
read.append("\t").append("//field->"+field.getName()).append("\n");
readWriteField(field, write, read);
writesb.append(write.toString());
readsb.append(read.toString());
} catch (Exception e) {
log.error(clazz.getSimpleName()+"==>buildFieldError:field="+field.getName()+",error="+e.getMessage());
}
}
writesb.append("\t").append("}").append("\n");
readsb.append("\t").append("}").append("\n");
}
public boolean skipField(Field field)
{
for(Predicate<Field> f:fieldFilter)
{
if(f.test(field))
{
return true;
}
}
return false;
}
/**
*
* @param field
* @param writesb
* @param readsb
*/
public void readWriteField(Field field,StringBuilder writesb,StringBuilder readsb)
{
Class<?> type=field.getType();
String varName=field.getName();
Type[] actTypes=new Type[]{};
if(field.getGenericType() instanceof ParameterizedType)
{
actTypes=((ParameterizedType)field.getGenericType()).getActualTypeArguments();
}
declearVar(type, varName, writesb, readsb,actTypes);
if(type.isPrimitive() && type.equals(boolean.class))
{
writesb.append("\t").append(varName+"=is"+fieldUper(field.getName())+"();").append("\n");
}else
{
writesb.append("\t").append(varName+"=get"+fieldUper(field.getName())+"();").append("\n");
}
readWriteVar(type, varName, writesb, readsb,true,actTypes);
readsb.append("\t").append("set" + fieldUper(field.getName()) + "(" + varName + ");").append("\n");
}
public String getVarTypeName(Class<?> varType)
{
String str=varType.getSimpleName();
if(varType.isPrimitive())
{
str=varType.getName();
}
str=str.replace('$','.');
return str;
}
/**
*
* @param type
* @param actTypes
* @return
*/
public String getVarTypeName(Class<?> type,Type ...actTypes)
{
String varType=getVarTypeName(type);
if(actTypes!=null)
{
List<String> acts=new ArrayList<>();
for(Type act:actTypes)
{
acts.add(act.getTypeName());
}
if(!acts.isEmpty())
{
if(acts.size()==1)
{
varType+="<"+acts.remove(0)+">";
}else
{
varType+="<"+String.join(",", acts)+">";
}
}
}
varType=varType.replace('$','.');
return varType;
}
/**
*
* @param type
* @param varName
*/
public void declearVar(Class<?> type,String varName,StringBuilder writesb,StringBuilder readsb,Type ...actTypes)
{
String varType=getVarTypeName(type, actTypes);
if(type.isPrimitive())
{
if(type.equals(boolean.class))
{
writesb.append("\t").append(varType+" "+varName+"=false;").append("\n");
}else
{
writesb.append("\t").append(varType+" "+varName+"=0;").append("\n");
readsb.append("\t").append(varType+" "+varName+"=0;").append("\n");
}
}else
{
writesb.append("\t").append(varType+" "+varName+"=null;").append("\n");
readsb.append("\t").append(varType+" "+varName+"=null;").append("\n");
}
}
/**
*
* @param type
* @param varName
* @param writesb
* @param readsb
*/
public void readWriteVar(Class<?> type,String varName,StringBuilder writesb,StringBuilder readsb,boolean nullCheck,Type ...actualType)
{
// if(type.isArray())
// Class<?> ctype=type.getComponentType();
// String varTypeName=getVarTypeName(type);
// String i=varName+"_i";
// String var_data=varName+"_d";
// String var_dataTypeName=getVarTypeName(ctype);
// String var_len=varName+"_l";
// if(nullCheck)
// writesb.append("\t").append("if (" + varName + "!=null){").append("\n");
// writesb.append("\t").append("buffer.writeBoolean(true);").append("\n");
// readsb.append("\t").append("if (buffer.readBoolean()){").append("\n");
// writesb.append("\t").append("int "+var_len+"="+varName+".length;").append("\n");
// writesb.append("\t").append("buffer.writeInt("+var_len+");").append("\n");
// writesb.append("\t").append("for(int "+i +"=0;" +i+"<"+var_len+";"+i+"++){").append("\n");
// writesb.append("\t").append(var_dataTypeName+" "+var_data+"="+varName+"["+i+"];").append("\n");
// readsb.append("\t").append("int "+var_len+"=buffer.readInt();").append("\n");
// readsb.append("\t").append(varName+"=("+varTypeName+") java.lang.reflect.Array.newInstance("+var_dataTypeName+".class,"+var_len+");").append("\n");
// readsb.append("\t").append("for(int "+i +"=0;" +i+"<"+var_len+";"+i+"++){").append("\n");
// readsb.append("\t").append(var_dataTypeName+" "+var_data+";").append("\n");
// readWriteVar_Base(ctype, var_data, writesb, readsb, false);
// readsb.append("\t").append(varName+"["+i+"]="+var_data+";").append("\n");
// writesb.append("\t").append("}").append("\n");
// readsb.append("\t").append("}").append("\n");
// if(nullCheck)
// writesb.append("\t").append("}else{");
// writesb.append("\t").append("buffer.writeBoolean(false);}").append("\n");
// readsb.append("\t").append("}").append("\n");
// return ;
if(Map.class.isAssignableFrom(type))
{
Type keyType_=actualType[0];
Type valueType_=actualType[1];
Class<?> keyType=null;
Class<?> valueType=null;
Type[] keyTypeActs=new Type[]{};
Type[] valueTypeActs=new Type[]{};
if(keyType_ instanceof ParameterizedType)
{
ParameterizedType pt=(ParameterizedType)keyType_;
keyType=(Class<?>)pt.getRawType();
keyTypeActs=pt.getActualTypeArguments();
}else
{
keyType=(Class<?>)keyType_;
}
if(valueType_ instanceof ParameterizedType)
{
ParameterizedType pt=(ParameterizedType)valueType_;
valueType=(Class<?>)pt.getRawType();
valueTypeActs=pt.getActualTypeArguments();
}else
{
valueType=(Class<?>)valueType_;
}
String var_mapSize=varName+"_ms";
String var_mapI=varName+"_mi";
String var_mapKey=varName+"_mk";
String var_mapValue=varName+"_mv";
String var_mapKeyType=getVarTypeName(keyType,keyTypeActs);
String var_mapValueType=getVarTypeName(valueType,valueTypeActs);
String varInstanceType=type.getCanonicalName();
if(type==Map.class)
{
varInstanceType="java.util.HashMap";
}
if(nullCheck)
{
writesb.append("\t").append("if (" + varName + "!=null){").append("\n");
writesb.append("\t").append("buffer.writeBoolean(true);").append("\n");
readsb.append("\t").append("if (buffer.readBoolean()){").append("\n");
}
writesb.append("\t").append("int "+var_mapSize+"="+varName+".size();").append("\n");
writesb.append("\t").append("buffer.writeInt("+var_mapSize+");").append("\n");
writesb.append("\t").append("for("+var_mapKeyType+" "+var_mapKey +":" +varName+".keySet()){").append("\n");
writesb.append("\t").append(var_mapValueType+" "+var_mapValue+"="+varName+".get("+var_mapKey+");").append("\n");
readsb.append("\t").append("int "+var_mapSize+"=buffer.readInt();").append("\n");
readsb.append("\t").append(varName+"=new "+varInstanceType+"<>();").append("\n");
readsb.append("\t").append("for(int "+var_mapI +"=0;" +var_mapI+"<"+var_mapSize+";"+var_mapI+"++){").append("\n");
readsb.append("\t").append(var_mapKeyType+" "+var_mapKey+";").append("\n");
readsb.append("\t").append(var_mapValueType+" "+var_mapValue+";").append("\n");
if(keyTypeActs.length>0)
{
readWriteVar(keyType, var_mapKey, writesb, readsb, false,keyTypeActs);
}else
{
readWriteVar_Base(keyType, var_mapKey, writesb, readsb, false);
}
if(valueTypeActs.length>0)
{
readWriteVar(valueType, var_mapValue, writesb, readsb, false,valueTypeActs);
}else
{
readWriteVar_Base(valueType, var_mapValue, writesb, readsb, false);
}
readsb.append("\t").append(varName+".put("+var_mapKey+","+var_mapValue+");").append("\n");
writesb.append("\t").append("}").append("\n");
readsb.append("\t").append("}").append("\n");
if(nullCheck)
{
writesb.append("\t").append("}else{");
writesb.append("\t").append("buffer.writeBoolean(false);}").append("\n");
readsb.append("\t").append("}").append("\n");
}
return ;
}
if(Collection.class.isAssignableFrom(type))
{
Type valueType_=actualType[0];
Class<?> valueType=null;
Type[] valueTypeActs=new Type[]{};
if(valueType_ instanceof ParameterizedType)
{
ParameterizedType pt=(ParameterizedType)valueType_;
valueType=(Class<?>)pt.getRawType();
valueTypeActs=pt.getActualTypeArguments();
}else
{
valueType=(Class<?>)valueType_;
}
String var_listSize=varName+"_ls";
String var_listI=varName+"_li";
String var_listValue=varName+"_lv";
String var_listValueType=getVarTypeName(valueType,valueTypeActs);
String varInstanceType=type.getCanonicalName();
if(List.class.isAssignableFrom(type))
{
if(type==List.class)
{
varInstanceType="java.util.ArrayList";
}
}
if(Queue.class.isAssignableFrom(type))
{
if(type==Queue.class)
{
varInstanceType="java.util.concurrent.ConcurrentLinkedQueue";
}
}
if(Set.class.isAssignableFrom(type))
{
if(type==Set.class)
{
varInstanceType="java.util.HashSet";
}
}
if(nullCheck)
{
writesb.append("\t").append("if (" + varName + "!=null){").append("\n");
writesb.append("\t").append("buffer.writeBoolean(true);").append("\n");
readsb.append("\t").append("if (buffer.readBoolean()){").append("\n");
}
writesb.append("\t").append("int "+var_listSize+"="+varName+".size();").append("\n");
writesb.append("\t").append("buffer.writeInt("+var_listSize+");").append("\n");
writesb.append("\t").append("for("+var_listValueType +" "+var_listValue+":" +varName+"){").append("\n");
readsb.append("\t").append("int "+var_listSize+"=buffer.readInt();").append("\n");
readsb.append("\t").append(varName+"=new "+varInstanceType+"<>();").append("\n");
readsb.append("\t").append("for(int "+var_listI +"=0;" +var_listI+"<"+var_listSize+";"+var_listI+"++){").append("\n");
readsb.append("\t").append(var_listValueType+" "+var_listValue+";").append("\n");
if(valueTypeActs.length>0)
{
readWriteVar(valueType, var_listValue, writesb, readsb, false,valueTypeActs);
}else
{
readWriteVar_Base(valueType, var_listValue, writesb, readsb, false);
}
readsb.append("\t").append(varName+".add("+var_listValue+");").append("\n");
writesb.append("\t").append("}").append("\n");
readsb.append("\t").append("}").append("\n");
if(nullCheck)
{
writesb.append("\t").append("}else{");
writesb.append("\t").append("buffer.writeBoolean(false);}").append("\n");
readsb.append("\t").append("}").append("\n");
}
return ;
}
readWriteVar_Base(type, varName, writesb, readsb, nullCheck);
}
/**
*
* @param type
* @param varName
* @param writesb
* @param readsb
* @param nullCheck
*/
public void readWriteVar_Base(Class<?> type,String varName,StringBuilder write,StringBuilder read,boolean nullCheck)
{
if (type.isPrimitive())
{
String typeName = type.getName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
write.append("\t").append("buffer.write"+typeName+"(" + varName + ");").append("\n");
read.append("\t").append(varName+"=buffer.read"+typeName+"();").append("\n");
return ;
}
StringBuilder writesb=new StringBuilder();
StringBuilder readsb=new StringBuilder();
if(nullCheck)
{
writesb.append("\t").append("if (" + varName + "!=null){").append("\n");
writesb.append("\t").append("buffer.writeBoolean(true);").append("\n");
readsb.append("\t").append("if (buffer.readBoolean()){").append("\n");
}
boolean match=false;
if(!match && type.isArray())
{
Class<?> ctype=type.getComponentType();
String varTypeName=getVarTypeName(type);
String i=varName+"_i";
String var_data=varName+"_d";
String var_dataTypeName=getVarTypeName(ctype);
String var_len=varName+"_l";
writesb.append("\t").append("int "+var_len+"="+varName+".length;").append("\n");
writesb.append("\t").append("buffer.writeInt("+var_len+");").append("\n");
writesb.append("\t").append("for(int "+i +"=0;" +i+"<"+var_len+";"+i+"++){").append("\n");
writesb.append("\t").append(var_dataTypeName+" "+var_data+"="+varName+"["+i+"];").append("\n");
readsb.append("\t").append("int "+var_len+"=buffer.readInt();").append("\n");
readsb.append("\t").append(varName+"=("+varTypeName+") java.lang.reflect.Array.newInstance("+var_dataTypeName+".class,"+var_len+");").append("\n");
readsb.append("\t").append("for(int "+i +"=0;" +i+"<"+var_len+";"+i+"++){").append("\n");
readsb.append("\t").append(var_dataTypeName+" "+var_data+";").append("\n");
readWriteVar_Base(ctype, var_data, writesb, readsb, false);
readsb.append("\t").append(varName+"["+i+"]="+var_data+";").append("\n");
writesb.append("\t").append("}").append("\n");
readsb.append("\t").append("}").append("\n");
match=true;
}
if(!match && type.isEnum())
{
String typeName = getVarTypeName(type);
writesb.append("\t").append("buffer.writeUTF(" + varName + ".name());").append("\n");
readsb.append("\t").append(varName+"="+typeName+".valueOf(buffer.readUTF());").append("\n");
match=true;
}
if(!match && String.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeUTF(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readUTF();").append("\n");
match=true;
}
if(!match && Boolean.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeBoolean(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readBoolean();").append("\n");
match=true;
}
if(!match && Byte.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeByte(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readByte();").append("\n");
match=true;
}
if(!match && Short.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeShort(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readShort();").append("\n");
match=true;
}
if(!match && Integer.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeInt(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readInt();").append("\n");
match=true;
}
if(!match && Long.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeLong(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readLong();").append("\n");
match=true;
}
if(!match && Double.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeDouble(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readDouble();").append("\n");
match=true;
}
if(!match && Float.class.isAssignableFrom(type))
{
writesb.append("\t").append("buffer.writeFloat(" + varName + ");").append("\n");
readsb.append("\t").append(varName+"=buffer.readFloat();").append("\n");
match=true;
}
if(!match)
{
boolean arrayType=type.isArray();
if(arrayType)
{
readWriteVar(type, varName, writesb, readsb, nullCheck);
}else
{
StringBuilder tmpRead=new StringBuilder();
StringBuilder tmpWrite=new StringBuilder();
Context ctx=new Context(){
@Override
public Class<?> varType() {
return type;
}
@Override
public String varName() {
return varName;
}
@Override
public String varBuffer() {
return "buffer";
}
@Override
public StringBuilder read() {
return tmpRead;
}
@Override
public StringBuilder write() {
return tmpWrite;
}
@Override
public String writeMethodName() {
return writeMethodName;
}
@Override
public String readMethodName() {
return readMethodName;
}
};
for(TypeHandler t:typeHandler)
{
match=t.handle(ctx);
if(match)
{
break;
}
}
if(match)
{
writesb.append(tmpWrite.toString());
readsb.append(tmpRead.toString());
}else
{
throw new RuntimeException("unSupported type:"+type+",varName:"+varName);
}
}
}
if(nullCheck)
{
writesb.append("\t").append("}else{");
writesb.append("\t").append("buffer.writeBoolean(false);}").append("\n");
readsb.append("\t").append("}").append("\n");
}
write.append(writesb.toString());
read.append(readsb.toString());
}
@FunctionalInterface
public static interface TypeHandler{
public boolean handle(Context context);
}
public static interface Context{
Class<?> varType();
String varName();
String varBuffer();
StringBuilder read();
StringBuilder write();
String writeMethodName();
String readMethodName();
}
protected boolean isAbstract(Class<?> type)
{
return Modifier.isAbstract(type.getModifiers());
}
/**
*
* @param filedName
* @return
*/
protected String fieldUper(String filedName)
{
return filedName.substring(0, 1).toUpperCase() + filedName.substring(1);
}
}
|
package org.zanata.webtrans.client.presenter;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.zanata.webtrans.shared.model.TransMemoryResultItem.MatchType;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import net.customware.gwt.presenter.client.EventBus;
import org.hamcrest.Matchers;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.zanata.common.ContentState;
import org.zanata.common.LocaleId;
import org.zanata.common.ProjectType;
import org.zanata.model.TestFixture;
import org.zanata.rest.dto.stats.ContainerTranslationStatistics;
import org.zanata.webtrans.client.events.CopyDataToEditorEvent;
import org.zanata.webtrans.client.events.TransMemoryShortcutCopyEvent;
import org.zanata.webtrans.client.events.TransUnitSelectionEvent;
import org.zanata.webtrans.client.events.UserConfigChangeEvent;
import org.zanata.webtrans.client.keys.KeyShortcut;
import org.zanata.webtrans.client.keys.ShortcutContext;
import org.zanata.webtrans.client.resources.WebTransMessages;
import org.zanata.webtrans.client.rpc.CachingDispatchAsync;
import org.zanata.webtrans.client.view.TranslationMemoryDisplay;
import org.zanata.webtrans.shared.auth.Identity;
import org.zanata.webtrans.shared.model.AuditInfo;
import org.zanata.webtrans.shared.model.DiffMode;
import org.zanata.webtrans.shared.model.DocumentId;
import org.zanata.webtrans.shared.model.DocumentInfo;
import org.zanata.webtrans.shared.model.ProjectIterationId;
import org.zanata.webtrans.shared.model.TransMemoryResultItem;
import org.zanata.webtrans.shared.model.TransUnit;
import org.zanata.webtrans.shared.model.UserWorkspaceContext;
import org.zanata.webtrans.shared.model.WorkspaceContext;
import org.zanata.webtrans.shared.model.WorkspaceId;
import org.zanata.webtrans.shared.rpc.GetTranslationMemory;
import org.zanata.webtrans.shared.rpc.GetTranslationMemoryResult;
import org.zanata.webtrans.shared.rpc.HasSearchType.SearchType;
import com.google.common.collect.Lists;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasValue;
@Test(groups = { "unit-tests" })
public class TransMemoryPresenterTest
{
private TransMemoryPresenter presenter;
@Mock
private TranslationMemoryDisplay display;
@Mock
private EventBus eventBus;
@Mock
private Identity identity;
@Mock
private UserWorkspaceContext userWorkspaceContext;
@Mock
private WorkspaceContext workspaceContext;
@Mock
private CachingDispatchAsync dispatcher;
@Mock
private TransMemoryDetailsPresenter transMemoryDetailsPresenter;
@Mock
private WebTransMessages messages;
@Mock
private KeyShortcutPresenter keyShortcutPresenter;
@Mock
private TransMemoryMergePresenter transMemoryMergePresenter;
@Mock
private HasValue<SearchType> searchType;
@Mock
private HasText tMTextBox;
@Mock
private ArrayList<TransMemoryResultItem> currentResult;
@Captor
private ArgumentCaptor<GetTranslationMemory> getTMActionCaptor;
@Captor
private ArgumentCaptor<AsyncCallback<GetTranslationMemoryResult>> callbackCaptor;
@Mock
private TransMemoryResultItem transMemoryResultItem;
@Captor
private ArgumentCaptor<CopyDataToEditorEvent> copyTMEventCaptor;
private UserConfigHolder configHolder;
@BeforeMethod
public void beforeMethod()
{
MockitoAnnotations.initMocks(this);
configHolder = new UserConfigHolder();
presenter = new TransMemoryPresenter(display, eventBus, dispatcher, messages, transMemoryDetailsPresenter, userWorkspaceContext, transMemoryMergePresenter, keyShortcutPresenter, configHolder);
verify(display).setDisplayMode(configHolder.getState().getTransMemoryDisplayMode());
}
@Test
public void onBind()
{
when(display.getSearchType()).thenReturn(searchType);
when(messages.searchTM()).thenReturn("Search TM");
presenter.bind();
verify(searchType).setValue(SearchType.FUZZY);
verify(eventBus).addHandler(TransUnitSelectionEvent.getType(), presenter);
verify(eventBus).addHandler(TransMemoryShortcutCopyEvent.getType(), presenter);
verify(display).setListener(presenter);
verify(keyShortcutPresenter).register(isA(KeyShortcut.class));
}
@Test
public void onTMMergeClick()
{
when(display.getSearchType()).thenReturn(searchType);
presenter.onTMMergeClick();
verify(transMemoryMergePresenter).prepareTMMerge();
}
@Test
public void showDiffLegend()
{
when(display.getSearchType()).thenReturn(searchType);
presenter.showDiffLegend(true);
verify(display).showDiffLegend(true);
}
@Test
public void hideDiffLegend()
{
when(display.getSearchType()).thenReturn(searchType);
presenter.showDiffLegend(false);
verify(display).showDiffLegend(false);
}
@Test
public void showTMDetails()
{
TransMemoryResultItem object = new TransMemoryResultItem(new ArrayList<String>(), new ArrayList<String>(), MatchType.ApprovedInternal, 0, 0);
when(display.getSearchType()).thenReturn(searchType);
presenter.showTMDetails(object);
verify(transMemoryDetailsPresenter).show(object);
}
@Test
public void fireCopyEvent()
{
TransMemoryResultItem object = new TransMemoryResultItem(new ArrayList<String>(), new ArrayList<String>(), MatchType.ApprovedInternal, 0, 0);
ArgumentCaptor<CopyDataToEditorEvent> eventCaptor = ArgumentCaptor.forClass(CopyDataToEditorEvent.class);
when(display.getSearchType()).thenReturn(searchType);
presenter.fireCopyEvent(object);
verify(eventBus).fireEvent(eventCaptor.capture());
}
@Test
public void createTMRequestForTransUnit()
{
WorkspaceId workspaceId = new WorkspaceId(new ProjectIterationId("projectSlug", "iterationSlug", ProjectType.Podir), LocaleId.EN_US);
DocumentInfo docInfo = new DocumentInfo(new DocumentId(new Long(1), ""), "test", "test/path", LocaleId.EN_US, new ContainerTranslationStatistics(), new AuditInfo(new Date(), "Translator"), new HashMap<String, String>(), new AuditInfo(new Date(), "last translator"));
when(display.getTmTextBox()).thenReturn(tMTextBox);
when(tMTextBox.getText()).thenReturn("query");
when(display.getSearchType()).thenReturn(searchType);
when(searchType.getValue()).thenReturn(SearchType.FUZZY);
when(userWorkspaceContext.getWorkspaceContext()).thenReturn(workspaceContext);
when(workspaceContext.getWorkspaceId()).thenReturn(workspaceId);
when(userWorkspaceContext.getSelectedDoc()).thenReturn(docInfo);
presenter.createTMRequestForTransUnit(TestFixture.makeTransUnit(1));
verify(display).startProcessing();
verify(dispatcher).execute(getTMActionCaptor.capture(), callbackCaptor.capture());
}
@Test
public void willDoNothingIfAlreadyHaveSubmittedRequest()
{
// Given: already have submitted request
GetTranslationMemory submittedRequest = mock(GetTranslationMemory.class);
presenter.setStatesForTesting(null, submittedRequest);
LocaleId localeId = new LocaleId("zh");
ProjectIterationId projectIterationId = new ProjectIterationId("project", "master", ProjectType.Podir);
when(userWorkspaceContext.getWorkspaceContext()).thenReturn(new WorkspaceContext(new WorkspaceId(projectIterationId, localeId), "workspaceName", localeId.getId()));
when(userWorkspaceContext.getSelectedDoc()).thenReturn(new DocumentInfo(new DocumentId(new Long(1), ""), "doc.txt", "/pot", new LocaleId("en-US"), new ContainerTranslationStatistics(), new AuditInfo(new Date(), "Translator"), new HashMap<String, String>(), new AuditInfo(new Date(), "last translator")));
// When:
presenter.createTMRequestForTransUnit(TestFixture.makeTransUnit(1));
// Then:
verifyZeroInteractions(dispatcher);
}
@Test
public void onFocus()
{
boolean isFocused = true;
when(display.getSearchType()).thenReturn(searchType);
presenter.onFocus(isFocused);
verify(keyShortcutPresenter).setContextActive(ShortcutContext.TM, isFocused);
verify(keyShortcutPresenter).setContextActive(ShortcutContext.Navigation, !isFocused);
verify(keyShortcutPresenter).setContextActive(ShortcutContext.Edit, !isFocused);
}
@Test
public void onBlur()
{
boolean isFocused = false;
when(display.getSearchType()).thenReturn(searchType);
presenter.onFocus(isFocused);
verify(keyShortcutPresenter).setContextActive(ShortcutContext.TM, isFocused);
verify(keyShortcutPresenter).setContextActive(ShortcutContext.Navigation, !isFocused);
verify(keyShortcutPresenter).setContextActive(ShortcutContext.Edit, !isFocused);
}
@Test
public void canFireSearchEvent()
{
// Given:
LocaleId targetLocale = new LocaleId("zh");
ProjectIterationId projectIterationId = new ProjectIterationId("project", "master", ProjectType.Podir);
when(userWorkspaceContext.getWorkspaceContext()).thenReturn(new WorkspaceContext(new WorkspaceId(projectIterationId, targetLocale), "workspaceName", targetLocale.getId()));
LocaleId sourceLocale = new LocaleId("en-US");
when(userWorkspaceContext.getSelectedDoc()).thenReturn(new DocumentInfo(new DocumentId(new Long(1), ""), "doc.txt", "/pot", sourceLocale, new ContainerTranslationStatistics(), new AuditInfo(new Date(), "Translator"), new HashMap<String, String>(), new AuditInfo(new Date(), "last translator")));
when(display.getTmTextBox()).thenReturn(tMTextBox);
when(tMTextBox.getText()).thenReturn("search query");
when(display.getSearchType()).thenReturn(searchType);
when(searchType.getValue()).thenReturn(SearchType.FUZZY);
// When:
presenter.fireSearchEvent();
// Then:
InOrder inOrder = inOrder(display, dispatcher);
inOrder.verify(display).startProcessing();
inOrder.verify(dispatcher).execute(getTMActionCaptor.capture(), callbackCaptor.capture());
// verify action
GetTranslationMemory action = getTMActionCaptor.getValue();
assertThat(action.getSearchType(), Matchers.equalTo(SearchType.FUZZY));
assertThat(action.getLocaleId(), Matchers.equalTo(targetLocale));
assertThat(action.getSourceLocaleId(), Matchers.equalTo(sourceLocale));
assertThat(action.getQuery().getQueries(), Matchers.contains("search query"));
}
@Test
public void fireSearchEventCallbackOnFailure()
{
// Given:
LocaleId localeId = new LocaleId("zh");
ProjectIterationId projectIterationId = new ProjectIterationId("project", "master", ProjectType.Podir);
when(userWorkspaceContext.getWorkspaceContext()).thenReturn(new WorkspaceContext(new WorkspaceId(projectIterationId, localeId), "workspaceName", localeId.getId()));
when(userWorkspaceContext.getSelectedDoc()).thenReturn(new DocumentInfo(new DocumentId(new Long(1), ""), "doc.txt", "/pot", new LocaleId("en-US"), new ContainerTranslationStatistics(), new AuditInfo(new Date(), "Translator"), new HashMap<String, String>(), new AuditInfo(new Date(), "last translator")));
when(display.getTmTextBox()).thenReturn(tMTextBox);
when(display.getSearchType()).thenReturn(searchType);
// When:
presenter.fireSearchEvent();
// Then:
InOrder inOrder = inOrder(display, dispatcher);
inOrder.verify(display).startProcessing();
inOrder.verify(dispatcher).execute(getTMActionCaptor.capture(), callbackCaptor.capture());
// verify callback on failure
AsyncCallback<GetTranslationMemoryResult> callback = callbackCaptor.getValue();
callback.onFailure(new RuntimeException("fail"));
inOrder.verify(display).stopProcessing(false);
}
@Test
public void fireSearchEventCallbackOnSuccess()
{
// Given:
LocaleId localeId = new LocaleId("zh");
ProjectIterationId projectIterationId = new ProjectIterationId("project", "master", ProjectType.Podir);
when(userWorkspaceContext.getWorkspaceContext()).thenReturn(new WorkspaceContext(new WorkspaceId(projectIterationId, localeId), "workspaceName", localeId.getId()));
when(userWorkspaceContext.getSelectedDoc()).thenReturn(new DocumentInfo(new DocumentId(new Long(1), ""), "doc.txt", "/pot", new LocaleId("en-US"), new ContainerTranslationStatistics(), new AuditInfo(new Date(), "Translator"), new HashMap<String, String>(), new AuditInfo(new Date(), "last translator")));
when(display.getTmTextBox()).thenReturn(tMTextBox);
when(tMTextBox.getText()).thenReturn("search query");
when(display.getSearchType()).thenReturn(searchType);
when(searchType.getValue()).thenReturn(SearchType.FUZZY);
// When:
presenter.fireSearchEvent();
// Then:
InOrder inOrder = inOrder(display, dispatcher);
inOrder.verify(display).startProcessing();
inOrder.verify(dispatcher).execute(getTMActionCaptor.capture(), callbackCaptor.capture());
// verify callback on success
AsyncCallback<GetTranslationMemoryResult> callback = callbackCaptor.getValue();
ArrayList<TransMemoryResultItem> transMemories = Lists.newArrayList(transMemoryResultItem);
callback.onSuccess(new GetTranslationMemoryResult(getTMActionCaptor.getValue(), transMemories));
inOrder.verify(display).renderTable(transMemories, Lists.newArrayList("search query"));
inOrder.verify(display).stopProcessing(true);
}
@Test
public void fireSearchEventCallbackOnSuccessButResultIsEmpty()
{
// Given:
LocaleId localeId = new LocaleId("zh");
ProjectIterationId projectIterationId = new ProjectIterationId("project", "master", ProjectType.Podir);
when(userWorkspaceContext.getWorkspaceContext()).thenReturn(new WorkspaceContext(new WorkspaceId(projectIterationId, localeId), "workspaceName", localeId.getId()));
when(userWorkspaceContext.getSelectedDoc()).thenReturn(new DocumentInfo(new DocumentId(new Long(1), ""), "doc.txt", "/pot", new LocaleId("en-US"), new ContainerTranslationStatistics(), new AuditInfo(new Date(), "Translator"), new HashMap<String, String>(), new AuditInfo(new Date(), "last translator")));
when(display.getTmTextBox()).thenReturn(tMTextBox);
when(display.getSearchType()).thenReturn(searchType);
when(searchType.getValue()).thenReturn(SearchType.FUZZY);
// When:
presenter.fireSearchEvent();
// Then:
InOrder inOrder = inOrder(display, dispatcher);
inOrder.verify(display).startProcessing();
inOrder.verify(dispatcher).execute(getTMActionCaptor.capture(), callbackCaptor.capture());
// verify callback on success
AsyncCallback<GetTranslationMemoryResult> callback = callbackCaptor.getValue();
ArrayList<TransMemoryResultItem> transMemories = Lists.newArrayList();
callback.onSuccess(new GetTranslationMemoryResult(getTMActionCaptor.getValue(), transMemories));
inOrder.verify(display).stopProcessing(false);
}
@Test
public void testOnTransUnitSelected()
{
TransUnit selection = TestFixture.makeTransUnit(1);
TransMemoryPresenter spyPresenter = spy(presenter);
doNothing().when(spyPresenter).createTMRequestForTransUnit(selection);
spyPresenter.onTransUnitSelected(new TransUnitSelectionEvent(selection));
verify(spyPresenter).createTMRequestForTransUnit(selection);
}
@Test
public void testOnTransMemoryCopy()
{
presenter.setStatesForTesting(Lists.newArrayList(transMemoryResultItem), null);
when(userWorkspaceContext.hasEditTranslationAccess()).thenReturn(true);
List<String> targetContents = Lists.newArrayList("a");
when(transMemoryResultItem.getTargetContents()).thenReturn(targetContents);
presenter.onTransMemoryCopy(new TransMemoryShortcutCopyEvent(0));
verify(eventBus).fireEvent(copyTMEventCaptor.capture());
assertThat(copyTMEventCaptor.getValue().getTargetResult(), Matchers.equalTo(targetContents));
}
@Test
public void onClearContent()
{
List<TransMemoryResultItem> currentResult = Lists.newArrayList(transMemoryResultItem);
presenter.setStatesForTesting(currentResult, null);
when(display.getTmTextBox()).thenReturn(tMTextBox);
presenter.clearContent();
verify(tMTextBox).setText("");
verify(display).clearTableContent();
assertThat(currentResult, Matchers.<TransMemoryResultItem>empty());
}
@Test
public void onDiffModeChanged()
{
List<TransMemoryResultItem> currentResult = Lists.newArrayList(transMemoryResultItem);
presenter.setStatesForTesting(currentResult, null);
presenter.onDiffModeChanged();
verify(display).redrawTable(currentResult);
}
@Test
public void willIgnoreDiffModeChangeIfNoCurrentResult()
{
presenter.setStatesForTesting(null, null);
presenter.onDiffModeChanged();
verify(display, never()).redrawTable(Mockito.anyList());
}
@Test
public void onEditorConfigOptionChange()
{
List<TransMemoryResultItem> currentResult = Lists.newArrayList(transMemoryResultItem);
presenter.setStatesForTesting(currentResult, null);
configHolder.setTMDisplayMode(DiffMode.HIGHLIGHT);
presenter.onUserConfigChanged(UserConfigChangeEvent.EDITOR_CONFIG_CHANGE_EVENT);
verify(display).setDisplayMode(configHolder.getState().getTransMemoryDisplayMode());
verify(display).redrawTable(currentResult);
}
@Test
public void ignoreIfNotEditorConfigOptionChange()
{
presenter.onUserConfigChanged(UserConfigChangeEvent.DOCUMENT_CONFIG_CHANGE_EVENT);
verifyNoMoreInteractions(display);
}
/**
* Make sure the Match type enum order is not changed as the UI depends on it.
* @throws Exception
* @see org.zanata.webtrans.server.rpc.GetTransMemoryHandler.TransMemoryResultComparator
*/
@Test
public void matchTypeEnumOrder() throws Exception
{
assertThat(MatchType.ApprovedInternal, greaterThan(MatchType.TranslatedInternal));
assertThat(MatchType.TranslatedInternal, greaterThan(MatchType.Imported));
}
}
|
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.InetAddress;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
//TODO : change the System.out.println with appropriate log event
/**
* This class holds the GUI part of the applet. It creates the GUI objects :
* button, fields, label and the ping globe and is responsible for their drawing
*
* @author RaphaelBonaque
*/
public class PingsGUI implements ActionListener {
private PingsApplet applet;
//GUI related variables, they holds the GUI components
private JButton pause_button, rename_button ;
private JLabel pings_counter_display, client_info_display;
private JTextField nickname_field;
private PingsGlobe ping_globe;
private Container button_container;
private Color text_color = new Color(227, 90, 0); //orange
private Color background_color = Color.white;
//GUI component for the retry
private JTextArea retry_message;
private JButton retry_button;
//State variables
private AtomicInteger pings_counter;
private GeoipInfo client_geoip_info = null;
private String ips = "";
//The observers of the subclients that add pings effect on the globe
// see ClientThreadObserver for more details
private clientThreadObserver[][] clients_observers;
//Some strings
private String pause_tooltip = "Pause the application once the current pings are done.";
private String resume_tooltip = "Resume the application.";
/**
* Create and initialize the components of the GUI.
* <p>
* That is :the globe , one pause/resume button and a field to change the
* client's nickname.
* The globe is turnable, zoomable and show an effect for pings
* The buttons comes with tooltips and shortcuts.
*/
PingsGUI(PingsApplet parent, int old_pings_counter) {
pings_counter = new AtomicInteger(old_pings_counter);
applet = parent;
applet.setBackground(background_color);
//Recover the content and background of the applet to add components
button_container = applet.getContentPane();
button_container.setBackground(background_color);
button_container.setLayout(null);
//Add the pause/resume button to the applet
pause_button = new JButton("Pause");
pause_button.setMnemonic(KeyEvent.VK_P);
pause_button.setToolTipText(pause_tooltip);
pause_button.setActionCommand("pause");
pause_button.addActionListener(this);
button_container.add(pause_button);
//Add the button to change the nickname
rename_button = new JButton("Change");
rename_button.setMnemonic(KeyEvent.VK_U);
rename_button.setToolTipText("Update your name for the leaderboard");
rename_button.setActionCommand("rename");
rename_button.addActionListener(this);
rename_button.setEnabled(false);
button_container.add(rename_button);
//Add the field to change the nickname
nickname_field = new JTextField(15);
nickname_field.setText(applet.pings_clients[0].getNickname());
//Add a listener to able/disable the rename_button if the nickname is
//different from the one stored
nickname_field.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
check_enable_button();
}
public void insertUpdate(DocumentEvent e) {
check_enable_button();
}
public void removeUpdate(DocumentEvent e) {
check_enable_button();
}
});
//Add a listener to update the name when 'ENTER' key is hit
nickname_field.addKeyListener(
new KeyListener() {
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
rename_button.doClick();
}
}
});
button_container.add(nickname_field);
//Add the display for the number of pings done
pings_counter_display = new JLabel("No ping sent yet");
pings_counter_display.setForeground(text_color);
button_container.add(pings_counter_display);
//Add the display for the client info
client_info_display = new JLabel("");
client_info_display.setForeground(text_color);
button_container.add(client_info_display);
//Add the globe
ping_globe = new PingsGlobe();
ping_globe.resizeGlobe(Math.min(applet.getWidth(),applet.getHeight()));
applet.getContentPane().add(ping_globe);
//Create the component for the "retry view" but don't hook them to the applet
retry_message = new JTextArea("");
retry_button = new JButton();
//Set the layout
setLayout();
//Add an observer to refresh globe on resize
applet.addComponentListener(new onResize());
//Add an observer to the client to update the GUI.
clients_observers = new clientThreadObserver[applet.nb_clients][];
for (int i = 0; i < applet.nb_clients; i++) {
PingsClient.subClient[] subClientsPool = applet.pings_clients[i].getSubClientsPoolCopy();
clients_observers[i] = new clientThreadObserver[subClientsPool.length];
for (int j = 0; j < subClientsPool.length; j++) {
clients_observers[i][j] = new clientThreadObserver();
subClientsPool[j].addObserver(clients_observers[i][j]);
}
}
}
/**
* Position the component of the GUI.
*
* Currently use absolute positioning to gather most of the component in the
* top-left corner.
*/
private void setLayout() {
//Set the globe to use the full space available
ping_globe.setBounds(0, 0, applet.getWidth(), applet.getHeight());
//First raw of display
Dimension name_size = nickname_field.getPreferredSize();
Dimension update_name_size = rename_button.getPreferredSize();
Dimension client_info_size = client_info_display.getPreferredSize();
int row_height = name_size.height;
nickname_field.setBounds(5,5,
name_size.width,row_height);
rename_button.setBounds(8 + name_size.width, 5,
update_name_size.width, row_height);
client_info_display.setBounds(11 + name_size.width + update_name_size.width, 5,
client_info_size.width,row_height );
//Second raw of display
Dimension counter_size = pings_counter_display.getPreferredSize();
Dimension pause_size = pause_button.getMinimumSize();
pings_counter_display.setBounds(5, 8 + row_height,
counter_size.width, row_height);
pause_button.setBounds(8 + counter_size.width,8 + row_height,
pause_size.width, row_height);
retry_message.setBounds((applet.getWidth()/2)-200, (applet.getHeight()/2)-50, 400, 100);
retry_button.setBounds((applet.getWidth()/2)-100, (applet.getHeight()/2)+50, 200, 50);
}
/**
* Update the counter displaying the number of ping sent
*/
private void updatePingsCounterDisplay() {
int nb = pings_counter.get();
if (nb == 0) {
pings_counter_display.setText("No ping sent yet");
}
else {
pings_counter_display.setText(nb + " ip tested");
}
setLayout();
}
private void updateClientInfoDisplay(String ip_address, GeoipInfo client_info) {
String info_str = ip_address;
int nb = 0;
if (ip_address != null && !ip_address.equals(""))
nb += 1;
if (client_info != null &&
(client_info.city != null) &&
!client_info.city.equals("")){
if (nb > 0){
info_str += ", ";
}
info_str += client_info.city;
nb += 1;
}
if (client_info != null &&
(client_info.region != null) &&
!client_info.region.equals("")){
if (nb > 0){
info_str += ", ";
}
info_str += client_info.region;
}
if (client_info != null &&
(client_info.country != null) &&
!client_info.country.equals("")){
if (nb > 0){
info_str += ", ";
}
info_str += client_info.country;
}
if (info_str.equals(ip_address)){
if (nb > 0){
info_str += ", ";
}
info_str += "No geographic information";
}
client_info_display.setText(info_str);
if (client_info != null)
ping_globe.setOrigin(client_info);
setLayout();
applet.repaint();
}
public void check_enable_button() {
if (nickname_field.getText().equals(applet.pings_clients[0].getNickname())) {
rename_button.setEnabled(false);
}
else {
rename_button.setEnabled(true);
}
}
public int getPingsCount() {
return pings_counter.get();
}
class clientThreadObserver implements Observer {
private PingsGlobe.PingGUI gui_effect = null;
private InetAddress last_address = null ;
public void update(Observable o, Object arg) {
PingsClient.subClient client = (PingsClient.subClient)o;
if (client.getSourceGeoip() != null || client_info_display.getText().length() == 0) {
if (client_info_display.getText().length() == 0 ||
!client.getSourceGeoip().equals(client_geoip_info)) {
client_geoip_info = client.getSourceGeoip();
InetAddress local = client.getSourceAddress();
InetAddress global = null;
try{
global = client.getSourceExternalAddress();
} catch (RuntimeException _) {}
String ip = "";
if (local != null){
ip += "Local ip: ";
String s = local.toString();
if (s.charAt(0) == '/')
ip += s.substring(1);
}
if (global != null){
if (ip.length() > 0)
ip += ", ";
ip += "Global ip: ";
String s = global.toString();
if (s.charAt(0) == '/')
ip += s.substring(1);
}
ips = ip;
//FIXME: get ip from server
SwingUtilities.invokeLater( new Runnable() {
public void run() {
updateClientInfoDisplay(ips, client_geoip_info);
}
});
}
}
GeoipInfo current_ping_geoip = client.getCurrentDestGeoip();
InetAddress current_ping_address = client.getCurrentPingDest();
//If there are several subClient threads then this might still be
// reachable as they try to set the same geoip several times
if (current_ping_address == null) return;
//If there is a new ping add it to the counter and register an
//effect for the globe
if (gui_effect == null && last_address != current_ping_address) {
last_address = current_ping_address;
pings_counter.incrementAndGet();
SwingUtilities.invokeLater( new Runnable() {
public void run() {
updatePingsCounterDisplay();
}
});
gui_effect = ping_globe.addPing(current_ping_geoip);
}
//Else if it's the last ping update it
else if (gui_effect != null && last_address == current_ping_address) {
gui_effect.updatePingGUIValue(client.getCurrentPingResult());
gui_effect = null;
}
//Else there are two case :
//_ either the destination address is the same (and with the
//current implementation there is no way to know it). This case has a
//very low probability.
//_ or we somehow missed the result of the previous ping, hence
//we need to do some workaround for the old ping and declare a
//new one.
else {
if (gui_effect != null) gui_effect.unknownError();
String value = client.getCurrentPingResult();
gui_effect = ping_globe.addPing(current_ping_geoip);
if (value!= null && !value.equals("")) {
gui_effect.updatePingGUIValue(client.getCurrentPingResult());
gui_effect = null;
}
}
}
}
/**
* This method is used to refresh the Pause/Resume button to make it show
* 'Pause' or 'Resume' and act accordingly depending on the client state
* expressed by the 'm_is_running' variable.
* <p>
* If the client is running this makes the button show "Pause" otherwise it
* shows "Resume".
*/
private void refreshPauseButton() {
if (!applet.pings_clients[0].isRunning()) {
pause_button.setText("Resume");
pause_button.setToolTipText(resume_tooltip);
pause_button.setActionCommand("resume");
}
else {
pause_button.setText("Pause");
pause_button.setToolTipText(pause_tooltip);
pause_button.setActionCommand("pause");
}
setLayout();
}
/**
* The listener for events in the applet : the interactions with the
* components (other than the globe) are handled here.
*/
public void actionPerformed (ActionEvent event) {
//Find the issued command and store it in the 'command' variable
String command = event.getActionCommand();
//Handle the pause/resume button
if (command.equals("pause")) {
//Pause the client if it was running, do nothing otherwise
boolean was_running = applet.pings_clients[0].isRunning();
//Issue a warning if the client was not running
if (!was_running) {
//System.out.println ("Was already paused.");
}
else {
applet.stop();
}
//Then refresh the button
SwingUtilities.invokeLater( new Runnable() {
public void run() {
refreshPauseButton();
}
});
}
else if (command.equals("resume")) {
//resume the client if it was paused, do nothing otherwise
boolean was_running = applet.pings_clients[0].isRunning();
//Issue a warning if the client was running
if (was_running) {
//System.out.println ("Was already running.");
}
else {
applet.start();
}
//Then refresh the button
SwingUtilities.invokeLater( new Runnable() {
public void run() {
refreshPauseButton();
}
});
}
//Handle the rename button
else if (command.equals("rename")) {
String new_name = nickname_field.getText();
new_name = PingsClient.sanitize_string(new_name);
nickname_field.setText(new_name);
for (int i = 0; i < applet.nb_clients; i++) {
applet.pings_clients[i].setNickname(new_name);
}
SwingUtilities.invokeLater( new Runnable() {
public void run() {
rename_button.setEnabled(false);
}
});
System.out.println("Nick updated to " + new_name);
}
//Handle any other unknown component
else {
//FIXME
System.out.println ("Error in button interface.");
}
}
class onResize implements ComponentListener{
public void componentResized(ComponentEvent e) {
ping_globe.forceRefresh();
SwingUtilities.invokeLater( new Runnable() {
public void run() {
setLayout();
}
});
}
public void componentShown(ComponentEvent e) {}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
}
/**
* Destroy as much of the GUI as possible.
* <p>
* It remove the components and unregister the observers of the clients,
* for this reason it can fail is the client was destroyed before (hence the
* 'try').
*/
public void destroy() {
try {
ping_globe.removeAll();
button_container.removeAll();
for (int i = 0; i < applet.nb_clients; i++) {
PingsClient.subClient[] subClientsPool = applet.pings_clients[i].getSubClientsPoolCopy();
for (int j = 0; j < subClientsPool.length; j++) {
subClientsPool[j].deleteObserver(clients_observers[i][j]);
}
}
} catch (Exception _) {}
}
private class CreateRetryInterface implements Runnable, ActionListener{
private String message;
public CreateRetryInterface(String msg) {
this.message = msg;
}
//Handle the retry button
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
button_container.removeAll();
applet.restartApplet();
}
});
}
public void run() {
button_container = applet.getContentPane();
button_container.setBackground(background_color);
button_container.setLayout(null);
retry_message.setText(message);
retry_message.setForeground(text_color);
retry_message.setBackground(background_color);
retry_message.setLineWrap(true);
retry_message.setEditable(false);
button_container.add(retry_message);
retry_button.setText("Retry");
retry_button.setMnemonic(KeyEvent.VK_R);
retry_button.setToolTipText("Try to relaunch the application");
retry_button.setActionCommand("retry_connect");
retry_button.addActionListener(this);
button_container.add(retry_button);
setLayout();
applet.repaint();
}
}
public void createRetryInterface(String message) {
SwingUtilities.invokeLater( new CreateRetryInterface(message));
}
}
|
package example;
import java.awt.*;
import java.awt.event.ItemListener;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
// UIManager.put("Spinner.editorAlignment", SwingConstants.CENTER);
// System.out.println(UIManager.get("Spinner.editorAlignment"));
JRadioButton r1 = new JRadioButton("LEADING");
JRadioButton r2 = new JRadioButton("CENTER");
JRadioButton r3 = new JRadioButton("TRAILING");
ItemListener il = e -> {
int alignment;
if (e.getItemSelectable() == r1) {
alignment = SwingConstants.LEADING;
} else if (e.getItemSelectable() == r2) {
alignment = SwingConstants.CENTER;
} else {
alignment = SwingConstants.TRAILING;
}
UIManager.put("Spinner.editorAlignment", alignment);
SwingUtilities.updateComponentTreeUI(this);
};
ButtonGroup bg = new ButtonGroup();
Box box = Box.createHorizontalBox();
for (JRadioButton r : Arrays.asList(r1, r2, r3)) {
r.addItemListener(il);
bg.add(r);
box.add(r);
}
JTextArea log = new JTextArea();
log.setEditable(false);
List<String> weeks = Arrays.asList("Sun", "Mon", "Tue", "Wed", "Thu", "Sat");
JSpinner spinner0 = new JSpinner(new SpinnerListModel(weeks));
String str0 = getHorizontalAlignment((JSpinner.DefaultEditor) spinner0.getEditor());
log.append("SpinnerListModel: " + str0 + "\n");
@SuppressWarnings("JavaUtilDate")
Date d = new Date();
JSpinner spinner1 = new JSpinner(new SpinnerDateModel(d, d, null, Calendar.DAY_OF_MONTH));
spinner1.setEditor(new JSpinner.DateEditor(spinner1, "yyyy/MM/dd"));
String str1 = getHorizontalAlignment((JSpinner.DefaultEditor) spinner1.getEditor());
log.append("SpinnerDateModel: " + str1 + "\n");
JSpinner spinner2 = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
String str2 = getHorizontalAlignment((JSpinner.DefaultEditor) spinner2.getEditor());
log.append("SpinnerNumberModel: " + str2 + "\n");
JPanel p = new JPanel(new BorderLayout());
p.add(box, BorderLayout.NORTH);
p.add(makeSpinnerPanel(spinner0, spinner1, spinner2));
add(p, BorderLayout.NORTH);
add(new JScrollPane(log));
JMenuBar mb = new JMenuBar();
mb.add(LookAndFeelUtil.createLookAndFeelMenu());
EventQueue.invokeLater(() -> getRootPane().setJMenuBar(mb));
setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
setPreferredSize(new Dimension(320, 240));
}
private static JPanel makeSpinnerPanel(JSpinner sp0, JSpinner sp1, JSpinner sp2) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.weightx = 0.0;
c.insets = new Insets(5, 5, 5, 0);
c.anchor = GridBagConstraints.EAST;
JPanel p = new JPanel(new GridBagLayout());
c.gridy = 0;
p.add(new JLabel("SpinnerListModel: "), c);
c.gridy = 1;
p.add(new JLabel("SpinnerDateModel: "), c);
c.gridy = 2;
p.add(new JLabel("SpinnerNumberModel: "), c);
c.gridx = 1;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
p.add(sp0, c);
c.gridy = 1;
p.add(sp1, c);
c.gridy = 2;
p.add(sp2, c);
return p;
}
private static String getHorizontalAlignment(JSpinner.DefaultEditor editor) {
switch (editor.getTextField().getHorizontalAlignment()) {
case SwingConstants.LEFT:
return "LEFT";
case SwingConstants.CENTER:
return "CENTER";
case SwingConstants.RIGHT:
return "RIGHT";
case SwingConstants.LEADING:
return "LEADING";
case SwingConstants.TRAILING:
return "TRAILING";
default:
return "ERROR";
}
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
final class LookAndFeelUtil {
private static String lookAndFeel = UIManager.getLookAndFeel().getClass().getName();
private LookAndFeelUtil() {
/* Singleton */
}
public static JMenu createLookAndFeelMenu() {
JMenu menu = new JMenu("LookAndFeel");
ButtonGroup lafGroup = new ButtonGroup();
for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {
menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName(), lafGroup));
}
return menu;
}
private static JMenuItem createLookAndFeelItem(String laf, String lafClass, ButtonGroup bg) {
JMenuItem lafItem = new JRadioButtonMenuItem(laf, lafClass.equals(lookAndFeel));
lafItem.setActionCommand(lafClass);
lafItem.setHideActionText(true);
lafItem.addActionListener(e -> {
ButtonModel m = bg.getSelection();
try {
setLookAndFeel(m.getActionCommand());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
UIManager.getLookAndFeel().provideErrorFeedback((Component) e.getSource());
}
});
bg.add(lafItem);
return lafItem;
}
private static void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
String oldLookAndFeel = LookAndFeelUtil.lookAndFeel;
if (!oldLookAndFeel.equals(lookAndFeel)) {
UIManager.setLookAndFeel(lookAndFeel);
LookAndFeelUtil.lookAndFeel = lookAndFeel;
updateLookAndFeel();
// firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel);
}
}
private static void updateLookAndFeel() {
for (Window window : Window.getWindows()) {
SwingUtilities.updateComponentTreeUI(window);
}
}
}
|
package Sprites;
import tankattack.*;
/**
*
* @author Ruslan
*/
public class Minion extends Enemy {
public static String imageName = "minion.png";
private double leftXLimit, rightXLimit;
private boolean goingRight;
public Minion(double x, double y, World world) {
super(Minion.imageName, x, y, world);
this.health = 100.0;
this.healthBar = null;
System.out.println("in minion constructor, need to create HealthBar");
}
@Override
public void updateEnemyXY() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean isFiring() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package net.nunnerycode.bukkit.mythicdrops.armorsets;
import net.nunnerycode.bukkit.mythicdrops.api.armorsets.ArmorSet;
import net.nunnerycode.bukkit.mythicdrops.api.socketting.EffectTarget;
import net.nunnerycode.bukkit.mythicdrops.api.socketting.SocketEffect;
import net.nunnerycode.bukkit.mythicdrops.utils.ArmorSetUtil;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public final class ArmorSetListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
Entity e = event.getEntity();
Entity d = event.getDamager();
if (!(e instanceof LivingEntity)) {
return;
}
LivingEntity lee = (LivingEntity) e;
LivingEntity led;
if (d instanceof LivingEntity) {
led = (LivingEntity) d;
} else if (d instanceof Projectile) {
led = ((Projectile) d).getShooter();
} else {
return;
}
applyEffects(led, lee);
}
public void applyEffects(LivingEntity attacker, LivingEntity defender) {
if (attacker == null || defender == null) {
return;
}
Map<ArmorSet, Integer> attackArmorSets = ArmorSetUtil.getArmorSetsFromLivingEntity(attacker);
Map<ArmorSet, Integer> defendArmorSets = ArmorSetUtil.getArmorSetsFromLivingEntity(defender);
for (Map.Entry<ArmorSet, Integer> entry : attackArmorSets.entrySet()) {
List<SocketEffect> socketEffects = new ArrayList<>();
switch (entry.getValue()) {
case 5:
socketEffects.addAll(entry.getKey().getFiveItemEffects());
case 4:
socketEffects.addAll(entry.getKey().getFourItemEffects());
case 3:
socketEffects.addAll(entry.getKey().getThreeItemEffects());
case 2:
socketEffects.addAll(entry.getKey().getTwoItemEffects());
case 1:
socketEffects.addAll(entry.getKey().getOneItemEffects());
default:
break;
}
for (SocketEffect se : socketEffects) {
if (se.getEffectTarget() == EffectTarget.SELF) {
se.apply(attacker);
} else if (se.getEffectTarget() == EffectTarget.OTHER) {
se.apply(defender);
} else if (se.getEffectTarget() == EffectTarget.AREA) {
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
LivingEntity le = (LivingEntity) e;
if (le.equals(defender) && se.isAffectsTarget()) {
se.apply(le);
continue;
}
se.apply(le);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
}
}
}
for (Map.Entry<ArmorSet, Integer> entry : defendArmorSets.entrySet()) {
List<SocketEffect> socketEffects = new ArrayList<>();
switch (entry.getValue()) {
case 5:
socketEffects.addAll(entry.getKey().getFiveItemEffects());
case 4:
socketEffects.addAll(entry.getKey().getFourItemEffects());
case 3:
socketEffects.addAll(entry.getKey().getThreeItemEffects());
case 2:
socketEffects.addAll(entry.getKey().getTwoItemEffects());
case 1:
socketEffects.addAll(entry.getKey().getOneItemEffects());
default:
break;
}
for (SocketEffect se : socketEffects) {
if (se.getEffectTarget() == EffectTarget.SELF) {
se.apply(defender);
} else if (se.getEffectTarget() == EffectTarget.OTHER) {
se.apply(attacker);
} else if (se.getEffectTarget() == EffectTarget.AREA) {
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
LivingEntity le = (LivingEntity) e;
if (le.equals(attacker) && se.isAffectsTarget()) {
se.apply(le);
continue;
}
se.apply(le);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
}
}
}
}
}
|
package com.neatorobotics.sdk.android.example.robots;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.neatorobotics.sdk.android.NeatoCallback;
import com.neatorobotics.sdk.android.NeatoUser;
import com.neatorobotics.sdk.android.NeatoError;
import com.neatorobotics.sdk.android.example.R;
import com.neatorobotics.sdk.android.NeatoRobot;
import com.neatorobotics.sdk.android.nucleo.RobotCommands;
import com.neatorobotics.sdk.android.nucleo.RobotConstants;
import org.w3c.dom.Text;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Locale;
public class RobotsFragment extends Fragment {
private static final String TAG = "RobotsFragment";
private NeatoUser neatoUser;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private SwipeRefreshLayout swipeContainer;
private TextView noRobotsAvailableMessage;
private ArrayList<NeatoRobot> robots = new ArrayList<>();
public RobotsFragment() {}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList serializedRobots = new ArrayList();
for (NeatoRobot robot : robots) {
serializedRobots.add(robot.serialize());
}
outState.putSerializable("ROBOT_LIST",serializedRobots);
}
private void restoreState(Bundle inState) {
robots.clear();
ArrayList serializedRobots = (ArrayList) inState.getSerializable("ROBOT_LIST");
for (Object object : serializedRobots) {
robots.add(NeatoRobot.deserialize(getContext(),(Serializable) object));
}
if(robots.size() == 0) {
noRobotsAvailableMessage.setVisibility(View.VISIBLE);
}else {
noRobotsAvailableMessage.setVisibility(View.GONE);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
neatoUser = NeatoUser.getInstance(getContext());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_robots, container, false);
//recycler view
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.robot_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RobotsListAdapter();
mRecyclerView.setAdapter(mAdapter);
//swipe to refresh
swipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadRobots();
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(R.color.colorPrimary,
R.color.colorPrimaryDark,
R.color.colorPrimaryDark);
//end swipe to refresh
noRobotsAvailableMessage = (TextView)rootView.findViewById(R.id.noRobotsAvailableMessage);
if(savedInstanceState != null) {
restoreState(savedInstanceState);
}
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState == null) {
loadRobots();
}
mAdapter.notifyDataSetChanged();
}
private void loadRobots() {
neatoUser.loadRobots(new NeatoCallback<ArrayList<NeatoRobot>>(){
@Override
public void done(ArrayList<NeatoRobot> result) {
super.done(result);
robots.clear();
robots.addAll(result);
swipeContainer.setRefreshing(false);
if(result.size() == 0) {
noRobotsAvailableMessage.setVisibility(View.VISIBLE);
}else {
noRobotsAvailableMessage.setVisibility(View.GONE);
}
mAdapter.notifyDataSetChanged();
//request the robot states
for (NeatoRobot robot : result) {
robot.updateRobotState(new NeatoCallback<Void>(){
@Override
public void done(Void result) {
super.done(result);
mAdapter.notifyDataSetChanged();
}
@Override
public void fail(NeatoError error) {
super.fail(error);
mAdapter.notifyDataSetChanged();
}
});
}
}
@Override
public void fail(NeatoError error) {
super.fail(error);
swipeContainer.setRefreshing(false);
if(error == NeatoError.INVALID_TOKEN) {
Toast.makeText(getContext(), "Your session is expired.",Toast.LENGTH_SHORT).show();
}
}
});
}
public class RobotsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView robotName,robotModel, robotStatus, robotCharge;
public ItemViewHolder(View v) {
super(v);
this.robotName = (TextView) v.findViewById(R.id.robotName);
this.robotModel = (TextView) v.findViewById(R.id.robotModel);
this.robotStatus = (TextView) v.findViewById(R.id.robotStatus);
this.robotCharge = (TextView) v.findViewById(R.id.robotCharge);
v.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
final NeatoRobot robot = robots.get(position);
if(robot.getState() != null) {
Intent intent = new Intent(getContext(), RobotCommandsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("ROBOT", robot.serialize());
startActivity(intent);
}else {
Toast.makeText(getContext(),"No robot state available yet...", Toast.LENGTH_SHORT).show();
}
}
}
public RobotsListAdapter() {}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.robot_list_item, parent, false);
ItemViewHolder vh = new ItemViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
((ItemViewHolder)holder).robotName.setText(robots.get(position).getName());
((ItemViewHolder)holder).robotModel.setText(robots.get(position).getModel());
if(robots.get(position).getState() != null) {
((ItemViewHolder) holder).robotCharge.setText(robots.get(position).getState().getCharge() + "%");
if(robots.get(position).getState().getState() == RobotConstants.ROBOT_STATE_IDLE) {
((ItemViewHolder) holder).robotStatus.setTextColor(getResources().getColor(R.color.colorAccentSecondary));
((ItemViewHolder) holder).robotStatus.setText("ROBOT IDLE");
}else if(robots.get(position).getState().getState() == RobotConstants.ROBOT_STATE_BUSY){
((ItemViewHolder) holder).robotStatus.setTextColor(getResources().getColor(R.color.yellow));
((ItemViewHolder) holder).robotStatus.setText("ROBOT BUSY");
}else if(robots.get(position).getState().getState() == RobotConstants.ROBOT_STATE_ERROR){
((ItemViewHolder) holder).robotStatus.setTextColor(getResources().getColor(R.color.colorAccent));
((ItemViewHolder) holder).robotStatus.setText("ROBOT ERROR");
}
//TODO you can handle other robot state here if needed
else {
((ItemViewHolder) holder).robotStatus.setTextColor(getResources().getColor(R.color.colorPrimary));
((ItemViewHolder) holder).robotStatus.setText("OTHER ROBOT STATE");
}
((ItemViewHolder) holder).robotCharge.setTextColor(getResources().getColor(R.color.colorPrimary));
}else {
((ItemViewHolder) holder).robotStatus.setText("Not available or offline");
((ItemViewHolder) holder).robotCharge.setText("Battery status not available");
((ItemViewHolder) holder).robotStatus.setTextColor(getResources().getColor(R.color.colorAccent));
((ItemViewHolder) holder).robotCharge.setTextColor(getResources().getColor(R.color.colorAccent));
}
}
@Override
public int getItemViewType(int position) {
return 0;
}
@Override
public int getItemCount() {
return robots.size();
}
}
}
|
//#if ${BugTrack} == "T" or ${Categoria} == "T" or ${Cupom} == "T" or ${Endereco} == "T" or ${FormaPagament} == "T" or ${Mensagem} == "T" or ${Perfil} == "T" or ${Produto} == "T" or ${SituacaoBug} == "T" or ${StatusUsuario} == "T" or ${StatusVenda} == "T" or ${TipoMensagem} == "T" or ${UnidadeMedida} == "T" or ${UsuarioCupom} == "T" or ${UsuarioCupom} == "T" or ${Usuario} == "T" or ${Venda} == "T" or ${VendaProduto} == "T" or ${VendaProdutoEmbbed} == "T"
package br.com.webstore.facade;
import java.util.List;
//#if ${BugTrack} == "T"
import br.com.webstore.dao.BugTrackDao;
//#endif
//#if ${Categoria} == "T"
import br.com.webstore.dao.CategoriaDao;
//#endif
//#if ${Cupom} == "T"
import br.com.webstore.dao.CupomDao;
//#endif
//#if ${Endereco} == "T"
import br.com.webstore.dao.EnderecoDao;
//#endif
//#if ${Faq} == "T"
import br.com.webstore.dao.FaqDao;
//#endif
//#if ${FormaPagamento} == "T"
import br.com.webstore.dao.FormaPagamentDao;
//#endif
//#if ${Mensagem} == "T"
import br.com.webstore.dao.MensagemDao;
//#endif
//#if ${Perfil} == "T"
import br.com.webstore.dao.PerfilDao;
//#endif
//#if ${Produto} == "T"
import br.com.webstore.dao.ProdutoDao;
//#endif
//#if ${SituacaoBug} == "T"
import br.com.webstore.dao.SituacaoBugDao;
//#endif
//#if ${StatusUsuario} == "T"
import br.com.webstore.dao.StatusUsuarioDao;
//#endif
//#if ${StatusVenda} == "T"
import br.com.webstore.dao.StatusVendaDao;
//#endif
//#if ${TipoMensagem} == "T"
import br.com.webstore.dao.TipoMensagemDao;
//#endif
//#if ${UnidadeMedida} == "T"
import br.com.webstore.dao.UnidadeMedidaDao;
//#endif
//#if ${UsuarioCupom} == "T"
import br.com.webstore.dao.UsuarioCupomDao;
//#endif
//#if ${Usuario} == "T"
import br.com.webstore.dao.UsuarioDao;
//#endif
//#if ${Venda} == "T"
import br.com.webstore.dao.VendaDao;
//#endif
//#if ${VendaProduto} == "T"
import br.com.webstore.dao.VendaProdutoDao;
//#endif
//#if ${VendaProdutoEmbbed} == "T"
import br.com.webstore.dao.VendaProdutoEmbbedDao;
//#endif
//#if ${BugTrack} == "T"
import br.com.webstore.model.BugTrack;
//#endif
//#if ${Categoria} == "T"
import br.com.webstore.model.Categoria;
//#endif
//#if ${Cupom} == "T"
import br.com.webstore.model.Cupom;
//#endif
//#if ${Endereco} == "T"
import br.com.webstore.model.Endereco;
//#endif
//#if ${Faq} == "T"
import br.com.webstore.model.Faq;
//#endif
//#if ${FormaPagamento} == "T"
import br.com.webstore.model.FormaPagamento;
//#endif
//#if ${Mensagem} == "T"
import br.com.webstore.model.Mensagem;
//#endif
//#if ${Perfil} == "T"
import br.com.webstore.model.Perfil;
//#endif
//#if ${Produto} == "T"
import br.com.webstore.model.Produto;
//#endif
//#if ${SituacaoBug} == "T"
import br.com.webstore.model.SituacaoBug;
//#endif
//#if ${StatusUsuario} == "T"
import br.com.webstore.model.StatusUsuario;
//#endif
//#if ${StatusVenda} == "T"
import br.com.webstore.model.StatusVenda;
//#endif
//#if ${TipoMensagem} == "T"
import br.com.webstore.model.TipoMensagem;
//#endif
//#if ${UnidadeMedida} == "T"
import br.com.webstore.model.UnidadeMedida;
//#endif
//#if ${Usuario} == "T"
import br.com.webstore.model.Usuario;
//#endif
//#if ${UsuarioCupom} == "T"
import br.com.webstore.model.UsuarioCupom;
//#endif
//#if ${Venda} == "T"
import br.com.webstore.model.Venda;
//#endif
//#if ${VendaProduto} == "T"
import br.com.webstore.model.VendaProduto;
//#endif
//#if ${VendaProdutoEmbbed} == "T"
import br.com.webstore.model.VendaProdutoEmbbed;
//#endif
/**
* @author webstore
*
*/
public class GenericFacade {
//#if ${BugTrack} == "T"
private BugTrackDao bugTrackDao = new BugTrackDao();
public BugTrack insertBugTrack(BugTrack bugTrack) {
return bugTrackDao.insert(bugTrack);
}
public Boolean updateBugTrack(BugTrack bugTrack) {//TODO: remove retornar boolean
bugTrackDao.update(bugTrack);
return true;
}
public List<BugTrack> findBugTrack(BugTrack query) {
return bugTrackDao.getList();
}
public List<BugTrack> findBugTrack(String titulo, SituacaoBug situacao) {
return this.bugTrackDao.findByTitulo(titulo, situacao);
}
public List<BugTrack> findBugTrack(String titulo) {
return this.bugTrackDao.findByTitulo(titulo);
}
public List<BugTrack> findBugTrack() {
return bugTrackDao.getList();
}
public Boolean removeBugTrack(int id){ //TODO: remove retornar boolean
bugTrackDao.remove(id);
return true;
}
public BugTrack getBugTrack(int id) {
return bugTrackDao.find(id);
}
//#endif
//#if ${FAQ} == "T"
private FaqDao faqDataProvider = new FaqDao();
public Faq insertFaq(Faq faq) {
return this.faqDataProvider.insert(faq);
}
public void updateFaq(Faq faq) {
this.faqDataProvider.update(faq);
}
public List<Faq> findFaq(String descricao) {
return this.faqDataProvider.findByNome(descricao);
}
public Faq getFaqById(int id) {
return this.faqDataProvider.find(id);
}
public void removerFaq(int id) {
this.faqDataProvider.remove(id);
}
//#endif
//Categoria
//#if ${Categoria} == "T"
private CategoriaDao categoriaDataProvider = new CategoriaDao();
public Categoria insertCategoria(Categoria categoria) {
return this.categoriaDataProvider.insert(categoria);
//replace return categoriaDataProvider.insert(categoria);
}
public void updateCategoria(Categoria categoria) {
//replace categoriaDataProvider.update(categoria);
this.categoriaDataProvider.update(categoria);
}
public List<Categoria> findCategoria(String nome) {
//replace public List<Categoria> findCategoria() {
// return categoriaDataProvider.getList();
return this.categoriaDataProvider.findByNome(nome);
}
public Categoria getById(int id) {
return this.categoriaDataProvider.find(id);
}
public void removerCategoria(int id) {
this.categoriaDataProvider.remove(id);
}
public List<Categoria> getListCategoria() {
return categoriaDataProvider.getList();
}
//#endif
//Cupom
//#if ${Cupom} == "T"
private CupomDao cupomDataProvider = new CupomDao();
public Cupom insertCupom(Cupom cupom) {
return cupomDataProvider.insert(cupom);
}
public void updateCupom(Cupom cupom) {
cupomDataProvider.update(cupom);
}
public List<Cupom> findCupom(Cupom query) {
return cupomDataProvider.getList();
}
//#endif
//Endereco
//#if ${Endereco} == "T"
private EnderecoDao enderecoDataProvider = new EnderecoDao();
public Endereco insertEndereco(Endereco endereco) {
return enderecoDataProvider.insert(endereco);
}
public void updateEndereco(Endereco endereco) {
enderecoDataProvider.update(endereco);
}
public List<Endereco> findEndereco(Endereco query) {
return enderecoDataProvider.getList();
}
//#endif
//FormaPagamento
//#if ${FormaPagamento} == "T"
private FormaPagamentDao formaPagamentDataProvider = new FormaPagamentDao();
public FormaPagamento insertFormaPagamento(FormaPagamento formaPagamento) {
return formaPagamentDataProvider.insert(formaPagamento);
}
public void updateFormaPagamento(FormaPagamento formaPagamento) {
formaPagamentDataProvider.update(formaPagamento);
}
public List<FormaPagamento> findFormaPagamento(FormaPagamento query) {
return formaPagamentDataProvider.getList();
}
//#endif
//Mensagem
//#if ${Mensagem} == "T"
private MensagemDao mensagemDao = new MensagemDao();
public void insert(Mensagem mensagem) {
this.mensagemDao.insert(mensagem);
}
public void update(Mensagem mensagem) {
this.mensagemDao.update(mensagem);
}
public Mensagem find(Integer id) {
return this.mensagemDao.find(id);
}
public List<Mensagem> list(Mensagem query) {
return this.mensagemDao.getList();
}
//#endif
//Perfil
//#if ${Perfil} == "T"
private PerfilDao perfilDataProvider = new PerfilDao();
public Perfil insertPerfil(Perfil perfil) {
return perfilDataProvider.insert(perfil);
}
public void savePerfil(Perfil perfil) {
perfilDataProvider.update(perfil);
}
public List<Perfil> findPerfil(Perfil query) {
return perfilDataProvider.getList();
}
//#endif
//Produto
//#if ${Produto} == "T"
private ProdutoDao produtoDataProvider = new ProdutoDao();
public Produto insertProduto(Produto produto) {
return this.produtoDataProvider.insert(produto);
}
public void updateProduto(Produto produto) {
this.produtoDataProvider.update(produto);
}
public List<Produto> findProduto(String nome) {
return this.produtoDataProvider.findByNome(nome);
}
public Produto getProdutoById(int id) {
return this.produtoDataProvider.find(id);
}
public void removerProduto(int id) {
this.produtoDataProvider.remove(id);
}
//#endif
//SituacaoBug
//#if ${SituacaoBug} == "T"
private SituacaoBugDao situacaoBugDataProvider= new SituacaoBugDao();
public SituacaoBug insertSituacaoBug(SituacaoBug situacaoBug) {
return situacaoBugDataProvider.insert(situacaoBug);
}
public void updateSituacaoBug(SituacaoBug situacaoBug) {
situacaoBugDataProvider.update(situacaoBug);
}
public List<SituacaoBug> findSituacaoBug(SituacaoBug query) {
return situacaoBugDataProvider.getList();
}
public List<SituacaoBug> getListSituacaoBug() {
return situacaoBugDataProvider.getList();
}
public SituacaoBug findSituacaoBug(int id){
return situacaoBugDataProvider.find(id);
}
public SituacaoBugDao getDaoSituacaoBug(){
return situacaoBugDataProvider;
}
//#endif
//StatusUsuario
//#if ${StatusUsuario} == "T"
private StatusUsuarioDao statusUsuarioDataProvider = new StatusUsuarioDao();
public StatusUsuario insertStatusUsuario(StatusUsuario statusUsuario) {
return statusUsuarioDataProvider.insert(statusUsuario);
}
public void updateStatusUsuario(StatusUsuario statusUsuario) {
statusUsuarioDataProvider.update(statusUsuario);
}
public List<StatusUsuario> findStatusUsuario(StatusUsuario query) {
return statusUsuarioDataProvider.getList();
}
//#endif
//StatusVenda
//#if ${StatusVenda} == "T"
private StatusVendaDao statusVendaDataProvider = new StatusVendaDao();
public StatusVenda insertStatusVenda(StatusVenda statusVenda) {
return statusVendaDataProvider.insert(statusVenda);
}
public void updateStatusVenda(StatusVenda statusVenda) {
statusVendaDataProvider.update(statusVenda);
}
public List<StatusVenda> findStatusVenda(StatusVenda query) {
return statusVendaDataProvider.getList();
}
//#endif
//TipoMensagem
//#if ${TipoMensagem} == "T"
private TipoMensagemDao tipoMensagemDataProvider = new TipoMensagemDao();
public TipoMensagem findTipoMensagem(Integer id) {
return tipoMensagemDataProvider.find(id);
}
public List<TipoMensagem> listTipoMensagem() {
return tipoMensagemDataProvider.getList();
}
//#endif
//UnidadeMedida
//#if ${UnidadeMedida} == "T"
private UnidadeMedidaDao unidadeMedidaDao = new UnidadeMedidaDao();
public UnidadeMedida insertUnidadeMedida(UnidadeMedida unidadeMedida) {
return unidadeMedidaDao.insert(unidadeMedida);
}
public void updateUnidadeMedida(UnidadeMedida unidadeMedida) {
unidadeMedidaDao.update(unidadeMedida);
}
public List<UnidadeMedida> findUnidadeMedida(UnidadeMedida unidadeMedida) {
return unidadeMedidaDao.getList();
}
public List<UnidadeMedida> getListUnidadeMedida() {
return unidadeMedidaDao.getList();
}
//#endif
//UsuarioCupom
//#if ${UsuarioCupom} == "T"
private UsuarioCupomDao usuarioCupomDao;
public UsuarioCupom insertUsuarioCupom(UsuarioCupom usuarioCupom) {
return usuarioCupomDao.insert(usuarioCupom);
}
public void updateUsuarioCupom(UsuarioCupom usuarioCupom) {
usuarioCupomDao.update(usuarioCupom);
}
public List<UsuarioCupom> findUsuarioCupom(UsuarioCupom usuarioCupom) {
return usuarioCupomDao.getList();
}
//#endif
//Usuario
//#if ${Usuario} == "T"
private UsuarioDao usuarioDao = new UsuarioDao();
public Usuario insertUsuario(Usuario usuario) {
return usuarioDao.insert(usuario);
}
public void updateUsuario(Usuario usuario) {
usuarioDao.update(usuario);
}
public List<Usuario> findUsuario(Usuario usuario) {
return usuarioDao.getList();
}
public void removeUsuario(Integer id)
{
usuarioDao.remove(id);
}
public Usuario getUsuarioById(Integer id)
{
return usuarioDao.find(id);
}
//#endif
//Venda
//#if ${Venda} == "T"
private VendaDao vendaDao;
public Venda insertVenda(Venda venda) {
return vendaDao.insert(venda);
}
public void updateVenda(Venda venda) {
vendaDao.update(venda);
}
public List<Venda> findCategoria(Venda venda) {
return vendaDao.getList();
}
//#endif
//VendaProdutoEmbbed
//#if ${VendaProdutoEmbbed} == "T"
private VendaProdutoEmbbedDao vendaProdutoEmbbedDao = new VendaProdutoEmbbedDao();
public VendaProdutoEmbbed insertVendaProdutoEmbbed(VendaProdutoEmbbed vendaProdutoEmbbed) {
return vendaProdutoEmbbedDao.insert(vendaProdutoEmbbed);
}
public void updateVendaProdutoEmbbed(VendaProdutoEmbbed vendaProdutoEmbbed) {
vendaProdutoEmbbedDao.update(vendaProdutoEmbbed);
}
public List<VendaProdutoEmbbed> findVendaProdutoEmbbed(VendaProdutoEmbbed vendaProdutoEmbbed) {
return vendaProdutoEmbbedDao.getList();
}
//#endif
//VendaProduto
//#if ${VendaProduto} == "T"
private VendaProdutoDao vendaProdutoDao = new VendaProdutoDao();
public VendaProduto insertVendaProduto(VendaProduto vendaProduto) {
return vendaProdutoDao.insert(vendaProduto);
}
public void updateVendaProduto(VendaProduto vendaProduto) {
vendaProdutoDao.update(vendaProduto);
}
public List<VendaProduto> findVendaProduto(VendaProduto vendaProduto) {
return vendaProdutoDao.getList();
}
//#endif
}
//#endif
|
package com.hubspot.singularity.executor;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jets3t.service.S3Service;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageObject;
import org.jets3t.service.security.AWSCredentials;
import org.slf4j.Logger;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.hubspot.deploy.S3Artifact;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.executor.config.SingularityExecutorConfiguration;
public class S3ArtifactDownloader {
private final Logger log;
private final SingularityExecutorConfiguration configuration;
public S3ArtifactDownloader(SingularityExecutorConfiguration configuration, Logger log) {
this.configuration = configuration;
this.log = log;
}
public void download(S3Artifact s3Artifact, Path downloadTo) {
final long start = System.currentTimeMillis();
boolean success = false;
try {
downloadThrows(s3Artifact, downloadTo);
success = true;
} catch (Throwable t) {
throw Throwables.propagate(t);
} finally {
log.info("S3 Download {}/{} finished {} after {}", s3Artifact.getS3Bucket(), s3Artifact.getS3ObjectKey(), success ? "successfully" : "with error", JavaUtils.duration(start));
}
}
private Callable<Path> buildChunkDownloader(final S3Service s3, final S3Artifact s3Artifact, final Path downloadTo, final int chunk, final long length) {
return new Callable<Path>() {
@Override
public Path call() throws Exception {
final Path chunkPath = (chunk == 0) ? downloadTo : Paths.get(downloadTo + "_" + chunk);
chunkPath.toFile().deleteOnExit();
final long startTime = System.currentTimeMillis();
final long byteRangeStart = chunk * configuration.getS3ChunkSize();
final long byteRangeEnd = Math.min((chunk + 1) * configuration.getS3ChunkSize() - 1, length);
log.info("Downloading chunk {} ({}-{}) to {}", chunk, byteRangeStart, byteRangeEnd, chunkPath);
S3Object fetchedObject = s3.getObject(s3Artifact.getS3Bucket(), s3Artifact.getS3ObjectKey(), null, null, null, null, byteRangeStart, byteRangeEnd);
try (InputStream is = fetchedObject.getDataInputStream()) {
Files.copy(is, chunkPath, StandardCopyOption.REPLACE_EXISTING);
}
log.info("Finished downloading chunk {} ({} bytes) in {}", chunk, byteRangeEnd - byteRangeStart, JavaUtils.duration(startTime));
return chunkPath;
}
};
}
private void downloadThrows(final S3Artifact s3Artifact, final Path downloadTo) throws Exception {
final S3Service s3 = new RestS3Service(new AWSCredentials(configuration.getS3AccessKey(), configuration.getS3SecretKey()));
long length = 0;
if (s3Artifact.getFilesize().isPresent()) {
length = s3Artifact.getFilesize().get();
} else {
StorageObject details = s3.getObjectDetails(s3Artifact.getS3Bucket(), s3Artifact.getS3ObjectKey());
Preconditions.checkNotNull(details, "Couldn't find object at %s/%s", s3Artifact.getS3Bucket(), s3Artifact.getS3ObjectKey());
length = details.getContentLength();
}
int numChunks = (int) (length / configuration.getS3ChunkSize());
if (length % configuration.getS3ChunkSize() > 0) {
numChunks++;
}
log.info("Downloading {}/{} in {} chunks of {} bytes to {}", s3Artifact.getS3Bucket(), s3Artifact.getS3ObjectKey(), numChunks, configuration.getS3ChunkSize(), downloadTo);
final ExecutorService chunkExecutorService = Executors.newFixedThreadPool(numChunks, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("S3ArtifactDownloaderChunkThread-%d").build());
final List<Future<Path>> futures = Lists.newArrayListWithCapacity(numChunks);
for (int i = 0; i < numChunks; i++) {
final int chunk = i;
futures.add(chunkExecutorService.submit(buildChunkDownloader(s3, s3Artifact, downloadTo, chunk, length)));
}
long remainingMillis = configuration.getS3DownloadTimeoutMillis();
boolean failed = false;
for (int chunk = 0; chunk < numChunks; chunk++) {
final Future<Path> future = futures.get(chunk);
if (failed) {
future.cancel(true);
continue;
}
final long start = System.currentTimeMillis();
if (!handleChunk(future, downloadTo, chunk, start, remainingMillis)) {
failed = true;
}
remainingMillis -= (System.currentTimeMillis() - start);
}
chunkExecutorService.shutdown();
Preconditions.checkState(!failed, "Downloading %s/%s failed", s3Artifact.getS3Bucket(), s3Artifact.getS3ObjectKey());
}
private boolean handleChunk(Future<Path> future, Path downloadTo, int chunk, long start, long remainingMillis) {
if (remainingMillis <= 0) {
remainingMillis = 1;
}
try {
Path path = future.get(remainingMillis, TimeUnit.MILLISECONDS);
if (chunk > 0) {
combineChunk(downloadTo, path);
}
return true;
} catch (TimeoutException te) {
log.error("Chunk {} timed out after {} - had {} remaining", chunk, JavaUtils.duration(start), JavaUtils.durationFromMillis(remainingMillis));
future.cancel(true);
} catch (InterruptedException ie ) {
log.warn("Chunk {} interrupted", chunk);
} catch (Throwable t) {
log.error("Error while downloading chunk {}", chunk, t);
}
return false;
}
private void combineChunk(Path downloadTo, Path path) throws Exception {
final long start = System.currentTimeMillis();
long bytes = 0;
log.info("Writing {} to {}", path, downloadTo);
try (WritableByteChannel wbs = Files.newByteChannel(downloadTo, EnumSet.of(StandardOpenOption.APPEND, StandardOpenOption.WRITE))) {
try (FileChannel readChannel = FileChannel.open(path, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.DELETE_ON_CLOSE))) {
bytes = readChannel.size();
readChannel.transferTo(0, bytes, wbs);
}
}
log.info("Finished writing {} bytes in {}", bytes, JavaUtils.duration(start));
}
}
|
package com.hubspot.singularity.scheduler;
import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.mesos.Resources;
import com.hubspot.singularity.DeployState;
import com.hubspot.singularity.ExtendedTaskState;
import com.hubspot.singularity.MachineState;
import com.hubspot.singularity.RequestState;
import com.hubspot.singularity.RequestType;
import com.hubspot.singularity.ScheduleType;
import com.hubspot.singularity.SingularityAgent;
import com.hubspot.singularity.SingularityCreateResult;
import com.hubspot.singularity.SingularityDeployKey;
import com.hubspot.singularity.SingularityDeployMarker;
import com.hubspot.singularity.SingularityDeployStatistics;
import com.hubspot.singularity.SingularityDeployStatisticsBuilder;
import com.hubspot.singularity.SingularityKilledTaskIdRecord;
import com.hubspot.singularity.SingularityMachineAbstraction;
import com.hubspot.singularity.SingularityManagedThreadPoolFactory;
import com.hubspot.singularity.SingularityPendingDeploy;
import com.hubspot.singularity.SingularityPendingRequest;
import com.hubspot.singularity.SingularityPendingRequest.PendingType;
import com.hubspot.singularity.SingularityPendingTask;
import com.hubspot.singularity.SingularityPendingTaskId;
import com.hubspot.singularity.SingularityRack;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityRequestDeployState;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskCleanup;
import com.hubspot.singularity.SingularityTaskHistoryUpdate;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskRequest;
import com.hubspot.singularity.SingularityTaskShellCommandRequestId;
import com.hubspot.singularity.TaskCleanupType;
import com.hubspot.singularity.TaskFailureEvent;
import com.hubspot.singularity.TaskFailureType;
import com.hubspot.singularity.async.CompletableFutures;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.AbstractMachineManager;
import com.hubspot.singularity.data.AgentManager;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.RackManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.data.TaskRequestManager;
import com.hubspot.singularity.expiring.SingularityExpiringBounce;
import com.hubspot.singularity.helpers.RFC5545Schedule;
import com.hubspot.singularity.helpers.RebalancingHelper;
import com.hubspot.singularity.mesos.SingularityMesosSchedulerClient;
import com.hubspot.singularity.mesos.SingularitySchedulerLock;
import com.hubspot.singularity.smtp.SingularityMailer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Singleton;
import org.apache.mesos.v1.Protos;
import org.apache.mesos.v1.Protos.AgentID;
import org.apache.mesos.v1.Protos.TaskID;
import org.apache.mesos.v1.Protos.TaskStatus.Reason;
import org.apache.mesos.v1.scheduler.Protos.Call.Reconcile.Task;
import org.dmfs.rfc5545.recur.InvalidRecurrenceRuleException;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class SingularityScheduler {
private static final Logger LOG = LoggerFactory.getLogger(SingularityScheduler.class);
private final SingularityConfiguration configuration;
private final SingularityCrashLoops crashLoops;
private final TaskManager taskManager;
private final RequestManager requestManager;
private final TaskRequestManager taskRequestManager;
private final DeployManager deployManager;
private final AgentManager agentManager;
private final RebalancingHelper rebalancingHelper;
private final RackManager rackManager;
private final SingularityMailer mailer;
private final SingularityLeaderCache leaderCache;
private final SingularitySchedulerLock lock;
private final ExecutorService schedulerExecutorService;
private final SingularityMesosSchedulerClient mesosSchedulerClient;
private final Map<SingularityTaskId, Long> requestedReconciles;
@Inject
public SingularityScheduler(
TaskRequestManager taskRequestManager,
SingularityConfiguration configuration,
SingularityCrashLoops crashLoops,
DeployManager deployManager,
TaskManager taskManager,
RequestManager requestManager,
AgentManager agentManager,
RebalancingHelper rebalancingHelper,
RackManager rackManager,
SingularityMailer mailer,
SingularityLeaderCache leaderCache,
SingularitySchedulerLock lock,
SingularityManagedThreadPoolFactory threadPoolFactory,
SingularityMesosSchedulerClient mesosSchedulerClient
) {
this.taskRequestManager = taskRequestManager;
this.configuration = configuration;
this.deployManager = deployManager;
this.taskManager = taskManager;
this.requestManager = requestManager;
this.agentManager = agentManager;
this.rebalancingHelper = rebalancingHelper;
this.rackManager = rackManager;
this.mailer = mailer;
this.crashLoops = crashLoops;
this.leaderCache = leaderCache;
this.lock = lock;
this.schedulerExecutorService =
threadPoolFactory.get("scheduler", configuration.getCoreThreadpoolSize());
this.mesosSchedulerClient = mesosSchedulerClient;
this.requestedReconciles = new HashMap<>();
}
private void cleanupTaskDueToDecomission(
final Map<String, Optional<String>> requestIdsToUserToReschedule,
final Set<SingularityTaskId> matchingTaskIds,
SingularityTask task,
SingularityMachineAbstraction<?> decommissioningObject
) {
requestIdsToUserToReschedule.put(
task.getTaskRequest().getRequest().getId(),
decommissioningObject.getCurrentState().getUser()
);
matchingTaskIds.add(task.getTaskId());
LOG.trace(
"Scheduling a cleanup task for {} due to decomissioning {}",
task.getTaskId(),
decommissioningObject
);
taskManager.createTaskCleanup(
new SingularityTaskCleanup(
decommissioningObject.getCurrentState().getUser(),
TaskCleanupType.DECOMISSIONING,
System.currentTimeMillis(),
task.getTaskId(),
Optional.of(
String.format(
"%s %s is decomissioning",
decommissioningObject.getTypeName(),
decommissioningObject.getName()
)
),
Optional.<String>empty(),
Optional.<SingularityTaskShellCommandRequestId>empty()
)
);
}
private <T extends SingularityMachineAbstraction<T>> Map<T, MachineState> getDefaultMap(
List<T> objects
) {
Map<T, MachineState> map = Maps.newHashMapWithExpectedSize(objects.size());
for (T object : objects) {
map.put(object, MachineState.DECOMMISSIONING);
}
return map;
}
@Timed
public void checkForDecomissions() {
final long start = System.currentTimeMillis();
final Map<String, Optional<String>> requestIdsToUserToReschedule = Maps.newHashMap();
final Set<SingularityTaskId> matchingTaskIds = Sets.newHashSet();
final Collection<SingularityTaskId> activeTaskIds = leaderCache.getActiveTaskIds();
final Map<SingularityAgent, MachineState> agents = getDefaultMap(
agentManager.getObjectsFiltered(MachineState.STARTING_DECOMMISSION)
);
for (SingularityAgent agent : agents.keySet()) {
boolean foundTask = false;
for (SingularityTask activeTask : taskManager.getTasksOnAgent(
activeTaskIds,
agent
)) {
cleanupTaskDueToDecomission(
requestIdsToUserToReschedule,
matchingTaskIds,
activeTask,
agent
);
foundTask = true;
}
if (!foundTask) {
agents.put(agent, MachineState.DECOMMISSIONED);
}
}
final Map<SingularityRack, MachineState> racks = getDefaultMap(
rackManager.getObjectsFiltered(MachineState.STARTING_DECOMMISSION)
);
for (SingularityRack rack : racks.keySet()) {
final String sanitizedRackId = JavaUtils.getReplaceHyphensWithUnderscores(
rack.getId()
);
boolean foundTask = false;
for (SingularityTaskId activeTaskId : activeTaskIds) {
if (sanitizedRackId.equals(activeTaskId.getSanitizedRackId())) {
foundTask = true;
}
if (matchingTaskIds.contains(activeTaskId)) {
continue;
}
if (sanitizedRackId.equals(activeTaskId.getSanitizedRackId())) {
Optional<SingularityTask> maybeTask = taskManager.getTask(activeTaskId);
cleanupTaskDueToDecomission(
requestIdsToUserToReschedule,
matchingTaskIds,
maybeTask.get(),
rack
);
}
}
if (!foundTask) {
racks.put(rack, MachineState.DECOMMISSIONED);
}
}
for (Entry<String, Optional<String>> requestIdAndUser : requestIdsToUserToReschedule.entrySet()) {
final String requestId = requestIdAndUser.getKey();
LOG.trace("Rescheduling request {} due to decomissions", requestId);
Optional<String> maybeDeployId = deployManager.getInUseDeployId(requestId);
if (maybeDeployId.isPresent()) {
requestManager.addToPendingQueue(
new SingularityPendingRequest(
requestId,
maybeDeployId.get(),
start,
requestIdAndUser.getValue(),
PendingType.DECOMISSIONED_SLAVE_OR_RACK,
Optional.<Boolean>empty(),
Optional.<String>empty()
)
);
} else {
LOG.warn(
"Not rescheduling a request ({}) because of no active deploy",
requestId
);
}
}
changeState(agents, agentManager);
changeState(racks, rackManager);
if (
agents.isEmpty() &&
racks.isEmpty() &&
requestIdsToUserToReschedule.isEmpty() &&
matchingTaskIds.isEmpty()
) {
LOG.trace("Decomission check found nothing");
} else {
LOG.info(
"Found {} decomissioning agents, {} decomissioning racks, rescheduling {} requests and scheduling {} tasks for cleanup in {}",
agents.size(),
racks.size(),
requestIdsToUserToReschedule.size(),
matchingTaskIds.size(),
JavaUtils.duration(start)
);
}
}
private <T extends SingularityMachineAbstraction<T>> void changeState(
Map<T, MachineState> map,
AbstractMachineManager<T> manager
) {
for (Entry<T, MachineState> entry : map.entrySet()) {
manager.changeState(
entry.getKey().getId(),
entry.getValue(),
entry.getKey().getCurrentState().getMessage(),
entry.getKey().getCurrentState().getUser()
);
}
}
@Timed
public void drainPendingQueue() {
final long start = System.currentTimeMillis();
final ImmutableList<SingularityPendingRequest> pendingRequests = ImmutableList.copyOf(
requestManager.getPendingRequests()
);
if (pendingRequests.isEmpty()) {
LOG.trace("Pending queue was empty");
return;
}
LOG.info("Pending queue had {} requests", pendingRequests.size());
Map<SingularityDeployKey, List<SingularityPendingRequest>> deployKeyToPendingRequests = pendingRequests
.stream()
.collect(
Collectors.groupingBy(
request ->
new SingularityDeployKey(request.getRequestId(), request.getDeployId())
)
);
AtomicInteger totalNewScheduledTasks = new AtomicInteger(0);
AtomicInteger heldForScheduledActiveTask = new AtomicInteger(0);
AtomicInteger obsoleteRequests = new AtomicInteger(0);
List<CompletableFuture<Void>> checkFutures = deployKeyToPendingRequests
.entrySet()
.stream()
.map(
e ->
CompletableFuture.runAsync(
() ->
lock.runWithRequestLock(
() ->
handlePendingRequestsForDeployKeySafe(
obsoleteRequests,
heldForScheduledActiveTask,
totalNewScheduledTasks,
e.getKey(),
e.getValue()
),
e.getKey().getRequestId(),
String.format("%s#%s", getClass().getSimpleName(), "drainPendingQueue")
),
schedulerExecutorService
)
)
.collect(Collectors.toList());
CompletableFutures.allOf(checkFutures).join();
LOG.info(
"Scheduled {} new tasks ({} obsolete requests, {} held) in {}",
totalNewScheduledTasks.get(),
obsoleteRequests.get(),
heldForScheduledActiveTask.get(),
JavaUtils.duration(start)
);
}
private void handlePendingRequestsForDeployKeySafe(
AtomicInteger obsoleteRequests,
AtomicInteger heldForScheduledActiveTask,
AtomicInteger totalNewScheduledTasks,
SingularityDeployKey deployKey,
List<SingularityPendingRequest> pendingRequestsForDeploy
) {
try {
handlePendingRequestsForDeployKey(
obsoleteRequests,
heldForScheduledActiveTask,
totalNewScheduledTasks,
deployKey,
pendingRequestsForDeploy
);
} catch (Exception e) {
LOG.error("Error handling pending requests for {}, skipping", deployKey, e);
}
}
private void handlePendingRequestsForDeployKey(
AtomicInteger obsoleteRequests,
AtomicInteger heldForScheduledActiveTask,
AtomicInteger totalNewScheduledTasks,
SingularityDeployKey deployKey,
List<SingularityPendingRequest> pendingRequestsForDeploy
) {
final String requestId = deployKey.getRequestId();
final Optional<SingularityRequestWithState> maybeRequest = requestManager.getRequest(
requestId
);
final SingularityDeployStatistics deployStatistics = getDeployStatistics(
deployKey.getRequestId(),
deployKey.getDeployId()
);
if (!isRequestActive(maybeRequest)) {
LOG.debug(
"Pending request {} was obsolete (request {})",
requestId,
SingularityRequestWithState.getRequestState(maybeRequest)
);
obsoleteRequests.getAndIncrement();
for (SingularityPendingRequest pendingRequest : pendingRequestsForDeploy) {
requestManager.deletePendingRequest(pendingRequest);
}
return;
}
SingularityRequestWithState request = maybeRequest.get();
Optional<SingularityRequestDeployState> maybeRequestDeployState = deployManager.getRequestDeployState(
requestId
);
Optional<SingularityPendingDeploy> maybePendingDeploy = deployManager.getPendingDeploy(
requestId
);
List<SingularityTaskId> matchingTaskIds = getMatchingTaskIds(
request.getRequest(),
deployKey
);
List<SingularityPendingRequest> effectivePendingRequests = new ArrayList<>();
// Things that are closest to now (ie smaller timestamps) should come first in the queue
pendingRequestsForDeploy.sort(
Comparator.comparingLong(SingularityPendingRequest::getTimestamp)
);
int scheduledTasks = 0;
for (SingularityPendingRequest pendingRequest : pendingRequestsForDeploy) {
final SingularityRequest updatedRequest = updatedRequest(
maybePendingDeploy,
pendingRequest,
request
);
if (
!shouldScheduleTasks(
updatedRequest,
pendingRequest,
maybePendingDeploy,
maybeRequestDeployState
)
) {
LOG.debug(
"Pending request {} was obsolete (request {})",
pendingRequest,
SingularityRequestWithState.getRequestState(maybeRequest)
);
obsoleteRequests.getAndIncrement();
requestManager.deletePendingRequest(pendingRequest);
continue;
}
int missingInstances = getNumMissingInstances(
matchingTaskIds,
updatedRequest,
pendingRequest,
maybePendingDeploy
);
if (
missingInstances == 0 &&
!matchingTaskIds.isEmpty() &&
updatedRequest.isScheduled() &&
pendingRequest.getPendingType() == PendingType.NEW_DEPLOY
) {
LOG.trace(
"Holding pending request {} because it is scheduled and has an active task",
pendingRequest
);
heldForScheduledActiveTask.getAndIncrement();
continue;
}
if (effectivePendingRequests.isEmpty()) {
effectivePendingRequests.add(pendingRequest);
RequestState requestState = checkCooldown(
request.getState(),
request.getRequest(),
deployStatistics
);
scheduledTasks +=
scheduleTasks(
request.getRequest(),
requestState,
pendingRequest,
matchingTaskIds,
maybePendingDeploy
);
requestManager.deletePendingRequest(pendingRequest);
} else if (pendingRequest.getPendingType() == PendingType.IMMEDIATE) {
effectivePendingRequests.add(pendingRequest);
RequestState requestState = checkCooldown(
request.getState(),
request.getRequest(),
deployStatistics
);
scheduledTasks +=
scheduleTasks(
request.getRequest(),
requestState,
pendingRequest,
matchingTaskIds,
maybePendingDeploy
);
requestManager.deletePendingRequest(pendingRequest);
} else if (pendingRequest.getPendingType() == PendingType.ONEOFF) {
effectivePendingRequests.add(pendingRequest);
RequestState requestState = checkCooldown(
request.getState(),
request.getRequest(),
deployStatistics
);
scheduledTasks +=
scheduleTasks(
request.getRequest(),
requestState,
pendingRequest,
matchingTaskIds,
maybePendingDeploy
);
requestManager.deletePendingRequest(pendingRequest);
} else if (
updatedRequest.isScheduled() &&
(
pendingRequest.getPendingType() == PendingType.NEW_DEPLOY ||
pendingRequest.getPendingType() == PendingType.TASK_DONE
)
) {
// If we are here, there is already an immediate of run of the scheduled task launched. Drop anything that would
// leave a second instance of the request in the pending queue.
requestManager.deletePendingRequest(pendingRequest);
}
// Any other subsequent requests are not honored until after the pending queue is cleared.
}
totalNewScheduledTasks.getAndAdd(scheduledTasks);
}
private RequestState checkCooldown(
RequestState requestState,
SingularityRequest request,
SingularityDeployStatistics deployStatistics
) {
if (requestState != RequestState.SYSTEM_COOLDOWN) {
return requestState;
}
if (crashLoops.hasCooldownExpired(deployStatistics, Optional.empty())) {
requestManager.exitCooldown(
request,
System.currentTimeMillis(),
Optional.empty(),
Optional.empty()
);
return RequestState.ACTIVE;
}
return requestState;
}
private boolean shouldScheduleTasks(
SingularityRequest request,
SingularityPendingRequest pendingRequest,
Optional<SingularityPendingDeploy> maybePendingDeploy,
Optional<SingularityRequestDeployState> maybeRequestDeployState
) {
if (
request.isDeployable() &&
pendingRequest.getPendingType() == PendingType.NEW_DEPLOY &&
!maybePendingDeploy.isPresent()
) {
return false;
}
if (
request.getRequestType() == RequestType.RUN_ONCE &&
pendingRequest.getPendingType() == PendingType.NEW_DEPLOY
) {
return true;
}
return isDeployInUse(maybeRequestDeployState, pendingRequest.getDeployId(), false);
}
@Timed
public List<SingularityTaskRequest> getDueTasks() {
final List<SingularityPendingTask> tasks = taskManager.getPendingTasks();
final long now = System.currentTimeMillis();
final List<SingularityPendingTask> dueTasks = Lists.newArrayListWithCapacity(
tasks.size()
);
for (SingularityPendingTask task : tasks) {
if (task.getPendingTaskId().getNextRunAt() <= now) {
dueTasks.add(task);
}
}
final List<SingularityTaskRequest> dueTaskRequests = taskRequestManager.getTaskRequests(
dueTasks
);
return checkForStaleScheduledTasks(dueTasks, dueTaskRequests);
}
private List<SingularityTaskRequest> checkForStaleScheduledTasks(
List<SingularityPendingTask> pendingTasks,
List<SingularityTaskRequest> taskRequests
) {
final Set<String> foundPendingTaskId = Sets.newHashSetWithExpectedSize(
taskRequests.size()
);
final Set<String> requestIds = Sets.newHashSetWithExpectedSize(taskRequests.size());
for (SingularityTaskRequest taskRequest : taskRequests) {
foundPendingTaskId.add(taskRequest.getPendingTask().getPendingTaskId().getId());
requestIds.add(taskRequest.getRequest().getId());
}
for (SingularityPendingTask pendingTask : pendingTasks) {
if (!foundPendingTaskId.contains(pendingTask.getPendingTaskId().getId())) {
LOG.info("Removing stale pending task {}", pendingTask.getPendingTaskId());
taskManager.deletePendingTask(pendingTask.getPendingTaskId());
}
}
// TODO this check isn't necessary if we keep track better during deploys
final Map<String, SingularityRequestDeployState> deployStates = deployManager.getRequestDeployStatesByRequestIds(
requestIds
);
final List<SingularityTaskRequest> taskRequestsWithValidDeploys = Lists.newArrayListWithCapacity(
taskRequests.size()
);
for (SingularityTaskRequest taskRequest : taskRequests) {
SingularityRequestDeployState requestDeployState = deployStates.get(
taskRequest.getRequest().getId()
);
if (
!matchesDeploy(requestDeployState, taskRequest) &&
!(taskRequest.getRequest().getRequestType() == RequestType.RUN_ONCE)
) {
LOG.info(
"Removing stale pending task {} because the deployId did not match active/pending deploys {}",
taskRequest.getPendingTask().getPendingTaskId(),
requestDeployState
);
taskManager.deletePendingTask(taskRequest.getPendingTask().getPendingTaskId());
} else {
taskRequestsWithValidDeploys.add(taskRequest);
}
}
return taskRequestsWithValidDeploys;
}
private boolean matchesDeploy(
SingularityRequestDeployState requestDeployState,
SingularityTaskRequest taskRequest
) {
if (requestDeployState == null) {
return false;
}
return (
matchesDeployMarker(
requestDeployState.getActiveDeploy(),
taskRequest.getDeploy().getId()
) ||
matchesDeployMarker(
requestDeployState.getPendingDeploy(),
taskRequest.getDeploy().getId()
)
);
}
private boolean matchesDeployMarker(
Optional<SingularityDeployMarker> deployMarker,
String deployId
) {
return deployMarker.isPresent() && deployMarker.get().getDeployId().equals(deployId);
}
private void deleteScheduledTasks(
final Collection<SingularityPendingTask> scheduledTasks,
SingularityPendingRequest pendingRequest
) {
List<SingularityPendingTask> tasksForDeploy = scheduledTasks
.stream()
.filter(
task ->
pendingRequest.getRequestId().equals(task.getPendingTaskId().getRequestId())
)
.filter(
task -> pendingRequest.getDeployId().equals(task.getPendingTaskId().getDeployId())
)
.collect(Collectors.toList());
for (SingularityPendingTask task : tasksForDeploy) {
LOG.debug(
"Deleting pending task {} in order to reschedule {}",
task.getPendingTaskId().getId(),
pendingRequest
);
taskManager.deletePendingTask(task.getPendingTaskId());
}
}
private List<SingularityTaskId> getMatchingTaskIds(
SingularityRequest request,
SingularityDeployKey deployKey
) {
List<SingularityTaskId> activeTaskIdsForRequest = leaderCache.getActiveTaskIdsForRequest(
deployKey.getRequestId()
);
if (request.isLongRunning()) {
Set<SingularityTaskId> killedTaskIds = leaderCache
.getKilledTasks()
.stream()
.map(SingularityKilledTaskIdRecord::getTaskId)
.collect(Collectors.toSet());
List<SingularityTaskId> matchingTaskIds = new ArrayList<>();
for (SingularityTaskId taskId : activeTaskIdsForRequest) {
if (!taskId.getDeployId().equals(deployKey.getDeployId())) {
continue;
}
if (leaderCache.getCleanupTaskIds().contains(taskId)) {
continue;
}
if (killedTaskIds.contains(taskId)) {
continue;
}
matchingTaskIds.add(taskId);
}
return matchingTaskIds;
} else {
return new ArrayList<>(activeTaskIdsForRequest);
}
}
private int scheduleTasks(
SingularityRequest request,
RequestState state,
SingularityPendingRequest pendingRequest,
List<SingularityTaskId> matchingTaskIds,
Optional<SingularityPendingDeploy> maybePendingDeploy
) {
if (request.getRequestType() != RequestType.ON_DEMAND) {
deleteScheduledTasks(leaderCache.getPendingTasks(), pendingRequest);
}
final int numMissingInstances = getNumMissingInstances(
matchingTaskIds,
request,
pendingRequest,
maybePendingDeploy
);
LOG.debug(
"Missing {} instances of request {} (matching tasks: {}), pending request: {}, pending deploy: {}",
numMissingInstances,
request.getId(),
matchingTaskIds.size() < 20 ? matchingTaskIds : matchingTaskIds.size(),
pendingRequest,
maybePendingDeploy
);
if (numMissingInstances > 0) {
schedule(numMissingInstances, matchingTaskIds, request, state, pendingRequest);
} else if (numMissingInstances < 0) {
final long now = System.currentTimeMillis();
if (maybePendingDeploy.isPresent()) {
matchingTaskIds.sort(SingularityTaskId.INSTANCE_NO_COMPARATOR); // For deploy steps we replace lowest instances first, so clean those
} else {
matchingTaskIds.sort(
Collections.reverseOrder(SingularityTaskId.INSTANCE_NO_COMPARATOR)
); // clean the highest numbers
}
List<SingularityTaskId> remainingActiveTasks = new ArrayList<>(matchingTaskIds);
final int expectedInstances = numMissingInstances + matchingTaskIds.size();
LOG.info("expected {} active {}", expectedInstances, matchingTaskIds);
List<Integer> usedIds = new ArrayList<>();
for (SingularityTaskId taskId : matchingTaskIds) {
if (
usedIds.contains(taskId.getInstanceNo()) ||
taskId.getInstanceNo() > expectedInstances
) {
remainingActiveTasks.remove(taskId);
LOG.info(
"Cleaning up task {} due to new request {} - scaling down to {} instances",
taskId.getId(),
request.getId(),
request.getInstancesSafe()
);
taskManager.createTaskCleanup(
new SingularityTaskCleanup(
pendingRequest.getUser(),
TaskCleanupType.SCALING_DOWN,
now,
taskId,
Optional.empty(),
Optional.empty(),
Optional.empty()
)
);
}
usedIds.add(taskId.getInstanceNo());
}
if (request.isRackSensitive() && configuration.isRebalanceRacksOnScaleDown()) {
rebalanceRacks(request, state, pendingRequest, remainingActiveTasks);
}
if (request.getAgentAttributeMinimums().isPresent()) {
rebalanceAttributeDistribution(
request,
state,
pendingRequest,
remainingActiveTasks
);
}
}
return numMissingInstances;
}
private void rebalanceAttributeDistribution(
SingularityRequest request,
RequestState state,
SingularityPendingRequest pendingRequest,
List<SingularityTaskId> remainingActiveTasks
) {
Set<SingularityTaskId> extraTasksToClean = rebalancingHelper.rebalanceAttributeDistribution(
request,
pendingRequest.getUser(),
remainingActiveTasks
);
remainingActiveTasks.removeAll(extraTasksToClean);
schedule(
extraTasksToClean.size(),
remainingActiveTasks,
request,
state,
pendingRequest
);
}
private void rebalanceRacks(
SingularityRequest request,
RequestState state,
SingularityPendingRequest pendingRequest,
List<SingularityTaskId> remainingActiveTasks
) {
List<SingularityTaskId> extraCleanedTasks = rebalancingHelper.rebalanceRacks(
request,
remainingActiveTasks,
pendingRequest.getUser()
);
remainingActiveTasks.removeAll(extraCleanedTasks);
if (extraCleanedTasks.size() > 0) {
schedule(
extraCleanedTasks.size(),
remainingActiveTasks,
request,
state,
pendingRequest
);
}
}
private void schedule(
int numMissingInstances,
List<SingularityTaskId> matchingTaskIds,
SingularityRequest request,
RequestState state,
SingularityPendingRequest pendingRequest
) {
final List<SingularityPendingTask> scheduledTasks = getScheduledTaskIds(
numMissingInstances,
matchingTaskIds,
request,
state,
pendingRequest.getDeployId(),
pendingRequest
);
if (!scheduledTasks.isEmpty()) {
LOG.trace("Scheduling tasks: {}", scheduledTasks);
for (SingularityPendingTask scheduledTask : scheduledTasks) {
taskManager.savePendingTask(scheduledTask);
}
} else {
LOG.info(
"No new scheduled tasks found for {}, setting state to {}",
request.getId(),
RequestState.FINISHED
);
requestManager.finish(request, System.currentTimeMillis());
}
}
private boolean isRequestActive(
Optional<SingularityRequestWithState> maybeRequestWithState
) {
return SingularityRequestWithState.isActive(maybeRequestWithState);
}
private boolean isDeployInUse(
Optional<SingularityRequestDeployState> requestDeployState,
String deployId,
boolean mustMatchActiveDeploy
) {
if (!requestDeployState.isPresent()) {
return false;
}
if (matchesDeployMarker(requestDeployState.get().getActiveDeploy(), deployId)) {
return true;
}
if (mustMatchActiveDeploy) {
return false;
}
return matchesDeployMarker(requestDeployState.get().getPendingDeploy(), deployId);
}
private Optional<PendingType> handleCompletedTaskWithStatistics(
Optional<SingularityTask> task,
SingularityTaskId taskId,
long timestamp,
ExtendedTaskState state,
SingularityDeployStatistics deployStatistics,
SingularityCreateResult taskHistoryUpdateCreateResult,
Protos.TaskStatus status
) {
final Optional<SingularityRequestWithState> maybeRequestWithState = requestManager.getRequest(
taskId.getRequestId()
);
final Optional<SingularityPendingDeploy> maybePendingDeploy = deployManager.getPendingDeploy(
taskId.getRequestId()
);
if (!isRequestActive(maybeRequestWithState)) {
LOG.warn(
"Not scheduling a new task, {} is {}",
taskId.getRequestId(),
SingularityRequestWithState.getRequestState(maybeRequestWithState)
);
return Optional.empty();
}
RequestState requestState = maybeRequestWithState.get().getState();
final SingularityRequest request = maybePendingDeploy.isPresent()
? maybePendingDeploy
.get()
.getUpdatedRequest()
.orElse(maybeRequestWithState.get().getRequest())
: maybeRequestWithState.get().getRequest();
final Optional<SingularityRequestDeployState> requestDeployState = deployManager.getRequestDeployState(
request.getId()
);
if (!isDeployInUse(requestDeployState, taskId.getDeployId(), true)) {
LOG.debug(
"Task {} completed, but it didn't match active deploy state {} - ignoring",
taskId.getId(),
requestDeployState
);
return Optional.empty();
}
if (
taskHistoryUpdateCreateResult == SingularityCreateResult.CREATED &&
requestState != RequestState.SYSTEM_COOLDOWN
) {
mailer.queueTaskCompletedMail(task, taskId, request, state);
} else if (requestState == RequestState.SYSTEM_COOLDOWN) {
LOG.debug(
"Not sending a task completed email because task {} is in SYSTEM_COOLDOWN",
taskId
);
} else {
LOG.debug(
"Not sending a task completed email for task {} because Singularity already processed this update",
taskId
);
}
if (!status.hasReason() || !status.getReason().equals(Reason.REASON_INVALID_OFFERS)) {
if (
state != ExtendedTaskState.TASK_KILLED &&
!state.isSuccess() &&
taskHistoryUpdateCreateResult == SingularityCreateResult.CREATED &&
crashLoops.shouldEnterCooldown(request, requestState, deployStatistics, timestamp)
) {
LOG.info(
"Request {} is entering cooldown due to task {}",
request.getId(),
taskId
);
requestState = RequestState.SYSTEM_COOLDOWN;
requestManager.cooldown(request, System.currentTimeMillis());
mailer.sendRequestInCooldownMail(request);
}
} else {
LOG.debug(
"Not triggering cooldown due to TASK_LOST from invalid offers for request {}",
request.getId()
);
}
PendingType pendingType = PendingType.TASK_DONE;
Optional<List<String>> cmdLineArgsList = Optional.empty();
Optional<Resources> resources = Optional.empty();
Optional<String> message = Optional.empty();
if (!state.isSuccess() && shouldRetryImmediately(request, deployStatistics, task)) {
LOG.debug("Retrying {} because {}", request.getId(), state);
pendingType = PendingType.RETRY;
if (task.isPresent()) {
cmdLineArgsList =
task.get().getTaskRequest().getPendingTask().getCmdLineArgsList();
resources = task.get().getTaskRequest().getPendingTask().getResources();
message = task.get().getTaskRequest().getPendingTask().getMessage();
}
} else if (!request.isAlwaysRunning()) {
return Optional.empty();
}
if (
state.isSuccess() &&
!request.isLongRunning() &&
requestState == RequestState.SYSTEM_COOLDOWN
) {
LOG.info("Request {} succeeded a task, removing from cooldown", request.getId());
requestManager.exitCooldown(
request,
System.currentTimeMillis(),
Optional.<String>empty(),
Optional.<String>empty()
);
}
SingularityPendingRequest pendingRequest = new SingularityPendingRequest(
request.getId(),
requestDeployState.get().getActiveDeploy().get().getDeployId(),
System.currentTimeMillis(),
Optional.empty(),
pendingType,
cmdLineArgsList,
Optional.empty(),
Optional.empty(),
message,
Optional.empty(),
resources,
Collections.emptyList(),
Optional.empty(),
Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyList(),
Optional.empty()
);
requestManager.addToPendingQueue(pendingRequest);
return Optional.of(pendingType);
}
private SingularityDeployStatistics getDeployStatistics(
String requestId,
String deployId
) {
final Optional<SingularityDeployStatistics> maybeDeployStatistics = deployManager.getDeployStatistics(
requestId,
deployId
);
return maybeDeployStatistics.orElseGet(
() -> new SingularityDeployStatisticsBuilder(requestId, deployId).build()
);
}
public void handleCompletedTask(
Optional<SingularityTask> task,
SingularityTaskId taskId,
long timestamp,
ExtendedTaskState state,
SingularityCreateResult taskHistoryUpdateCreateResult,
Protos.TaskStatus status
) {
final SingularityDeployStatistics deployStatistics = getDeployStatistics(
taskId.getRequestId(),
taskId.getDeployId()
);
if (!task.isPresent() || task.get().getTaskRequest().getRequest().isLoadBalanced()) {
taskManager.createLBCleanupTask(taskId);
}
if (requestManager.isBouncing(taskId.getRequestId())) {
List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIdsForRequest(
taskId.getRequestId()
);
boolean foundBouncingTask = false;
for (SingularityTaskId activeTaskId : activeTaskIds) {
Optional<SingularityTaskHistoryUpdate> maybeCleaningUpdate = taskManager.getTaskHistoryUpdate(
activeTaskId,
ExtendedTaskState.TASK_CLEANING
);
if (maybeCleaningUpdate.isPresent()) {
if (maybeCleaningUpdate.get().getStatusReason().orElse("").contains("BOUNCE")) { // TaskCleanupType enum is included in status message
LOG.debug("Found task {} still waiting for bounce to complete", activeTaskId);
foundBouncingTask = true;
break;
} else if (!maybeCleaningUpdate.get().getPrevious().isEmpty()) {
for (SingularityTaskHistoryUpdate previousUpdate : maybeCleaningUpdate
.get()
.getPrevious()) {
if (previousUpdate.getStatusMessage().orElse("").contains("BOUNCE")) {
LOG.debug(
"Found task {} still waiting for bounce to complete",
activeTaskId
);
foundBouncingTask = true;
break;
}
}
}
}
}
if (!foundBouncingTask) {
LOG.info(
"Bounce completed for request {}, no cleaning tasks due to bounce found",
taskId.getRequestId()
);
Optional<SingularityExpiringBounce> expiringBounce = requestManager.getExpiringBounce(
taskId.getRequestId()
);
if (
expiringBounce.isPresent() &&
expiringBounce.get().getDeployId().equals(taskId.getDeployId())
) {
requestManager.removeExpiringBounce(taskId.getRequestId());
}
requestManager.markBounceComplete(taskId.getRequestId());
}
}
final Optional<PendingType> scheduleResult = handleCompletedTaskWithStatistics(
task,
taskId,
timestamp,
state,
deployStatistics,
taskHistoryUpdateCreateResult,
status
);
if (taskHistoryUpdateCreateResult == SingularityCreateResult.EXISTED) {
return;
}
updateDeployStatistics(
deployStatistics,
taskId,
task,
timestamp,
state,
scheduleResult,
status
);
}
private void updateDeployStatistics(
SingularityDeployStatistics deployStatistics,
SingularityTaskId taskId,
Optional<SingularityTask> task,
long timestamp,
ExtendedTaskState state,
Optional<PendingType> scheduleResult,
Protos.TaskStatus status
) {
SingularityDeployStatisticsBuilder bldr = deployStatistics.toBuilder();
if (!state.isFailed()) {
if (bldr.getAverageRuntimeMillis().isPresent()) {
long newAvgRuntimeMillis =
(
bldr.getAverageRuntimeMillis().get() *
bldr.getNumTasks() +
(timestamp - taskId.getStartedAt())
) /
(bldr.getNumTasks() + 1);
bldr.setAverageRuntimeMillis(Optional.of(newAvgRuntimeMillis));
} else {
bldr.setAverageRuntimeMillis(Optional.of(timestamp - taskId.getStartedAt()));
}
}
if (task.isPresent()) {
long dueTime = task
.get()
.getTaskRequest()
.getPendingTask()
.getPendingTaskId()
.getNextRunAt();
long startedAt = taskId.getStartedAt();
if (bldr.getAverageSchedulingDelayMillis().isPresent()) {
long newAverageSchedulingDelayMillis =
(
bldr.getAverageSchedulingDelayMillis().get() *
bldr.getNumTasks() +
(startedAt - dueTime)
) /
(bldr.getNumTasks() + 1);
bldr.setAverageSchedulingDelayMillis(
Optional.of(newAverageSchedulingDelayMillis)
);
} else {
bldr.setAverageSchedulingDelayMillis(Optional.of(startedAt - dueTime));
}
}
bldr.setNumTasks(bldr.getNumTasks() + 1);
if (!bldr.getLastFinishAt().isPresent() || timestamp > bldr.getLastFinishAt().get()) {
bldr.setLastFinishAt(Optional.of(timestamp));
bldr.setLastTaskState(Optional.of(state));
}
if (
task.isPresent() &&
task.get().getTaskRequest().getRequest().isLongRunning() &&
state == ExtendedTaskState.TASK_FINISHED
) {
bldr.addTaskFailureEvent(
new TaskFailureEvent(
taskId.getInstanceNo(),
timestamp,
TaskFailureType.UNEXPECTED_EXIT
)
);
}
if (state == ExtendedTaskState.TASK_KILLED) {
if (status.hasMessage()) {
Optional<TaskCleanupType> maybeCleanupType = getCleanupType(
taskId,
status.getMessage()
);
if (
maybeCleanupType.isPresent() &&
(
maybeCleanupType.get() == TaskCleanupType.OVERDUE_NEW_TASK ||
maybeCleanupType.get() == TaskCleanupType.UNHEALTHY_NEW_TASK
)
) {
bldr.addTaskFailureEvent(
new TaskFailureEvent(
taskId.getInstanceNo(),
timestamp,
TaskFailureType.STARTUP_FAILURE
)
);
}
}
}
if (!state.isSuccess()) {
if (
SingularityTaskHistoryUpdate
.getUpdate(
taskManager.getTaskHistoryUpdates(taskId),
ExtendedTaskState.TASK_CLEANING
)
.isPresent()
) {
LOG.debug(
"{} failed with {} after cleaning - ignoring it for cooldown/crash loop",
taskId,
state
);
} else {
if (state.isFailed()) {
if (
(
status.hasMessage() && status.getMessage().contains("Memory limit exceeded")
) ||
(
status.hasReason() &&
status.getReason() == Reason.REASON_CONTAINER_LIMITATION_MEMORY
)
) {
bldr.addTaskFailureEvent(
new TaskFailureEvent(taskId.getInstanceNo(), timestamp, TaskFailureType.OOM)
);
} else if (
status.hasReason() &&
status.getReason() == Reason.REASON_CONTAINER_LIMITATION_DISK
) {
bldr.addTaskFailureEvent(
new TaskFailureEvent(
taskId.getInstanceNo(),
timestamp,
TaskFailureType.OUT_OF_DISK_SPACE
)
);
} else {
bldr.addTaskFailureEvent(
new TaskFailureEvent(
taskId.getInstanceNo(),
timestamp,
TaskFailureType.BAD_EXIT_CODE
)
);
}
}
if (state == ExtendedTaskState.TASK_LOST && status.hasReason()) {
if (isMesosError(status.getReason())) {
bldr.addTaskFailureEvent(
new TaskFailureEvent(
taskId.getInstanceNo(),
timestamp,
TaskFailureType.MESOS_ERROR
)
);
} else if (isLostAgent(status.getReason())) {
bldr.addTaskFailureEvent(
new TaskFailureEvent(
taskId.getInstanceNo(),
timestamp,
TaskFailureType.LOST_SLAVE
)
);
}
}
bldr.setNumSuccess(0);
bldr.setNumFailures(bldr.getNumFailures() + 1);
}
} else {
bldr.setNumSuccess(bldr.getNumSuccess() + 1);
bldr.setNumFailures(0);
}
if (scheduleResult.isPresent() && scheduleResult.get() == PendingType.RETRY) {
bldr.setNumSequentialRetries(bldr.getNumSequentialRetries() + 1);
} else {
bldr.setNumSequentialRetries(0);
}
bldr.trimTaskFailureEvents(50);
final SingularityDeployStatistics newStatistics = bldr.build();
LOG.trace("Saving new deploy statistics {}", newStatistics);
deployManager.saveDeployStatistics(newStatistics);
}
private boolean isMesosError(Reason reason) {
switch (reason) {
case REASON_COMMAND_EXECUTOR_FAILED:
case REASON_CONTAINER_LAUNCH_FAILED:
case REASON_CONTAINER_PREEMPTED:
case REASON_CONTAINER_UPDATE_FAILED:
case REASON_EXECUTOR_REGISTRATION_TIMEOUT:
case REASON_EXECUTOR_REREGISTRATION_TIMEOUT:
case REASON_EXECUTOR_TERMINATED:
case REASON_EXECUTOR_UNREGISTERED:
case REASON_FRAMEWORK_REMOVED:
case REASON_GC_ERROR:
case REASON_INVALID_FRAMEWORKID:
case REASON_INVALID_OFFERS:
case REASON_MASTER_DISCONNECTED:
case REASON_RECONCILIATION:
case REASON_RESOURCES_UNKNOWN:
case REASON_TASK_GROUP_INVALID:
case REASON_TASK_GROUP_UNAUTHORIZED:
case REASON_TASK_INVALID:
case REASON_TASK_UNAUTHORIZED:
case REASON_TASK_UNKNOWN:
return true;
default:
return false;
}
}
private boolean isLostAgent(Reason reason) {
switch (reason) {
case REASON_AGENT_REMOVED:
case REASON_AGENT_RESTARTED:
case REASON_AGENT_UNKNOWN:
case REASON_AGENT_DISCONNECTED:
case REASON_AGENT_REMOVED_BY_OPERATOR:
return true;
default:
return false;
}
}
private Optional<TaskCleanupType> getCleanupType(
SingularityTaskId taskId,
String statusMessage
) {
try {
String[] cleanupTypeString = statusMessage.split("\\s+");
if (cleanupTypeString.length > 0) {
return Optional.of(TaskCleanupType.valueOf(cleanupTypeString[0]));
}
} catch (Throwable t) {
LOG.info("Could not parse cleanup type from {} for {}", statusMessage, taskId);
}
return Optional.empty();
}
private boolean shouldRetryImmediately(
SingularityRequest request,
SingularityDeployStatistics deployStatistics,
Optional<SingularityTask> task
) {
if (!request.getNumRetriesOnFailure().isPresent()) {
return false;
}
if (task.isPresent()) {
if (
task
.get()
.getTaskRequest()
.getPendingTask()
.getPendingTaskId()
.getPendingType() ==
PendingType.IMMEDIATE &&
request.getRequestType() == RequestType.SCHEDULED
) {
return false; // don't retry UI triggered scheduled jobs (UI triggered on-demand jobs are okay to retry though)
}
Optional<SingularityTaskHistoryUpdate> taskHistoryUpdate = taskManager.getTaskHistoryUpdate(
task.get().getTaskId(),
ExtendedTaskState.TASK_CLEANING
);
if (
taskHistoryUpdate.isPresent() &&
request.getRequestType() == RequestType.ON_DEMAND &&
Stream
.of("USER_REQUESTED", "PAUSE")
.anyMatch(
cleaningReason ->
taskHistoryUpdate
.get()
.getStatusMessage()
.orElse("")
.contains(cleaningReason)
)
) {
return false; // don't retry one-off launches of on-demand jobs if they were killed by the user
}
}
final int numRetriesInARow = deployStatistics.getNumSequentialRetries();
if (numRetriesInARow >= request.getNumRetriesOnFailure().get()) {
LOG.debug(
"Request {} had {} retries in a row, not retrying again (num retries on failure: {})",
request.getId(),
numRetriesInARow,
request.getNumRetriesOnFailure()
);
return false;
}
LOG.debug(
"Request {} had {} retries in a row - retrying again (num retries on failure: {})",
request.getId(),
numRetriesInARow,
request.getNumRetriesOnFailure()
);
return true;
}
private int getNumMissingInstances(
List<SingularityTaskId> matchingTaskIds,
SingularityRequest request,
SingularityPendingRequest pendingRequest,
Optional<SingularityPendingDeploy> maybePendingDeploy
) {
PendingType pendingType = pendingRequest.getPendingType();
if (request.isOneOff()) {
if (pendingType == PendingType.ONEOFF || pendingType == PendingType.RETRY) {
return 1;
} else {
return 0;
}
} else if (
request.getRequestType() == RequestType.RUN_ONCE &&
pendingType == PendingType.NEW_DEPLOY
) {
return 1;
}
return (
numInstancesExpected(request, pendingRequest, maybePendingDeploy) -
matchingTaskIds.size()
);
}
private int numInstancesExpected(
SingularityRequest request,
SingularityPendingRequest pendingRequest,
Optional<SingularityPendingDeploy> maybePendingDeploy
) {
if (!maybePendingDeploy.isPresent()) {
return request.getInstancesSafe();
}
boolean pendingRequestIsForPendingDeploy = maybePendingDeploy
.get()
.getDeployMarker()
.getDeployId()
.equals(pendingRequest.getDeployId());
if (!pendingRequestIsForPendingDeploy) {
if (maybePendingDeploy.get().getDeployProgress().isCanary()) {
return (
request.getInstancesSafe() -
maybePendingDeploy.get().getDeployProgress().getCurrentActiveInstances()
);
} else {
return request.getInstancesSafe();
}
}
if (
maybePendingDeploy.get().getCurrentDeployState() == DeployState.CANCELED ||
maybePendingDeploy.get().getCurrentDeployState() == DeployState.CANCELING
) {
return 0;
}
// Pending request is for the in progress deploy, calculate instances from deploy progress
return maybePendingDeploy.get().getDeployProgress().getTargetActiveInstances();
}
private List<SingularityPendingTask> getScheduledTaskIds(
int numMissingInstances,
List<SingularityTaskId> matchingTaskIds,
SingularityRequest request,
RequestState state,
String deployId,
SingularityPendingRequest pendingRequest
) {
final Optional<Long> nextRunAt = getNextRunAt(request, state, pendingRequest);
if (!nextRunAt.isPresent()) {
return Collections.emptyList();
}
final Set<Integer> inuseInstanceNumbers = Sets.newHashSetWithExpectedSize(
matchingTaskIds.size()
);
for (SingularityTaskId matchingTaskId : matchingTaskIds) {
inuseInstanceNumbers.add(matchingTaskId.getInstanceNo());
}
final List<SingularityPendingTask> newTasks = Lists.newArrayListWithCapacity(
numMissingInstances
);
int nextInstanceNumber = 1;
for (int i = 0; i < numMissingInstances; i++) {
while (inuseInstanceNumbers.contains(nextInstanceNumber)) {
nextInstanceNumber++;
}
newTasks.add(
new SingularityPendingTask(
new SingularityPendingTaskId(
request.getId(),
deployId,
nextRunAt.get(),
nextInstanceNumber,
pendingRequest.getPendingType(),
pendingRequest.getTimestamp()
),
pendingRequest.getCmdLineArgsList(),
pendingRequest.getUser(),
pendingRequest.getRunId(),
pendingRequest.getSkipHealthchecks(),
pendingRequest.getMessage(),
pendingRequest.getResources(),
pendingRequest.getS3UploaderAdditionalFiles(),
pendingRequest.getRunAsUserOverride(),
pendingRequest.getEnvOverrides(),
pendingRequest.getRequiredAgentAttributeOverrides(),
pendingRequest.getAllowedAgentAttributeOverrides(),
pendingRequest.getExtraArtifacts(),
pendingRequest.getActionId()
)
);
nextInstanceNumber++;
}
return newTasks;
}
private Optional<Long> getNextRunAt(
SingularityRequest request,
RequestState state,
SingularityPendingRequest pendingRequest
) {
PendingType pendingType = pendingRequest.getPendingType();
final long now = System.currentTimeMillis();
long nextRunAt = now;
if (request.isScheduled()) {
if (pendingType == PendingType.IMMEDIATE || pendingType == PendingType.RETRY) {
LOG.info("Scheduling requested immediate run of {}", request.getId());
} else {
try {
Date nextRunAtDate = null;
Date scheduleFrom = null;
if (request.getScheduleTypeSafe() == ScheduleType.RFC5545) {
final RFC5545Schedule rfc5545Schedule = new RFC5545Schedule(
request.getSchedule().get()
);
nextRunAtDate = rfc5545Schedule.getNextValidTime();
scheduleFrom = new Date(rfc5545Schedule.getStartDateTime().getMillis());
} else {
scheduleFrom = new Date(now);
final CronExpression cronExpression = new CronExpression(
request.getQuartzScheduleSafe()
);
if (request.getScheduleTimeZone().isPresent()) {
cronExpression.setTimeZone(
TimeZone.getTimeZone(request.getScheduleTimeZone().get())
);
}
nextRunAtDate = cronExpression.getNextValidTimeAfter(scheduleFrom);
}
if (nextRunAtDate == null) {
return Optional.empty();
}
LOG.trace(
"Calculating nextRunAtDate for {} (schedule: {}): {} (from: {})",
request.getId(),
request.getSchedule(),
nextRunAtDate,
scheduleFrom
);
nextRunAt = Math.max(nextRunAtDate.getTime(), now); // don't create a schedule that is overdue as this is used to indicate that singularity is not fulfilling requests.
LOG.trace(
"Scheduling next run of {} (schedule: {}) at {} (from: {})",
request.getId(),
request.getSchedule(),
nextRunAtDate,
scheduleFrom
);
} catch (ParseException | InvalidRecurrenceRuleException pe) {
LOG.error("Failed to get next run on {}", request, pe);
throw new RuntimeException(pe);
}
}
}
if (!request.isLongRunning() && pendingRequest.getRunAt().isPresent()) {
nextRunAt = Math.max(nextRunAt, pendingRequest.getRunAt().get());
}
if (
pendingType == PendingType.TASK_DONE &&
request.getWaitAtLeastMillisAfterTaskFinishesForReschedule().orElse(0L) > 0
) {
nextRunAt =
Math.max(
nextRunAt,
now + request.getWaitAtLeastMillisAfterTaskFinishesForReschedule().get()
);
LOG.trace(
"Adjusted next run of {} to {} (by {}) due to waitAtLeastMillisAfterTaskFinishesForReschedule",
request.getId(),
nextRunAt,
JavaUtils.durationFromMillis(
request.getWaitAtLeastMillisAfterTaskFinishesForReschedule().get()
)
);
}
if (state == RequestState.SYSTEM_COOLDOWN && pendingType != PendingType.NEW_DEPLOY) {
final long prevNextRunAt = nextRunAt;
nextRunAt =
Math.max(
nextRunAt,
now + TimeUnit.SECONDS.toMillis(configuration.getCooldownMinScheduleSeconds())
);
LOG.trace(
"Adjusted next run of {} to {} (from: {}) due to cooldown",
request.getId(),
nextRunAt,
prevNextRunAt
);
}
return Optional.of(nextRunAt);
}
private SingularityRequest updatedRequest(
Optional<SingularityPendingDeploy> maybePendingDeploy,
SingularityPendingRequest pendingRequest,
SingularityRequestWithState currentRequest
) {
if (
maybePendingDeploy.isPresent() &&
pendingRequest
.getDeployId()
.equals(maybePendingDeploy.get().getDeployMarker().getDeployId())
) {
return maybePendingDeploy
.get()
.getUpdatedRequest()
.orElse(currentRequest.getRequest());
} else {
return currentRequest.getRequest();
}
}
public void checkForStalledTaskLaunches() {
long now = System.currentTimeMillis();
taskManager
.getLaunchingTasks()
.stream()
.filter(
t -> {
if (t.getStartedAt() < now - configuration.getReconcileLaunchAfterMillis()) {
Long maybeLastReconcileTime = requestedReconciles.get(t);
// Don't overwhelm ourselves with status updates, only reconcile each task every 15s
return maybeLastReconcileTime == null || now - maybeLastReconcileTime > 15000;
} else {
return false;
}
}
)
.forEach(
taskId -> {
Optional<SingularityTask> maybeTask = taskManager.getTask(taskId);
if (maybeTask.isPresent()) {
mesosSchedulerClient.reconcile(
Collections.singletonList(
Task
.newBuilder()
.setTaskId(TaskID.newBuilder().setValue(taskId.toString()).build())
.setAgentId(
AgentID
.newBuilder()
.setValue(maybeTask.get().getAgentId().getValue())
.build()
)
.build()
)
);
LOG.info("Requested explicit reconcile of task {}", taskId);
} else {
LOG.warn("Could not find full content for task {}", taskId);
}
}
);
Set<SingularityTaskId> toRemove = requestedReconciles
.keySet()
.stream()
.filter(t -> t.getStartedAt() < now - TimeUnit.MINUTES.toMillis(15))
.collect(Collectors.toSet());
toRemove.forEach(requestedReconciles::remove);
}
}
|
package io.enmasse.controller;
import io.enmasse.address.model.AddressSpace;
import io.enmasse.address.model.AddressSpaceBuilder;
import io.enmasse.address.model.AddressSpaceStatusConnector;
import io.enmasse.admin.model.v1.*;
import io.enmasse.config.AnnotationKeys;
import io.enmasse.controller.router.config.*;
import io.enmasse.k8s.api.AuthenticationServiceRegistry;
import io.enmasse.k8s.api.LogEventLogger;
import io.enmasse.model.CustomResourceDefinitions;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretKeySelector;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RouterConfigControllerTest {
private NamespacedKubernetesClient client;
public KubernetesServer kubernetesServer = new KubernetesServer(false, true);
private AuthenticationServiceRegistry authenticationServiceRegistry;
@BeforeAll
public static void init() {
CustomResourceDefinitions.registerAll();
}
@BeforeEach
public void setup() {
kubernetesServer.before();
client = kubernetesServer.getClient();
authenticationServiceRegistry = mock(AuthenticationServiceRegistry.class);
when(authenticationServiceRegistry.findAuthenticationService(any())).thenReturn(Optional.of(
new AuthenticationServiceBuilder()
.editOrNewMetadata()
.withName("test")
.endMetadata()
.editOrNewSpec()
.withType(AuthenticationServiceType.standard)
.withRealm("myrealm")
.endSpec()
.editOrNewStatus()
.withHost("auth.example.com")
.withPort(5671)
.endStatus()
.build()));
}
@Test
public void testReconcile() throws Exception {
RouterConfigController configController = new RouterConfigController(
client,
"test",
new AuthenticationServiceResolver(authenticationServiceRegistry),
new RouterStatusCache(new LogEventLogger(), Duration.ofSeconds(100), mock(NamespacedKubernetesClient.class), "test", Duration.ofSeconds(100), Duration.ofSeconds(100)));
StandardInfraConfig appliedConfig = new StandardInfraConfigBuilder()
.editOrNewMetadata()
.withName("test")
.endMetadata()
.editOrNewSpec()
.editOrNewRouter()
.withIdleTimeout(2)
.withLinkCapacity(50)
.withHandshakeTimeout(20)
.withNewPolicy()
.withMaxConnections(30)
.withMaxConnectionsPerHost(10)
.withMaxConnectionsPerUser(10)
.withMaxReceiversPerConnection(2)
.withMaxSendersPerConnection(3)
.withMaxSessionsPerConnection(4)
.endPolicy()
.endRouter()
.endSpec()
.build();
AddressSpace addressSpace = new AddressSpaceBuilder()
.editOrNewMetadata()
.withName("myspace")
.addToAnnotations(AnnotationKeys.INFRA_UUID, "1234")
.endMetadata()
.editOrNewSpec()
.withType("type1")
.withPlan("plan1")
.withNewAuthenticationService()
.withName("test")
.endAuthenticationService()
.endSpec()
.build();
InfraConfigs.setCurrentInfraConfig(addressSpace, appliedConfig);
configController.reconcileAnyState(addressSpace);
ConfigMap routerConfigMap = client.configMaps().inNamespace("test").withName("qdrouterd-config.1234").get();
assertNotNull(routerConfigMap);
RouterConfig actual = RouterConfig.fromMap(routerConfigMap.getData());
assertEquals("${HOSTNAME}", actual.getRouter().getId());
assertEquals(3, actual.getSslProfiles().size());
assertEquals(8, actual.getListeners().size());
assertEquals(2, actual.getLinkRoutes().size());
assertEquals(1, actual.getAutoLinks().size());
assertEquals(5, actual.getAddresses().size());
assertEquals(1, actual.getConnectors().size());
assertEquals(1, actual.getPolicies().size());
assertEquals(2, actual.getVhosts().size());
assertEquals(1, actual.getAuthServicePlugins().size());
Listener amqpPublic = getListenerOnPort(5672, actual.getListeners());
assertNotNull(amqpPublic);
assertEquals(2, amqpPublic.getIdleTimeoutSeconds());
assertEquals(20, amqpPublic.getInitialHandshakeTimeoutSeconds());
assertEquals(50, amqpPublic.getLinkCapacity());
VhostPolicy internal = getPolicyForHostname("$default", actual.getVhosts());
assertNotNull(internal);
assertNull(internal.getMaxConnections());
assertNull(internal.getMaxConnectionsPerHost());
assertNull(internal.getMaxConnectionsPerUser());
assertNull(internal.getGroups().get("$default").getMaxSessions());
assertNull(internal.getGroups().get("$default").getMaxSenders());
assertNull(internal.getGroups().get("$default").getMaxReceivers());
VhostPolicy pub = getPolicyForHostname("public", actual.getVhosts());
assertNotNull(pub);
assertEquals(30, pub.getMaxConnections());
assertEquals(10, pub.getMaxConnectionsPerUser());
assertEquals(10, pub.getMaxConnectionsPerHost());
assertEquals(4, pub.getGroups().get("$default").getMaxSessions());
assertEquals(3, pub.getGroups().get("$default").getMaxSenders());
assertEquals(2, pub.getGroups().get("$default").getMaxReceivers());
appliedConfig.getSpec().getRouter().setIdleTimeout(20);
appliedConfig.getSpec().getRouter().getPolicy().setMaxConnectionsPerUser(300);
InfraConfigs.setCurrentInfraConfig(addressSpace, appliedConfig);
configController.reconcileAnyState(addressSpace);
routerConfigMap = client.configMaps().inNamespace("test").withName("qdrouterd-config.1234").get();
assertNotNull(routerConfigMap);
actual = RouterConfig.fromMap(routerConfigMap.getData());
amqpPublic = getListenerOnPort(5672, actual.getListeners());
assertNotNull(amqpPublic);
assertEquals(20, amqpPublic.getIdleTimeoutSeconds());
assertEquals(20, amqpPublic.getInitialHandshakeTimeoutSeconds());
assertEquals(50, amqpPublic.getLinkCapacity());
pub = getPolicyForHostname("public", actual.getVhosts());
assertNotNull(pub);
assertEquals(30, pub.getMaxConnections());
assertEquals(300, pub.getMaxConnectionsPerUser());
}
@Test
public void testReconcileConnector() throws Exception {
RouterStatusCache routerStatusCache = new RouterStatusCache(new LogEventLogger(), Duration.ofSeconds(100), mock(NamespacedKubernetesClient.class), "test", Duration.ofSeconds(100), Duration.ofSeconds(100));
RouterConfigController configController = new RouterConfigController(
client,
"test",
new AuthenticationServiceResolver(authenticationServiceRegistry),
routerStatusCache);
StandardInfraConfig appliedConfig = new StandardInfraConfigBuilder()
.editOrNewMetadata()
.withName("test")
.endMetadata()
.build();
AddressSpace addressSpace = new AddressSpaceBuilder()
.editOrNewMetadata()
.withName("myspace")
.withNamespace("space")
.addToAnnotations(AnnotationKeys.INFRA_UUID, "1234")
.endMetadata()
.editOrNewSpec()
.withType("standard")
.withPlan("plan1")
.withNewAuthenticationService()
.withName("test")
.endAuthenticationService()
.addNewConnector()
.withName("remote1")
.addNewEndpointHost()
.withHost("messaging.example.com")
.withPort(5671)
.endEndpointHost()
.addNewEndpointHost()
.withHost("messaging2.example.com")
.endEndpointHost()
.withIdleTimeout(12000)
.withMaxFrameSize(12345)
.withRole("normal")
.withNewTls()
.withNewCaCert()
.withValueFromSecret(new SecretKeySelector("ca.crt", "remote-certs", false))
.endCaCert()
.withNewClientCert()
.withValueFromSecret(new SecretKeySelector("tls.crt", "remote-certs", false))
.endClientCert()
.withNewClientKey()
.withValueFromSecret(new SecretKeySelector("tls.key", "remote-certs", false))
.endClientKey()
.endTls()
.withNewCredentials()
.withNewUsername()
.withValue("test")
.endUsername()
.withNewPassword()
.withValue("test")
.endPassword()
.endCredentials()
.addNewAddress()
.withName("pat1")
.withPattern("foo*")
.endAddress()
.endConnector()
.endSpec()
.build();
InfraConfigs.setCurrentInfraConfig(addressSpace, appliedConfig);
routerStatusCache.reconcileAll(Collections.singletonList(addressSpace));
routerStatusCache.checkRouterStatus(a -> Collections.singletonList(new RouterStatus("r1",
new RouterConnections(Collections.singletonList("messaging.example.com:5671"), Collections.singletonList(true), Collections.singletonList("up")),
Collections.emptyList(),
0)));
/*
client.apps().statefulSets().inNamespace("test").createOrReplaceWithNew()
.editOrNewMetadata()
.withName(KubeUtil.getRouterSetName(addressSpace))
.withNamespace("test")
.endMetadata()
.editOrNewSpec()
.withReplicas(1)
.editOrNewTemplate()
.editOrNewSpec()
.addNewContainer()
.withName("router")
.addNewVolumeMount()
.withName("external-connector-old")
.endVolumeMount()
.endContainer()
.addNewVolume()
.withName("external-connector-old")
.withNewSecret()
.withSecretName("external-connector-old")
.endSecret()
.endVolume()
.endSpec()
.endTemplate()
.endSpec()
.done();
*/
configController.reconcileAnyState(addressSpace);
AddressSpaceStatusConnector status = addressSpace.getStatus().getConnectors().get(0);
assertNotNull(status);
assertEquals("remote1", status.getName());
assertFalse(status.isReady());
assertTrue(status.getMessages().contains("Unable to locate value or secret for caCert"));
assertTrue(status.getMessages().contains("Unable to locate value or secret for clientCert"));
assertTrue(status.getMessages().contains("Unable to locate value or secret for clientKey"));
ConfigMap routerConfigMap = client.configMaps().inNamespace("test").withName("qdrouterd-config.1234").get();
assertNotNull(routerConfigMap);
RouterConfig actual = RouterConfig.fromMap(routerConfigMap.getData());
SslProfile profile = getSslProfile("connector_remote1_settings", actual.getSslProfiles());
assertNull(profile);
Connector remote = getConnectorForHost("messaging.example.com", actual.getConnectors());
assertNull(remote);
status.setReady(true);
status.clearMessages();
client.secrets().inNamespace("space").createOrReplaceWithNew()
.editOrNewMetadata()
.withName("remote-certs")
.endMetadata()
.addToData("tls.crt", "cert")
.addToData("tls.key", "key")
.addToData("ca.crt", "ca")
.done();
configController.reconcileAnyState(addressSpace);
routerConfigMap = client.configMaps().inNamespace("test").withName("qdrouterd-config.1234").get();
assertNotNull(routerConfigMap);
actual = RouterConfig.fromMap(routerConfigMap.getData());
profile = getSslProfile("connector_remote1_settings", actual.getSslProfiles());
assertNotNull(profile);
assertEquals("connector_remote1_settings", profile.getName());
assertEquals("/etc/enmasse-connectors/remote1/ca.crt", profile.getCaCertFile());
assertEquals("/etc/enmasse-connectors/remote1/tls.crt", profile.getCertFile());
assertEquals("/etc/enmasse-connectors/remote1/tls.key", profile.getPrivateKeyFile());
remote = getConnectorForHost("messaging.example.com", actual.getConnectors());
assertNotNull(remote);
assertEquals("amqps://messaging2.example.com:5671", remote.getFailoverUrls());
assertEquals("connector_remote1_settings", remote.getSslProfile());
assertEquals("EXTERNAL PLAIN", remote.getSaslMechanisms());
assertEquals(12000, remote.getIdleTimeoutSeconds());
assertEquals(12345, remote.getMaxFrameSize());
assertEquals("normal", remote.getRole().toValue());
assertEquals(5671, remote.getPort());
assertEquals("test", remote.getSaslUsername());
assertEquals("test", remote.getSaslPassword());
LinkRoute lrIn = getLinkRoute("override.connector.remote1.pat1.in", actual.getLinkRoutes());
assertNotNull(lrIn);
assertEquals("remote1/foo*", lrIn.getPattern());
assertEquals(LinkDirection.in, lrIn.getDirection());
assertEquals("remote1", lrIn.getConnection());
LinkRoute lrOut = getLinkRoute("override.connector.remote1.pat1.out", actual.getLinkRoutes());
assertNotNull(lrOut);
assertEquals("remote1/foo*", lrOut.getPattern());
assertEquals(LinkDirection.out, lrOut.getDirection());
assertEquals("remote1", lrOut.getConnection());
status = addressSpace.getStatus().getConnectors().get(0);
assertNotNull(status);
assertEquals("remote1", status.getName());
assertTrue(status.isReady(), String.join(",", status.getMessages()));
Secret certs = client.secrets().inNamespace("test").withName("external-connector-1234-remote1").get();
assertNotNull(certs);
assertEquals("ca", certs.getData().get("ca.crt"));
assertEquals("key", certs.getData().get("tls.key"));
assertEquals("cert", certs.getData().get("tls.crt"));
/*
StatefulSet router = client.apps().statefulSets().inNamespace("test").withName("qdrouterd-1234").get();
assertNotNull(router);
*/
}
@Test
public void testVhostPolicyGen() {
RouterPolicySpec policySpec = new RouterPolicySpecBuilder()
.withMaxConnections(1000)
.withMaxConnectionsPerHost(10)
.withMaxConnectionsPerUser(10)
.withMaxSendersPerConnection(5)
.withMaxReceiversPerConnection(5)
.withMaxSessionsPerConnection(5)
.build();
List<VhostPolicy> policyList = RouterConfigController.createVhostPolices(policySpec);
assertEquals(2, policyList.size());
VhostPolicy internal = getPolicyForHostname("$default", policyList);
assertNotNull(internal);
assertNull(internal.getMaxConnections());
assertNull(internal.getMaxConnectionsPerHost());
assertNull(internal.getMaxConnectionsPerUser());
assertNull(internal.getGroups().get("$default").getMaxSessions());
assertNull(internal.getGroups().get("$default").getMaxSenders());
assertNull(internal.getGroups().get("$default").getMaxReceivers());
VhostPolicy pub = getPolicyForHostname("public", policyList);
assertNotNull(pub);
assertEquals(1000, pub.getMaxConnections());
assertEquals(10, pub.getMaxConnectionsPerUser());
assertEquals(10, pub.getMaxConnectionsPerHost());
assertEquals(5, pub.getGroups().get("$default").getMaxSessions());
assertEquals(5, pub.getGroups().get("$default").getMaxSenders());
assertEquals(5, pub.getGroups().get("$default").getMaxReceivers());
}
private Listener getListenerOnPort(int port, List<Listener> listeners) {
for (Listener listener : listeners) {
if (port == listener.getPort()) {
return listener;
}
}
return null;
}
private VhostPolicy getPolicyForHostname(String hostname, List<VhostPolicy> vhostPolicies) {
for (VhostPolicy vhostPolicy : vhostPolicies) {
if (hostname.equals(vhostPolicy.getHostname())) {
return vhostPolicy;
}
}
return null;
}
private SslProfile getSslProfile(String name, List<SslProfile> sslProfiles) {
for (SslProfile sslProfile : sslProfiles) {
if (name.equals(sslProfile.getName())) {
return sslProfile;
}
}
return null;
}
private Connector getConnectorForHost(String hostname, List<Connector> connectors) {
for (Connector connector : connectors) {
if (hostname.equals(connector.getHost())) {
return connector;
}
}
return null;
}
private LinkRoute getLinkRoute(String name, List<LinkRoute> linkRoutes) {
for (LinkRoute lr : linkRoutes) {
if (name.equals(lr.getName())) {
return lr;
}
}
return null;
}
}
|
package br.com.kosawalabs.apprecommendation.presentation.list;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import br.com.kosawalabs.apprecommendation.R;
import br.com.kosawalabs.apprecommendation.data.network.AppNetworkRepository;
import br.com.kosawalabs.apprecommendation.data.pojo.App;
import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailActivity;
import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailFragment;
import br.com.kosawalabs.apprecommendation.service.UploadMyAppsIService;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static br.com.kosawalabs.apprecommendation.MainApplication.EXTRAS_SESSION_TOKEN;
public class AppListActivity extends AppCompatActivity implements AppListView {
private boolean mTwoPane;
private boolean isRecommended;
private AppListPresenterImpl presenter;
private String token;
private LinearLayoutManager layoutManager;
private SimpleItemRecyclerViewAdapter listAdapter;
private ProgressBar progress;
private RecyclerView listFrame;
private View errorFrame;
private View sendDataFrame;
private TextView errorDesc;
public static void start(Activity activity, String token) {
Intent intent = new Intent(activity, AppListActivity.class);
intent.putExtra(EXTRAS_SESSION_TOKEN, token);
activity.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
final BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new MyBottomNavListener());
listFrame = (RecyclerView) findViewById(R.id.list_frame);
assert listFrame != null;
layoutManager = new LinearLayoutManager(this);
listFrame.setLayoutManager(layoutManager);
listFrame.addOnScrollListener(new AppListOnScrollListener());
if (findViewById(R.id.app_detail_container) != null) {
mTwoPane = true;
}
progress = (ProgressBar) findViewById(R.id.progress_bar);
errorFrame = findViewById(R.id.error_frame);
sendDataFrame = findViewById(R.id.send_data_frame);
errorDesc = (TextView) findViewById(R.id.list_error_description);
token = getIntent().getStringExtra(EXTRAS_SESSION_TOKEN);
presenter = new AppListPresenterImpl(this, new AppNetworkRepository(token));
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.update_my_apps:
Toast.makeText(this, R.string.toast_sending_packages, Toast.LENGTH_SHORT).show();
UploadMyAppsIService.startActionUploadApps(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onResume() {
super.onResume();
refreshList();
}
@Override
public void showApps(List<App> apps) {
progress.setVisibility(GONE);
errorFrame.setVisibility(GONE);
sendDataFrame.setVisibility(GONE);
listFrame.setVisibility(VISIBLE);
listAdapter = new SimpleItemRecyclerViewAdapter(apps);
listFrame.setAdapter(listAdapter);
}
@Override
public void showMoreApps(List<App> apps) {
progress.setVisibility(GONE);
errorFrame.setVisibility(GONE);
sendDataFrame.setVisibility(GONE);
listFrame.setVisibility(VISIBLE);
listAdapter.setApps(apps);
}
@Override
public void showError(String errorCause) {
progress.setVisibility(GONE);
listFrame.setVisibility(GONE);
sendDataFrame.setVisibility(GONE);
errorFrame.setVisibility(VISIBLE);
errorDesc.setText(errorCause);
}
@Override
public void showSendDataButton() {
progress.setVisibility(GONE);
listFrame.setVisibility(GONE);
errorFrame.setVisibility(GONE);
sendDataFrame.setVisibility(VISIBLE);
}
private void refreshList() {
if (presenter.shouldLoadMore()) {
if (!isRecommended) {
presenter.fetchFirstPage();
} else {
presenter.fetchRecommendedFirstPage();
}
}
}
private void loadMore() {
if (!isRecommended) {
presenter.fetchNextPage();
} else {
presenter.fetchRecommendedNextPage();
}
}
private boolean listIsAtTheEnd() {
int visibleItemCount = getVisibleItemCount();
int totalItemCount = getTotalItemCount();
int firstVisibleItemPosition = getFirstVisibleItemPosition();
return (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
&& firstVisibleItemPosition >= 0
&& totalItemCount >= presenter.getPageSize();
}
private int getVisibleItemCount() {
return layoutManager.getChildCount();
}
private int getTotalItemCount() {
return layoutManager.getItemCount();
}
private int getFirstVisibleItemPosition() {
return layoutManager.findFirstVisibleItemPosition();
}
public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<App> apps;
public SimpleItemRecyclerViewAdapter(List<App> apps) {
this.apps = apps;
}
public void setApps(List<App> moreApps) {
this.apps.addAll(moreApps);
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.app_list_content, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = this.apps.get(position);
holder.mIdView.setText(String.valueOf(this.apps.get(position).getId()));
holder.mContentView.setText(this.apps.get(position).getName());
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putInt(AppDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
arguments.putString(EXTRAS_SESSION_TOKEN, token);
AppDetailFragment fragment = new AppDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.app_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, AppDetailActivity.class);
Bundle arguments = new Bundle();
arguments.putInt(AppDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
arguments.putString(EXTRAS_SESSION_TOKEN, token);
intent.putExtras(arguments);
context.startActivity(intent);
}
}
});
}
@Override
public int getItemCount() {
return this.apps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public App mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
private class AppListOnScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (presenter.shouldLoadMore()) {
if (listIsAtTheEnd()) {
loadMore();
}
}
}
}
private class MyBottomNavListener implements BottomNavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_list:
isRecommended = false;
break;
case R.id.action_list_recommended:
isRecommended = true;
break;
default:
return false;
}
refreshList();
return true;
}
}
}
|
package nodomain.freeyourgadget.gadgetbridge.activities;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.ActivityKind;
import nodomain.freeyourgadget.gadgetbridge.util.AndroidUtils;
import nodomain.freeyourgadget.gadgetbridge.util.DateTimeUtils;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
public class ActivitySummaryDetail extends AbstractGBActivity {
private static final Logger LOG = LoggerFactory.getLogger(ActivitySummaryDetail.class);
private GBDevice mGBDevice;
private JSONObject groupData = setGroups();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary_details);
Intent intent = getIntent();
mGBDevice = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE);
final String gpxTrack = intent.getStringExtra("GpxTrack");
Button show_track_btn = (Button) findViewById(R.id.showTrack);
show_track_btn.setVisibility(View.GONE);
if (gpxTrack != null) {
show_track_btn.setVisibility(View.VISIBLE);
show_track_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
AndroidUtils.viewFile(gpxTrack, Intent.ACTION_VIEW, ActivitySummaryDetail.this);
} catch (IOException e) {
GB.toast(getApplicationContext(), "Unable to display GPX track: " + e.getMessage(), Toast.LENGTH_LONG, GB.ERROR, e);
}
}
});
}
String activitykindname = ActivityKind.asString(intent.getIntExtra("ActivityKind",0), getApplicationContext());
Date starttime = (Date) intent.getSerializableExtra("StartTime");
Date endtime = (Date) intent.getSerializableExtra("EndTime");
String starttimeS = DateTimeUtils.formatDateTime(starttime);
String endtimeS = DateTimeUtils.formatDateTime(endtime);
String durationhms = DateTimeUtils.formatDurationHoursMinutes((endtime.getTime() - starttime.getTime()), TimeUnit.MILLISECONDS);
ImageView activity_icon = (ImageView) findViewById(R.id.item_image);
activity_icon.setImageResource(ActivityKind.getIconId(intent.getIntExtra("ActivityKind",0)));
TextView activity_kind = (TextView) findViewById(R.id.activitykind);
activity_kind.setText(activitykindname);
TextView start_time = (TextView) findViewById(R.id.starttime);
start_time.setText(starttimeS);
TextView end_time = (TextView) findViewById(R.id.endtime);
end_time.setText(endtimeS);
TextView activity_duration = (TextView) findViewById(R.id.duration);
activity_duration.setText(durationhms);
JSONObject summaryData = null;
String sumData = intent.getStringExtra("SummaryData");
if (sumData != null) {
try {
summaryData = new JSONObject(sumData);
} catch (JSONException e) {
LOG.error("SportsActivity", e);
}
}
if (summaryData == null) return;
JSONObject listOfSummaries = makeSummaryList(summaryData);
makeSummaryContent(listOfSummaries);
}
private void makeSummaryContent (JSONObject data){
//build view, use localized names
Iterator<String> keys = data.keys();
DecimalFormat df = new DecimalFormat("
while (keys.hasNext()) {
String key = keys.next();
try {
LOG.error("SportsActivity:" + key + ": " + data.get(key) + "\n");
JSONArray innerList = (JSONArray) data.get(key);
TableLayout fieldLayout = findViewById(R.id.summaryDetails);
TableRow label_row = new TableRow(ActivitySummaryDetail.this);
TextView label_field = new TextView(ActivitySummaryDetail.this);
label_field.setTextSize(16);
label_field.setTypeface(null, Typeface.BOLD);
label_field.setText(String.format("%s", getStringResourceByName(key)));
label_row.addView(label_field);
fieldLayout.addView(label_row);
for (int i = 0; i < innerList.length(); i++) {
JSONObject innerData = innerList.getJSONObject(i);
double value = innerData.getDouble("value");
String unit = innerData.getString("unit");
String name = innerData.getString("name");
//special casing here:
switch(unit){
case "meters_second":
value = value *3.6;
unit = "km_h";
break;
case "seconds_m":
value = 3.6/value;
unit = "minutes_km";
break;
case "seconds_km":
value = value /60;
unit = "minutes_km";
break;
}
TableRow field_row = new TableRow(ActivitySummaryDetail.this);
if (i % 2 == 0) field_row.setBackgroundColor(Color.rgb(237,237,237));
TextView name_field = new TextView(ActivitySummaryDetail.this);
TextView value_field = new TextView(ActivitySummaryDetail.this);
name_field.setGravity(Gravity.START);
value_field.setGravity(Gravity.END);
if (unit.equals("seconds")) { //rather then plain seconds, show formatted duration
value_field.setText(DateTimeUtils.formatDurationHoursMinutes((long) value, TimeUnit.SECONDS));
}else {
value_field.setText(String.format("%s %s", df.format(value), getStringResourceByName(unit)));
}
name_field.setText(getStringResourceByName(name));
TableRow.LayoutParams params = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1f);
value_field.setLayoutParams(params);
field_row.addView(name_field);
field_row.addView(value_field);
fieldLayout.addView(field_row);
}
} catch (JSONException e) {
LOG.error("SportsActivity", e);
}
}
}
private JSONObject setGroups(){
String groupDefinitions = "{'Strokes':['averageStrokeDistance','averageStrokesPerSecond','strokes'], " +
"'Swimming':['swolfIndex','swimStyle'], " +
"'Elevation':['ascentMeters','descentMeters','maxAltitude','minAltitude','ascentSeconds','descentSeconds','flatSeconds'], " +
"'Speed':['maxSpeed','minPace','maxPace','averageKMPaceSeconds'], " +
"'Activity':['distanceMeters','steps','activeSeconds','caloriesBurnt','totalStride'," +
"'averageHR','averageStride'], " +
"'Laps':['averageLapPace','laps']}";
JSONObject data = null;
try {
data = new JSONObject(groupDefinitions);
} catch (JSONException e) {
LOG.error("SportsActivity", e);
}
return data;
}
private String getGroup(String searchItem) {
String defaultGroup = "Activity";
if (groupData == null) return defaultGroup;
Iterator<String> keys = groupData.keys();
while (keys.hasNext()) {
String key = keys.next();
try {
JSONArray itemList = (JSONArray) groupData.get(key);
for (int i = 0; i < itemList.length(); i++) {
if (itemList.getString(i).equals(searchItem)) {
return key;
}
}
} catch (JSONException e) {
LOG.error("SportsActivity", e);
}
}
return defaultGroup;
}
private JSONObject makeSummaryList(JSONObject summaryData){
//make dictionary with data for each group
JSONObject list = new JSONObject();
Iterator<String> keys = summaryData.keys();
LOG.error("SportsActivity JSON:" + summaryData + keys);
while (keys.hasNext()) {
String key = keys.next();
try {
LOG.error("SportsActivity:" + key + ": " + summaryData.get(key) + "\n");
JSONObject innerData = (JSONObject) summaryData.get(key);
Object value = innerData.get("value");
String unit = innerData.getString("unit");
String group = getGroup(key);
if (!list.has(group)) {
list.put(group,new JSONArray());
}
JSONArray tmpl = (JSONArray) list.get(group);
JSONObject innernew = new JSONObject();
innernew.put("name", key);
innernew.put("value", value);
innernew.put("unit", unit);
tmpl.put(innernew);
list.put(group, tmpl);
} catch (JSONException e) {
LOG.error("SportsActivity", e);
}
}
return list;
}
private String getStringResourceByName(String aString) {
String packageName = getPackageName();
int resId = getResources().getIdentifier(aString, "string", packageName);
if (resId==0){
LOG.warn("SportsActivity " + "Missing string in strings:" + aString);
return aString;
}else{
return getString(resId);
}
}
}
|
package com.ca.apm.swat.epaplugins.asm.monitor;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.Inflater;
import org.apache.commons.codec.binary.Base64;
import com.ca.apm.swat.epaplugins.asm.reporting.MetricMap;
import com.ca.apm.swat.epaplugins.utils.AsmMessages;
import com.ca.apm.swat.epaplugins.utils.AsmProperties;
import com.wily.introscope.epagent.EpaUtils;
public class InflatingBase64Decoder implements Handler {
protected Handler successor = null;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
/**
* Generate metrics from API call result.
* InflatingBase64Decoder decodes the Base64 encoded string and unzips it
* before forwarding the string to the next handler.
*
* @param encodedString Base64 encoded string
* @param metricTree metric tree prefix
* @return metricMap map containing the metrics
*/
public MetricMap generateMetrics(String encodedString, String metricTree) {
// doesn't make sense if nobody handles the result
if (null != successor) {
if (EpaUtils.getFeedback().isVerboseEnabled()) {
EpaUtils.getFeedback().verbose("InflatingBase64Decoder start");
}
// decode base64
byte[] decoded = Base64.decodeBase64(encodedString);
if (decoded != null) {
// decompress
byte[] bytesDecompressed = decompress(decoded);
if (bytesDecompressed != null) {
// convert to UTF8
String decodedString;
try {
decodedString = new String(bytesDecompressed, 0,
bytesDecompressed.length, EpaUtils.getEncoding());
} catch (UnsupportedEncodingException e) {
// should not happen: UTF8 should be supported
String errorMessage = AsmMessages.getMessage(AsmMessages.RUN_ERROR,
AsmProperties.ASM_PRODUCT_NAME,
this.getClass(),
e.getMessage());
EpaUtils.getFeedback().error(errorMessage);
throw new Error(errorMessage, e);
}
// call next handler in chain
return successor.generateMetrics(decodedString, metricTree);
} else {
EpaUtils.getFeedback().warn(
"InflatingBase64Decoder decompress == null! metricTree = " + metricTree);
}
} else {
EpaUtils.getFeedback().warn(
"InflatingBase64Decoder decoded == null! metricTree = " + metricTree);
}
} else {
EpaUtils.getFeedback().warn("InflatingBase64Decoder has no sucessor!");
}
return new MetricMap();
}
/**
* Inflate compressed data.
* @param data compressed data
* @return uncompressed data
*/
public byte[] decompress(byte[] data) {
try {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
inflater.end();
return output;
} catch (Exception ex) {
return null;
}
}
}
|
package org.ovirt.engine.core.bll;
import org.ovirt.engine.core.common.queries.GetAllNetworkQueryParamenters;
import org.ovirt.engine.core.compat.Guid;
public class GetAllNetworksQuery<P extends GetAllNetworkQueryParamenters> extends QueriesCommandBase<P> {
public GetAllNetworksQuery(P parameters) {
super(parameters);
}
@Override
protected void executeQueryCommand() {
if (getParameters().getStoragePoolId() == null
|| getParameters().getStoragePoolId().equals(Guid.Empty)) {
getQueryReturnValue().setReturnValue(getDbFacade().getNetworkDAO().getAll());
} else {
getQueryReturnValue().setReturnValue(
getDbFacade().getNetworkDAO().getAllForDataCenter(getParameters().getStoragePoolId()));
}
}
}
|
package org.biojava.bio.structure.io.mmcif;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.biojava.bio.structure.AminoAcid;
import org.biojava.bio.structure.AminoAcidImpl;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.AtomImpl;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.ChainImpl;
import org.biojava.bio.structure.DBRef;
import org.biojava.bio.structure.Element;
import org.biojava.bio.structure.Group;
import org.biojava.bio.structure.HetatomImpl;
import org.biojava.bio.structure.NucleotideImpl;
import org.biojava.bio.structure.PDBHeader;
import org.biojava.bio.structure.ResidueNumber;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureImpl;
import org.biojava.bio.structure.StructureTools;
import org.biojava.bio.structure.UnknownPdbAminoAcidException;
import org.biojava.bio.structure.io.FileParsingParameters;
import org.biojava.bio.structure.io.PDBParseException;
import org.biojava.bio.structure.io.SeqRes2AtomAligner;
import org.biojava.bio.structure.io.mmcif.model.AtomSite;
import org.biojava.bio.structure.io.mmcif.model.AuditAuthor;
import org.biojava.bio.structure.io.mmcif.model.ChemComp;
import org.biojava.bio.structure.io.mmcif.model.ChemCompDescriptor;
import org.biojava.bio.structure.io.mmcif.model.DatabasePDBremark;
import org.biojava.bio.structure.io.mmcif.model.DatabasePDBrev;
import org.biojava.bio.structure.io.mmcif.model.Entity;
import org.biojava.bio.structure.io.mmcif.model.EntityPolySeq;
import org.biojava.bio.structure.io.mmcif.model.Exptl;
import org.biojava.bio.structure.io.mmcif.model.PdbxEntityNonPoly;
import org.biojava.bio.structure.io.mmcif.model.PdbxNonPolyScheme;
import org.biojava.bio.structure.io.mmcif.model.PdbxPolySeqScheme;
import org.biojava.bio.structure.io.mmcif.model.PdbxStructAssembly;
import org.biojava.bio.structure.io.mmcif.model.PdbxStructAssemblyGen;
import org.biojava.bio.structure.io.mmcif.model.PdbxStructOperList;
import org.biojava.bio.structure.io.mmcif.model.Refine;
import org.biojava.bio.structure.io.mmcif.model.Struct;
import org.biojava.bio.structure.io.mmcif.model.StructAsym;
import org.biojava.bio.structure.io.mmcif.model.StructKeywords;
import org.biojava.bio.structure.io.mmcif.model.StructRef;
import org.biojava.bio.structure.io.mmcif.model.StructRefSeq;
import org.biojava.bio.structure.quaternary.BiologicalAssemblyBuilder;
import org.biojava.bio.structure.quaternary.ModelTransformationMatrix;
/** A MMcifConsumer implementation that build a in-memory representation of the
* content of a mmcif file as a BioJava Structure object.
* @author Andreas Prlic
* @since 1.7
*/
public class SimpleMMcifConsumer implements MMcifConsumer {
boolean DEBUG = false;
Structure structure;
Chain current_chain;
Group current_group;
int atomCount;
List<Chain> current_model;
List<Entity> entities;
List<StructRef> strucRefs;
List<Chain> seqResChains;
List<Chain> entityChains; // needed to link entities, chains and compounds...
List<StructAsym> structAsyms; // needed to link entities, chains and compounds...
List<PdbxStructOperList> structOpers ;
List<PdbxStructAssembly> strucAssemblies;
List<PdbxStructAssemblyGen> strucAssemblyGens;
Map<String,String> asymStrandId;
String current_nmr_model ;
FileParsingParameters params;
public static Logger logger = Logger.getLogger("org.biojava.bio.structure");
public SimpleMMcifConsumer(){
params = new FileParsingParameters();
documentStart();
}
public void newEntity(Entity entity) {
if (DEBUG)
System.out.println(entity);
entities.add(entity);
}
public void newPdbxStructOperList(PdbxStructOperList structOper){
structOpers.add(structOper);
}
public void newStructAsym(StructAsym sasym){
structAsyms.add(sasym);
}
private Entity getEntity(String entity_id){
for (Entity e: entities){
if (e.getId().equals(entity_id)){
return e;
}
}
return null;
}
@SuppressWarnings("deprecation")
public void newStructKeywords(StructKeywords kw){
PDBHeader header = structure.getPDBHeader();
if ( header == null)
header = new PDBHeader();
header.setDescription(kw.getPdbx_keywords());
header.setClassification(kw.getPdbx_keywords());
Map<String, Object> h = structure.getHeader();
h.put("classification", kw.getPdbx_keywords());
}
@SuppressWarnings("deprecation")
public void setStruct(Struct struct) {
//System.out.println(struct);
PDBHeader header = structure.getPDBHeader();
if ( header == null)
header = new PDBHeader();
header.setTitle(struct.getTitle());
header.setIdCode(struct.getEntry_id());
//header.setDescription(struct.getPdbx_descriptor());
//header.setClassification(struct.getPdbx_descriptor());
//header.setDescription(struct.getPdbx_descriptor());
//System.out.println(struct.getPdbx_model_details());
Map<String, Object> h = structure.getHeader();
h.put("title", struct.getTitle());
//h.put("classification", struct.getPdbx_descriptor());
structure.setPDBHeader(header);
structure.setPDBCode(struct.getEntry_id());
}
/** initiate new group, either Hetatom, Nucleotide, or AminoAcid */
private Group getNewGroup(String recordName,Character aminoCode1, long seq_id,String groupCode3) {
if ( params.isLoadChemCompInfo() ){
Group g = ChemCompGroupFactory.getGroupFromChemCompDictionary(groupCode3);
if ( g != null) {
if ( g instanceof AminoAcidImpl) {
AminoAcidImpl aa = (AminoAcidImpl) g;
aa.setId(seq_id);
} else if ( g instanceof NucleotideImpl) {
NucleotideImpl nuc = (NucleotideImpl) g;
nuc.setId(seq_id);
} else if ( g instanceof HetatomImpl) {
HetatomImpl het = (HetatomImpl)g;
het.setId(seq_id);
}
return g;
}
}
Group group;
if ( recordName.equals("ATOM") ) {
if (aminoCode1 == null) {
// it is a nucleotide
NucleotideImpl nu = new NucleotideImpl();
group = nu;
nu.setId(seq_id);
} else if (aminoCode1 == StructureTools.UNKNOWN_GROUP_LABEL){
HetatomImpl h = new HetatomImpl();
h.setId(seq_id);
group = h;
} else {
AminoAcidImpl aa = new AminoAcidImpl() ;
aa.setAminoType(aminoCode1);
aa.setId(seq_id);
group = aa ;
}
}
else {
HetatomImpl h = new HetatomImpl();
h.setId(seq_id);
group = h;
}
//System.out.println("new group type: "+ group.getType() );
return group ;
}
/** test if the chain is already known (is in current_model
* ArrayList) and if yes, returns the chain
* if no -> returns null
*/
private Chain isKnownChain(String chainID, List<Chain> chains){
for (int i = 0; i< chains.size();i++){
Chain testchain = chains.get(i);
//System.out.println("comparing chainID >"+chainID+"< against testchain " + i+" >" +testchain.getName()+"<");
if (chainID.equals(testchain.getChainID())) {
//System.out.println("chain "+ chainID+" already known ...");
return testchain;
}
}
return null;
}
/** during mmcif parsing the full atom name string gets truncated, fix this...
*
* @param name
* @return
*/
private String fixFullAtomName(String name){
if (name.equals("N")){
return " N ";
}
if (name.equals("CA")){
return " CA ";
}
if (name.equals("C")){
return " C ";
}
if (name.equals("O")){
return " O ";
}
if (name.equals("CB")){
return " CB ";
}
if (name.equals("CG"))
return " CG ";
if (name.length() == 2)
return " " + name + " ";
if (name.length() == 1)
return " " + name + " ";
if (name.length() == 3)
return " " + name ;
return name;
}
public void newAtomSite(AtomSite atom) {
// Warning: getLabel_asym_id is not the "chain id" in the PDB file
// it is the internally used chain id.
// later on we will fix this...
// later one needs to map the asym id to the pdb_strand_id
//TODO: add support for MAX_ATOMS
boolean startOfNewChain = false;
//String chain_id = atom.getAuth_asym_id();
String chain_id = atom.getLabel_asym_id();
String fullname = fixFullAtomName(atom.getLabel_atom_id());
String recordName = atom.getGroup_PDB();
String residueNumberS = atom.getAuth_seq_id();
Integer residueNrInt = Integer.parseInt(residueNumberS);
// the 3-letter name of the group:
String groupCode3 = atom.getLabel_comp_id();
if ( groupCode3.length() == 1){
groupCode3 = " " + groupCode3;
}
if ( groupCode3.length() == 2){
groupCode3 = " " + groupCode3;
}
Character aminoCode1 = null;
if ( recordName.equals("ATOM") )
aminoCode1 = StructureTools.get1LetterCode(groupCode3);
else {
aminoCode1 = StructureTools.get1LetterCode(groupCode3);
if ( aminoCode1.equals(StructureTools.UNKNOWN_GROUP_LABEL))
aminoCode1 = null;
}
String insCodeS = atom.getPdbx_PDB_ins_code();
Character insCode = null;
if (! insCodeS.equals("?")) {
insCode = insCodeS.charAt(0);
}
// we store the internal seq id in the Atom._id field
// this is not a PDB file field but we need this to internally assign the insertion codes later
// from the pdbx_poly_seq entries..
long seq_id = -1;
try {
seq_id = Long.parseLong(atom.getLabel_seq_id());
} catch (NumberFormatException e){
}
String nmrModel = atom.getPdbx_PDB_model_num();
if ( current_nmr_model == null) {
current_nmr_model = nmrModel;
}
if (! current_nmr_model.equals(nmrModel)){
current_nmr_model = nmrModel;
// add previous data
if ( current_chain != null ) {
current_chain.addGroup(current_group);
}
// we came to the beginning of a new NMR model
structure.setNmr(true);
structure.addModel(current_model);
current_model = new ArrayList<Chain>();
current_chain = null;
current_group = null;
}
if (current_chain == null) {
current_chain = new ChainImpl();
current_chain.setChainID(chain_id);
current_model.add(current_chain);
startOfNewChain = true;
}
//System.out.println("BEFORE: " + chain_id + " " + current_chain.getName());
if ( ! chain_id.equals(current_chain.getChainID()) ) {
startOfNewChain = true;
// end up old chain...
current_chain.addGroup(current_group);
// see if old chain is known ...
Chain testchain ;
testchain = isKnownChain(current_chain.getChainID(),current_model);
//System.out.println("trying to re-using known chain " + current_chain.getName() + " " + chain_id);
if ( testchain != null && testchain.getChainID().equals(chain_id)){
//System.out.println("re-using known chain " + current_chain.getName() + " " + chain_id);
} else {
testchain = isKnownChain(chain_id,current_model);
}
if ( testchain == null) {
//System.out.println("unknown chain. creating new chain.");
current_chain = new ChainImpl();
current_chain.setChainID(chain_id);
} else {
current_chain = testchain;
}
if ( ! current_model.contains(current_chain))
current_model.add(current_chain);
}
ResidueNumber residueNumber = new ResidueNumber(chain_id,residueNrInt, insCode);
if (current_group == null) {
current_group = getNewGroup(recordName,aminoCode1,seq_id, groupCode3);
//current_group.setPDBCode(residueNumber);
current_group.setResidueNumber(residueNumber);
try {
current_group.setPDBName(groupCode3);
} catch (PDBParseException e){
System.err.println(e.getMessage());
}
}
if ( startOfNewChain){
current_group = getNewGroup(recordName,aminoCode1,seq_id, groupCode3);
// current_group.setPDBCode(residueNumber);
current_group.setResidueNumber(residueNumber);
try {
current_group.setPDBName(groupCode3);
} catch (PDBParseException e){
e.printStackTrace();
}
}
Group altGroup = null;
String altLocS = atom.getLabel_alt_id();
Character altLoc = ' ';
if ( altLocS.length()>0) {
altLoc = altLocS.charAt(0);
if ( altLoc.equals('.') )
altLoc = ' ';
}
// check if residue number is the same ...
// insertion code is part of residue number
if ( ! residueNumber.equals(current_group.getResidueNumber())) {
//System.out.println("end of residue: "+current_group.getPDBCode()+" "+residueNrInt);
current_chain.addGroup(current_group);
current_group = getNewGroup(recordName,aminoCode1,seq_id,groupCode3);
//current_group.setPDBCode(pdbCode);
try {
current_group.setPDBName(groupCode3);
} catch (PDBParseException e){
e.printStackTrace();
}
current_group.setResidueNumber(residueNumber);
// System.out.println("Made new group: " + groupCode3 + " " + resNum + " " + iCode);
} else {
// same residueNumber, but altLocs...
// test altLoc
if ( ! altLoc.equals(' ') && ( ! altLoc.equals('.'))) {
altGroup = getCorrectAltLocGroup( altLoc,recordName,aminoCode1,groupCode3, seq_id);
//System.out.println("found altLoc! " + altLoc + " " + current_group + " " + altGroup);
}
}
if ( params.isHeaderOnly())
return;
atomCount++;
//System.out.println("fixing atom name for >" + atom.getLabel_atom_id() + "< >" + fullname + "<");
if ( params.isParseCAOnly() ){
// yes , user wants to get CA only
// only parse CA atoms...
if (! fullname.equals(" CA ")){
//System.out.println("ignoring " + line);
atomCount
return;
}
}
//see if chain_id is one of the previous chains ...
Atom a = convertAtom(atom);
//see if chain_id is one of the previous chains ...
if ( altGroup != null) {
altGroup.addAtom(a);
altGroup = null;
}
else {
current_group.addAtom(a);
}
//System.out.println(">" + atom.getLabel_atom_id()+"< " + a.getGroup().getPDBName() + " " + a.getGroup().getChemComp() );
//System.out.println(current_group);
}
/** convert a MMCif AtomSite object to a BioJava Atom object
*
* @param atom the mmmcif AtomSite record
* @return an Atom
*/
private Atom convertAtom(AtomSite atom){
Atom a = new AtomImpl();
a.setPDBserial(Integer.parseInt(atom.getId()));
a.setName(atom.getLabel_atom_id());
a.setFullName(fixFullAtomName(atom.getLabel_atom_id()));
double x = Double.parseDouble (atom.getCartn_x());
double y = Double.parseDouble (atom.getCartn_y());
double z = Double.parseDouble (atom.getCartn_z());
a.setX(x);
a.setY(y);
a.setZ(z);
double occupancy = Double.parseDouble(atom.getOccupancy());
a.setOccupancy(occupancy);
double temp = Double.parseDouble(atom.getB_iso_or_equiv());
a.setTempFactor(temp);
String alt = atom.getLabel_alt_id();
if (( alt != null ) && ( alt.length() > 0) && (! alt.equals("."))){
a.setAltLoc(new Character(alt.charAt(0)));
} else {
a.setAltLoc(new Character(' '));
}
Element element = Element.R;
try {
element = Element.valueOfIgnoreCase(atom.getType_symbol());
} catch (IllegalArgumentException e){}
a.setElement(element);
return a;
}
private Group getCorrectAltLocGroup( Character altLoc,
String recordName, Character aminoCode1, String groupCode3, long seq_id) {
// see if we know this altLoc already;
List<Atom> atoms = current_group.getAtoms();
if ( atoms.size() > 0) {
Atom a1 = atoms.get(0);
// we are just adding atoms to the current group
// probably there is a second group following later...
if (a1.getAltLoc().equals(altLoc)) {
return current_group;
}
}
List<Group> altLocs = current_group.getAltLocs();
for ( Group altLocG : altLocs ){
atoms = altLocG.getAtoms();
if ( atoms.size() > 0) {
for ( Atom a1 : atoms) {
if (a1.getAltLoc().equals( altLoc)) {
return altLocG;
}
}
}
}
// no matching altLoc group found.
// build it up.
if ( groupCode3.equals(current_group.getPDBName())) {
if ( current_group.getAtoms().size() == 0)
return current_group;
//System.out.println("cloning current group");
Group altLocG = (Group) current_group.clone();
current_group.addAltLoc(altLocG);
return altLocG;
}
Group altLocG = getNewGroup(recordName,aminoCode1,seq_id,groupCode3);
try {
altLocG.setPDBName(groupCode3);
} catch (PDBParseException e) {
e.printStackTrace();
}
altLocG.setResidueNumber(current_group.getResidueNumber());
current_group.addAltLoc(altLocG);
return altLocG;
}
/** Start the parsing
*
*/
public void documentStart() {
structure = new StructureImpl();
current_chain = null;
current_group = null;
current_nmr_model = null;
atomCount = 0;
current_model = new ArrayList<Chain>();
entities = new ArrayList<Entity>();
strucRefs = new ArrayList<StructRef>();
seqResChains = new ArrayList<Chain>();
entityChains = new ArrayList<Chain>();
structAsyms = new ArrayList<StructAsym>();
asymStrandId = new HashMap<String, String>();
structOpers = new ArrayList<PdbxStructOperList>();
strucAssemblies = new ArrayList<PdbxStructAssembly>();
strucAssemblyGens = new ArrayList<PdbxStructAssemblyGen>();
}
public void documentEnd() {
// a problem occurred earlier so current_chain = null ...
// most likely the buffered reader did not provide data ...
if ( current_chain != null ) {
current_chain.addGroup(current_group);
if (isKnownChain(current_chain.getChainID(),current_model) == null) {
current_model.add(current_chain);
}
} else {
if ( DEBUG){
System.err.println("current chain is null at end of document.");
}
}
structure.addModel(current_model);
// Goal is to reproduce the PDB files exactly:
// What has to be done is to use the auth_mon_id for the assignment. For this
// map entities to Chains and Compound objects...
for (StructAsym asym : structAsyms) {
if ( DEBUG )
System.out.println("entity " + asym.getEntity_id() + " matches asym id:" + asym.getId() );
Chain s = getEntityChain(asym.getEntity_id());
Chain seqres = (Chain)s.clone();
seqres.setChainID(asym.getId());
seqResChains.add(seqres);
if ( DEBUG )
System.out.println(" seqres: " + asym.getId() + " " + seqres + "<") ;
}
if ( params.isAlignSeqRes() ){
SeqRes2AtomAligner aligner = new SeqRes2AtomAligner();
aligner.align(structure,seqResChains);
}
//TODO: add support for these:
//structure.setConnections(connects);
//structure.setCompounds(compounds);
//linkChains2Compound(structure);
// mismatching Author assigned chain IDS and PDB internal chain ids:
// fix the chain IDS in the current model:
Set<String> asymIds = asymStrandId.keySet();
for (int i =0; i< structure.nrModels() ; i++){
List<Chain>model = structure.getModel(i);
List<Chain> pdbChains = new ArrayList<Chain>();
for (Chain chain : model) {
for (String asym : asymIds) {
if ( chain.getChainID().equals(asym)){
if (DEBUG)
System.out.println("renaming " + asym + " to : " + asymStrandId.get(asym));
chain.setChainID(asymStrandId.get(asym));
chain.setInternalChainID(asym);
Chain known = isKnownChain(chain.getChainID(), pdbChains);
if ( known == null ){
pdbChains.add(chain);
} else {
// and now we join the 2 chains together again, because in cif files the data can be split up...
for ( Group g : chain.getAtomGroups()){
known.addGroup(g);
}
}
break;
}
}
}
structure.setModel(i,pdbChains);
}
// set the oligomeric state info in the header...
PDBHeader header = structure.getPDBHeader();
header.setNrBioAssemblies(strucAssemblies.size());
// the more detailed mapping of chains to rotation operations happens in StructureIO...
// TODO clean this up and move it here...
//header.setBioUnitTranformationMap(tranformationMap);
Map<Integer,List<ModelTransformationMatrix>> transformationMap = new HashMap<Integer, List<ModelTransformationMatrix>>();
int total = strucAssemblies.size();
for ( int defaultBioAssembly = 1 ; defaultBioAssembly <= total; defaultBioAssembly++){
//List<ModelTransformationMatrix>tmp = getBioUnitTransformationList(pdbId, i +1);
PdbxStructAssembly psa = strucAssemblies.get(defaultBioAssembly-1);
List<PdbxStructAssemblyGen> psags = new ArrayList<PdbxStructAssemblyGen>(1);
for ( PdbxStructAssemblyGen psag: strucAssemblyGens ) {
if ( psag.getAssembly_id().equals(defaultBioAssembly+"")) {
psags.add(psag);
}
}
//System.out.println("psags: " + psags.size());
BiologicalAssemblyBuilder builder = new BiologicalAssemblyBuilder();
// these are the transformations that need to be applied to our model
List<ModelTransformationMatrix> transformations = builder.getBioUnitTransformationList(psa, psags, structOpers);
transformationMap.put(defaultBioAssembly,transformations);
//System.out.println("mmcif header: " + (defaultBioAssembly+1) + " " + transformations.size() +" " + transformations);
}
structure.getPDBHeader().setBioUnitTranformationMap(transformationMap);
}
/** This method will return the parsed protein structure, once the parsing has been finished
*
* @return a BioJava protein structure object
*/
public Structure getStructure() {
return structure;
}
@SuppressWarnings("deprecation")
public void newDatabasePDBrev(DatabasePDBrev dbrev) {
//System.out.println("got a database revision:" + dbrev);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
PDBHeader header = structure.getPDBHeader();
Map<String, Object> h = structure.getHeader();
if ( header == null) {
header = new PDBHeader();
}
if (dbrev.getNum().equals("1")){
try {
String date = dbrev.getDate_original();
//System.out.println(date);
Date dep = dateFormat.parse(date);
//System.out.println(dep);
header.setDepDate(dep);
h.put("depDate", date);
Date mod = dateFormat.parse(dbrev.getDate());
header.setModDate(mod);
h.put("revDate",dbrev.getDate());
} catch (ParseException e){
e.printStackTrace();
}
} else {
try {
Date mod = dateFormat.parse(dbrev.getDate());
header.setModDate(mod);
h.put("revDate",dbrev.getDate());
} catch (ParseException e){
e.printStackTrace();
}
}
structure.setPDBHeader(header);
}
@SuppressWarnings("deprecation")
public void newDatabasePDBremark(DatabasePDBremark remark) {
//System.out.println(remark);
String id = remark.getId();
if (id.equals("2")){
//this remark field contains the resolution information:
String line = remark.getText();
int i = line.indexOf("ANGSTROM");
if ( i > 5) {
// line contains ANGSTROM info...
String resolution = line.substring(i-5,i).trim();
// convert string to float
float res = 99 ;
try {
res = Float.parseFloat(resolution);
} catch (NumberFormatException e) {
System.err.println(e.getMessage());
System.err.println("could not parse resolution from line and ignoring it " + line);
return ;
}
// support for old style header
Map<String,Object> header = structure.getHeader();
header.put("resolution",new Float(res));
structure.setHeader(header);
PDBHeader pdbHeader = structure.getPDBHeader();
pdbHeader.setResolution(res);
}
}
}
@SuppressWarnings("deprecation")
public void newRefine(Refine r){
// copy the resolution to header
PDBHeader pdbHeader = structure.getPDBHeader();
try {
pdbHeader.setResolution(Float.parseFloat(r.getLs_d_res_high()));
} catch (NumberFormatException e){
logger.warning("could not parse resolution from " + r.getLs_d_res_high() + " " + e.getMessage());
}
Map<String,Object> header = structure.getHeader();
header.put("resolution",pdbHeader.getResolution());
}
public void newAuditAuthor(AuditAuthor aa){
String name = aa.getName();
StringBuffer famName = new StringBuffer();
StringBuffer initials = new StringBuffer();
boolean afterComma = false;
for ( char c: name.toCharArray()) {
if ( c == ' ')
continue;
if ( c == ','){
afterComma = true;
continue;
}
if ( afterComma)
initials.append(c);
else
famName.append(c);
}
StringBuffer newaa = new StringBuffer();
newaa.append(initials);
newaa.append(famName);
PDBHeader header = structure.getPDBHeader();
String auth = header.getAuthors();
if (auth == null) {
header.setAuthors(newaa.toString());
}else {
auth += "," + newaa.toString();
header.setAuthors(auth);
}
}
@SuppressWarnings("deprecation")
public void newExptl(Exptl exptl) {
PDBHeader pdbHeader = structure.getPDBHeader();
String method = exptl.getMethod();
String old = pdbHeader.getTechnique();
if ( (old != null) && (! old.equals(""))){
method = old+"; " + method;
}
pdbHeader.setTechnique(method);
Map<String,Object> header = structure.getHeader();
header.put("technique",method);
}
public void newStructRef(StructRef sref) {
if (DEBUG)
System.out.println(sref);
strucRefs.add(sref);
}
private StructRef getStructRef(String ref_id){
for (StructRef structRef : strucRefs) {
if (structRef.getId().equals(ref_id)){
return structRef;
}
}
return null;
}
/** create a DBRef record from the StrucRefSeq record:
* <pre>
PDB record DBREF
Field Name mmCIF Data Item
Section n.a.
PDB_ID_Code _struct_ref_seq.pdbx_PDB_id_code
Strand_ID _struct_ref_seq.pdbx_strand_id
Begin_Residue_Number _struct_ref_seq.pdbx_auth_seq_align_beg
Begin_Ins_Code _struct_ref_seq.pdbx_seq_align_beg_ins_code
End_Residue_Number _struct_ref_seq.pdbx_auth_seq_align_end
End_Ins_Code _struct_ref_seq.pdbx_seq_align_end_ins_code
Database _struct_ref.db_name
Database_Accession_No _struct_ref_seq.pdbx_db_accession
Database_ID_Code _struct_ref.db_code
Database_Begin_Residue_Number _struct_ref_seq.db_align_beg
Databaes_Begin_Ins_Code _struct_ref_seq.pdbx_db_align_beg_ins_code
Database_End_Residue_Number _struct_ref_seq.db_align_end
Databaes_End_Ins_Code _struct_ref_seq.pdbx_db_align_end_ins_code
</pre>
*
*
*/
public void newStructRefSeq(StructRefSeq sref) {
//if (DEBUG)
// System.out.println(sref);
DBRef r = new DBRef();
//if (DEBUG)
// System.out.println( " " + sref.getPdbx_PDB_id_code() + " " + sref.getPdbx_db_accession());
r.setIdCode(sref.getPdbx_PDB_id_code());
r.setDbAccession(sref.getPdbx_db_accession());
r.setDbIdCode(sref.getPdbx_db_accession());
//TODO: make DBRef chain IDs a string for chainIDs that are longer than one char...
r.setChainId(new Character(sref.getPdbx_strand_id().charAt(0)));
StructRef structRef = getStructRef(sref.getRef_id());
if (structRef == null){
logger.warning("could not find StructRef " + sref.getRef_id() + " for StructRefSeq " + sref);
} else {
r.setDatabase(structRef.getDb_name());
r.setDbIdCode(structRef.getDb_code());
}
int seqbegin = Integer.parseInt(sref.getPdbx_auth_seq_align_beg());
int seqend = Integer.parseInt(sref.getPdbx_auth_seq_align_end());
Character begin_ins_code = new Character(sref.getPdbx_seq_align_beg_ins_code().charAt(0));
Character end_ins_code = new Character(sref.getPdbx_seq_align_end_ins_code().charAt(0));
if (begin_ins_code == '?')
begin_ins_code = ' ';
if (end_ins_code == '?')
end_ins_code = ' ';
r.setSeqBegin(seqbegin);
r.setInsertBegin(begin_ins_code);
r.setSeqEnd(seqend);
r.setInsertEnd(end_ins_code);
int dbseqbegin = Integer.parseInt(sref.getDb_align_beg());
int dbseqend = Integer.parseInt(sref.getDb_align_end());
Character db_begin_in_code = new Character(sref.getPdbx_db_align_beg_ins_code().charAt(0));
Character db_end_in_code = new Character(sref.getPdbx_db_align_end_ins_code().charAt(0));
if (db_begin_in_code == '?')
db_begin_in_code = ' ';
if (db_end_in_code == '?')
db_end_in_code = ' ';
r.setDbSeqBegin(dbseqbegin);
r.setIdbnsBegin(db_begin_in_code);
r.setDbSeqEnd(dbseqend);
r.setIdbnsEnd(db_end_in_code);
List<DBRef> dbrefs = structure.getDBRefs();
if ( dbrefs == null)
dbrefs = new ArrayList<DBRef>();
dbrefs.add(r);
if ( DEBUG)
System.out.println(r.toPDB());
structure.setDBRefs(dbrefs);
}
private Chain getChainFromList(List<Chain> chains, String name){
for (Chain chain : chains) {
if ( chain.getChainID().equals(name)){
return chain;
}
}
// does not exist yet, so create...
Chain chain = new ChainImpl();
chain.setChainID(name);
chains.add(chain);
return chain;
}
private Chain getEntityChain(String entity_id){
return getChainFromList(entityChains,entity_id);
}
//private Chain getSeqResChain(String chainID){
// return getChainFromList(seqResChains, chainID);
/** The EntityPolySeq object provide the amino acid sequence objects for the Entities.
* Later on the entities are mapped to the BioJava Chain and Compound objects.
* @param epolseq the EntityPolySeq record for one amino acid
*/
public void newEntityPolySeq(EntityPolySeq epolseq) {
if (DEBUG)
System.out.println("NEW entity poly seq " + epolseq);
Entity e = getEntity(epolseq.getEntity_id());
if (e == null){
System.err.println("could not find entity "+ epolseq.getEntity_id()+". Can not match sequence to it.");
return;
}
Chain entityChain = getEntityChain(epolseq.getEntity_id());
// create group from epolseq;
// by default this are the SEQRES records...
AminoAcid g = new AminoAcidImpl();
g.setRecordType(AminoAcid.SEQRESRECORD);
try {
g.setPDBName(epolseq.getMon_id());
Character code1 = StructureTools.convert_3code_1code(epolseq.getMon_id());
g.setAminoType(code1);
g.setResidueNumber(ResidueNumber.fromString(epolseq.getNum()));
// ARGH at this stage we don;t know about insertion codes
// this has to be obtained from _pdbx_poly_seq_scheme
entityChain.addGroup(g);
} catch (PDBParseException ex) {
if ( StructureTools.isNucleotide(epolseq.getMon_id())) {
// the group is actually a nucleotide group...
NucleotideImpl n = new NucleotideImpl();
n.setResidueNumber(ResidueNumber.fromString(epolseq.getNum()));
entityChain.addGroup(n);
}
else {
logger.warning(ex.getMessage() + " creating a hetatom called XXX ");
HetatomImpl h = new HetatomImpl();
try {
h.setPDBName(epolseq.getMon_id());
//h.setAminoType('X');
h.setResidueNumber(ResidueNumber.fromString(epolseq.getNum()));
entityChain.addGroup(h);
} catch (PDBParseException exc) {
System.err.println("this is a helpless case and I am dropping group " + epolseq.getMon_id());
}
//ex.printStackTrace();
}
} catch (UnknownPdbAminoAcidException ex){
//logger.warning("no sure what to do with:" + epolseq.getMon_id()+ " " + ex.getMessage());
HetatomImpl h = new HetatomImpl();
try {
h.setPDBName(epolseq.getMon_id());
//h.setAminoType('X');
h.setResidueNumber(ResidueNumber.fromString(epolseq.getNum()));
entityChain.addGroup(h);
} catch (PDBParseException exc) {
System.err.println("this is a helpless case and I am dropping group " + epolseq.getMon_id() + " " + ex.getMessage());
}
//System.err.println(ex.getMessage());
}
}
/* returns the chains from all models that have the provided chainId
*
*/
private List<Chain> getChainsFromAllModels(String chainId){
List<Chain> chains = new ArrayList<Chain>();
for (int i=0 ; i < structure.nrModels();i++){
List<Chain> model = structure.getModel(i);
for (Chain c: model){
if (c.getChainID().equals(chainId)) {
chains.add(c);
}
}
}
return chains;
}
/** finds the residue in the internal representation and fixes the residue number and insertion code
*
* @param ppss
*/
private void replaceGroupSeqPos(PdbxPolySeqScheme ppss){
if (ppss.getAuth_seq_num().equals("?"))
return;
// at this stage we are still using the internal asym ids...
List<Chain> matchinChains = getChainsFromAllModels(ppss.getAsym_id());
long sid = Long.parseLong(ppss.getSeq_id());
for (Chain c: matchinChains){
Group target = null;
for (Group g: c.getAtomGroups()){
if ( g instanceof AminoAcidImpl){
AminoAcidImpl aa = (AminoAcidImpl)g;
if (aa.getId() == sid ) {
// found it:
target = g;
break;
}
}
else if ( g instanceof NucleotideImpl) {
NucleotideImpl n = (NucleotideImpl)g;
if ( n.getId() == sid) {
target = g;
break;
}
} else if ( g instanceof HetatomImpl){
HetatomImpl h = (HetatomImpl)g;
if ( h.getId() == sid){
target =h;
break;
}
}
}
if (target == null){
logger.info("could not find group at seq. position " +
ppss.getSeq_id() + " in internal chain " + c.getChainID() + ". " + ppss);
continue;
}
if (! target.getPDBName().equals(ppss.getMon_id())){
logger.info("could not match PdbxPolySeqScheme to chain:" + ppss);
continue;
}
// fix the residue number to the one used in the PDB files...
Integer pdbResNum = Integer.parseInt(ppss.getAuth_seq_num());
// check the insertion code...
String insCodeS = ppss.getPdb_ins_code();
Character insCode = null;
if ( ( insCodeS != null) && (! insCodeS.equals(".")) && insCodeS.length()>0){
//pdbResNum += insCode
insCode = insCodeS.charAt(0);
}
ResidueNumber residueNumber = new ResidueNumber(null, pdbResNum,insCode);
target.setResidueNumber(residueNumber);
}
}
public void newPdbxPolySeqScheme(PdbxPolySeqScheme ppss) {
//if ( headerOnly)
// return;
// replace the group asym ids with the real PDB ids!
replaceGroupSeqPos(ppss);
// merge the EntityPolySeq info and the AtomSite chains into one...
//already known ignore:
if (asymStrandId.containsKey(ppss.getAsym_id()))
return;
// this is one of the interal mmcif rules it seems...
if ( ppss.getPdb_strand_id() == null) {
asymStrandId.put(ppss.getAsym_id(), ppss.getAuth_mon_id());
return;
}
//System.out.println(ppss.getAsym_id() + " = " + ppss.getPdb_strand_id());
asymStrandId.put(ppss.getAsym_id(), ppss.getPdb_strand_id());
}
public void newPdbxNonPolyScheme(PdbxNonPolyScheme ppss) {
//if (headerOnly)
// return;
// merge the EntityPolySeq info and the AtomSite chains into one...
//already known ignore:
if (asymStrandId.containsKey(ppss.getAsym_id()))
return;
// this is one of the interal mmcif rules it seems...
if ( ppss.getPdb_strand_id() == null) {
asymStrandId.put(ppss.getAsym_id(), ppss.getAsym_id());
return;
}
asymStrandId.put(ppss.getAsym_id(), ppss.getPdb_strand_id());
}
public void newPdbxEntityNonPoly(PdbxEntityNonPoly pen){
// TODO: do something with them...
}
public void newChemComp(ChemComp c) {
// TODO: do something with them...
}
public void newGenericData(String category, List<String> loopFields,
List<String> lineData) {
if (DEBUG) {
System.err.println("unhandled category so far: " + category);
}
}
public FileParsingParameters getFileParsingParameters()
{
return params;
}
public void setFileParsingParameters(FileParsingParameters params)
{
this.params = params;
}
public void newChemCompDescriptor(ChemCompDescriptor ccd) {
// todo: nothing happening here yet.
}
public List<PdbxStructOperList> getStructOpers() {
return structOpers;
}
@Override
public void newPdbxStrucAssembly(PdbxStructAssembly strucAssembly) {
strucAssemblies.add(strucAssembly);
}
public List<PdbxStructAssembly> getStructAssemblies(){
return strucAssemblies;
}
@Override
public void newPdbxStrucAssemblyGen(PdbxStructAssemblyGen strucAssembly) {
strucAssemblyGens.add(strucAssembly);
}
public List<PdbxStructAssemblyGen> getStructAssemblyGens(){
return strucAssemblyGens;
}
}
|
package org.pescuma.buildhealth.extractor.findbugs;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.io.File;
import java.io.InputStream;
import org.junit.Test;
import org.pescuma.buildhealth.extractor.BaseExtractorTest;
import org.pescuma.buildhealth.extractor.PseudoFiles;
import org.pescuma.buildhealth.extractor.staticanalysis.FindBugsExtractor;
public class FindBugsExtractorTest extends BaseExtractorTest {
@Test
public void test1Folder1Bug() {
InputStream stream = load("findbugs.1folder.1bug.xml");
FindBugsExtractor extractor = new FindBugsExtractor(new PseudoFiles(stream));
extractor.extractTo(table, tracker);
verify(tracker).onStreamProcessed();
verify(tracker, never()).onFileProcessed(any(File.class));
assertEquals(1, table.size());
assertEquals(1, table.filter("Static analysis", "Java", "FindBugs").sum(),
// "C:\\buildhealth.core\\src\\org\\pescuma\\buildhealth\\computer\\loc\\LOCComputer.java",
// "Internationalization",
// "Reliance on default encoding",
// "Found reliance on default encoding in org.pescuma.buildhealth.computer.loc.LOCComputer.createFileList(): new java.io.FileWriter(File)\n"
// "Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly."),
0.0001);
}
@Test
public void test2Folder2Bugs() {
InputStream stream = load("findbugs.2folders.2bugs.xml");
FindBugsExtractor extractor = new FindBugsExtractor(new PseudoFiles(stream));
extractor.extractTo(table, tracker);
verify(tracker).onStreamProcessed();
verify(tracker, never()).onFileProcessed(any(File.class));
assertEquals(2, table.size());
assertEquals(2, table.sum(), 0.001);
}
}
|
package net.tomp2p.dht;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import net.tomp2p.connection.Bindings;
import net.tomp2p.connection.ChannelClientConfiguration;
import net.tomp2p.connection.ChannelServerConfiguration;
import net.tomp2p.connection.PeerException;
import net.tomp2p.connection.PeerException.AbortCause;
import net.tomp2p.futures.BaseFuture;
import net.tomp2p.futures.BaseFutureAdapter;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureDirect;
import net.tomp2p.futures.FutureDone;
import net.tomp2p.futures.FuturePeerConnection;
import net.tomp2p.message.Buffer;
import net.tomp2p.p2p.AutomaticFuture;
import net.tomp2p.p2p.DefaultBroadcastHandler;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.p2p.RequestP2PConfiguration;
import net.tomp2p.p2p.RoutingConfiguration;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.Number320;
import net.tomp2p.peers.Number480;
import net.tomp2p.peers.Number640;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.peers.PeerMap;
import net.tomp2p.peers.PeerMapConfiguration;
import net.tomp2p.peers.PeerStatistic;
import net.tomp2p.rpc.DigestResult;
import net.tomp2p.rpc.ObjectDataReply;
import net.tomp2p.rpc.RawDataReply;
import net.tomp2p.storage.Data;
import net.tomp2p.utils.Utils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestDHT {
final private static Random rnd = new Random(42L);
private static final Logger LOG = LoggerFactory.getLogger(TestDHT.class);
@Test
public void testPutBig() throws Exception {
PeerDHT[] peers = null;
try {
peers = testPutBig1("1");
//Thread.sleep(5 * 1000);
//master = testPutBig1("2");
//Thread.sleep(5 * 1000);
//master = testPutBig1("3");
//Thread.sleep(5 * 1000);
//Thread.sleep(Integer.MAX_VALUE);
} finally {
for (PeerDHT peerDHT:peers) {
if(peerDHT!=null) {
peerDHT.shutdown().await();
}
}
System.out.println("done");
}
}
private PeerDHT[] testPutBig1(String key) throws Exception {
Peer[] peers = UtilsDHT2.createRealNodes(10, rnd, 4001, new AutomaticFuture() {
@Override
public void futureCreated(BaseFuture future) { }
});
PeerDHT[] peers2 = new PeerDHT[10];
for(int i=0;i<peers.length;i++) {
peers2[i] = new PeerBuilderDHT(peers[i]).start();
}
UtilsDHT2.perfectRouting(peers2);
Data data1 = new Data(new byte[10*1024*1024]);
RequestP2PConfiguration rp = new RequestP2PConfiguration(1, 0, 0);
//for(int i=0;i<10000;i++) {
PutBuilder pb = peers2[0].put(Number160.createHash(key)).requestP2PConfiguration(rp).data(data1);
FuturePut futurePut = pb.start();
futurePut.awaitUninterruptibly();
Assert.assertEquals(true, futurePut.isSuccess());
System.out.println("stored on "+futurePut.result());
FutureRemove fr = peers2[0].remove(Number160.createHash(key)).start().awaitUninterruptibly();
System.out.println("removed from "+fr.result());
return peers2;
}
@Test
public void testPutTwo() throws Exception {
PeerDHT master = null;
try {
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final Data data1 = new Data(new byte[1]);
data1.ttlSeconds(3);
FuturePut futurePut = master.put(Number160.createHash("test")).data(data1).start();
futurePut.awaitUninterruptibly();
Assert.assertEquals(true, futurePut.isSuccess());
FutureGet futureGet = peers[1].get(Number160.createHash("test")).start();
futureGet.awaitUninterruptibly();
Assert.assertEquals(true, futureGet.isSuccess());
// LOG.error("done");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutVersion() throws Exception {
final Random rnd = new Random(42L);
PeerDHT master = null;
try {
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final Data data1 = new Data(new byte[1]);
data1.ttlSeconds(3);
FuturePut futurePut = master.put(Number160.createHash("test")).versionKey(Number160.MAX_VALUE)
.data(data1).start();
futurePut.awaitUninterruptibly();
Assert.assertEquals(true, futurePut.isSuccess());
Map<Number640, Data> map = peers[0].storageLayer().get();
Assert.assertEquals(Number160.MAX_VALUE, map.entrySet().iterator().next().getKey().versionKey());
LOG.error("done");
} finally {
if (master != null) {
master.shutdown().awaitUninterruptibly();
master.shutdown().awaitListenersUninterruptibly();
}
}
}
@Test
public void testPutPerforomance() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
for (int i = 0; i < 500; i++) {
//long start = System.currentTimeMillis();
FuturePut fp = peers[444].put(Number160.createHash("1")).data(new Data("test")).start();
fp.awaitUninterruptibly();
fp.futureRequests().awaitUninterruptibly();
//long stop = System.currentTimeMillis();
//System.out.println("Test " + fp.failedReason() + " / " + (stop - start) + "ms");
Assert.assertEquals(true, fp.isSuccess());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPut() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fp = peers[444].put(peers[30].peerID())
.data(Number160.createHash("test"), new Number160(5), data).requestP2PConfiguration(pc)
.routingConfiguration(rc).start();
fp.awaitUninterruptibly();
fp.futureRequests().awaitUninterruptibly();
System.out.println("Test " + fp.failedReason());
Assert.assertEquals(true, fp.isSuccess());
peers[30].peerBean().peerMap();
// search top 3
TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(PeerMap.createXORAddressComparator(peers[30]
.peer().peerID()));
int i = 0;
for (PeerDHT node : peers) {
tmp.put(node.peer().peerAddress(), i);
i++;
}
Entry<PeerAddress, Integer> e = tmp.pollFirstEntry();
System.out.println("1 (" + e.getValue() + ")" + e.getKey());
Assert.assertEquals(peers[e.getValue()].peerAddress(), peers[30].peerAddress());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
System.out.println("2 (" + e.getValue() + ")" + e.getKey());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
System.out.println("3 " + e.getKey());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
System.out.println("4 " + e.getKey());
testForArray(peers[e.getValue()], peers[30].peerID(), false);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetAlone() throws Exception {
PeerDHT master = null;
try {
master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start();
FuturePut fdht = master.put(Number160.ONE).data(new Data("hallo")).start();
fdht.awaitUninterruptibly();
fdht.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
FutureGet fdht2 = master.get(Number160.ONE).start();
fdht2.awaitUninterruptibly();
System.out.println(fdht2.failedReason());
Assert.assertEquals(true, fdht2.isSuccess());
Data tmp = fdht2.data();
Assert.assertEquals("hallo", tmp.object().toString());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutTimeout() throws Exception {
PeerDHT master = null;
try {
Peer pmaster = new PeerBuilder(new Number160(rnd)).ports(4001).start();
master = new PeerBuilderDHT(pmaster).storage(new StorageMemory(1)).start();
Data data = new Data("hallo");
data.ttlSeconds(1);
FuturePut fdht = master.put(Number160.ONE).data(data).start();
fdht.awaitUninterruptibly();
fdht.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
Thread.sleep(3000);
FutureGet fdht2 = master.get(Number160.ONE).start();
fdht2.awaitUninterruptibly();
System.out.println(fdht2.failedReason());
//we get an empty result, this means it did not fail, just it did not return anything
Assert.assertEquals(true, fdht2.isSuccess());
Data tmp = fdht2.data();
Assert.assertNull(tmp);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPut2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(500, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(0, 0, 1);
RequestP2PConfiguration pc = new RequestP2PConfiguration(1, 0, 0);
FuturePut fdht = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fdht.awaitUninterruptibly();
fdht.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
peers[30].peerBean().peerMap();
// search top 3
TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(PeerMap.createXORAddressComparator(peers[30]
.peerID()));
int i = 0;
for (PeerDHT node : peers) {
tmp.put(node.peerAddress(), i);
i++;
}
Entry<PeerAddress, Integer> e = tmp.pollFirstEntry();
Assert.assertEquals(peers[e.getValue()].peerAddress(), peers[30].peerAddress());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].peerID(), false);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].peerID(), false);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].peerID(), false);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(0, 0, 10, 1);
pc = new RequestP2PConfiguration(1, 0, 0);
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.rawData().size());
Assert.assertEquals(true, fget.isMinReached());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutConvert() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
NavigableMap<Number160, Data> tmp = new TreeMap<Number160, Data>();
tmp.put(new Number160(5), data);
FuturePut fput = peers[444].put(peers[30].peerID()).dataMapContent(tmp)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
System.out.println(fput.failedReason());
Assert.assertEquals(true, fput.isSuccess());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(3, fget.rawData().size());
Assert.assertEquals(true, fget.isMinReached());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet3() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(1, 0, 10, 1);
pc = new RequestP2PConfiguration(1, 0, 0);
for (int i = 0; i < 1000; i++) {
FutureGet fget = peers[100 + i].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc)
.start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.rawData().size());
Assert.assertEquals(true, fget.isMinReached());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetRemove() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].peerID()).domainKey(Number160.createHash("test"))
.data(new Number160(5), data).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(3, 0, 0);
FutureRemove frem = peers[222].remove(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
Assert.assertEquals(3, frem.rawKeys().size());
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isEmpty());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetRemove2() throws Exception {
PeerDHT master = null;
try {
// rnd.setSeed(253406013991563L);
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(3, fput.rawResult().size());
Assert.assertEquals(true, fput.isSuccess());
System.out.println("remove");
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(3, 0, 0);
FutureRemove frem = peers[222].remove(peers[30].peerID()).returnResults()
.domainKey(Number160.createHash("test")).contentKey(new Number160(5))
.routingConfiguration(rc).requestP2PConfiguration(pc).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
Assert.assertEquals(3, frem.rawData().size());
System.out.println("get");
rc = new RoutingConfiguration(4, 0, 0, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertTrue(fget.isEmpty());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDirect() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final AtomicInteger ai = new AtomicInteger(0);
for (int i = 0; i < peers.length; i++) {
peers[i].peer().objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
ai.incrementAndGet();
return "ja";
}
});
}
// do testing
FutureSend fdir = peers[400].send(new Number160(rnd)).object("hallo").start();
fdir.awaitUninterruptibly();
System.out.println(fdir.failedReason());
Assert.assertEquals(true, fdir.isSuccess());
Assert.assertEquals(true, ai.get() >= 3 && ai.get() <= 6);
System.out.println("called: " + ai.get());
Assert.assertEquals("ja", fdir.object());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddListGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo1";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
FuturePut fput = peers[30].add(nr).data(data1).list(true).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).list(true).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// majority voting with getDataMap is not possible since we create
// random content key on the recipient
Assert.assertEquals(2, fget.rawData().values().iterator().next().values().size());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
FuturePut fput = peers[30].add(nr).data(data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDigest() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
String toStore3 = "hallo3";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
Data data3 = new Data(toStore3.getBytes());
FuturePut fput = peers[30].add(nr).data(data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
fput = peers[51].add(nr).data(data3).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore3 + " (" + fput.isSuccess() + ")");
FutureDigest fget = peers[77].digest(nr).all().start();
fget.awaitUninterruptibly();
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(3, fget.digest().keyDigest().size());
Number160 test = new Number160("0x37bb570100c9f5445b534757ebc613a32df3836d");
List<Number160> test2 = new ArrayList<Number160>();
test2.add(test);
fget = peers[67].digest(nr).contentKeys(test2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.digest().keyDigest().size());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void removeTestLoop() throws IOException, ClassNotFoundException {
for(int i=0;i<100;i++) {
System.out.println("removeTestLoop() call nr "+i);
removeTest();
}
}
@Test
public void removeTest() throws IOException, ClassNotFoundException {
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start();
p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer())
.start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
String locationKey = "location";
String contentKey = "content";
String data = "testme";
// data.generateVersionKey();
p2.put(Number160.createHash(locationKey)).data(Number160.createHash(contentKey), new Data(data))
.versionKey(Number160.ONE).start().awaitUninterruptibly();
FutureRemove futureRemove = p1.remove(Number160.createHash(locationKey)).domainKey(Number160.ZERO)
.contentKey(Number160.createHash(contentKey)).versionKey(Number160.ONE).start();
futureRemove.awaitUninterruptibly();
FutureDigest futureDigest = p1.digest(Number160.createHash(locationKey)).domainKey(Number160.ZERO)
.contentKey(Number160.createHash(contentKey)).versionKey(Number160.ONE).start();
futureDigest.awaitUninterruptibly();
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
} finally {
if(p1 != null) {
p1.shutdown().awaitUninterruptibly();
}
if(p2 != null) {
p2.shutdown().awaitUninterruptibly();
}
}
}
@Test
public void testDigest2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
String toStore3 = "hallo3";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
Data data3 = new Data(toStore3.getBytes());
Number160 key1 = new Number160(1);
Number160 key2 = new Number160(2);
Number160 key3 = new Number160(3);
FuturePut fput = peers[30].put(nr).data(key1, data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].put(nr).data(key2, data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
fput = peers[51].put(nr).data(key3, data3).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore3 + " (" + fput.isSuccess() + ")");
Number640 from = new Number640(nr, Number160.ZERO, Number160.ZERO, Number160.ZERO);
Number640 to = new Number640(nr, Number160.MAX_VALUE, Number160.MAX_VALUE, Number160.MAX_VALUE);
FutureDigest fget = peers[77].digest(nr).from(from).to(to).returnNr(1).start();
fget.awaitUninterruptibly();
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.digest().keyDigest().size());
Assert.assertEquals(key1, fget.digest().keyDigest().keySet().iterator().next().contentKey());
fget = peers[67].digest(nr).from(from).to(to).returnNr(1).descending().start();
fget.awaitUninterruptibly();
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.digest().keyDigest().size());
Assert.assertEquals(key3, fget.digest().keyDigest().keySet().iterator().next().contentKey());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDigest3() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// initialize test data
Number160 lKey = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
String toStore3 = "hallo3";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
Data data3 = new Data(toStore3.getBytes());
Number160 ckey = new Number160(rnd);
data1.addBasedOn(Number160.ONE);
Number160 versionKey1 = new Number160(1, data1.hash());
data2.addBasedOn(versionKey1);
Number160 versionKey2 = new Number160(2, data2.hash());
data3.addBasedOn(versionKey2);
Number160 versionKey3 = new Number160(3, data3.hash());
// put test data
FuturePut fput = peers[30].put(lKey).data(ckey, data1, versionKey1).start();
fput.awaitUninterruptibly();
fput = peers[50].put(lKey).data(ckey, data2, versionKey2).start();
fput.awaitUninterruptibly();
fput = peers[51].put(lKey).data(ckey, data3, versionKey3).start();
fput.awaitUninterruptibly();
// get digest
FutureDigest fget = peers[77].digest(lKey).all().start();
fget.awaitUninterruptibly();
DigestResult dr = fget.digest();
NavigableMap<Number640, Collection<Number160>> map = dr.keyDigest();
// verify fetched digest
Entry<Number640, Collection<Number160>> e1 = map.pollFirstEntry();
Assert.assertEquals(Number160.ONE, e1.getValue().iterator().next());
Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey1), e1.getKey());
Entry<Number640, Collection<Number160>> e2 = map.pollFirstEntry();
Assert.assertEquals(versionKey1, e2.getValue().iterator().next());
Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey2), e2.getKey());
Entry<Number640, Collection<Number160>> e3 = map.pollFirstEntry();
Assert.assertEquals(versionKey2, e3.getValue().iterator().next());
Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey3), e3.getKey());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDigest4() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// initialize test data
Number160 lKey = new Number160(rnd);
Number160 dKey = new Number160(rnd);
Number160 ckey = new Number160(rnd);
NavigableMap<Number640, Data> dataMap = new TreeMap<Number640, Data>();
Number160 bKey = Number160.ONE;
for (int i = 0; i < 10; i++) {
Data data = new Data(UUID.randomUUID());
data.addBasedOn(bKey);
Number160 vKey = new Number160(i, data.hash());
dataMap.put(new Number640(lKey, dKey, ckey, vKey), data);
bKey = vKey;
}
// put test data
for (Number640 key : dataMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(100)].put(lKey).domainKey(dKey)
.data(ckey, dataMap.get(key)).versionKey(key.versionKey()).start();
fput.awaitUninterruptibly();
}
// get digest
FutureDigest fget = peers[rnd.nextInt(100)].digest(lKey)
.from(new Number640(lKey, dKey, ckey, Number160.ZERO))
.to(new Number640(lKey, dKey, ckey, Number160.MAX_VALUE)).start();
fget.awaitUninterruptibly();
DigestResult dr = fget.digest();
NavigableMap<Number640, Collection<Number160>> fetchedDataMap = dr.keyDigest();
// verify fetched digest
Assert.assertEquals(dataMap.size(), fetchedDataMap.size());
for (Number640 key : dataMap.keySet()) {
Assert.assertTrue(fetchedDataMap.containsKey(key));
Assert.assertEquals(dataMap.get(key).basedOnSet().iterator().next(), fetchedDataMap.get(key)
.iterator().next());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testData() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
ByteBuf c = Unpooled.buffer();
c.writeInt(77);
Buffer b = new Buffer(c);
peers[50].peer().rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) {
System.out.println(requestBuffer.buffer().readInt());
ByteBuf c = Unpooled.buffer();
c.writeInt(88);
Buffer ret = new Buffer(c);
return ret;
}
});
FutureDirect fd = master.peer().sendDirect(peers[50].peerAddress()).buffer(b).start();
fd.await();
if (fd.buffer() == null) {
System.out.println("damm");
Assert.fail();
}
int read = fd.buffer().buffer().readInt();
Assert.assertEquals(88, read);
System.out.println("done");
// for(FutureBootstrap fb:tmp)
// fb.awaitUninterruptibly();
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testData2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
ByteBuf c = Unpooled.buffer();
c.writeInt(77);
Buffer b = new Buffer(c);
peers[50].peer().rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) {
System.out.println("got it");
return requestBuffer;
}
});
FutureDirect fd = master.peer().sendDirect(peers[50].peerAddress()).buffer(b).start();
fd.await();
System.out.println("done1");
Assert.assertEquals(true, fd.isSuccess());
Assert.assertNull(fd.buffer());
// int read = fd.getBuffer().readInt();
// Assert.assertEquals(88, read);
System.out.println("done2");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testObjectLoop() throws Exception {
for (int i = 0; i < 1000; i++) {
if(i%10==0) {
System.out.println("nr: " + i);
}
testObject();
}
}
@Test
public void testObject() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
Data data1 = new Data(toStore1);
Data data2 = new Data(toStore2);
//System.out.println("begin add : ");
FuturePut fput = peers[30].add(nr).data(data1).start();
fput.awaitUninterruptibly();
//System.out.println("stop added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
//System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).all().start();
fget.awaitUninterruptibly();
fget.futureRequests().awaitUninterruptibly();
if (!fget.isSuccess())
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(2, fget.dataMap().size());
//System.out.println("got it");
} finally {
if (master != null) {
master.shutdown().awaitUninterruptibly();
master.shutdown().awaitListenersUninterruptibly();
}
}
}
@Test
public void testMaintenanceInit() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRoutingIndirect(peers);
// do testing
PeerStatistic peerStatatistic = master.peerBean().peerMap()
.nextForMaintenance(new ArrayList<PeerAddress>());
Assert.assertNotEquals(master.peerAddress(), peerStatatistic.peerAddress());
Thread.sleep(10000);
System.out.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddGetPermits() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
List<FuturePut> list = new ArrayList<FuturePut>();
for (int i = 0; i < peers.length; i++) {
String toStore1 = "hallo" + i;
Data data1 = new Data(toStore1.getBytes());
FuturePut fput = peers[i].add(nr).data(data1).start();
list.add(fput);
}
for (FuturePut futureDHT : list) {
futureDHT.awaitUninterruptibly();
Assert.assertEquals(true, futureDHT.isSuccess());
}
System.out.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testhalt() throws Exception {
PeerDHT master1 = null;
PeerDHT master2 = null;
PeerDHT master3 = null;
try {
master1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4001).start()).start();
master2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4002).start()).start();
master3 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4003).start()).start();
// perfect routing
master1.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
master1.peerBean().peerMap().peerFound(master3.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master1.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master3.peerAddress(), null, null, null);
master3.peerBean().peerMap().peerFound(master1.peerAddress(), null, null, null);
master3.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
Number160 id = master2.peerID();
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = master1.put(id).data(new Number160(5), data).domainKey(Number160.createHash("test"))
.requestP2PConfiguration(pc).routingConfiguration(rc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
// Collection<Number160> tmp = new ArrayList<Number160>();
// tmp.add(new Number160(5));
Assert.assertEquals(true, fput.isSuccess());
// search top 3
master2.shutdown().await();
FutureGet fget = master1.get(id).routingConfiguration(rc).requestP2PConfiguration(pc)
.domainKey(Number160.createHash("test")).contentKey(new Number160(5)).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
master1.peerBean().peerMap().peerFailed(master2.peerAddress(), new PeerException(AbortCause.SHUTDOWN, "shutdown"));
master3.peerBean().peerMap().peerFailed(master2.peerAddress(), new PeerException(AbortCause.SHUTDOWN, "shutdown"));
master2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4002).start()).start();
master1.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
master3.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master1.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master3.peerAddress(), null, null, null);
System.out.println("no more exceptions here!!");
fget = master1.get(id).routingConfiguration(rc).requestP2PConfiguration(pc)
.domainKey(Number160.createHash("test")).contentKey(new Number160(5)).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
} finally {
if (master1 != null) {
master1.shutdown().await();
}
if (master2 != null) {
master2.shutdown().await();
}
if (master3 != null) {
master3.shutdown().await();
}
}
}
@Test
public void testObjectSendExample() throws Exception {
Peer p1 = null;
Peer p2 = null;
try {
p1 = new PeerBuilder(new Number160(rnd)).ports(4001).start();
p2 = new PeerBuilder(new Number160(rnd)).ports(4002).start();
// attach reply handler
p2.objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
System.out.println("request [" + request + "]");
return "world";
}
});
FutureDirect futureData = p1.sendDirect(p2.peerAddress()).object("hello").start();
futureData.awaitUninterruptibly();
System.out.println("reply [" + futureData.object() + "]");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testObjectSend() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(500, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
for (int i = 0; i < peers.length; i++) {
System.out.println("node " + i);
peers[i].peer().objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
return request;
}
});
peers[i].peer().rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) throws Exception {
return requestBuffer;
}
});
}
// do testing
System.out.println("round start");
Random rnd = new Random(42L);
byte[] toStore1 = new byte[10 * 1024];
for (int j = 0; j < 5; j++) {
System.out.println("round " + j);
for (int i = 0; i < peers.length - 1; i++) {
send1(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)], toStore1, 100);
send2(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)],
Unpooled.wrappedBuffer(toStore1), 100);
System.out.println("round1 " + i);
}
}
System.out.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testKeys() throws Exception {
final Random rnd = new Random(42L);
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
Number160 n1 = new Number160(rnd);
Data d1 = new Data("hello");
Data d2 = new Data("world!");
// setup (step 1)
p1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start();
FuturePut fput = p1.add(n1).data(d1).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
p2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
// test (step 2)
fput = p1.add(n1).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
FutureGet fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.dataMap().size());
// test (step 3)
FutureRemove frem = p1.remove(n1).contentKey(d2.hash()).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.dataMap().size());
// test (step 4)
fput = p1.add(n1).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.dataMap().size());
// test (remove all)
frem = p1.remove(n1).contentKey(d1.hash()).start();
frem.awaitUninterruptibly();
frem = p1.remove(n1).contentKey(d2.hash()).start();
frem.awaitUninterruptibly();
fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(0, fget.dataMap().size());
System.out.println("testKeys done");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testKeys2() throws Exception {
final Random rnd = new Random(42L);
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
Number160 n1 = new Number160(rnd);
Number160 n2 = new Number160(rnd);
Data d1 = new Data("hello");
Data d2 = new Data("world!");
// setup (step 1)
p1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start();
FuturePut fput = p1.put(n1).data(d1).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
p2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
// test (step 2)
fput = p1.put(n2).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
FutureGet fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.dataMap().size());
// test (step 3)
FutureRemove frem = p1.remove(n2).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(0, fget.dataMap().size());
// test (step 4)
fput = p1.put(n2).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.dataMap().size());
System.out.println("testKeys2 done");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testPutGetAll() throws Exception {
final AtomicBoolean running = new AtomicBoolean(true);
PeerDHT master = null;
try {
// setup
final PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final Number160 key = Number160.createHash("test");
final Data data1 = new Data("test1");
data1.ttlSeconds(3);
final Data data2 = new Data("test2");
data2.ttlSeconds(3);
// add every second a two values
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (running.get()) {
peers[10].add(key).data(data1).start().awaitUninterruptibly();
peers[10].add(key).data(data2).start().awaitUninterruptibly();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
// wait until the first data is stored.
Thread.sleep(1000);
for (int i = 0; i < 30; i++) {
FutureGet fget = peers[20 + i].get(key).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.dataMap().size());
Thread.sleep(1000);
}
} finally {
running.set(false);
if (master != null) {
master.shutdown().await();
}
}
}
/**
* This will probably fail on your machine since you have to have eth0
* configured. This testcase is suited for running on the tomp2p.net server
*
* @throws Exception
*/
@Test
public void testBindings() throws Exception {
final Random rnd = new Random(42L);
Peer p1 = null;
Peer p2 = null;
try {
// setup (step 1)
Bindings b = new Bindings();
p1 = new PeerBuilder(new Number160(rnd)).ports(4001).bindings(b).start();
p2 = new PeerBuilder(new Number160(rnd)).ports(4002).bindings(b).start();
FutureBootstrap fb = p2.bootstrap().peerAddress(p1.peerAddress()).start();
fb.awaitUninterruptibly();
Assert.assertEquals(true, fb.isSuccess());
System.out.println("testBindings done");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testBroadcast() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
master.peer().broadcast(Number160.createHash("blub")).udp(false).start();
DefaultBroadcastHandler d = (DefaultBroadcastHandler) master.peer().broadcastRPC().broadcastHandler();
int counter = 0;
while (d.getBroadcastCounter() < 500) {
Thread.sleep(200);
counter++;
if (counter > 100) {
System.out.println("did not broadcast to 1000 peers, but to " + d.getBroadcastCounter());
Assert.fail("did not broadcast to 1000 peers, but to " + d.getBroadcastCounter());
}
}
System.out.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testTooManyOpenFilesInSystem() throws Exception {
Peer master = null;
Peer slave = null;
try {
// since we have two peers, we need to reduce the connections -> we
// will have 300 * 2 (peer connection)
// plus 100 * 2 * 2. The last multiplication is due to discover,
// where the recipient creates a connection
// with its own limit. Since the limit is 1024 and we stop at 1000
// only for the connection, we may run into
// too many open files
PeerBuilder masterMaker = new PeerBuilder(new Number160(rnd)).ports(4001);
master = masterMaker.enableMaintenance(false).start();
PeerBuilder slaveMaker = new PeerBuilder(new Number160(rnd)).ports(4002);
slave = slaveMaker.enableMaintenance(false).start();
System.out.println("peers up and running");
slave.rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean last) throws Exception {
final byte[] b1 = new byte[10000];
int i = requestBuffer.buffer().getInt(0);
ByteBuf buf = Unpooled.wrappedBuffer(b1);
buf.setInt(0, i);
return new Buffer(buf);
}
});
List<BaseFuture> list1 = new ArrayList<BaseFuture>();
List<BaseFuture> list2 = new ArrayList<BaseFuture>();
List<FuturePeerConnection> list3 = new ArrayList<FuturePeerConnection>();
for (int i = 0; i < 125; i++) {
final byte[] b = new byte[10000];
FuturePeerConnection pc = master.createPeerConnection(slave.peerAddress());
list1.add(master.sendDirect(pc).buffer(new Buffer(Unpooled.wrappedBuffer(b))).start());
list3.add(pc);
// pc.close();
}
for (int i = 0; i < 20000; i++) {
list2.add(master.discover().peerAddress(slave.peerAddress()).start());
final byte[] b = new byte[10000];
byte[] me = Utils.intToByteArray(i);
System.arraycopy(me, 0, b, 0, 4);
list2.add(master.sendDirect(slave.peerAddress()).buffer(new Buffer(Unpooled.wrappedBuffer(b)))
.start());
}
for (BaseFuture bf : list1) {
bf.awaitUninterruptibly();
bf.awaitListenersUninterruptibly();
if (bf.isFailed()) {
System.out.println("WTF " + bf.failedReason());
} else {
System.out.print(",");
}
Assert.assertEquals(true, bf.isSuccess());
}
for (FuturePeerConnection pc : list3) {
pc.close().awaitUninterruptibly();
pc.close().awaitListenersUninterruptibly();
}
for (BaseFuture bf : list2) {
bf.awaitUninterruptibly();
bf.awaitListenersUninterruptibly();
if (bf.isFailed()) {
System.out.println("WTF " + bf.failedReason());
} else {
System.out.print(".");
}
Assert.assertEquals(true, bf.isSuccess());
}
System.out.println("done!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("done!1!");
if (master != null) {
master.shutdown().await();
}
if (slave != null) {
slave.shutdown().await();
}
}
}
@Test
public void testThreads() throws Exception {
PeerDHT master = null;
PeerDHT slave = null;
try {
DefaultEventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(250);
ChannelClientConfiguration ccc1 = PeerBuilder.createDefaultChannelClientConfiguration();
ccc1.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(eventExecutorGroup));
ChannelServerConfiguration ccs1 = PeerBuilder.createDefaultChannelServerConfiguration();
ccs1.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(eventExecutorGroup));
master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).channelClientConfiguration(ccc1)
.channelServerConfiguration(ccs1).start()).start();
slave = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).channelClientConfiguration(ccc1)
.channelServerConfiguration(ccs1).start()).start();
master.peer().bootstrap().peerAddress(slave.peerAddress()).start().awaitUninterruptibly();
slave.peer().bootstrap().peerAddress(master.peerAddress()).start().awaitUninterruptibly();
System.out.println("peers up and running");
final int count = 100;
final CountDownLatch latch = new CountDownLatch(count);
final AtomicBoolean correct = new AtomicBoolean(true);
for (int i = 0; i < count; i++) {
FuturePut futurePut = master.put(Number160.ONE).data(new Data("test")).start();
futurePut.addListener(new BaseFutureAdapter<FuturePut>() {
@Override
public void operationComplete(FuturePut future) throws Exception {
Thread.sleep(1000);
latch.countDown();
System.out.println("block in "+Thread.currentThread().getName());
if(!Thread.currentThread().getName().contains("EventExecutorGroup")) {
correct.set(false);
}
}
});
}
latch.await(10, TimeUnit.SECONDS);
Assert.assertTrue(correct.get());
} finally {
System.out.println("done!1!");
if (master != null) {
master.shutdown().await();
}
if (slave != null) {
slave.shutdown().await();
}
System.out.println("done!2!");
}
}
@Test
public void removeFromToTest3() throws IOException, ClassNotFoundException {
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start();
p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
String data = "test";
p2.put(lKey).data(cKey, new Data(data)).domainKey(dKey).start().awaitUninterruptibly();
FutureRemove futureRemove = p1.remove(lKey).domainKey(dKey).contentKey(cKey).start();
futureRemove.awaitUninterruptibly();
// check with a normal digest
FutureDigest futureDigest = p1.digest(lKey).contentKey(cKey).domainKey(dKey).start();
futureDigest.awaitUninterruptibly();
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
// check with a from/to digest
futureDigest = p1.digest(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureDigest.awaitUninterruptibly();
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
} finally {
if (p1 != null) {
p1.shutdown().awaitUninterruptibly();
}
if (p2 != null) {
p2.shutdown().awaitUninterruptibly();
}
}
}
@Test
public void removeFromToTest4() throws IOException, ClassNotFoundException {
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start();
p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
String data = "test";
p2.put(lKey).data(cKey, new Data(data)).domainKey(dKey).start().awaitUninterruptibly();
FutureRemove futureRemove = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureRemove.awaitUninterruptibly();
FutureDigest futureDigest = p1.digest(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureDigest.awaitUninterruptibly();
// should be empty
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
} finally {
if (p1 != null) {
p1.shutdown().awaitUninterruptibly();
}
if (p2 != null) {
p2.shutdown().awaitUninterruptibly();
}
}
}
@Test
public void testShutdown() throws Exception {
PeerDHT master = null;
try {
// setup
Random rnd = new Random();
final int nrPeers = 10;
final int port = 4001;
// Peer[] peers = Utils2.createNodes(nrPeers, rnd, port);
// Peer[] peers =
// createAndAttachNodesWithReplicationShortId(nrPeers, port);
// Peer[] peers = createNodes(nrPeers, rnd, port, null, true);
PeerDHT[] peers = createNodesWithShortId(nrPeers, rnd, port, null);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
final int peerTest = 3;
peers[peerTest].put(Number160.createHash(1000)).data(new Data("Test")).start().awaitUninterruptibly();
for (int i = 0; i < nrPeers; i++) {
for (Data d : peers[i].storageLayer().get().values())
System.out.println("peer[" + i + "]: " + d.object().toString() + " ");
}
FutureDone<Void> futureShutdown = peers[peerTest].peer().announceShutdown().start();
futureShutdown.awaitUninterruptibly();
// we need to wait a bit, since the quit RPC is a fire and forget
// and we return immediately
Thread.sleep(2000);
peers[peerTest].shutdown().awaitUninterruptibly();
System.out.println("peer " + peerTest + " is shutdown");
for (int i = 0; i < nrPeers; i++) {
for (Data d : peers[i].storageLayer().get().values())
System.out.println("peer[" + i + "]: " + d.object().toString() + " ");
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutPreparePutConfirmGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put data with a prepare flag
Data data = new Data("test").prepareFlag();
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
Number160 versionKey = Number160.createHash("version");
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey).data(contentKey, data)
.domainKey(domainKey).versionKey(versionKey).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
// get shouldn't see provisional put
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).versionKey(versionKey).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isEmpty());
// confirm prepared put
Data tmp = new Data();
FuturePut fputConfirm = peers[rnd.nextInt(10)].put(locationKey).data(contentKey, tmp)
.domainKey(domainKey).versionKey(versionKey).putConfirm().start();
fputConfirm.awaitUninterruptibly();
fputConfirm.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fputConfirm.isSuccess());
// get should see confirmed put
fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey).contentKey(contentKey)
.versionKey(versionKey).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(data.object(), fget.data().object());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
/**
* .../2b../4b-5b../7b..................................
* .....................................................
* 0-1-2a-3-4a-5a-6-7a..................................
*
* result should be 2b, 5b, 7a, 7b
*/
@Test
public void testGetLatestVersion1() throws Exception {
// create test data
NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>();
String content0 = generateRandomString();
Number160 vKey0 = generateVersionKey(0, content0);
Data data0 = new Data(content0);
sortedMap.put(vKey0, data0);
String content1 = generateRandomString();
Number160 vKey1 = generateVersionKey(1, content1);
Data data1 = new Data(content1);
data1.addBasedOn(vKey0);
sortedMap.put(vKey1, data1);
String content2a = generateRandomString();
Number160 vKey2a = generateVersionKey(2, content2a);
Data data2a = new Data(content2a);
data2a.addBasedOn(vKey1);
sortedMap.put(vKey2a, data2a);
String content2b = generateRandomString();
Number160 vKey2b = generateVersionKey(2, content2b);
Data data2b = new Data(content2b);
data2b.addBasedOn(vKey1);
sortedMap.put(vKey2b, data2b);
String content3 = generateRandomString();
Number160 vKey3 = generateVersionKey(3, content3);
Data data3 = new Data(content3);
data3.addBasedOn(vKey2a);
sortedMap.put(vKey3, data3);
String content4a = generateRandomString();
Number160 vKey4a = generateVersionKey(4, content4a);
Data data4a = new Data(content4a);
data4a.addBasedOn(vKey3);
sortedMap.put(vKey4a, data4a);
String content4b = generateRandomString();
Number160 vKey4b = generateVersionKey(4, content4b);
Data data4b = new Data(content4b);
data4b.addBasedOn(vKey3);
sortedMap.put(vKey4b, data4b);
String content5a = generateRandomString();
Number160 vKey5a = generateVersionKey(5, content5a);
Data data5a = new Data(content5a);
data5a.addBasedOn(vKey4a);
sortedMap.put(vKey5a, data5a);
String content5b = generateRandomString();
Number160 vKey5b = generateVersionKey(5, content5b);
Data data5b = new Data(content5b);
data5b.addBasedOn(vKey4b);
sortedMap.put(vKey5b, data5b);
String content6 = generateRandomString();
Number160 vKey6 = generateVersionKey(6, content6);
Data data6 = new Data(content6);
data6.addBasedOn(vKey5a);
sortedMap.put(vKey6, data6);
String content7a = generateRandomString();
Number160 vKey7a = generateVersionKey(7, content7a);
Data data7a = new Data(content7a);
data7a.addBasedOn(vKey6);
sortedMap.put(vKey7a, data7a);
String content7b = generateRandomString();
Number160 vKey7b = generateVersionKey(7, content7b);
Data data7b = new Data(content7b);
data7b.addBasedOn(vKey6);
sortedMap.put(vKey7b, data7b);
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put test data
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
for (Number160 vKey : sortedMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey)
.data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey)
.start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
}
// get latest versions
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// check result
Map<Number640, Data> dataMap = fget.dataMap();
Assert.assertEquals(4, dataMap.size());
Number480 key480 = new Number480(locationKey, domainKey, contentKey);
Number640 key2b = new Number640(key480, vKey2b);
Assert.assertTrue(dataMap.containsKey(key2b));
Assert.assertEquals(data2b.object(), dataMap.get(key2b).object());
Number640 key5b = new Number640(key480, vKey5b);
Assert.assertTrue(dataMap.containsKey(key5b));
Assert.assertEquals(data5b.object(), dataMap.get(key5b).object());
Number640 key7a = new Number640(key480, vKey7a);
Assert.assertTrue(dataMap.containsKey(key7a));
Assert.assertEquals(data7a.object(), dataMap.get(key7a).object());
Number640 key7b = new Number640(key480, vKey7b);
Assert.assertTrue(dataMap.containsKey(key7b));
Assert.assertEquals(data7b.object(), dataMap.get(key7b).object());
// get latest versions with digest
FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().withDigest().start();
fgetWithDigest.awaitUninterruptibly();
Assert.assertTrue(fgetWithDigest.isSuccess());
// check digest result
DigestResult digestResult = fgetWithDigest.digest();
Assert.assertEquals(12, digestResult.keyDigest().size());
for (Number160 vKey : sortedMap.keySet()) {
Number640 key = new Number640(locationKey, domainKey, contentKey, vKey);
Assert.assertTrue(digestResult.keyDigest().containsKey(key));
Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest()
.get(key).size());
for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) {
Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey));
}
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
/**
* .........../5c.......................................
* .....................................................
* .../2b../4b-5b./6b...................................
* .....................................................
* 0-1-2a-3-4a-5a.-6a-7.................................
*
* result should be 2b, 5b, 5c, 6b, 7
*/
@Test
public void testGetLatestVersion2() throws Exception {
NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>();
String content0 = generateRandomString();
Number160 vKey0;
vKey0 = generateVersionKey(0, content0);
Data data0 = new Data(content0);
sortedMap.put(vKey0, data0);
String content1 = generateRandomString();
Number160 vKey1 = generateVersionKey(1, content1);
Data data1 = new Data(content1);
data1.addBasedOn(vKey0);
sortedMap.put(vKey1, data1);
String content2a = generateRandomString();
Number160 vKey2a = generateVersionKey(2, content2a);
Data data2a = new Data(content2a);
data2a.addBasedOn(vKey1);
sortedMap.put(vKey2a, data2a);
String content2b = generateRandomString();
Number160 vKey2b = generateVersionKey(2, content2b);
Data data2b = new Data(content2b);
data2b.addBasedOn(vKey1);
sortedMap.put(vKey2b, data2b);
String content3 = generateRandomString();
Number160 vKey3 = generateVersionKey(3, content3);
Data data3 = new Data(content3);
data3.addBasedOn(vKey2a);
sortedMap.put(vKey3, data3);
String content4a = generateRandomString();
Number160 vKey4a = generateVersionKey(4, content4a);
Data data4a = new Data(content4a);
data4a.addBasedOn(vKey3);
sortedMap.put(vKey4a, data4a);
String content4b = generateRandomString();
Number160 vKey4b = generateVersionKey(4, content4b);
Data data4b = new Data(content4b);
data4b.addBasedOn(vKey3);
sortedMap.put(vKey4b, data4b);
String content5a = generateRandomString();
Number160 vKey5a = generateVersionKey(5, content5a);
Data data5a = new Data(content5a);
data5a.addBasedOn(vKey4a);
sortedMap.put(vKey5a, data5a);
String content5b = generateRandomString();
Number160 vKey5b = generateVersionKey(5, content5b);
Data data5b = new Data(content5b);
data5b.addBasedOn(vKey4b);
sortedMap.put(vKey5b, data5b);
String content5c = generateRandomString();
Number160 vKey5c = generateVersionKey(5, content5c);
Data data5c = new Data(content5c);
data5c.addBasedOn(vKey4b);
sortedMap.put(vKey5c, data5c);
String content6a = generateRandomString();
Number160 vKey6a = generateVersionKey(6, content6a);
Data data6a = new Data(content6a);
data6a.addBasedOn(vKey5a);
sortedMap.put(vKey6a, data6a);
String content6b = generateRandomString();
Number160 vKey6b = generateVersionKey(6, content6b);
Data data6b = new Data(content6b);
data6b.addBasedOn(vKey5a);
sortedMap.put(vKey6b, data6b);
String content7 = generateRandomString();
Number160 vKey7 = generateVersionKey(7, content7);
Data data7 = new Data(content7);
data7.addBasedOn(vKey6a);
sortedMap.put(vKey7, data7);
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put test data
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
for (Number160 vKey : sortedMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey)
.data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey)
.start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
}
// get latest versions
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// check result
Map<Number640, Data> dataMap = fget.dataMap();
Assert.assertEquals(5, dataMap.size());
Number480 key480 = new Number480(locationKey, domainKey, contentKey);
Number640 key2b = new Number640(key480, vKey2b);
Assert.assertTrue(dataMap.containsKey(key2b));
Assert.assertEquals(data2b.object(), dataMap.get(key2b).object());
Number640 key5b = new Number640(key480, vKey5b);
Assert.assertTrue(dataMap.containsKey(key5b));
Assert.assertEquals(data5b.object(), dataMap.get(key5b).object());
Number640 key5c = new Number640(key480, vKey5c);
Assert.assertTrue(dataMap.containsKey(key5c));
Assert.assertEquals(data5c.object(), dataMap.get(key5c).object());
Number640 key6b = new Number640(key480, vKey6b);
Assert.assertTrue(dataMap.containsKey(key6b));
Assert.assertEquals(data6b.object(), dataMap.get(key6b).object());
Number640 key7 = new Number640(key480, vKey7);
Assert.assertTrue(dataMap.containsKey(key7));
Assert.assertEquals(data7.object(), dataMap.get(key7).object());
// get latest versions with digest
FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().withDigest().start();
fgetWithDigest.awaitUninterruptibly();
Assert.assertTrue(fgetWithDigest.isSuccess());
// check digest result
DigestResult digestResult = fgetWithDigest.digest();
Assert.assertEquals(13, digestResult.keyDigest().size());
for (Number160 vKey : sortedMap.keySet()) {
Number640 key = new Number640(locationKey, domainKey, contentKey, vKey);
Assert.assertTrue(digestResult.keyDigest().containsKey(key));
Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest()
.get(key).size());
for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) {
Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey));
}
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
/**
* 0-1-2
*
* result should return version 2
*/
@Test
public void testGetLatestVersion3() throws Exception {
NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>();
String content0 = generateRandomString();
Number160 vKey0;
vKey0 = generateVersionKey(0, content0);
Data data0 = new Data(content0);
sortedMap.put(vKey0, data0);
String content1 = generateRandomString();
Number160 vKey1 = generateVersionKey(1, content1);
Data data1 = new Data(content1);
data1.addBasedOn(vKey0);
sortedMap.put(vKey1, data1);
String content2 = generateRandomString();
Number160 vKey2 = generateVersionKey(2, content2);
Data data2 = new Data(content2);
data2.addBasedOn(vKey1);
sortedMap.put(vKey2, data2);
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put test data
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
for (Number160 vKey : sortedMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey)
.data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey)
.start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
}
// get latest versions
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// check result
Map<Number640, Data> dataMap = fget.dataMap();
Assert.assertEquals(1, dataMap.size());
Number480 key480 = new Number480(locationKey, domainKey, contentKey);
Number640 key2 = new Number640(key480, vKey2);
Assert.assertTrue(dataMap.containsKey(key2));
Assert.assertEquals(data2.object(), dataMap.get(key2).object());
// get latest versions with digest
FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().withDigest().start();
fgetWithDigest.awaitUninterruptibly();
Assert.assertTrue(fgetWithDigest.isSuccess());
// check digest result
DigestResult digestResult = fgetWithDigest.digest();
Assert.assertEquals(3, digestResult.keyDigest().size());
for (Number160 vKey : sortedMap.keySet()) {
Number640 key = new Number640(locationKey, domainKey, contentKey, vKey);
Assert.assertTrue(digestResult.keyDigest().containsKey(key));
Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest()
.get(key).size());
for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) {
Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey));
}
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testShutdown3Peers() throws IOException, ClassNotFoundException {
//create 3 peers, store data, shut one peer down, joins -> data should be there
PeerMapConfiguration pmc = new PeerMapConfiguration(Number160.createHash( "1" ) ).peerNoVerification();
PeerMap pm = new PeerMap(pmc);
PeerDHT peer1 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "1" ) ).peerMap( pm ).ports( 3000 ).start() ).start();
PeerDHT peer2 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "2" ) ).ports( 3001 ).start() ).start();
PeerDHT peer3 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "3" ) ).ports( 3002 ).start() ).start();
BaseFuture fb1 = peer2.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
BaseFuture fb2 = peer3.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
Assert.assertTrue( fb1.isSuccess() );
Assert.assertTrue( fb2.isSuccess() );
FuturePut fp = peer2.put( Number160.ONE ).object( "test" ).start().awaitUninterruptibly();
Assert.assertTrue( fp.isSuccess() );
peer2.shutdown().awaitUninterruptibly();
peer2 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "2" ) ).ports( 3001 ).start() ).start();
BaseFuture fb3 = peer2.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
Assert.assertTrue( fb3.isSuccess() );
FutureGet fg1 = peer2.get( Number160.ONE ).start().awaitUninterruptibly();
Assert.assertTrue( fg1.isSuccess() );
Assert.assertEquals( "test", fg1.data().object() );
peer3.shutdown().awaitUninterruptibly();
peer3 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "3" ) ).ports( 3002 ).start() ).start();
BaseFuture fb4 = peer3.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
Assert.assertTrue( fb4.isSuccess() );
FutureGet fg2 = peer3.get( Number160.ONE ).start().awaitUninterruptibly();
Assert.assertTrue( fg2.isSuccess() );
Assert.assertEquals( "test", fg2.data().object() );
}
private static String generateRandomString() {
return UUID.randomUUID().toString();
}
private static Number160 generateVersionKey(long basedOnCounter, Serializable object) throws IOException {
// get a MD5 hash of the object itself
byte[] hash = generateMD5Hash(serializeObject(object));
return new Number160(basedOnCounter, new Number160(Arrays.copyOf(hash, Number160.BYTE_ARRAY_SIZE)));
}
private static byte[] generateMD5Hash(byte[] data) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
}
md.reset();
md.update(data, 0, data.length);
return md.digest();
}
private static byte[] serializeObject(Serializable object) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
byte[] result = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
result = baos.toByteArray();
} catch (IOException e) {
throw e;
} finally {
try {
if (oos != null)
oos.close();
if (baos != null)
baos.close();
} catch (IOException e) {
throw e;
}
}
return result;
}
public static PeerDHT[] createNodesWithShortId(int nrOfPeers, Random rnd, int port, AutomaticFuture automaticFuture) throws Exception {
if (nrOfPeers < 1) {
throw new IllegalArgumentException("Cannot create less than 1 peer");
}
final Peer master;
PeerDHT[] peers = new PeerDHT[nrOfPeers];
if (automaticFuture != null) {
master = new PeerBuilder(new Number160(1111))
.ports(port).start().addAutomaticFuture(automaticFuture);
peers[0] = new PeerBuilderDHT(master).start();
} else {
master = new PeerBuilder(new Number160(1111)).ports(port)
.start();
peers[0] = new PeerBuilderDHT(master).start();
}
for (int i = 1; i < nrOfPeers; i++) {
if (automaticFuture != null) {
Peer peer = new PeerBuilder(new Number160(i))
.masterPeer(master).start().addAutomaticFuture(automaticFuture);
peers[i] = new PeerBuilderDHT(peer).start();
} else {
Peer peer = new PeerBuilder(new Number160(i))
.masterPeer(master).start();
peers[i] = new PeerBuilderDHT(peer).start();
}
}
System.out.println("peers created.");
return peers;
}
private void send2(final PeerDHT p1, final PeerDHT p2, final ByteBuf toStore1, final int count) throws IOException {
if (count == 0) {
return;
}
Buffer b = new Buffer(toStore1);
FutureDirect fd = p1.peer().sendDirect(p2.peerAddress()).buffer(b).start();
fd.addListener(new BaseFutureAdapter<FutureDirect>() {
@Override
public void operationComplete(FutureDirect future) throws Exception {
if (future.isFailed()) {
// System.out.println(future.getFailedReason());
send2(p1, p2, toStore1, count - 1);
}
}
});
}
private void send1(final PeerDHT p1, final PeerDHT p2, final byte[] toStore1, final int count) throws IOException {
if (count == 0) {
return;
}
FutureDirect fd = p1.peer().sendDirect(p2.peerAddress()).object(toStore1).start();
fd.addListener(new BaseFutureAdapter<FutureDirect>() {
@Override
public void operationComplete(FutureDirect future) throws Exception {
if (future.isFailed()) {
//System.out.println(future.getFailedReason());
send1(p1, p2, toStore1, count - 1);
}
}
});
}
private void testForArray(PeerDHT peer, Number160 locationKey, boolean find) {
Collection<Number160> tmp = new ArrayList<Number160>();
tmp.add(new Number160(5));
Number640 min = new Number640(locationKey, Number160.createHash("test"), Number160.ZERO, Number160.ZERO);
Number640 max = new Number640(locationKey, Number160.createHash("test"), Number160.MAX_VALUE,
Number160.MAX_VALUE);
Map<Number640, Data> test = peer.storageLayer().get(min, max, -1, true);
if (find) {
Assert.assertEquals(1, test.size());
Assert.assertEquals(
44444,
test.get(
new Number640(new Number320(locationKey, Number160.createHash("test")), new Number160(5),
Number160.ZERO)).length());
} else
Assert.assertEquals(0, test.size());
}
}
|
package com.sometrik.framework;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.android.trivialdrivesample.util.IabHelper;
import com.android.trivialdrivesample.util.IabHelper.IabAsyncInProgressException;
import com.android.trivialdrivesample.util.IabResult;
import com.android.trivialdrivesample.util.Inventory;
import com.android.trivialdrivesample.util.Purchase;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.ScrollView;
import android.widget.Toast;
public class NativeCommand {
private int internalId = 0;
private int childInternalId = 0;
private int value = 0;
private int flags = 0;
private byte[] byteArray;
private byte[] byteArray2;
private CommandType command;
private String key;
private FrameWork frame;
private ArrayList<PopupMenu> menuList = new ArrayList<PopupMenu>();
private int rowNumber = -1;
private int columnNumber = -1;
private int sheet = 0;
private int width = 0;
private int height = 0;
private final int FLAG_PADDING_LEFT = 1;
private final int FLAG_PADDING_RIGHT = 2;
private final int FLAG_PADDING_TOP = 4;
private final int FLAG_PADDING_BOTTOM = 8;
private final int FLAG_PASSWORD = 16;
private final int FLAG_NUMERIC = 32;
private final int FLAG_HYPERLINK = 64;
private final int FLAG_USE_PURCHASES_API = 128;
private final int FLAG_SLIDERVIEW = 256;
private final int FLAG_STICKY_HEADER = 512;
public enum CommandType {
CREATE_APPLICATION,
CREATE_BASICVIEW,
CREATE_FORMVIEW,
CREATE_NAVIGATIONVIEW,
CREATE_OPENGL_VIEW,
CREATE_TEXTFIELD, // For viewing single value
CREATE_TEXTVIEW, // For viewing multiline text
CREATE_LISTVIEW, // For viewing lists
CREATE_SIMPLELISTVIEW,
CREATE_GRIDVIEW, // For viewing tables
CREATE_BUTTON,
CREATE_SWITCH,
CREATE_PICKER, // called Spinner in Android
CREATE_LINEAR_LAYOUT,
CREATE_RELATIVE_LAYOUT,
CREATE_TABLE_LAYOUT,
CREATE_AUTO_COLUMN_LAYOUT,
CREATE_PANEL,
CREATE_TEXT,
CREATE_DIALOG,
CREATE_IMAGEVIEW,
CREATE_ACTION_SHEET,
CREATE_CHECKBOX,
CREATE_RADIO_GROUP,
CREATE_SEPARATOR,
CREATE_SLIDER,
CREATE_ACTIONBAR,
CREATE_NAVIGATIONBAR,
CREATE_TOAST,
DELETE_ELEMENT,
END_MODAL,
SHOW_DIALOG,
SHOW_MESSAGE_DIALOG,
SHOW_INPUT_DIALOG,
SHOW_ACTION_SHEET,
LAUNCH_BROWSER,
HISTORY_GO_BACK,
HISTORY_GO_FORWARD,
CLEAR,
SET_INT_VALUE, // Sets value of radio groups, checkboxes and pickers
SET_TEXT_VALUE, // Sets value of textfields, labels and images
SET_INT_DATA,
SET_TEXT_DATA,
SET_LABEL, // Sets label for buttons and checkboxes
SET_ENABLED,
SET_READONLY,
SET_VISIBILITY,
SET_SHAPE, // Specifies the number of rows and columns in a GridView
SET_STYLE,
SET_ERROR,
SET_IMAGE,
FLUSH_VIEW,
UPDATE_PREFERENCE,
COMMIT_PREFERENCES,
ADD_OPTION,
ADD_SHEET,
ADD_COLUMN,
RESHAPE_TABLE,
RESHAPE_SHEET,
QUIT_APP,
// Timers
CREATE_TIMER,
// In-app purchases
LIST_PRODUCTS,
BUY_PRODUCT,
LIST_PURCHASES,
CONSUME_PURCHASE
}
public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags, int row, int column, int sheet, int width, int height){
this.frame = frame;
command = CommandType.values()[messageTypeId];
this.internalId = internalId;
this.childInternalId = childInternalId;
this.value = value;
this.flags = flags;
this.rowNumber = row;
this.columnNumber = column;
this.sheet = sheet;
this.width = width;
this.height = height;
byteArray = textValue;
byteArray2 = textValue2;
}
public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags){
this.frame = frame;
command = CommandType.values()[messageTypeId];
this.internalId = internalId;
this.childInternalId = childInternalId;
this.value = value;
this.flags = flags;
byteArray = textValue;
byteArray2 = textValue2;
}
private String getTextValueAsString() {
if (byteArray != null) {
return new String(byteArray, frame.getCharset());
} else {
return "";
}
}
private byte[] getTextValueAsBinary() {
return byteArray;
}
private String getTextValue2AsString() {
if (byteArray2 != null) {
return new String(byteArray2, frame.getCharset());
} else {
return "";
}
}
private byte[] getTextValue2AsBinary() {
return byteArray2;
}
public void apply(NativeCommandHandler view) {
// System.out.println("Processing message " + command + " id: " + internalId + " Child id: " + getChildInternalId());
switch (command) {
case CREATE_FORMVIEW:
FWScrollView scrollView = new FWScrollView(frame, getTextValueAsString());
scrollView.setId(getChildInternalId());
scrollView.setBackground(frame.getResources().getDrawable(android.R.drawable.screen_background_light));
FrameWork.addToViewList(scrollView);
if (view == null){
System.out.println("view was null");
if (frame.getCurrentViewId() == 0){
scrollView.setValue(2);
}
} else {
view.addChild(scrollView);
}
break;
case CREATE_NAVIGATIONVIEW:
NavigationLayout navigationLayout = new NavigationLayout(frame);
navigationLayout.setId(getChildInternalId());
FrameWork.addToViewList(navigationLayout);
if (frame.getCurrentDrawerViewId() == 0){
System.out.println("setting current navigationDrawer to " + getChildInternalId());
frame.setCurrentDrawerViewId(getChildInternalId());
}
break;
case CREATE_BASICVIEW:
case CREATE_LINEAR_LAYOUT:
case CREATE_PANEL: {
FWLayout layout = createLinearLayout();
if (view != null) {
view.addChild(layout);
}
break;
}
case CREATE_RELATIVE_LAYOUT: {
FWRelativeLayout layout = new FWRelativeLayout(frame);
layout.setId(getChildInternalId());
FrameWork.addToViewList(layout);
view.addChild(layout);
break;
}
case CREATE_AUTO_COLUMN_LAYOUT:{
FWAuto auto = new FWAuto(frame);
auto.setId(getChildInternalId());
FrameWork.addToViewList(auto);
view.addChild(auto);
}
break;
case CREATE_TABLE_LAYOUT:
FWTable table = createTableLayout(false);
view.addChild(table);
break;
case CREATE_BUTTON:
FWButton button = createButton();
view.addChild(button);
break;
case CREATE_PICKER:
FWPicker picker = createSpinner();
view.addChild(picker);
break;
case CREATE_SWITCH:
FWSwitch click = createSwitch();
view.addChild(click);
break;
case CLEAR:
view.clear();
break;
case CREATE_GRIDVIEW:
//TODO
//Fix from being debug status
// FWLayout debugList = createDebugResultsScreen();
FWList debugList = new FWList(frame, new FWAdapter2(frame, null));
debugList.setId(childInternalId);
FrameWork.addToViewList(debugList);
view.addChild(debugList);
break;
case CREATE_SIMPLELISTVIEW:{
FWScrollView simpleListScroller = new FWScrollView(frame);
simpleListScroller.setFillViewport(true);
FWSimpleList simpleList = new FWSimpleList(frame);
final float scale = frame.getResources().getDisplayMetrics().density;
int widthPixels = (int) (350 * scale + 0.5f);
int heightPixels = (int) (300 * scale + 0.5f);
simpleListScroller.setMaxHeight(450);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(widthPixels, LinearLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
simpleListScroller.setLayoutParams(params);
simpleListScroller.addView(simpleList);
simpleList.setLayoutParams(params2);
simpleList.setId(childInternalId);
view.addChild(simpleListScroller);
FrameWork.addToViewList(simpleList);
break;
}
case CREATE_LISTVIEW:
if (isSet(FLAG_SLIDERVIEW)) {
// Real slider stuff
SliderLayout slider = new SliderLayout(frame);
slider.setId(childInternalId);
FrameWork.addToViewList(slider);
view.addChild(slider);
} else {
FWList listView = new FWList(frame, new FWAdapter2(frame, null));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
// params.gravity = Gravity.TOP;
listView.setLayoutParams(params);
listView.setId(childInternalId);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int groupPosition, long id) {
System.out.println("row clicked. Sending intChangedEvent of " + (groupPosition - 1));
frame.intChangedEvent(System.currentTimeMillis() / 1000.0, childInternalId, (groupPosition - 1), 0);
}
});
FrameWork.addToViewList(listView);
view.addChild(listView);
}
break;
case CREATE_TIMER:
Timer timer = new Timer();
timer.scheduleAtFixedRate((new TimerTask() {
@Override
public void run() {
FrameWork.timerEvent(System.currentTimeMillis() / 1000, internalId, childInternalId);
}
}), 1000, 1000);
break;
case CREATE_CHECKBOX:
FWCheckBox checkBox = createCheckBox();
FrameWork.addToViewList(checkBox);
view.addChild(checkBox);
break;
case CREATE_OPENGL_VIEW:
frame.createNativeOpenGLView(childInternalId);
break;
case CREATE_TEXTVIEW:
FWEditText editTextView = createBigEditText();
view.addChild(editTextView);
break;
case CREATE_TEXTFIELD:
FWEditText editText = createEditText();
view.addChild(editText);
break;
case CREATE_RADIO_GROUP:
FWRadioGroup radioGroup = new FWRadioGroup(frame);
radioGroup.setId(childInternalId);
break;
case CREATE_TEXT:
FWTextView textView = createTextView();
view.addChild(textView);
break;
case CREATE_IMAGEVIEW:
FWImageView imageView = new FWImageView(frame);
imageView.setId(childInternalId);
if (getTextValueAsString() != null && getTextValueAsString() != "") {
imageView.setImageFromAssets(getTextValueAsString());
}
// imageView.setImage(getTextValueAsBinary());
FrameWork.addToViewList(imageView);
view.addChild(imageView);
break;
case CREATE_TOAST:
Toast toast = Toast.makeText(frame, getTextValueAsString(), getValue() != 0 ? getValue() : 2);
toast.show();
break;
case ADD_OPTION:
view.addOption(getValue(), getTextValueAsString());
break;
case ADD_COLUMN:
view.addColumn(getTextValueAsString(), getValue());
break;
case ADD_SHEET:
System.out.println("add_sheet: " + getTextValueAsString() + " " + rowNumber + " " + columnNumber + " " + sheet);
view.setValue(getTextValueAsString());
break;
case CREATE_APPLICATION:
frame.setAppId(getChildInternalId());
if (isSet(FLAG_USE_PURCHASES_API)) {
System.out.println("Initializing purchaseHelper");
frame.initializePurchaseHelper(getTextValue2AsString(), new IabHelper.OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
System.out.println("PurchaseHelper successfully setup");
sendInventory(frame.getPurchaseHelperInventory());
} else {
System.out.println("PurchaseHelper failed to setup");
}
}
});
}
break;
case SET_INT_VALUE:
view.setValue(getValue());
break;
case SET_TEXT_VALUE:
view.setValue(getTextValueAsString());
break;
case SET_TEXT_DATA:
System.out.println("set_text_data: " + getTextValueAsString() + " " + rowNumber + " " + columnNumber + " " + sheet);
view.addData(getTextValueAsString(), rowNumber, columnNumber, sheet);
break;
case SET_VISIBILITY:
if (view != null) {
view.setViewVisibility(value != 0);
}
break;
case SET_ENABLED:
view.setViewEnabled(value != 0);
break;
case SET_STYLE:
view.setStyle(getTextValueAsString(), getTextValue2AsString());
break;
case SET_LABEL:
frame.actionBar.setValue(getTextValueAsString());
break;
case SET_ERROR:
view.setError(value != 0, getTextValueAsString());
break;
case SET_IMAGE:
switch (value) {
case 3:
view.setImage(byteArray, width, height, Bitmap.Config.RGB_565);
break;
case 5: case 6:
view.setImage(byteArray, width, height, Bitmap.Config.ARGB_8888);
break;
default:
System.out.println("ERROR: unable to display format " + value);
}
break;
case LAUNCH_BROWSER:
frame.launchBrowser(getTextValueAsString());
break;
case END_MODAL:
view.setValue(0);
break;
case SHOW_DIALOG:
view.setValue(1);
break;
case SHOW_MESSAGE_DIALOG:
showMessageDialog(getTextValueAsString(), getTextValue2AsString());
break;
case SHOW_INPUT_DIALOG:
showInputDialog(getTextValueAsString(), getTextValue2AsString());
break;
case CREATE_DIALOG:
FWDialog dialog = new FWDialog(frame, childInternalId);
dialog.setTitle(getTextValueAsString());
FrameWork.addToViewList(dialog);
break;
case CREATE_ACTION_SHEET:
createActionSheet();
break;
case CREATE_ACTIONBAR:
FWActionBar ab = new FWActionBar(frame, getTextValueAsString(), childInternalId);
frame.actionBar = ab;
FrameWork.addToViewList(ab);
break;
case CREATE_NAVIGATIONBAR:
NavigationBar bar = new NavigationBar(frame);
bar.setId(childInternalId);
view.addChild(bar);
FrameWork.addToViewList(bar);
case FLUSH_VIEW:
view.flush();
break;
case QUIT_APP:
// TODO
frame.finish();
break;
case UPDATE_PREFERENCE: // Now stores String value to string key
System.out.println("UPDATE_PREFERENCE: " + getTextValueAsString() + " " + getTextValue2AsString());
frame.getPreferencesEditor().putString(getTextValueAsString(), getTextValue2AsString());
break;
case COMMIT_PREFERENCES:
frame.getPreferencesEditor().apply();
break;
case DELETE_ELEMENT:
deleteElement(view, childInternalId);
break;
case BUY_PRODUCT:
try {
launchPurchase(getTextValueAsString());
} catch (IabAsyncInProgressException e) {
e.printStackTrace();
System.out.println("Error on launchPurchase with message: " + e.getMessage());
}
break;
case RESHAPE_SHEET:
view.reshape(sheet, value);
break;
case RESHAPE_TABLE:
System.out.println("reshape table: " + value);
view.reshape(value);
break;
default:
System.out.println("Command couldn't be handled " + command + " id: " + internalId + " Child id: " + getChildInternalId());
break;
}
}
private void createActionSheet(){
PopupMenu menu = new PopupMenu(frame, null);
menu.setOnMenuItemClickListener(new OnMenuItemClickListener(){
@Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
menuList.add(menu);
}
private FWTable createTableLayout(boolean autoSize){
FWTable table = new FWTable(frame);
table.setId(getChildInternalId());
if (autoSize){
table.setAutoSize(true);
} else {
Log.d("table", "ALERT " + value);
table.setColumnCount(value);
}
table.setStretchAllColumns(true);
table.setShrinkAllColumns(true);
FrameWork.addToViewList(table);
return table;
}
private FWSwitch createSwitch() {
FWSwitch click = new FWSwitch(frame);
click.setId(childInternalId);
if (getTextValueAsString() != "") {
click.setTextOn(getTextValueAsString());
}
if (getTextValue2AsString() != "") {
click.setTextOff(getTextValue2AsString());
}
click.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
frame.intChangedEvent(System.currentTimeMillis() / 1000.0, buttonView.getId(), isChecked ? 1 : 0, 0);
}
});
FrameWork.addToViewList(click);
return click;
}
private void deleteElement(NativeCommandHandler parent, int childId) {
FrameWork.views.remove(childInternalId);
if (parent instanceof ViewGroup) {
ViewGroup group = (ViewGroup) parent;
int childCount = group.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = group.getChildAt(i);
if (view.getId() == childInternalId) {
((ViewGroup) parent).removeViewAt(i);
break;
}
}
} else {
System.out.println("Deletion parent was not an instance of ViewGroup");
}
}
private ImageView createImageView() {
ImageView imageView = new ImageView(frame);
imageView.setId(childInternalId);
try {
InputStream is = frame.getAssets().open(getTextValueAsString());
Bitmap bitmap = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bitmap);
return imageView;
} catch (IOException e) {
e.printStackTrace();
System.out.println("error loading asset file to imageView");
System.exit(1);
}
return null;
}
private FWLayout createLinearLayout() {
FWLayout layout = new FWLayout(frame);
layout.setId(getChildInternalId());
FrameWork.addToViewList(layout);
if (getValue() == 2) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.weight = 1.0f;
layout.setLayoutParams(params);
layout.setOrientation(LinearLayout.HORIZONTAL);
} else {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
layout.setLayoutParams(params);
layout.setOrientation(LinearLayout.VERTICAL);
}
return layout;
}
private FWButton createButton() {
FWButton button = new FWButton(frame);
button.setId(getChildInternalId());
button.setText(getTextValueAsString());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// params.weight = 1;
// params.gravity = Gravity.BOTTOM;
button.setLayoutParams(params);
FrameWork.addToViewList(button);
return button;
}
private FWEditText createEditText(){
final FWEditText editText = new FWEditText(frame);
editText.setId(getChildInternalId());
editText.setText(getTextValueAsString());
// editText.setMinWidth(80);
editText.setSingleLine();
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
if (isSet(FLAG_PASSWORD) && isSet(FLAG_NUMERIC)){
editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
} else if (isSet(FLAG_PASSWORD)) {
editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else if (isSet(FLAG_NUMERIC)){
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
}
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {
String inputText = editable.toString();
byte[] b = inputText.getBytes(frame.getCharset());
frame.textChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), b);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
FrameWork.addToViewList(editText);
return editText;
}
private FWEditText createBigEditText() {
final FWEditText editText = new FWEditText(frame);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
editText.setMinLines(4);
editText.setLayoutParams(params);
editText.setId(getChildInternalId());
editText.setText(getTextValueAsString());
editText.setVerticalScrollBarEnabled(true);
editText.setMovementMethod(new ScrollingMovementMethod());
editText.addDelayedChangeListener(getChildInternalId());
FrameWork.addToViewList(editText);
return editText;
}
private FWPicker createSpinner(){
FWPicker picker = new FWPicker(frame);
picker.setId(getChildInternalId());
FrameWork.addToViewList(picker);
return picker;
}
private FWCheckBox createCheckBox() {
FWCheckBox checkBox = new FWCheckBox(frame);
checkBox.setPadding(0, 0, 10, 0);
checkBox.setId(childInternalId);
if (getTextValueAsString() != "") {
checkBox.setText(getTextValueAsString());
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton box, boolean isChecked) {
frame.intChangedEvent(System.currentTimeMillis() / 1000.0, childInternalId, isChecked ? 1 : 0, 0);
}
});
return checkBox;
}
private FWTextView createTextView() {
FWTextView textView = new FWTextView(frame);
textView.setId(getChildInternalId());
if (isSet(FLAG_HYPERLINK)) {
textView.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='" + getTextValue2AsString() + "'>" + getTextValueAsString() + "</a>";
textView.setText(Html.fromHtml(text));
} else {
textView.setText(getTextValueAsString());
}
FrameWork.addToViewList(textView);
return textView;
}
// Create dialog with user text input
private void showInputDialog(String title, String message) {
System.out.println("Creating input dialog");
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(frame);
// Building an alert
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(true);
final EditText input = new EditText(frame);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
frame.endModal(System.currentTimeMillis() / 1000.0, 0, null);
}
});
// Negative button listener
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
frame.endModal(System.currentTimeMillis() / 1000.0, 0, null);
dialog.dismiss();
}
});
// Positive button listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String inputText = String.valueOf(input.getText());
byte[] b = inputText.getBytes(frame.getCharset());
frame.endModal(System.currentTimeMillis() / 1000.0, 1, b);
dialog.dismiss();
}
});
// Create and show the alert
AlertDialog alert = builder.create();
alert.show();
}
// create Message dialog
private void showMessageDialog(String title, String message) {
System.out.println("creating message dialog");
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(frame);
// Building an alert
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(true);
builder.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
frame.endModal(System.currentTimeMillis() / 1000.0, 0, null);
}
});
// Positive button listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
frame.endModal(System.currentTimeMillis() / 1000.0, 1, null);
dialog.dismiss();
}
});
// Create and show the alert
AlertDialog alert = builder.create();
alert.show();
System.out.println("message dialog created");
}
private void launchPurchase(final String productId) throws IabAsyncInProgressException {
// Sku = product id from google account
frame.getPurchaseHelper().launchPurchaseFlow(frame, productId, IabHelper.ITEM_TYPE_INAPP, null, 1, new IabHelper.OnIabPurchaseFinishedListener() {
@Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
if (result.isSuccess()) {
System.out.println("Purchase of product id " + productId + " completed");
FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), info.getSku(), true, info.getPurchaseTime() / 1000.0);
// TODO
} else {
System.out.println("Purchase of product id " + productId + " failed");
// TODO
}
}
}, "");
}
private void sendInventory(Inventory inventory) {
List<Purchase> purchaseList = inventory.getAllPurchases();
System.out.println("getting purchase history. Purchase child size: " + purchaseList.size());
for (Purchase purchase : inventory.getAllPurchases()) {
FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), purchase.getSku(), false, purchase.getPurchaseTime() / 1000.0);
}
}
private Boolean isSet(int flag) {
return (flags & flag) != 0;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public int getInternalId() {
return internalId;
}
public int getChildInternalId() {
return childInternalId;
}
public CommandType getCommand() {
return command;
}
public int getValue() {
return value;
}
}
|
package com.sometrik.framework;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.android.trivialdrivesample.util.IabHelper;
import com.android.trivialdrivesample.util.IabHelper.IabAsyncInProgressException;
import com.android.trivialdrivesample.util.IabResult;
import com.android.trivialdrivesample.util.Inventory;
import com.android.trivialdrivesample.util.Purchase;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TableLayout;
import android.widget.TextView;
public class NativeCommand {
private int internalId = 0;
private int childInternalId = 0;
private int value = 0;
private int flags = 0;
private String textValue = "";
private String textValue2 = "";
private CommandType command;
private String key;
private FrameWork frame;
private ArrayList<PopupMenu> menuList = new ArrayList<PopupMenu>();
private final int FLAG_PADDING_LEFT = 1;
private final int FLAG_PADDING_RIGHT = 2;
private final int FLAG_PADDING_TOP = 4;
private final int FLAG_PADDING_BOTTOM = 8;
private final int FLAG_PASSWORD = 16;
private final int FLAG_NUMERIC = 32;
private final int FLAG_HYPERLINK = 64;
private final int FLAG_USE_PURCHASES_API = 128;
public enum CommandType {
CREATE_PLATFORM,
CREATE_APPLICATION,
CREATE_BASICVIEW,
CREATE_FORMVIEW,
CREATE_OPENGL_VIEW,
CREATE_TEXTFIELD, // For viewing single value
CREATE_TEXTVIEW, // For viewing multiline text
CREATE_LISTVIEW, // For viewing lists
CREATE_GRIDVIEW, // For viewing tables
CREATE_BUTTON,
CREATE_SWITCH,
CREATE_PICKER, // called Spinner in Android
CREATE_LINEAR_LAYOUT,
CREATE_TABLE_LAYOUT,
CREATE_AUTO_COLUMN_LAYOUT,
CREATE_HEADING_TEXT,
CREATE_TEXT,
CREATE_DIALOG, // For future
CREATE_IMAGEVIEW,
CREATE_ACTION_SHEET,
CREATE_CHECKBOX,
CREATE_RADIO_GROUP,
CREATE_SEPARATOR,
CREATE_SLIDER,
CREATE_ACTIONBAR,
DELETE_ELEMENT,
SHOW_MESSAGE_DIALOG,
SHOW_INPUT_DIALOG,
SHOW_ACTION_SHEET,
LAUNCH_BROWSER,
POST_NOTIFICATION,
HISTORY_GO_BACK,
HISTORY_GO_FORWARD,
SET_INT_VALUE, // Sets value of radio groups, checkboxes and pickers
SET_TEXT_VALUE, // Sets value of textfields, labels and images
SET_LABEL, // Sets label for buttons and checkboxes
SET_ENABLED,
SET_STYLE,
SET_ERROR,
UPDATE_PREFERENCE,
ADD_OPTION,
QUIT_APP,
// Timers
CREATE_TIMER,
// In-app purchases
LIST_PRODUCTS,
BUY_PRODUCT,
LIST_PURCHASES,
CONSUME_PURCHASE
}
public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags){
this.frame = frame;
command = CommandType.values()[messageTypeId];
this.internalId = internalId;
this.childInternalId = childInternalId;
this.value = value;
this.flags = flags;
if (textValue != null) {
this.textValue = new String(textValue, Charset.forName("UTF-8"));
}
if (textValue2 != null) {
this.textValue2 = new String(textValue2, Charset.forName("UTF-8"));
}
}
public void apply(NativeCommandHandler view) {
System.out.println("Processing message " + command + " id: " + internalId + " Child id: " + getChildInternalId());
switch (command) {
case CREATE_FORMVIEW:
FWScrollView scrollView = new FWScrollView(frame);
scrollView.setId(getChildInternalId());
FrameWork.addToViewList(scrollView);
if (view == null){
System.out.println("view was null");
if (frame.getCurrentViewId() == 0){
scrollView.setValue(1);
}
} else {
view.addChild(scrollView);
}
break;
case CREATE_BASICVIEW:
case CREATE_LINEAR_LAYOUT:
FWLayout layout = createLinearLayout();
view.addChild(layout);
break;
case CREATE_AUTO_COLUMN_LAYOUT:
final FWGridView autoLayout = new FWGridView(frame);
autoLayout.setId(getChildInternalId());
autoLayout.setColumnWidth(200);
autoLayout.setNumColumns(GridView.AUTO_FIT);
autoLayout.setVerticalSpacing(0);
autoLayout.setHorizontalSpacing(0);
autoLayout.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
final FWAdapter adapteri = new FWAdapter(frame, new ArrayList<View>());
autoLayout.post(new Runnable() {
public void run() {
autoLayout.setAdapter(adapteri);
autoLayout.setupAdapter(adapteri);
}
});
// autoLayout.setAdapter(adapteri);
// FlowLayout autoLayout = new FlowLayout(frame, null);
// autoLayout.setId(getChildInternalId());
FrameWork.addToViewList(autoLayout);
view.addChild(autoLayout);
break;
case CREATE_TABLE_LAYOUT:
FWTable table = createTableLayout();
view.addChild(table);
break;
case CREATE_BUTTON:
FWButton button = createButton();
view.addChild(button);
break;
case CREATE_PICKER:
FWPicker picker = createSpinner();
view.addChild(picker);
break;
case CREATE_SWITCH:
FWSwitch click = createSwitch();
view.addChild(click);
break;
case CREATE_CHECKBOX:
FWCheckBox checkBox = new FWCheckBox(frame);
checkBox.setId(childInternalId);
if (textValue != "") {
checkBox.setText(textValue);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton box, boolean isChecked) {
frame.intChangedEvent(System.currentTimeMillis() / 1000.0, childInternalId, isChecked ? 1 : 0);
}
});
FrameWork.addToViewList(checkBox);
view.addChild(checkBox);
break;
case CREATE_OPENGL_VIEW:
NativeSurface surface = frame.createNativeOpenGLView(childInternalId);
break;
case CREATE_TEXTVIEW:
FWEditText editTextView = createBigEditText();
view.addChild(editTextView);
break;
case CREATE_TEXTFIELD:
FWEditText editText = createEditText();
view.addChild(editText);
break;
case CREATE_RADIO_GROUP:
FWRadioGroup radioGroup = new FWRadioGroup(frame);
radioGroup.setId(childInternalId);
break;
case CREATE_HEADING_TEXT:
case CREATE_TEXT:
FWTextView textView = createTextView();
view.addChild(textView);
break;
case CREATE_IMAGEVIEW:
ImageView imageView = createImageView();
view.addChild(imageView);
break;
case ADD_OPTION:
// Forward Command to FWPicker
view.addOption(getValue(), getTextValue());
break;
case POST_NOTIFICATION:
frame.createNotification(getTextValue(), getTextValue2());
break;
case CREATE_APPLICATION:
frame.setAppId(getInternalId());
frame.setSharedPreferences(textValue);
if (isSet(FLAG_USE_PURCHASES_API)) {
System.out.println("Initializing purchaseHelper");
frame.initializePurchaseHelper(textValue2, new IabHelper.OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
System.out.println("PurchaseHelper successfully setup");
sendInventory(frame.getPurchaseHelperInventory());
} else {
System.out.println("PurchaseHelper failed to setup");
}
}
});
}
break;
case SET_INT_VALUE:
view.setValue(getValue());
break;
case SET_TEXT_VALUE:
view.setValue(textValue);
break;
case SET_ENABLED:
view.setViewEnabled(value != 0);
break;
case SET_STYLE:
view.setStyle(textValue, textValue2);
break;
case SET_ERROR:
view.setError(value != 0, textValue);
break;
case LAUNCH_BROWSER:
frame.launchBrowser(getTextValue());
break;
case SHOW_MESSAGE_DIALOG:
showMessageDialog(textValue, textValue2);
break;
case SHOW_INPUT_DIALOG:
showInputDialog(textValue, textValue2);
break;
case CREATE_ACTION_SHEET:
createActionSheet();
break;
case CREATE_ACTIONBAR:
//TODO not everything is set
ActionBar ab = frame.getActionBar();
ab.setTitle(textValue);
break;
case QUIT_APP:
// TODO
frame.finish();
break;
case UPDATE_PREFERENCE:
//Now stores String value to string key.
frame.getPreferencesEditor().putString(textValue, textValue2);
frame.getPreferencesEditor().apply();
break;
case DELETE_ELEMENT:
FrameWork.views.remove(childInternalId);
((ViewGroup) view).removeViewAt(childInternalId);
break;
case BUY_PRODUCT:
try {
launchPurchase(textValue);
} catch (IabAsyncInProgressException e) {
e.printStackTrace();
System.out.println("Error on launchPurchase with message: " + e.getMessage());
}
default:
System.out.println("Message couldn't be handled");
break;
}
}
private void createActionSheet(){
PopupMenu menu = new PopupMenu(frame, null);
menu.setOnMenuItemClickListener(new OnMenuItemClickListener(){
@Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
menuList.add(menu);
}
private FWTable createTableLayout(){
FWTable table = new FWTable(frame);
table.setId(getChildInternalId());
table.setColumnCount(value);
FrameWork.addToViewList(table);
return table;
}
private FWSwitch createSwitch() {
FWSwitch click = new FWSwitch(frame);
click.setId(childInternalId);
if (textValue != "") {
click.setTextOn(textValue);
}
if (textValue2 != "") {
click.setTextOff(textValue2);
}
click.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
frame.intChangedEvent(System.currentTimeMillis() / 1000.0, buttonView.getId(), isChecked ? 1 : 0);
}
});
FrameWork.addToViewList(click);
return click;
}
private ImageView createImageView() {
ImageView imageView = new ImageView(frame);
imageView.setId(childInternalId);
try {
InputStream is = frame.getAssets().open(textValue);
Bitmap bitmap = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bitmap);
return imageView;
} catch (IOException e) {
e.printStackTrace();
System.out.println("error loading asset file to imageView");
System.exit(1);
}
return null;
}
private FWLayout createLinearLayout() {
FWLayout layout = new FWLayout(frame);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.FILL;
layout.setBaselineAligned(false);
layout.setLayoutParams(params);
layout.setId(getChildInternalId());
FrameWork.addToViewList(layout);
if (getValue() == 2) {
layout.setOrientation(LinearLayout.HORIZONTAL);
} else {
layout.setOrientation(LinearLayout.VERTICAL);
}
return layout;
}
private FWButton createButton() {
FWButton button = new FWButton(frame);
button.setId(getChildInternalId());
button.setText(getTextValue());
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
System.out.println("Java: my button was clicked with id " + getChildInternalId());
frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), 1);
}
});
FrameWork.addToViewList(button);
return button;
}
private FWEditText createEditText(){
final FWEditText editText = new FWEditText(frame);
editText.setId(getChildInternalId());
editText.setText(getTextValue());
editText.setMinimumWidth(120000 / (int) frame.getScreenWidth());
if (isSet(FLAG_PASSWORD) && isSet(FLAG_NUMERIC)){
editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
} else if (isSet(FLAG_PASSWORD)) {
editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else if (isSet(FLAG_NUMERIC)){
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
}
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {
String inputText = editable.toString();
byte[] b = inputText.getBytes(Charset.forName("UTF-8"));
frame.textChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), b);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
FrameWork.addToViewList(editText);
return editText;
}
private FWEditText createBigEditText() {
final FWEditText editText = new FWEditText(frame);
editText.setId(getChildInternalId());
editText.setText(getTextValue());
// editText.setMinimumWidth(120000 / (int) frame.getScreenWidth());
editText.setVerticalScrollBarEnabled(true);
editText.setMovementMethod(new ScrollingMovementMethod());
editText.addDelayedChangeListener(getChildInternalId());
FrameWork.addToViewList(editText);
return editText;
}
private FWPicker createSpinner(){
FWPicker picker = new FWPicker(frame);
picker.setId(getChildInternalId());
FrameWork.addToViewList(picker);
return picker;
}
private FWTextView createTextView() {
FWTextView textView = new FWTextView(frame);
textView.setId(getChildInternalId());
if (isSet(FLAG_HYPERLINK)) {
textView.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='" + textValue2 + "'>" + textValue + "</a>";
textView.setText(Html.fromHtml(text));
} else {
textView.setText(textValue);
}
FrameWork.addToViewList(textView);
return textView;
}
// Create dialog with user text input
private void showInputDialog(String title, String message) {
System.out.println("Creating input dialog");
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(frame);
// Building an alert
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(true);
final EditText input = new EditText(frame);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
frame.endModal(System.currentTimeMillis() / 1000.0, 0, null);
}
});
// Negative button listener
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
frame.endModal(System.currentTimeMillis() / 1000.0, 0, null);
dialog.cancel();
}
});
// Positive button listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String inputText = String.valueOf(input.getText());
byte[] b = inputText.getBytes(Charset.forName("UTF-8"));
frame.endModal(System.currentTimeMillis() / 1000.0, 1, b);
dialog.cancel();
}
});
// Create and show the alert
AlertDialog alert = builder.create();
alert.show();
}
// create Message dialog
private void showMessageDialog(String title, String message) {
System.out.println("creating message dialog");
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(frame);
// Building an alert
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(true);
builder.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
frame.endModal(System.currentTimeMillis() / 1000.0, 0, null);
}
});
// Positive button listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
frame.endModal(System.currentTimeMillis() / 1000.0, 1, null);
dialog.dismiss();
}
});
// Create and show the alert
AlertDialog alert = builder.create();
alert.show();
System.out.println("message dialog created");
}
private void launchPurchase(final String productId) throws IabAsyncInProgressException {
// Sku = product id from google account
frame.getPurchaseHelper().launchPurchaseFlow(frame, productId, IabHelper.ITEM_TYPE_INAPP, null, 1, new IabHelper.OnIabPurchaseFinishedListener() {
@Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
if (result.isSuccess()) {
System.out.println("Purchase of product id " + productId + " completed");
FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), info.getSku(), true, info.getPurchaseTime() / 1000.0);
// TODO
} else {
System.out.println("Purchase of product id " + productId + " failed");
// TODO
}
}
}, "");
}
private void sendInventory(Inventory inventory) {
List<Purchase> purchaseList = inventory.getAllPurchases();
System.out.println("getting purchase history. Purchase list size: " + purchaseList.size());
for (Purchase purchase : inventory.getAllPurchases()) {
FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), purchase.getSku(), false, purchase.getPurchaseTime() / 1000.0);
}
}
private Boolean isSet(int flag) {
return (flags & flag) != 0;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public int getInternalId() {
return internalId;
}
public int getChildInternalId() {
return childInternalId;
}
public String getTextValue() {
return textValue;
}
public String getTextValue2() {
return textValue2;
}
public CommandType getCommand() {
return command;
}
public int getValue() {
return value;
}
}
|
package tectonicus.raw;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.jnbt.ByteArrayTag;
import org.jnbt.ByteTag;
import org.jnbt.CompoundTag;
import org.jnbt.IntTag;
import org.jnbt.ListTag;
import org.jnbt.NBTInputStream;
import org.jnbt.NBTInputStream.Compression;
import org.jnbt.ShortTag;
import org.jnbt.StringTag;
import org.jnbt.Tag;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import tectonicus.BlockIds;
import tectonicus.ChunkCoord;
import tectonicus.util.FileUtils;
public class RawChunk
{
public static final int WIDTH = 16;
public static final int HEIGHT = 256;
public static final int DEPTH = 16;
public static final int MC_REGION_HEIGHT = 128;
public static final int SECTION_WIDTH = 16;
public static final int SECTION_HEIGHT = 16;
public static final int SECTION_DEPTH = 16;
public static final int MAX_LIGHT = 16;
private static final int MAX_SECTIONS = HEIGHT / SECTION_HEIGHT;
private byte[][] biomes;
private Section[] sections;
private int blockX, blockY, blockZ;
private ArrayList<RawSign> signs;
private ArrayList<TileEntity> flowerPots;
private ArrayList<TileEntity> paintings;
private ArrayList<TileEntity> skulls;
private ArrayList<TileEntity> beacons;
private ArrayList<TileEntity> banners;
private ArrayList<TileEntity> itemFrames;
private ArrayList<TileEntity> chests;
private Map<String, Object> filterData = new HashMap<String, Object>();
public RawChunk()
{
clear();
}
public RawChunk(File file) throws Exception
{
FileInputStream fileIn = new FileInputStream(file);
init(fileIn, Compression.Gzip);
}
public RawChunk(InputStream in, Compression compression) throws Exception
{
init(in, compression);
}
public void setFilterMetadata(String id, Object data)
{
this.filterData.put(id, data);
}
public void removeFilterMetadata(String id)
{
this.filterData.remove(id);
}
public Object getFilterMetadata(String id)
{
return this.filterData.get(id);
}
private void clear()
{
signs = new ArrayList<RawSign>();
flowerPots = new ArrayList<TileEntity>();
paintings = new ArrayList<TileEntity>();
skulls = new ArrayList<TileEntity>();
beacons = new ArrayList<TileEntity>();
banners = new ArrayList<TileEntity>();
itemFrames = new ArrayList<TileEntity>();
chests = new ArrayList<TileEntity>();
sections = new Section[MAX_SECTIONS];
}
private void init(InputStream in, Compression compression) throws Exception
{
clear();
NBTInputStream nbtIn = null;
try
{
nbtIn = new NBTInputStream(in, compression);
Tag tag = nbtIn.readTag();
if (tag instanceof CompoundTag)
{
CompoundTag root = (CompoundTag)tag;
CompoundTag level = NbtUtil.getChild(root, "Level", CompoundTag.class);
if (level != null)
{
blockX = blockY = blockZ = 0;
IntTag xPosTag = NbtUtil.getChild(level, "xPos", IntTag.class);
if (xPosTag != null)
blockX = xPosTag.getValue().intValue();
IntTag zPosTag = NbtUtil.getChild(level, "zPos", IntTag.class);
if (zPosTag != null)
blockZ = zPosTag.getValue().intValue();
ListTag sections = NbtUtil.getChild(level, "Sections", ListTag.class);
if (sections != null)
{
// Parse as anvil format
parseAnvilData(level);
}
else
{
// Parse as McRegion format
parseMcRegionData(level);
}
ListTag entitiesTag = NbtUtil.getChild(level, "Entities", ListTag.class);
if (entitiesTag != null)
{
for (Tag t : entitiesTag.getValue())
{
if (t instanceof CompoundTag)
{
CompoundTag entity = (CompoundTag)t;
StringTag idTag = NbtUtil.getChild(entity, "id", StringTag.class);
if (idTag.getValue().endsWith("Painting"))
{
StringTag motiveTag = NbtUtil.getChild(entity, "Motive", StringTag.class);
IntTag xTag = NbtUtil.getChild(entity, "TileX", IntTag.class);
IntTag yTag = NbtUtil.getChild(entity, "TileY", IntTag.class);
IntTag zTag = NbtUtil.getChild(entity, "TileZ", IntTag.class);
ByteTag oldDir = NbtUtil.getChild(entity, "Dir", ByteTag.class);
ByteTag dir = NbtUtil.getChild(entity, "Direction", ByteTag.class);
if (oldDir != null && dir == null){
dir = oldDir;
}
boolean is18 = false;
if (dir == null){
dir = NbtUtil.getChild(entity, "Facing", ByteTag.class);
is18 = true;
}
int direction = dir.getValue(); // Have to reverse 0 and 2 for the old Dir tag
if (oldDir != null && direction == 0){
direction = 2;
}
else if (oldDir != null && direction == 2){
direction = 0;
}
int x = xTag.getValue();
final int y = yTag.getValue();
int z = zTag.getValue();
if (is18 && direction == 0){
z = zTag.getValue() - 1;
}
else if (is18 && direction == 1){
x = xTag.getValue() + 1;
}
else if (is18 && direction == 2){
z = zTag.getValue() + 1;
}
else if (is18 && direction == 3){
x = xTag.getValue() - 1;
}
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
//System.out.println("Motive: " + motiveTag.getValue() + " Direction: " + dir.getValue() + " XYZ: " + x + ", " + y + ", " + z + " Local XYZ: " + localX +
//", " + localY + ", " + localZ);
paintings.add(new TileEntity(-1, 0, x, y, z, localX, localY, localZ, motiveTag.getValue(), direction));
}
else if (idTag.getValue().equals("ItemFrame"))
{
IntTag xTag = NbtUtil.getChild(entity, "TileX", IntTag.class);
IntTag yTag = NbtUtil.getChild(entity, "TileY", IntTag.class);
IntTag zTag = NbtUtil.getChild(entity, "TileZ", IntTag.class);
ByteTag dir = NbtUtil.getChild(entity, "Direction", ByteTag.class);
boolean is18 = false;
if (dir == null){
dir = NbtUtil.getChild(entity, "Facing", ByteTag.class);
is18 = true;
}
String item = "";
Map<String, Tag> map = entity.getValue();
CompoundTag itemTag = (CompoundTag) map.get("Item");
if(itemTag != null)
{
ShortTag itemIdTag = NbtUtil.getChild(itemTag, "id", ShortTag.class);
if (itemIdTag == null)
{
StringTag stringItemIdTag = NbtUtil.getChild(itemTag, "id", StringTag.class);
item = stringItemIdTag.getValue();
}
else
{
if (itemIdTag.getValue() == 358)
item = "minecraft:filled_map";
}
}
int x = xTag.getValue();
final int y = yTag.getValue();
int z = zTag.getValue();
if (is18 && dir.getValue() == 0){
z = zTag.getValue() - 1;
}
else if (is18 && dir.getValue() == 1){
x = xTag.getValue() + 1;
}
else if (is18 && dir.getValue() == 2){
z = zTag.getValue() + 1;
}
else if (is18 && dir.getValue() == 3){
x = xTag.getValue() - 1;
}
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
//System.out.println(" Direction: " + dir.getValue() + " XYZ: " + x + ", " + y + ", " + z + " Local XYZ: " + localX +
//", " + localY + ", " + localZ);
itemFrames.add(new TileEntity(-2, 0, x, y, z, localX, localY, localZ, item, dir.getValue()));
}
}
}
}
ListTag tileEntitiesTag = NbtUtil.getChild(level, "TileEntities", ListTag.class);
if (tileEntitiesTag != null)
{
for (Tag t : tileEntitiesTag.getValue())
{
if (t instanceof CompoundTag)
{
CompoundTag entity = (CompoundTag)t;
StringTag idTag = NbtUtil.getChild(entity, "id", StringTag.class);
IntTag xTag = NbtUtil.getChild(entity, "x", IntTag.class);
IntTag yTag = NbtUtil.getChild(entity, "y", IntTag.class);
IntTag zTag = NbtUtil.getChild(entity, "z", IntTag.class);
if (idTag != null && xTag != null && yTag != null && zTag != null)
{
String id = idTag.getValue();
if (id.equals("Sign"))
{
List<String> textLines = new ArrayList<String>();
for (int i=1; i<=4; i++)
{
String text = NbtUtil.getChild(entity, "Text"+i, StringTag.class).getValue();
if (!StringUtils.isEmpty(text) && FileUtils.isJSONValid(text)) // 1.9 sign text
{
textLines.add(textFromJSON(text));
}
else if (!StringUtils.isEmpty(text) && text.charAt(0) == '"' && text.charAt(text.length()-1) == '"' && text.length()>2) // 1.8 or older sign text
{
text = text.replaceAll("^\"|\"$", ""); //This removes begin and end double quotes
text = StringEscapeUtils.unescapeJava(text);
Gson gson = new GsonBuilder().create();
textLines.add(gson.toJson(text).replaceAll("^\"|\"$", ""));
}
else if (!StringUtils.isBlank(text)) // 1.7 or older sign text
{
text = text.replaceAll("^\"|\"$", "");
Gson gson = new GsonBuilder().create();
textLines.add(gson.toJson(text).replaceAll("^\"|\"$", ""));
}
else
{
textLines.add("");
}
}
final int x = xTag.getValue();
final int y = yTag.getValue();
final int z = zTag.getValue();
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
final int blockId = getBlockId(localX, localY, localZ);
final int data = getBlockData(localX, localY, localZ);
signs.add( new RawSign( blockId, data,
x, y, z,
localX, localY, localZ,
textLines.get(0), textLines.get(1), textLines.get(2), textLines.get(3)) );
}
else if (id.equals("FlowerPot"))
{
IntTag dataTag = NbtUtil.getChild(entity, "Data", IntTag.class);
IntTag itemTag = NbtUtil.getChild(entity, "Item", IntTag.class);
final int item;
if(itemTag == null)
{
StringTag stringIdTag = NbtUtil.getChild(entity, "Item", StringTag.class);
if (stringIdTag.getValue().equals("minecraft:sapling"))
item = 6;
else if (stringIdTag.getValue().equals("minecraft:red_flower"))
item = 38;
else
item = 0;
}
else
{
item = itemTag.getValue();
}
final int x = xTag.getValue();
final int y = yTag.getValue();
final int z = zTag.getValue();
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
final int blockData = getBlockData(localX, localY, localZ);
final int itemData = dataTag.getValue();
flowerPots.add(new TileEntity(0, blockData, x, y, z, localX, localY, localZ, itemData, item));
}
else if (id.equals("Skull"))
{
ByteTag skullType = NbtUtil.getChild(entity, "SkullType", ByteTag.class);
ByteTag rot = NbtUtil.getChild(entity, "Rot", ByteTag.class);
StringTag nameTag = null;
StringTag playerId = null;
String name = "";
String UUID = "";
String textureURL = "";
StringTag extraType = NbtUtil.getChild(entity, "ExtraType", StringTag.class);
CompoundTag owner = NbtUtil.getChild(entity, "Owner", CompoundTag.class);
if(owner != null)
{
nameTag = NbtUtil.getChild(owner, "Name", StringTag.class);
name = nameTag.getValue();
playerId = NbtUtil.getChild(owner, "Id", StringTag.class);
UUID = playerId.getValue().replace("-", "");
// Get skin URL
CompoundTag properties = NbtUtil.getChild(owner, "Properties", CompoundTag.class);
ListTag textures = NbtUtil.getChild(properties, "textures", ListTag.class);
CompoundTag tex = NbtUtil.getChild(textures, 0, CompoundTag.class);
StringTag value = NbtUtil.getChild(tex, "Value", StringTag.class);
byte[] decoded = DatatypeConverter.parseBase64Binary(value.getValue());
JSONObject obj = new JSONObject(new String(decoded, "UTF-8"));
textureURL = obj.getJSONObject("textures").getJSONObject("SKIN").getString("url");
}
else if (extraType != null && !(extraType.getValue().equals("")))
{
name = UUID = extraType.getValue();
textureURL = "http:
}
final int x = xTag.getValue();
final int y = yTag.getValue();
final int z = zTag.getValue();
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
skulls.add(new TileEntity( skullType.getValue(), rot.getValue(), x, y, z, localX, localY, localZ, name, UUID, textureURL, null));
}
else if (id.equals("Beacon"))
{
IntTag levels = NbtUtil.getChild(entity, "Levels", IntTag.class);
final int x = xTag.getValue();
final int y = yTag.getValue();
final int z = zTag.getValue();
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
beacons.add(new TileEntity(0, levels.getValue(), x, y, z, localX, localY, localZ, 0, 0));
}
else if (id.equals("Banner"))
{
IntTag base = NbtUtil.getChild(entity, "Base", IntTag.class);
ListTag patternList = NbtUtil.getChild(entity, "Patterns", ListTag.class);
final int x = xTag.getValue();
final int y = yTag.getValue();
final int z = zTag.getValue();
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
String patterns = "";
int numPatterns = 0;
if (patternList != null)
numPatterns = patternList.getValue().size();
if (numPatterns > 0)
{
//System.out.println(patternList + "\n");
patterns += "{";
for(int i=0; i<numPatterns; i++)
{
CompoundTag p = NbtUtil.getChild(patternList, i, CompoundTag.class);
StringTag pattern = NbtUtil.getChild(p, "Pattern", StringTag.class);
IntTag color = NbtUtil.getChild(p, "Color", IntTag.class);
patterns += "\"" + pattern.getValue() + "\"" + ": " + color.getValue().toString();
if(i < numPatterns-1)
patterns += ", ";
}
patterns += "}";
//System.out.println(patterns);
}
banners.add(new TileEntity(0, base.getValue(), x, y, z, localX, localY, localZ, patterns, 0));
//banners.add(new TileEntity(0, base.getValue(), x, y, z, localX, localY, localZ, 0, 0));
}
else if (id.equals("Chest"))
{
final StringTag customName = NbtUtil.getChild(entity, "CustomName", StringTag.class);
String name = "Chest";
if (customName != null)
name = customName.getValue();
final StringTag lootTable = NbtUtil.getChild(entity, "LootTable", StringTag.class);
int unopenedChestFlag = 0;
if (lootTable != null)
unopenedChestFlag = 1;
final int x = xTag.getValue();
final int y = yTag.getValue();
final int z = zTag.getValue();
final int localX = x-(blockX*WIDTH);
final int localY = y-(blockY*HEIGHT);
final int localZ = z-(blockZ*DEPTH);
chests.add(new TileEntity(0, unopenedChestFlag, x, y, z, localX, localY, localZ, name, 0));
}
// else if (id.equals("Furnace"))
// else if (id.equals("MobSpawner"))
}
}
}
}
// LongTag lastUpdateTag =
// NbtUtil.getChild(level, "LastUpdate", LongTag.class);
// ByteTag terrainPopulatedTag =
// NbtUtil.getChild(level, "TerrainPopulated", ByteTag.class);
}
}
}
finally
{
if (nbtIn != null)
nbtIn.close();
if (in != null)
in.close();
}
/* Old debug: put bricks in the corner of every chunk
for (int y=0; y<HEIGHT; y++)
{
if (blockIds[0][y][0] != BlockIds.AIR)
{
if (signs.size() > 0)
blockIds[0][y][0] = BlockIds.DIAMOND_BLOCK;
else
blockIds[0][y][0] = BlockIds.BRICK;
}
}
*/
}
private void parseAnvilData(CompoundTag level)
{
ListTag sectionsList = NbtUtil.getChild(level, "Sections", ListTag.class);
// sections shouldn't be null here
List<Tag> list = sectionsList.getValue();
for (Tag t : list)
{
if (!(t instanceof CompoundTag))
continue;
CompoundTag compound = (CompoundTag)t;
final int sectionY = NbtUtil.getByte(compound, "Y", (byte)0);
if (sectionY < 0 || sectionY >= MAX_SECTIONS)
continue;
Section newSection = new Section();
sections[sectionY] = newSection;
ByteArrayTag blocksTag = NbtUtil.getChild(compound, "Blocks", ByteArrayTag.class);
if (blocksTag != null)
{
for (int x=0; x<SECTION_WIDTH; x++)
{
for (int y=0; y<SECTION_HEIGHT; y++)
{
for (int z=0; z<SECTION_DEPTH; z++)
{
final int index = calcAnvilIndex(x, y, z);
final int id = blocksTag.getValue()[index] & 0xFF;
newSection.blockIds[x][y][z] = id;
}
}
}
}
ByteArrayTag addTag = NbtUtil.getChild(compound, "Add", ByteArrayTag.class);
if (addTag != null)
{
for (int x=0; x<SECTION_WIDTH; x++)
{
for (int y=0; y<SECTION_HEIGHT; y++)
{
for (int z=0; z<SECTION_DEPTH; z++)
{
final int addValue = getAnvil4Bit(addTag, x, y, z);
newSection.blockIds[x][y][z] = newSection.blockIds[x][y][z] | (addValue << 8);
}
}
}
}
ByteArrayTag dataTag = NbtUtil.getChild(compound, "Data", ByteArrayTag.class);
if (dataTag != null)
{
for (int x=0; x<SECTION_WIDTH; x++)
{
for (int y=0; y<SECTION_HEIGHT; y++)
{
for (int z=0; z<SECTION_DEPTH; z++)
{
final byte half = getAnvil4Bit(dataTag, x, y, z);
newSection.blockData[x][y][z] = half;
}
}
}
}
ByteArrayTag skylightTag = NbtUtil.getChild(compound, "SkyLight", ByteArrayTag.class);
if (skylightTag != null)
{
for (int x=0; x<SECTION_WIDTH; x++)
{
for (int y=0; y<SECTION_HEIGHT; y++)
{
for (int z=0; z<SECTION_DEPTH; z++)
{
final byte half = getAnvil4Bit(skylightTag, x, y, z);
newSection.skylight[x][y][z] = half;
}
}
}
}
ByteArrayTag blocklightTag = NbtUtil.getChild(compound, "BlockLight", ByteArrayTag.class);
if (blocklightTag != null)
{
for (int x=0; x<SECTION_WIDTH; x++)
{
for (int y=0; y<SECTION_HEIGHT; y++)
{
for (int z=0; z<SECTION_DEPTH; z++)
{
final byte half = getAnvil4Bit(blocklightTag, x, y, z);
newSection.blocklight[x][y][z] = half;
}
}
}
}
}
// Parse "Biomes" data (16x16)
ByteArrayTag biomeDataTag = NbtUtil.getChild(level, "Biomes", ByteArrayTag.class);
if (biomeDataTag != null)
{
biomes = new byte[SECTION_WIDTH][SECTION_DEPTH];
for (int x=0; x<SECTION_WIDTH; x++)
{
for (int z=0; z<SECTION_DEPTH; z++)
{
final int index = x * SECTION_WIDTH + z;
biomes[x][z] = biomeDataTag.getValue()[index];
}
}
}
}
private void parseMcRegionData(CompoundTag level)
{
// McRegion chunks are only 128 high, so just create the lower half of the sections
for (int i=0; i<8; i++)
{
sections[i] = new Section();
}
ByteArrayTag blocks = NbtUtil.getChild(level, "Blocks", ByteArrayTag.class);
if (blocks != null)
{
for (int x=0; x<WIDTH; x++)
{
for (int y=0; y<MC_REGION_HEIGHT; y++)
{
for (int z=0; z<DEPTH; z++)
{
final int index = calcIndex(x, y, z);
final byte blockId = blocks.getValue()[index];
setBlockId(x, y, z, blockId);
}
}
}
}
ByteArrayTag dataTag = NbtUtil.getChild(level, "Data", ByteArrayTag.class);
if (dataTag != null)
{
for (int x=0; x<WIDTH; x++)
{
for (int y=0; y<MC_REGION_HEIGHT; y++)
{
for (int z=0; z<DEPTH; z++)
{
final byte half = get4Bit(dataTag, x, y, z);
setBlockData(x, y, z, half);
}
}
}
}
ByteArrayTag skylightTag = NbtUtil.getChild(level, "SkyLight", ByteArrayTag.class);
if (skylightTag != null)
{
for (int x=0; x<WIDTH; x++)
{
for (int y=0; y<MC_REGION_HEIGHT; y++)
{
for (int z=0; z<DEPTH; z++)
{
final byte half = get4Bit(skylightTag, x, y, z);
setSkyLight(x, y, z, half);
}
}
}
}
ByteArrayTag blockLightTag = NbtUtil.getChild(level, "BlockLight", ByteArrayTag.class);
if (blockLightTag != null)
{
for (int x=0; x<WIDTH; x++)
{
for (int y=0; y<MC_REGION_HEIGHT; y++)
{
for (int z=0; z<DEPTH; z++)
{
final byte half = get4Bit(blockLightTag, x, y, z);
setBlockLight(x, y, z, half);
}
}
}
}
}
private static final int calcIndex(final int x, final int y, final int z)
{
// y + ( z * ChunkSizeY(=128) + ( x * ChunkSizeY(=128) * ChunkSizeZ(=16) ) ) ];
return y + (z * MC_REGION_HEIGHT) + (x * MC_REGION_HEIGHT * DEPTH);
}
private static final int calcAnvilIndex(final int x, final int y, final int z)
{
// Note that the old format is XZY ((x * 16 + z) * 128 + y)
// and the new format is YZX ((y * 16 + z) * 16 + x)
return x + (z * SECTION_HEIGHT) + (y * SECTION_HEIGHT * SECTION_DEPTH);
}
private static final int calc4BitIndex(final int x, final int y, final int z)
{
// Math.floor is bloody slow!
// Since calcIndex should always be +ive, we can just cast to int and get the same result
return (int)(calcIndex(x, y, z) / 2);
}
private static final int calcAnvil4BitIndex(final int x, final int y, final int z)
{
// Math.floor is bloody slow!
// Since calcIndex should always be +ive, we can just cast to int and get the same result
return (int)(calcAnvilIndex(x, y, z) / 2);
}
private static byte getAnvil4Bit(ByteArrayTag tag, final int x, final int y, final int z)
{
final int index = calcAnvil4BitIndex(x, y, z);
if (index == 2048)
System.out.println();;
final int doublet = tag.getValue()[index];
// Upper or lower half?
final boolean isUpper = (x % 2 == 1);
byte half;
if (isUpper)
{
half = (byte)((doublet >> 4) & 0xF);
}
else
{
half = (byte)(doublet & 0xF);
}
return half;
}
private static byte get4Bit(ByteArrayTag tag, final int x, final int y, final int z)
{
final int index = calc4BitIndex(x, y, z);
final int doublet = tag.getValue()[index];
// Upper or lower half?
final boolean isUpper = (y % 2 == 1);
byte half;
if (isUpper)
{
half = (byte)((doublet >> 4) & 0xF);
}
else
{
half = (byte)(doublet & 0xF);
}
return half;
}
public int getBlockId(final int x, final int y, final int z)
{
if (y < 0 || y >= RawChunk.HEIGHT || x < 0 || x > RawChunk.WIDTH || z < 0 || z > RawChunk.DEPTH)
return 0;
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s != null)
return s.blockIds[x][localY][z];
else
return BlockIds.AIR;
}
public void setBlockId(final int x, final int y, final int z, final int blockId)
{
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s == null)
{
s = new Section();
sections[sectionY] = s;
}
s.blockIds[x][localY][z] = blockId;
}
public void setBlockData(final int x, final int y, final int z, final byte val)
{
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s == null)
{
s = new Section();
sections[sectionY] = s;
}
s.blockData[x][localY][z] = val;
}
public int getBlockData(final int x, final int y, final int z)
{
if (y < 0 || y >= RawChunk.HEIGHT || x < 0 || x > RawChunk.WIDTH || z < 0 || z > RawChunk.DEPTH)
return 0;
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s != null && x >= 0 && x <= 15 && z >= 0 && z <= 15) //TODO: Fix this (workaround for painting and stair problems)
return s.blockData[x][localY][z];
else
return 0;
}
public void setSkyLight(final int x, final int y, final int z, final byte val)
{
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s == null)
{
s = new Section();
sections[sectionY] = s;
}
s.skylight[x][localY][z] = val;
}
public byte getSkyLight(final int x, final int y, final int z)
{
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s != null && x >= 0 && localY >= 0 && z >= 0) //TODO: Fix this (workaround for painting and stair problems)
return s.skylight[x][localY][z];
else
return MAX_LIGHT-1;
}
public void setBlockLight(final int x, final int y, final int z, final byte val)
{
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s == null)
{
s = new Section();
sections[sectionY] = s;
}
s.blocklight[x][localY][z] = val;
}
public byte getBlockLight(final int x, final int y, final int z)
{
final int sectionY = y / MAX_SECTIONS;
final int localY = y % SECTION_HEIGHT;
Section s = sections[sectionY];
if (s != null && x >= 0 && localY >= 0 && z >= 0) //TODO: Fix this (workaround for painting and stair problems)
return s.blocklight[x][localY][z];
else
return 0;
}
public int getBlockIdClamped(final int x, final int y, final int z, final int defaultId)
{
if (x < 0 || x >= WIDTH)
return defaultId;
if (y < 0 || y >= HEIGHT)
return defaultId;
if (z < 0 || z >= DEPTH)
return defaultId;
return getBlockId(x, y, z);
}
public int getBlockX() { return blockX; }
public int getBlockY() { return blockY; }
public int getBlockZ() { return blockZ; }
public ChunkCoord getChunkCoord() { return new ChunkCoord(blockX, blockZ); }
public long getMemorySize()
{
int blockIdTotal = 0;
int skyLightTotal = 0;
int blockLightTotal = 0;
int blockDataTotal = 0;
for (Section s : sections)
{
if (s != null)
{
blockIdTotal += s.blockIds.length * s.blockIds[0].length * s.blockIds[0][0].length;
skyLightTotal += s.skylight.length * s.skylight[0].length * s.skylight[0][0].length;
blockLightTotal += s.blocklight.length * s.blocklight[0].length * s.blocklight[0][0].length;
blockDataTotal += s.blockData.length * s.blockData[0].length * s.blockData[0][0].length;
}
}
return blockIdTotal + blockDataTotal + skyLightTotal + blockLightTotal;
}
public ArrayList<RawSign> getSigns()
{
return new ArrayList<RawSign>(signs);
}
public ArrayList<TileEntity> getFlowerPots()
{
return new ArrayList<TileEntity>(flowerPots);
}
public ArrayList<TileEntity> getPaintings()
{
return new ArrayList<TileEntity>(paintings);
}
public ArrayList<TileEntity> getSkulls()
{
return new ArrayList<TileEntity>(skulls);
}
public ArrayList<TileEntity> getBeacons()
{
return new ArrayList<TileEntity>(beacons);
}
public ArrayList<TileEntity> getBanners()
{
return new ArrayList<TileEntity>(banners);
}
public ArrayList<TileEntity> getItemFrames()
{
return new ArrayList<TileEntity>(itemFrames);
}
public ArrayList<TileEntity> getChests()
{
return new ArrayList<TileEntity>(chests);
}
public byte[] calculateHash(MessageDigest hashAlgorithm)
{
hashAlgorithm.reset();
for (Section s : sections)
{
if (s != null)
{
update(hashAlgorithm, s.blockIds);
update(hashAlgorithm, s.blockData);
update(hashAlgorithm, s.skylight);
update(hashAlgorithm, s.blocklight);
}
else
{
byte[][][] dummy = new byte[1][1][1];
update(hashAlgorithm, dummy);
}
}
for (RawSign sign : signs)
{
hashAlgorithm.update(Integer.toString(sign.x).getBytes());
hashAlgorithm.update(Integer.toString(sign.y).getBytes());
hashAlgorithm.update(Integer.toString(sign.z).getBytes());
hashAlgorithm.update(sign.text1.getBytes());
hashAlgorithm.update(sign.text2.getBytes());
hashAlgorithm.update(sign.text3.getBytes());
hashAlgorithm.update(sign.text4.getBytes());
}
return hashAlgorithm.digest();
}
private static void update(MessageDigest hashAlgorithm, int[][][] data)
{
for (int x=0; x<data.length; x++)
{
for (int y=0; y<data[0].length; y++)
{
for (int z=0; y<data[0][0].length; y++)
{
final int val = data[x][y][z];
hashAlgorithm.update((byte)((val) & 0xFF));
hashAlgorithm.update((byte)((val >> 8) & 0xFF));
hashAlgorithm.update((byte)((val >> 16) & 0xFF));
hashAlgorithm.update((byte)((val >> 24) & 0xFF));
}
}
}
}
private static void update(MessageDigest hashAlgorithm, byte[][][] data)
{
for (int x=0; x<data.length; x++)
{
for (int y=0; y<data[0].length; y++)
{
hashAlgorithm.update(data[x][y]);
}
}
}
public int getBiomeId(final int x, final int y, final int z)
{
if(biomes != null)
return biomes[x][z];
else
return BiomeIds.UNKNOWN;
}
private static class Section
{
public int[][][] blockIds;
public byte[][][] blockData;
public byte[][][] skylight;
public byte[][][] blocklight;
public Section()
{
blockIds = new int[SECTION_WIDTH][SECTION_HEIGHT][SECTION_DEPTH];
blockData = new byte[SECTION_WIDTH][SECTION_HEIGHT][SECTION_DEPTH];
skylight = new byte[SECTION_WIDTH][SECTION_HEIGHT][SECTION_DEPTH];
blocklight = new byte[SECTION_WIDTH][SECTION_HEIGHT][SECTION_DEPTH];
}
}
private static String textFromJSON(String rawMessage){
String result="";
String searchString = "\"text\":\"";
int pos=0;
int left=0;
int right=0;
while(pos != -1){
pos=rawMessage.indexOf(searchString, pos);
left=pos+8;
if(pos != -1){
int nBackslash=0;
// Find right delimiting ". Problem: \\\" is escaped, \\\\" is not.
for(int i=left; i<rawMessage.length(); i++){
if(rawMessage.charAt(i)=='\\'){
nBackslash++;
}
else if(rawMessage.charAt(i)=='"' && nBackslash % 2 == 0){
right=i;
break;
}
else{
nBackslash=0;
}
}
result=result+rawMessage.substring(left, right);
pos=left;
}
}
return result;
}
}
|
package com.telefonica.euro_iaas.sdc.manager.impl;
import java.util.List;
import org.apache.http.client.HttpClient;
import com.telefonica.euro_iaas.commons.dao.AlreadyExistsEntityException;
import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException;
import com.telefonica.euro_iaas.commons.dao.InvalidEntityException;
import com.telefonica.euro_iaas.sdc.dao.ProductDao;
import com.telefonica.euro_iaas.sdc.dao.ProductInstanceDao;
import com.telefonica.euro_iaas.sdc.exception.AlreadyInstalledException;
import com.telefonica.euro_iaas.sdc.exception.CanNotCallChefException;
import com.telefonica.euro_iaas.sdc.exception.FSMViolationException;
import com.telefonica.euro_iaas.sdc.exception.InstallatorException;
import com.telefonica.euro_iaas.sdc.exception.InvalidInstallProductRequestException;
import com.telefonica.euro_iaas.sdc.exception.NodeExecutionException;
import com.telefonica.euro_iaas.sdc.exception.NotTransitableException;
import com.telefonica.euro_iaas.sdc.exception.NotUniqueResultException;
import com.telefonica.euro_iaas.sdc.exception.SdcRuntimeException;
import com.telefonica.euro_iaas.sdc.installator.Installator;
import com.telefonica.euro_iaas.sdc.manager.ProductInstanceManager;
import com.telefonica.euro_iaas.sdc.model.Attribute;
import com.telefonica.euro_iaas.sdc.model.InstallableInstance.Status;
import com.telefonica.euro_iaas.sdc.model.Product;
import com.telefonica.euro_iaas.sdc.model.ProductInstance;
import com.telefonica.euro_iaas.sdc.model.ProductRelease;
import com.telefonica.euro_iaas.sdc.model.dto.VM;
import com.telefonica.euro_iaas.sdc.model.searchcriteria.ProductInstanceSearchCriteria;
import com.telefonica.euro_iaas.sdc.util.IpToVM;
import com.telefonica.euro_iaas.sdc.util.SystemPropertiesProvider;
import com.telefonica.euro_iaas.sdc.validation.ProductInstanceValidator;
import com.xmlsolutions.annotation.UseCase;
public class ProductInstanceManagerImpl implements ProductInstanceManager {
private ProductInstanceDao productInstanceDao;
private ProductDao productDao;
private ProductInstanceValidator validator;
private Installator chefInstallator;
private Installator puppetInstallator;
private String INSTALATOR_CHEF="chef";
protected String INSTALL = "install";
protected String UNINSTALL = "uninstall";
protected String CONFIGURE = "configure";
protected String DEPLOY_ARTIFACT = "deployArtifact";
protected String UNDEPLOY_ARTIFACT = "undeployArtifact";
@Override
public ProductInstance install(VM vm, String vdc, ProductRelease productRelease, List<Attribute> attributes) throws NodeExecutionException, AlreadyInstalledException, InvalidInstallProductRequestException,
EntityNotFoundException {
// if (INSTALATOR_CHEF.equals(product.getMapMetadata().get("installator"))) {
// }else{
// Check that there is not another product installed
ProductInstance instance = null;
try {
instance = productInstanceDao.load(vm.getFqn() + "_" + productRelease.getProduct().getName() + "_"
+ productRelease.getVersion());
System.out.println("intance:"+instance.getStatus());
if (instance.getStatus().equals(Status.INSTALLED)) {
throw new AlreadyInstalledException(instance);
} else if (!(instance.getStatus().equals(Status.UNINSTALLED))
&& !(instance.getStatus().equals(Status.ERROR)))
throw new InvalidInstallProductRequestException("Product " + productRelease.getProduct().getName()
+ " " + productRelease.getVersion() + " cannot be installed in the VM " + vm.getFqn()
+ " strage status: " + instance.getStatus());
} catch (EntityNotFoundException e) {
try {
instance = createProductInstance(productRelease, vm, vdc, attributes);
} catch (Exception e2) {
throw new InvalidInstallProductRequestException("Product " + productRelease.getProduct().getName()
+ " " + productRelease.getVersion() + " cannot be installed in the VM " + vm.getFqn()
+ " error in creating the isntance: " + e2.getMessage());
}
}
Status previousStatus = null;
try {
// makes the validations
// instance = getProductToInstall(product, vm, vdc, attributes);
previousStatus = instance.getStatus();
// now we have the productInstance so can validate the operation
validator.validateInstall(instance);
instance.setStatus(Status.INSTALLING);
instance.setVm(vm);
// Id for the ProductInstance
instance = productInstanceDao.update(instance);
Product product = productDao.load(productRelease.getProduct().getName());
if (INSTALATOR_CHEF.equals(product.getMapMetadata().get("installator"))) {
chefInstallator.validateInstalatorData(vm);
chefInstallator.callService(instance, vm, attributes, INSTALL);
} else {
puppetInstallator.validateInstalatorData(vm);
puppetInstallator.callService(vm, vdc, productRelease, INSTALL);
}
instance.setStatus(Status.INSTALLED);
return productInstanceDao.update(instance);
} catch (InstallatorException sce) {
restoreInstance(previousStatus, instance);
throw new SdcRuntimeException(sce);
} catch (InvalidEntityException e) {
throw new SdcRuntimeException(e);
} catch (RuntimeException e) {
// by default restore the previous state when a runtime is thrown
restoreInstance(previousStatus, instance);
throw new SdcRuntimeException(e);
}
}
@Override
public void uninstall(ProductInstance productInstance) throws NodeExecutionException, FSMViolationException,
EntityNotFoundException {
Status previousStatus = productInstance.getStatus();
try {
validator.validateUninstall(productInstance);
productInstance.setStatus(Status.UNINSTALLING);
productInstance = productInstanceDao.update(productInstance);
Product product = productDao.load(productInstance.getProductRelease().getProduct().getName());
if (INSTALATOR_CHEF.equals(product.getMapMetadata().get("installator"))) {
// canviar aqui callChef(uninstallRecipe,
// productInstance.getVm());
chefInstallator.callService(productInstance, UNINSTALL);
} else {
puppetInstallator.callService(productInstance.getVm(), productInstance.getVdc(),
productInstance.getProductRelease(), UNINSTALL);
}
productInstance.setStatus(Status.UNINSTALLED);
productInstanceDao.update(productInstance);
} catch (InstallatorException e) {
restoreInstance(previousStatus, productInstance);
throw new SdcRuntimeException(e);
} catch (InvalidEntityException e) {
throw new SdcRuntimeException(e);
} catch (RuntimeException e) {
// by default restore the previous state when a runtime is thrown
restoreInstance(previousStatus, productInstance);
throw new SdcRuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @throws InstallatorException
*/
@Override
public ProductInstance configure(ProductInstance productInstance, List<Attribute> configuration)
throws NodeExecutionException, FSMViolationException, InstallatorException {
System.out.println("Configuring product instance " + productInstance.getName() + " " + configuration);
Status previousStatus = productInstance.getStatus();
try {
validator.validateConfigure(productInstance);
productInstance.setStatus(Status.CONFIGURING);
productInstance = productInstanceDao.update(productInstance);
System.out.println("Get VM");
VM vm = productInstance.getVm();
System.out.println("Load product " + productInstance.getProductRelease().getProduct().getName());
Product product = productDao.load(productInstance.getProductRelease().getProduct().getName());
if (configuration != null) {
for (int j=0; j< configuration.size(); j++){
Attribute attribute = configuration.get(j);
product.addAttribute(attribute);
}
}
System.out.println("Update product " + productInstance.getProductRelease().getProduct().getName());
productDao.update(product);
ProductRelease productRelease = productInstance.getProductRelease();
productRelease.setProduct(product);
if (INSTALATOR_CHEF.equals(product.getMapMetadata().get("installator"))) {
chefInstallator.callService(productInstance, productInstance.getVm(), configuration, CONFIGURE);
} else {
throw new InstallatorException("Product not configurable in Puppet");
}
/*
* String recipe = recipeNamingGenerator
* .getInstallRecipe(productInstance); callChef(
* productInstance.getProductRelease().getProduct().getName(),
* recipe, productInstance.getVm(), configuration); String
* restoreRecipe = recipeNamingGenerator
* .getRestoreRecipe(productInstance); callChef(restoreRecipe, vm);
*/
productInstance.setProductRelease(productRelease);
productInstance.setStatus(Status.INSTALLED);
return productInstanceDao.update(productInstance);
} catch (InstallatorException e) {
restoreInstance(previousStatus, productInstance);
throw new SdcRuntimeException(e);
} catch (RuntimeException e) { // by runtime restore the previous state
// restore the status
restoreInstance(previousStatus, productInstance);
throw new SdcRuntimeException(e);
} catch (NodeExecutionException e) {
restoreInstance(Status.ERROR, productInstance);
throw e;
} catch (InvalidEntityException e) {
throw new SdcRuntimeException(e);
} catch (EntityNotFoundException e) {
throw new SdcRuntimeException(e);
}
}
/**
* Go to previous state when a runtime exception is thrown in any method
* which can change the status of the product instance.
*
* @param previousStatus
* the previous status
* @param instance
* the product instance
* @return the instance.
*/
private ProductInstance restoreInstance(Status previousStatus, ProductInstance instance) {
instance.setStatus(previousStatus);
return update(instance);
}
@Override
public ProductInstance update(ProductInstance productInstance) {
try {
return productInstanceDao.update(productInstance);
} catch (InvalidEntityException e) {
throw new SdcRuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @throws EntityNotFoundException
*/
@UseCase(traceTo = "UC_001.4", status = "implemented")
@Override
public ProductInstance upgrade(ProductInstance productInstance, ProductRelease productRelease)
throws NotTransitableException, NodeExecutionException, FSMViolationException, InstallatorException,
EntityNotFoundException {
Status previousStatus = productInstance.getStatus();
try {
validator.validateUpdate(productInstance, productRelease);
// update the status
productInstance.setStatus(Status.UPGRADING);
productInstance = productInstanceDao.update(productInstance);
productInstance.setProductRelease(productRelease);
VM vm = productInstance.getVm();
Product product = productDao.load(productInstance.getName());
if (INSTALATOR_CHEF.equals(product.getMapMetadata().get("installator"))) {
chefInstallator.upgrade(productInstance, vm);
} else {
throw new InstallatorException("Product not upgradeable in Puppet");
}
productInstance.setStatus(Status.INSTALLED);
return productInstanceDao.update(productInstance);
} catch (InvalidEntityException e) {
// don't restore the status because this exception is storing the
// product in database so it will fail anyway
throw new SdcRuntimeException(e);
} catch (RuntimeException e) { // by runtime restore the previous state
// restore the status
restoreInstance(previousStatus, productInstance);
throw new SdcRuntimeException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<ProductInstance> findAll() {
return productInstanceDao.findAll();
}
/**
* {@inheritDoc}
*/
@Override
public ProductInstance load(String vdc, Long id) throws EntityNotFoundException {
ProductInstance instance = productInstanceDao.load(id);
if (!instance.getVdc().equals(vdc)) {
throw new EntityNotFoundException(ProductInstance.class, "vdc", vdc);
}
return instance;
}
@Override
public ProductInstance load(String vdc, String name) throws EntityNotFoundException {
ProductInstance instance = productInstanceDao.load(name);
if (!instance.getVdc().equals(vdc)) {
throw new EntityNotFoundException(ProductInstance.class, "vdc", vdc);
}
return instance;
}
/**
* {@inheritDoc}
*/
@Override
public List<ProductInstance> findByCriteria(ProductInstanceSearchCriteria criteria) {
return productInstanceDao.findByCriteria(criteria);
}
/**
* {@inheritDoc}
*/
@Override
public ProductInstance loadByCriteria(ProductInstanceSearchCriteria criteria) throws EntityNotFoundException,
NotUniqueResultException {
List<ProductInstance> products = productInstanceDao.findByCriteria(criteria);
if (products.size() == 0) {
throw new EntityNotFoundException(ProductInstance.class, "searchCriteria", criteria.toString());
} else if (products.size() > 1) {
throw new NotUniqueResultException();
}
return products.get(0);
}
private ProductInstance createProductInstance(ProductRelease productRelease, VM vm, String vdc,
List<Attribute> attributes) throws InvalidEntityException, AlreadyExistsEntityException {
ProductInstance instance = new ProductInstance();
Product product = null;
try {
product = productDao.load(productRelease.getProduct().getName());
} catch (EntityNotFoundException e) {
product = new Product(productRelease.getProduct().getName(), productRelease.getProduct().getDescription());
}
product.setAttributes(attributes);
productRelease.setProduct(product);
instance.setProductRelease(productRelease);
instance.setVm(vm);
instance.setVdc(vdc);
instance.setStatus(Status.UNINSTALLED);
instance.setName(vm.getFqn() + "_" + productRelease.getProduct().getName() + "_" + productRelease.getVersion());
instance = productInstanceDao.create(instance);
return instance;
}
// //////////// I.O.C /////////////
/**
* @param productInstanceDao
* the productInstanceDao to set
*/
public void setProductInstanceDao(ProductInstanceDao productInstanceDao) {
this.productInstanceDao = productInstanceDao;
}
/**
* @param productDao
* the productDao to set
*/
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
/**
* @param validator
* the validator to set
*/
public void setValidator(ProductInstanceValidator validator) {
this.validator = validator;
}
public void setChefInstallator(Installator chefInstallator) {
this.chefInstallator = chefInstallator;
}
public void setPuppetInstallator(Installator puppetInstallator) {
this.puppetInstallator = puppetInstallator;
}
}
|
package org.hisp.dhis.android.core.parser.internal.service;
import static org.hisp.dhis.android.core.parser.internal.expression.ParserUtils.COMMON_EXPRESSION_ITEMS;
import static org.hisp.dhis.android.core.parser.internal.expression.ParserUtils.ITEM_EVALUATE;
import static org.hisp.dhis.android.core.parser.internal.expression.ParserUtils.ITEM_GET_DESCRIPTIONS;
import static org.hisp.dhis.android.core.parser.internal.expression.ParserUtils.ITEM_GET_IDS;
import static org.hisp.dhis.android.core.parser.internal.expression.ParserUtils.ITEM_REGENERATE;
import static org.hisp.dhis.android.core.validation.MissingValueStrategy.NEVER_SKIP;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.HASH_BRACE;
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.category.internal.CategoryOptionComboStore;
import org.hisp.dhis.android.core.common.ObjectWithUid;
import org.hisp.dhis.android.core.constant.Constant;
import org.hisp.dhis.android.core.dataelement.DataElement;
import org.hisp.dhis.android.core.dataelement.DataElementOperand;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitGroup;
import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor;
import org.hisp.dhis.android.core.parser.internal.expression.CommonParser;
import org.hisp.dhis.android.core.parser.internal.expression.ExpressionItem;
import org.hisp.dhis.android.core.parser.internal.expression.ExpressionItemMethod;
import org.hisp.dhis.android.core.parser.internal.expression.literal.RegenerateLiteral;
import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimItemDataElementAndOperand;
import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimensionalItemId;
import org.hisp.dhis.android.core.parser.internal.service.dataobject.DimensionalItemObject;
import org.hisp.dhis.android.core.validation.MissingValueStrategy;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
@SuppressWarnings({
"PMD.TooManyStaticImports",
"PMD.ExcessiveImports",
"PMD.CyclomaticComplexity",
"PMD.StdCyclomaticComplexity"})
public class ExpressionService {
private final IdentifiableObjectStore<DataElement> dataElementStore;
private final CategoryOptionComboStore categoryOptionComboStore;
private final IdentifiableObjectStore<OrganisationUnitGroup> organisationUnitGroupStore;
private final Map<Integer, ExpressionItem> validationRuleExpressionItems;
@Inject
public ExpressionService(IdentifiableObjectStore<DataElement> dataElementStore,
CategoryOptionComboStore categoryOptionComboStore,
IdentifiableObjectStore<OrganisationUnitGroup> organisationUnitGroupStore) {
this.dataElementStore = dataElementStore;
this.categoryOptionComboStore = categoryOptionComboStore;
this.organisationUnitGroupStore = organisationUnitGroupStore;
this.validationRuleExpressionItems = getValidationRuleExpressionItems();
}
private Map<Integer, ExpressionItem> getValidationRuleExpressionItems() {
Map<Integer, ExpressionItem> expressionItems = new HashMap<>(COMMON_EXPRESSION_ITEMS);
expressionItems.put(HASH_BRACE, new DimItemDataElementAndOperand());
return expressionItems;
}
public Set<DimensionalItemId> getDimensionalItemIds(String expression) {
if (expression == null) {
return Collections.emptySet();
}
Set<DimensionalItemId> itemIds = new HashSet<>();
CommonExpressionVisitor visitor = newVisitor(ITEM_GET_IDS, Collections.emptyMap());
visitor.setItemIds(itemIds);
CommonParser.visit(expression, visitor);
return itemIds;
}
public Set<DataElementOperand> getDataElementOperands(String expression) {
Set<DimensionalItemId> dimensionalItemIds = getDimensionalItemIds(expression);
Set<DataElementOperand> dataElementOperands = new HashSet<>();
for (DimensionalItemId di : dimensionalItemIds) {
if (di.isDataElementOrOperand()) {
dataElementOperands.add(DataElementOperand.builder()
.dataElement(ObjectWithUid.create(di.id0()))
.categoryOptionCombo(di.id1() == null ? null : ObjectWithUid.create(di.id1()))
.build());
}
}
return dataElementOperands;
}
public String getExpressionDescription(String expression, Map<String, Constant> constantMap) {
if (expression == null) {
return "";
}
CommonExpressionVisitor visitor = newVisitor(ITEM_GET_DESCRIPTIONS, constantMap);
CommonParser.visit(expression, visitor);
Map<String, String> itemDescriptions = visitor.getItemDescriptions();
String description = expression;
for (Map.Entry<String, String> entry : itemDescriptions.entrySet()) {
description = description.replace(entry.getKey(), entry.getValue());
}
return description;
}
public Object getExpressionValue(String expression) {
return getExpressionValue(expression, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(),
0, NEVER_SKIP);
}
public Object getExpressionValue(String expression,
Map<DimensionalItemObject, Double> valueMap,
Map<String, Constant> constantMap,
Map<String, Integer> orgUnitCountMap,
Integer days,
MissingValueStrategy missingValueStrategy) {
if (expression == null) {
return null;
}
CommonExpressionVisitor visitor = newVisitor(
ITEM_EVALUATE,
constantMap
);
Map<String, Double> itemValueMap = new HashMap<>();
for (Map.Entry<DimensionalItemObject, Double> entry : valueMap.entrySet()) {
itemValueMap.put(entry.getKey().getDimensionItem(), entry.getValue());
}
visitor.setItemValueMap(itemValueMap);
visitor.setOrgUnitCountMap(orgUnitCountMap);
if (days != null) {
visitor.setDays(Double.valueOf(days));
}
Object value = CommonParser.visit(expression, visitor);
int itemsFound = visitor.getItemsFound();
int itemValuesFound = visitor.getItemValuesFound();
switch (missingValueStrategy) {
case SKIP_IF_ANY_VALUE_MISSING:
if (itemValuesFound < itemsFound) {
return null;
}
case SKIP_IF_ALL_VALUES_MISSING:
if (itemsFound != 0 && itemValuesFound == 0) {
return null;
}
case NEVER_SKIP:
default:
if (value == null) {
// TODO Handle other ParseType
return 0d;
}
}
if (value instanceof Double && Double.isNaN((double) value)) {
return null;
} else {
return value;
}
}
public String regenerateExpression(String expression,
Map<DimensionalItemObject, Double> valueMap,
Map<String, Constant> constantMap,
Map<String, Integer> orgUnitCountMap,
Integer days) {
if (expression == null) {
return "";
}
CommonExpressionVisitor visitor = newVisitor(
ITEM_REGENERATE,
constantMap
);
Map<String, Double> itemValueMap = new HashMap<>();
for (Map.Entry<DimensionalItemObject, Double> entry : valueMap.entrySet()) {
itemValueMap.put(entry.getKey().getDimensionItem(), entry.getValue());
}
visitor.setItemValueMap(itemValueMap);
visitor.setOrgUnitCountMap(orgUnitCountMap);
visitor.setExpressionLiteral(new RegenerateLiteral());
if (days != null) {
visitor.setDays(Double.valueOf(days));
}
return (String) CommonParser.visit(expression, visitor);
}
// Supportive methods
/**
* Creates a new ExpressionItemsVisitor object.
*/
private CommonExpressionVisitor newVisitor(
//ParseType parseType,
ExpressionItemMethod itemMethod,
//List<Period> samplePeriods,
Map<String, Constant> constantMap) {
return CommonExpressionVisitor.newBuilder()
//.withItemMap( PARSE_TYPE_EXPRESSION_ITEMS.get( parseType ) )
.withItemMap(validationRuleExpressionItems)
.withItemMethod(itemMethod)
.withConstantMap(constantMap)
.withDataElementStore(dataElementStore)
.withCategoryOptionComboStore(categoryOptionComboStore)
.withOrganisationUnitGroupStore(organisationUnitGroupStore)
//.withSamplePeriods( samplePeriods )()
.buildForExpressions();
}
}
|
package com.orientechnologies.orient.core.index;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test
public class OPropertyIndexDefinitionTest {
private OPropertyIndexDefinition propertyIndex;
@BeforeMethod
public void beforeMethod() {
propertyIndex = new OPropertyIndexDefinition("testClass", "fOne", OType.INTEGER);
}
@Test
public void testCreateValueSingleParameter() {
final Object result = propertyIndex.createValue(Collections.singletonList("12"));
Assert.assertEquals(result, 12);
}
@Test
public void testCreateValueTwoParameters() {
final Object result = propertyIndex.createValue(Arrays.asList("12", "25"));
Assert.assertEquals(result, 12);
}
@Test
public void testCreateValueWrongParameter() {
final Object result = propertyIndex.createValue(Collections.singletonList("tt"));
Assert.assertNull(result);
}
@Test
public void testCreateValueSingleParameterArrayParams() {
final Object result = propertyIndex.createValue("12");
Assert.assertEquals(result, 12);
}
@Test
public void testCreateValueTwoParametersArrayParams() {
final Object result = propertyIndex.createValue("12", "25");
Assert.assertEquals(result, 12);
}
@Test
public void testCreateValueWrongParameterArrayParams() {
final Object result = propertyIndex.createValue("tt");
Assert.assertNull(result);
}
@Test
public void testGetDocumentValueToIndex() {
final ODocument document = new ODocument();
document.field("fOne", "15");
document.field("fTwo", 10);
final Object result = propertyIndex.getDocumentValueToIndex(document);
Assert.assertEquals(result, 15);
}
@Test
public void testGetFields() {
final List<String> result = propertyIndex.getFields();
Assert.assertEquals(result.size(), 1);
Assert.assertEquals(result.get(0), "fOne");
}
@Test
public void testGetTypes() {
final OType[] result = propertyIndex.getTypes();
Assert.assertEquals(result.length, 1);
Assert.assertEquals(result[0], OType.INTEGER);
}
@Test
public void testEmptyIndexReload() {
final ODatabaseDocumentTx database = new ODatabaseDocumentTx("memory:propertytest");
database.create();
propertyIndex = new OPropertyIndexDefinition("tesClass", "fOne", OType.INTEGER);
final ODocument docToStore = propertyIndex.toStream();
database.save(docToStore);
final ODocument docToLoad = database.load(docToStore.getIdentity());
final OPropertyIndexDefinition result = new OPropertyIndexDefinition();
result.fromStream(docToLoad);
database.delete();
Assert.assertEquals(result, propertyIndex);
}
@Test
public void testIndexReload() {
final ODocument docToStore = propertyIndex.toStream();
final OPropertyIndexDefinition result = new OPropertyIndexDefinition();
result.fromStream(docToStore);
Assert.assertEquals(result, propertyIndex);
}
@Test
public void testGetParamCount() {
Assert.assertEquals(propertyIndex.getParamCount(), 1);
}
@Test
public void testClassName() {
Assert.assertEquals("testClass", propertyIndex.getClassName());
}
}
|
package org.nanohttpd.junit.protocols.http.integration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.http.client.CookieStore;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.junit.Test;
import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.content.Cookie;
import org.nanohttpd.protocols.http.content.CookieHandler;
import org.nanohttpd.protocols.http.response.Response;
/**
* @author Paul S. Hawke (paul.hawke@gmail.com) On: 9/2/13 at 10:10 PM
*/
public class CookieIntegrationTest extends IntegrationTestBase<CookieIntegrationTest.CookieTestServer> {
public static class CookieTestServer extends NanoHTTPD {
List<Cookie> cookiesReceived = new ArrayList<Cookie>();
List<Cookie> cookiesToSend = new ArrayList<Cookie>();
public CookieTestServer() {
super(8192);
}
@Override
public Response serve(IHTTPSession session) {
CookieHandler cookies = session.getCookies();
for (String cookieName : cookies) {
this.cookiesReceived.add(new Cookie(cookieName, cookies.read(cookieName)));
}
for (Cookie c : this.cookiesToSend) {
cookies.set(c);
}
return Response.newFixedLengthResponse("Cookies!");
}
}
@Override
public CookieTestServer createTestServer() {
return new CookieTestServer();
}
@Test
public void testCookieSentBackToClient() throws Exception {
this.testServer.cookiesToSend.add(new Cookie("name", "value", 30));
HttpGet httpget = new HttpGet("http://localhost:8192/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
this.httpclient.execute(httpget, responseHandler);
CookieStore cookies = this.httpclient.getCookieStore();
assertEquals(1, cookies.getCookies().size());
assertEquals("name", cookies.getCookies().get(0).getName());
assertEquals("value", cookies.getCookies().get(0).getValue());
}
@Test
public void testMultipleCookieSentBackToClient() throws Exception {
this.testServer.cookiesToSend.add(new Cookie("name0", "value0", 30));
this.testServer.cookiesToSend.add(new Cookie("name1", "value1", 30));
this.testServer.cookiesToSend.add(new Cookie("name2", "value2", 30));
this.testServer.cookiesToSend.add(new Cookie("name3", "value3", 30));
HttpGet httpget = new HttpGet("http://localhost:8192/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
this.httpclient.execute(httpget, responseHandler);
assertEquals(4, this.httpclient.getCookieStore().getCookies().size());
}
@Test
public void testNoCookies() throws Exception {
HttpGet httpget = new HttpGet("http://localhost:8192/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
this.httpclient.execute(httpget, responseHandler);
CookieStore cookies = this.httpclient.getCookieStore();
assertEquals(0, cookies.getCookies().size());
}
@Test
public void testServerReceivesCookiesSentFromClient() throws Exception {
BasicClientCookie clientCookie = new BasicClientCookie("name", "value");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 100);
clientCookie.setExpiryDate(calendar.getTime());
clientCookie.setDomain("localhost");
this.httpclient.getCookieStore().addCookie(clientCookie);
HttpGet httpget = new HttpGet("http://localhost:8192/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
this.httpclient.execute(httpget, responseHandler);
assertEquals(1, this.testServer.cookiesReceived.size());
assertTrue(this.testServer.cookiesReceived.get(0).getHTTPHeader().contains("name=value"));
}
@Test
public void testServerReceivesMultipleCookiesSentFromClient() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 100);
Date date = calendar.getTime();
BasicClientCookie clientCookie0 = new BasicClientCookie("name0", "value0");
BasicClientCookie clientCookie1 = new BasicClientCookie("name1", "value1");
BasicClientCookie clientCookie2 = new BasicClientCookie("name2", "value2");
BasicClientCookie clientCookie3 = new BasicClientCookie("name3", "value3");
clientCookie0.setExpiryDate(date);
clientCookie0.setDomain("localhost");
clientCookie1.setExpiryDate(date);
clientCookie1.setDomain("localhost");
clientCookie2.setExpiryDate(date);
clientCookie2.setDomain("localhost");
clientCookie3.setExpiryDate(date);
clientCookie3.setDomain("localhost");
this.httpclient.getCookieStore().addCookie(clientCookie0);
this.httpclient.getCookieStore().addCookie(clientCookie1);
this.httpclient.getCookieStore().addCookie(clientCookie2);
this.httpclient.getCookieStore().addCookie(clientCookie3);
HttpGet httpget = new HttpGet("http://localhost:8192/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
this.httpclient.execute(httpget, responseHandler);
assertEquals(4, this.testServer.cookiesReceived.size());
}
}
|
package org.hisp.dhis.startup;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.jdbc.StatementBuilder;
import org.hisp.dhis.system.startup.AbstractStartupRoutine;
import org.hisp.quick.StatementHolder;
import org.hisp.quick.StatementManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Lars Helge Overland
*/
public class TableAlteror
extends AbstractStartupRoutine
{
private static final Log log = LogFactory.getLog( TableAlteror.class );
// Dependencies
@Autowired
private StatementManager statementManager;
@Autowired
private StatementBuilder statementBuilder;
// Execute
@Override
@Transactional
public void execute()
{
int defaultCategoryComboId = getDefaultCategoryCombo();
int defaultOptionComboId = getDefaultOptionCombo();
// Drop obsolete tables
executeSql( "DROP TABLE categoryoptioncomboname" );
executeSql( "DROP TABLE orgunitgroupsetstructure" );
executeSql( "DROP TABLE orgunitstructure" );
executeSql( "DROP TABLE orgunithierarchystructure" );
executeSql( "DROP TABLE orgunithierarchy" );
executeSql( "DROP TABLE columnorder" );
executeSql( "DROP TABLE roworder" );
executeSql( "DROP TABLE sectionmembers" );
executeSql( "DROP TABLE reporttable_categoryoptioncombos" );
executeSql( "DROP TABLE reporttable_dataelementgroupsets" );
executeSql( "DROP TABLE dashboardcontent_datamartexports" );
executeSql( "DROP TABLE dashboardcontent_mapviews" );
executeSql( "DROP TABLE dashboardcontent_documents" );
executeSql( "DROP TABLE dashboardcontent_maps" );
executeSql( "DROP TABLE dashboardcontent_reports" );
executeSql( "DROP TABLE dashboardcontent_reporttables" );
executeSql( "DROP TABLE dashboardcontent" );
executeSql( "DROP TABLE customvalue" );
executeSql( "DROP TABLE reporttable_displaycolumns" );
executeSql( "DROP TABLE reportreporttables" );
executeSql( "DROP TABLE frequencyoverrideassociation" );
executeSql( "DROP TABLE dataelement_dataelementgroupsetmembers" );
executeSql( "DROP TABLE dashboardcontent_olapurls" );
executeSql( "DROP TABLE olapurl" );
executeSql( "DROP TABLE target" );
executeSql( "DROP TABLE calculateddataelement" );
executeSql( "DROP TABLE systemsequence" );
executeSql( "DROP TABLE reporttablecolumn" );
executeSql( "DROP TABLE datamartexport" );
executeSql( "DROP TABLE datamartexportdataelements" );
executeSql( "DROP TABLE datamartexportindicators" );
executeSql( "DROP TABLE datamartexportorgunits" );
executeSql( "DROP TABLE datamartexportperiods" );
executeSql( "DROP TABLE datasetlockedperiods" );
executeSql( "DROP TABLE datasetlocksource" );
executeSql( "DROP TABLE datasetlock" );
executeSql( "DROP TABLE datasetlockexceptions" );
executeSql( "DROP TABLE indicator_indicatorgroupsetmembers" );
executeSql( "DROP TABLE maplegendsetindicator" );
executeSql( "DROP TABLE maplegendsetdataelement" );
executeSql( "DROP TABLE loginfailure" );
executeSql( "DROP TABLE dashboarditem_trackedentitytabularreports" );
executeSql( "DROP TABLE categoryoptioncombousergroupaccesses" );
executeSql( "DROP TABLE validationrulegroupuserrolestoalert" );
executeSql( "DROP TABLE expressionoptioncombo" );
executeSql( "DROP TABLE orgunitgroupdatasets" );
executeSql( "DROP TABLE datavalue_audit" );
executeSql( "DROP TABLE datadictionaryusergroupaccesses" );
executeSql( "DROP TABLE datadictionaryindicators" );
executeSql( "DROP TABLE datadictionarydataelements" );
executeSql( "DROP TABLE datadictionary" );
executeSql( "DROP TABLE caseaggregationcondition" );
executeSql( "DROP TABLE trackedentitytabularreportusergroupaccesses" );
executeSql( "DROP TABLE trackedentitytabularreport_filters" );
executeSql( "DROP TABLE trackedentitytabularreport_dimensions" );
executeSql( "DROP TABLE trackedentitytabularreport" );
executeSql( "DROP TABLE trackedentityaggregatereportusergroupaccesses" );
executeSql( "DROP TABLE trackedentityaggregatereport_filters" );
executeSql( "DROP TABLE trackedentityaggregatereport_dimension" );
executeSql( "DROP TABLE trackedentityaggregatereport" );
executeSql( "DROP TABLE validationcriteria" );
executeSql( "ALTER TABLE categoryoptioncombo drop column userid" );
executeSql( "ALTER TABLE categoryoptioncombo drop column publicaccess" );
executeSql( "ALTER TABLE categoryoptioncombo alter column name type text" );
executeSql( "ALTER TABLE dataelementcategoryoption drop column categoryid" );
executeSql( "ALTER TABLE reporttable DROP column paramleafparentorganisationunit" );
executeSql( "ALTER TABLE reporttable DROP column dimension_type" );
executeSql( "ALTER TABLE reporttable DROP column dimensiontype" );
executeSql( "ALTER TABLE reporttable DROP column tablename" );
executeSql( "ALTER TABLE reporttable DROP column existingtablename" );
executeSql( "ALTER TABLE reporttable DROP column docategoryoptioncombos" );
executeSql( "ALTER TABLE reporttable DROP column mode" );
executeSql( "ALTER TABLE categoryoptioncombo DROP COLUMN displayorder" );
executeSql( "ALTER TABLE section DROP COLUMN label" );
executeSql( "ALTER TABLE section DROP COLUMN title" );
executeSql( "ALTER TABLE organisationunit DROP COLUMN polygoncoordinates" );
executeSql( "ALTER TABLE organisationunit DROP COLUMN geocode" );
executeSql( "ALTER TABLE indicator DROP COLUMN extendeddataelementid" );
executeSql( "ALTER TABLE indicator DROP COLUMN numeratoraggregationtype" );
executeSql( "ALTER TABLE indicator DROP COLUMN denominatoraggregationtype" );
executeSql( "ALTER TABLE dataset DROP COLUMN locked" );
executeSql( "ALTER TABLE dataset DROP COLUMN skipaggregation" );
executeSql( "ALTER TABLE configuration DROP COLUMN completenessrecipientsid" );
executeSql( "ALTER TABLE dataelement DROP COLUMN alternativename" );
executeSql( "ALTER TABLE dataelement DROP COLUMN aggregateexportcategoryoptioncombo" );
executeSql( "ALTER TABLE dataelement DROP COLUMN aggregateexportattributeoptioncombo" );
executeSql( "ALTER TABLE dataset DROP COLUMN aggregateexportcategoryoptioncombo" );
executeSql( "ALTER TABLE dataset DROP COLUMN aggregateexportattributeoptioncombo" );
executeSql( "ALTER TABLE indicator DROP COLUMN alternativename" );
executeSql( "ALTER TABLE orgunitgroup DROP COLUMN image" );
executeSql( "ALTER TABLE report DROP COLUMN usingorgunitgroupsets" );
executeSql( "ALTER TABLE eventchart DROP COLUMN datatype" );
executeSql( "ALTER TABLE validationrule DROP COLUMN type" );
executeSql( "ALTER TABLE organisationunit DROP COLUMN active" );
executeSql( "ALTER TABLE organisationunit DROP COLUMN uuid" );
executeSql( "DROP INDEX datamart_crosstab" );
// prepare uid function
insertUidDbFunction();
// remove relative period type
executeSql( "DELETE FROM period WHERE periodtypeid=(select periodtypeid from periodtype where name in ( 'Survey', 'OnChange', 'Relative' ))" );
executeSql( "DELETE FROM periodtype WHERE name in ( 'Survey', 'OnChange', 'Relative' )" );
// mapping
executeSql( "DROP TABLE maporganisationunitrelation" );
executeSql( "ALTER TABLE mapview DROP COLUMN mapid" );
executeSql( "ALTER TABLE mapview DROP COLUMN mapsource" );
executeSql( "ALTER TABLE mapview DROP COLUMN mapsourcetype" );
executeSql( "ALTER TABLE mapview DROP COLUMN mapdatetype" );
executeSql( "ALTER TABLE mapview DROP COLUMN featuretype" );
executeSql( "ALTER TABLE mapview DROP COLUMN bounds" );
executeSql( "ALTER TABLE mapview DROP COLUMN valuetype" );
executeSql( "ALTER TABLE mapview DROP COLUMN legendtype" );
executeSql( "ALTER TABLE mapview ALTER COLUMN opacity TYPE double precision" );
executeSql( "UPDATE incomingsms SET userid = 0 WHERE userid IS NULL" );
executeSql( "ALTER TABLE smscommands ALTER COLUMN completenessmethod TYPE text" );
executeSql( "UPDATE smscommands SET completenessmethod='ALL_DATAVALUE' WHERE completenessmethod='1'" );
executeSql( "UPDATE smscommands SET completenessmethod='AT_LEAST_ONE_DATAVALUE' WHERE completenessmethod='2'" );
executeSql( "UPDATE smscommands SET completenessmethod='DO_NOT_MARK_COMPLETE' WHERE completenessmethod='3'" );
executeSql( "ALTER TABLE smscommands ALTER COLUMN uid set NOT NULL" );
executeSql( "ALTER TABLE smscommands ALTER COLUMN created set NOT NULL" );
executeSql( "ALTER TABLE smscommands ALTER COLUMN lastUpdated set NOT NULL" );
executeSql( "ALTER TABLE maplegend DROP CONSTRAINT maplegend_name_key" );
executeSql( "UPDATE mapview SET layer = 'thematic1' WHERE layer IS NULL" );
executeSql( "UPDATE mapview SET hidden = false WHERE hidden IS NULL" );
executeSql( "UPDATE mapview SET eventclustering = false WHERE eventclustering IS NULL" );
executeSql( "UPDATE mapview SET eventpointradius = 0 WHERE eventpointradius IS NULL" );
executeSql( "UPDATE programnotificationtemplate SET trackedentityattributeid = 0 WHERE trackedentityattributeid IS NULL" );
executeSql( "UPDATE programnotificationtemplate SET dataelementid = 0 WHERE dataelementid IS NULL" );
executeSql( "DELETE FROM systemsetting WHERE name = 'longitude'" );
executeSql( "DELETE FROM systemsetting WHERE name = 'latitude'" );
executeSql( "DELETE FROM systemsetting WHERE name = 'keySystemMonitoringUrl'" );
executeSql( "DELETE FROM systemsetting WHERE name = 'keySystemMonitoringUsername'" );
executeSql( "DELETE FROM systemsetting WHERE name = 'keySystemMonitoringPassword'" );
executeSql( "ALTER TABLE maplayer DROP CONSTRAINT maplayer_mapsource_key" );
executeSql( "ALTER TABLE maplayer DROP COLUMN mapsource" );
executeSql( "ALTER TABLE maplayer DROP COLUMN mapsourcetype" );
executeSql( "ALTER TABLE maplayer DROP COLUMN layer" );
// extended data element
executeSql( "ALTER TABLE dataelement DROP CONSTRAINT fk_dataelement_extendeddataelementid" );
executeSql( "ALTER TABLE dataelement DROP COLUMN extendeddataelementid" );
executeSql( "ALTER TABLE indicator DROP CONSTRAINT fk_indicator_extendeddataelementid" );
executeSql( "ALTER TABLE indicator DROP COLUMN extendeddataelementid" );
executeSql( "DROP TABLE extendeddataelement" );
executeSql( "ALTER TABLE organisationunit DROP COLUMN hasPatients" );
// category combo not null
executeSql( "update dataelement set categorycomboid = " + defaultCategoryComboId + " where categorycomboid is null" );
executeSql( "alter table dataelement alter column categorycomboid set not null" );
executeSql( "update dataset set categorycomboid = " + defaultCategoryComboId + " where categorycomboid is null" );
executeSql( "alter table dataset alter column categorycomboid set not null" );
executeSql( "update program set categorycomboid = " + defaultCategoryComboId + " where categorycomboid is null" );
executeSql( "alter table program alter column categorycomboid set not null" );
// categories_categoryoptions
// set to 0 temporarily
int c1 = executeSql( "UPDATE categories_categoryoptions SET sort_order=0 WHERE sort_order is NULL OR sort_order=0" );
if ( c1 > 0 )
{
updateSortOrder( "categories_categoryoptions", "categoryid", "categoryoptionid" );
}
executeSql( "ALTER TABLE categories_categoryoptions DROP CONSTRAINT categories_categoryoptions_pkey" );
executeSql( "ALTER TABLE categories_categoryoptions ADD CONSTRAINT categories_categoryoptions_pkey PRIMARY KEY (categoryid, sort_order)" );
// categorycombos_categories
// set to 0 temporarily
int c2 = executeSql( "update categorycombos_categories SET sort_order=0 where sort_order is NULL OR sort_order=0" );
if ( c2 > 0 )
{
updateSortOrder( "categorycombos_categories", "categorycomboid", "categoryid" );
}
executeSql( "ALTER TABLE categorycombos_categories DROP CONSTRAINT categorycombos_categories_pkey" );
executeSql( "ALTER TABLE categorycombos_categories ADD CONSTRAINT categorycombos_categories_pkey PRIMARY KEY (categorycomboid, sort_order)" );
// categorycombos_optioncombos
executeSql( "ALTER TABLE categorycombos_optioncombos DROP CONSTRAINT categorycombos_optioncombos_pkey" );
executeSql( "ALTER TABLE categorycombos_optioncombos ADD CONSTRAINT categorycombos_optioncombos_pkey PRIMARY KEY (categoryoptioncomboid)" );
executeSql( "ALTER TABLE categorycombos_optioncombos DROP CONSTRAINT fk4bae70f697e49675" );
// categoryoptioncombos_categoryoptions
executeSql( "alter table categoryoptioncombos_categoryoptions drop column sort_order" );
executeSql( "alter table categoryoptioncombos_categoryoptions add constraint categoryoptioncombos_categoryoptions_pkey primary key(categoryoptioncomboid, categoryoptionid)" );
// dataelementcategoryoption
executeSql( "ALTER TABLE dataelementcategoryoption DROP CONSTRAINT fk_dataelement_categoryid" );
executeSql( "ALTER TABLE dataelementcategoryoption DROP CONSTRAINT dataelementcategoryoption_shortname_key" );
// minmaxdataelement - If the old, non-unique index exists, drop it, make sure there are no duplicate values (delete the older ones), then create the unique index.
if ( executeSql( "DROP INDEX index_minmaxdataelement" ) == 0 )
{
executeSql( "delete from minmaxdataelement where minmaxdataelementid in (" +
"select a.minmaxdataelementid from minmaxdataelement a " +
"join minmaxdataelement b on a.sourceid = b.sourceid and a.dataelementid = b.dataelementid " +
"and a.categoryoptioncomboid = b.categoryoptioncomboid and a.minmaxdataelementid < b.minmaxdataelementid)" );
executeSql( "CREATE UNIQUE INDEX minmaxdataelement_unique_key ON minmaxdataelement USING btree (sourceid, dataelementid, categoryoptioncomboid)" );
}
// update periodType field to ValidationRule
executeSql( "UPDATE validationrule SET periodtypeid = (SELECT periodtypeid FROM periodtype WHERE name='Monthly') WHERE periodtypeid is null" );
// set varchar to text
executeSql( "ALTER TABLE dataelement ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE dataelementgroupset ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE indicatorgroupset ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE orgunitgroupset ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE indicator ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE validationrule ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE expression ALTER COLUMN expression TYPE text" );
executeSql( "ALTER TABLE translation ALTER COLUMN value TYPE text" );
executeSql( "ALTER TABLE organisationunit ALTER COLUMN comment TYPE text" );
executeSql( "ALTER TABLE program ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE trackedentityattribute ALTER COLUMN description TYPE text" );
executeSql( "ALTER TABLE programrule ALTER COLUMN condition TYPE text" );
executeSql( "ALTER TABLE programruleaction ALTER COLUMN content TYPE text" );
executeSql( "ALTER TABLE programruleaction ALTER COLUMN data TYPE text" );
executeSql( "ALTER TABLE trackedentitycomment ALTER COLUMN commenttext TYPE text" );
executeSql( "ALTER TABLE users ALTER COLUMN openid TYPE text" );
executeSql( "ALTER TABLE users ALTER COLUMN ldapid TYPE text" );
executeSql( "ALTER TABLE dataentryform ALTER COLUMN htmlcode TYPE text" );
executeSql( "ALTER TABLE minmaxdataelement RENAME minvalue TO minimumvalue" );
executeSql( "ALTER TABLE minmaxdataelement RENAME maxvalue TO maximumvalue" );
executeSql( "update minmaxdataelement set generatedvalue = generated where generatedvalue is null" );
executeSql( "alter table minmaxdataelement drop column generated" );
executeSql( "alter table minmaxdataelement alter column generatedvalue set not null" );
// orgunit shortname uniqueness
executeSql( "ALTER TABLE organisationunit DROP CONSTRAINT organisationunit_shortname_key" );
executeSql( "ALTER TABLE section DROP CONSTRAINT section_name_key" );
executeSql( "UPDATE section SET showrowtotals = false WHERE showrowtotals IS NULL" );
executeSql( "UPDATE section SET showcolumntotals = false WHERE showcolumntotals IS NULL" );
executeSql( "UPDATE dataelement SET aggregationtype='avg_sum_org_unit' where aggregationtype='average'" );
executeSql( "UPDATE dataelement SET aggregationtype='AVERAGE' where aggregationtype='AVERAGE_SUM_INT'" );
executeSql( "UPDATE dataelement SET aggregationtype='AVERAGE' where aggregationtype='AVERAGE_SUM_INT_DISAGGREGATION'" );
executeSql( "UPDATE dataelement SET aggregationtype='AVERAGE' where aggregationtype='AVERAGE_INT'" );
executeSql( "UPDATE dataelement SET aggregationtype='AVERAGE' where aggregationtype='AVERAGE_INT_DISAGGREGATION'" );
executeSql( "UPDATE dataelement SET aggregationtype='AVERAGE' where aggregationtype='AVERAGE_BOOL'" );
// revert prepare aggregate*Value tables for offline diffs
executeSql( "ALTER TABLE aggregateddatavalue DROP COLUMN modified" );
executeSql( "ALTER TABLE aggregatedindicatorvalue DROP COLUMN modified " );
executeSql( "UPDATE indicatortype SET indicatornumber=false WHERE indicatornumber is null" );
// program
executeSql( "ALTER TABLE programinstance ALTER COLUMN patientid DROP NOT NULL" );
// migrate charts from dimension to category, series, filter
executeSql( "UPDATE chart SET series='period', category='data', filter='organisationunit' WHERE dimension='indicator'" );
executeSql( "UPDATE chart SET series='data', category='organisationunit', filter='period' WHERE dimension='organisationUnit'" );
executeSql( "UPDATE chart SET series='period', category='data', filter='organisationunit' WHERE dimension='dataElement_period'" );
executeSql( "UPDATE chart SET series='data', category='organisationunit', filter='period' WHERE dimension='organisationUnit_dataElement'" );
executeSql( "UPDATE chart SET series='data', category='period', filter='organisationunit' WHERE dimension='period'" );
executeSql( "UPDATE chart SET series='data', category='period', filter='organisationunit' WHERE dimension='period_dataElement'" );
executeSql( "UPDATE chart SET type='bar' where type='bar3d'" );
executeSql( "UPDATE chart SET type='stackedbar' where type='stackedBar'" );
executeSql( "UPDATE chart SET type='stackedbar' where type='stackedBar3d'" );
executeSql( "UPDATE chart SET type='line' where type='line3d'" );
executeSql( "UPDATE chart SET type='pie' where type='pie'" );
executeSql( "UPDATE chart SET type='pie' where type='pie3d'" );
executeSql( "UPDATE programruleaction SET programnotificationtemplateid= 0 where programnotificationtemplateid is NULL" );
executeSql( "UPDATE chart SET type=lower(type), series=lower(series), category=lower(category), filter=lower(filter)" );
executeSql( "ALTER TABLE chart ALTER COLUMN dimension DROP NOT NULL" );
executeSql( "ALTER TABLE chart DROP COLUMN size" );
executeSql( "ALTER TABLE chart DROP COLUMN verticallabels" );
executeSql( "ALTER TABLE chart DROP COLUMN targetline" );
executeSql( "ALTER TABLE chart DROP COLUMN horizontalplotorientation" );
executeSql( "ALTER TABLE chart DROP COLUMN monthsLastYear" );
executeSql( "ALTER TABLE chart DROP COLUMN quartersLastYear" );
executeSql( "ALTER TABLE chart DROP COLUMN last6BiMonths" );
executeSql( "ALTER TABLE chart DROP CONSTRAINT chart_title_key" );
executeSql( "ALTER TABLE chart DROP CONSTRAINT chart_name_key" );
executeSql( "ALTER TABLE chart DROP COLUMN domainaxixlabel" );
executeSql( "ALTER TABLE chart DROP COLUMN rewindrelativeperiods" );
executeSql( "ALTER TABLE chart ALTER hideLegend DROP NOT NULL" );
executeSql( "ALTER TABLE chart ALTER regression DROP NOT NULL" );
executeSql( "ALTER TABLE chart ALTER hideSubtitle DROP NOT NULL" );
executeSql( "ALTER TABLE chart ALTER userOrganisationUnit DROP NOT NULL" );
// remove outdated relative periods
executeSql( "ALTER TABLE reporttable DROP COLUMN last6months" );
executeSql( "ALTER TABLE reporttable DROP COLUMN last9months" );
executeSql( "ALTER TABLE reporttable DROP COLUMN sofarthisyear" );
executeSql( "ALTER TABLE reporttable DROP COLUMN sofarthisfinancialyear" );
executeSql( "ALTER TABLE reporttable DROP COLUMN last3to6months" );
executeSql( "ALTER TABLE reporttable DROP COLUMN last6to9months" );
executeSql( "ALTER TABLE reporttable DROP COLUMN last9to12months" );
executeSql( "ALTER TABLE reporttable DROP COLUMN last12individualmonths" );
executeSql( "ALTER TABLE reporttable DROP COLUMN individualmonthsthisyear" );
executeSql( "ALTER TABLE reporttable DROP COLUMN individualquartersthisyear" );
executeSql( "ALTER TABLE reporttable DROP COLUMN programid" );
executeSql( "ALTER TABLE chart DROP COLUMN last6months" );
executeSql( "ALTER TABLE chart DROP COLUMN last9months" );
executeSql( "ALTER TABLE chart DROP COLUMN sofarthisyear" );
executeSql( "ALTER TABLE chart DROP COLUMN sofarthisfinancialyear" );
executeSql( "ALTER TABLE chart DROP COLUMN last3to6months" );
executeSql( "ALTER TABLE chart DROP COLUMN last6to9months" );
executeSql( "ALTER TABLE chart DROP COLUMN last9to12months" );
executeSql( "ALTER TABLE chart DROP COLUMN last12individualmonths" );
executeSql( "ALTER TABLE chart DROP COLUMN individualmonthsthisyear" );
executeSql( "ALTER TABLE chart DROP COLUMN individualquartersthisyear" );
executeSql( "ALTER TABLE chart DROP COLUMN organisationunitgroupsetid" );
executeSql( "ALTER TABLE chart DROP COLUMN programid" );
// remove source
executeSql( "ALTER TABLE datasetsource DROP CONSTRAINT fk766ae2938fd8026a" );
executeSql( "ALTER TABLE datasetlocksource DROP CONSTRAINT fk582fdf7e8fd8026a" );
executeSql( "ALTER TABLE completedatasetregistration DROP CONSTRAINT fk_datasetcompleteregistration_sourceid" );
executeSql( "ALTER TABLE minmaxdataelement DROP CONSTRAINT fk_minmaxdataelement_sourceid" );
executeSql( "ALTER TABLE datavalue DROP CONSTRAINT fk_datavalue_sourceid" );
executeSql( "ALTER TABLE organisationunit DROP CONSTRAINT fke509dd5ef1c932ed" );
executeSql( "DROP TABLE source CASCADE" );
executeSql( "DROP TABLE datavaluearchive" );
// message
executeSql( "ALTER TABLE messageconversation DROP COLUMN messageconversationkey" );
executeSql( "UPDATE messageconversation SET lastmessage=lastupdated WHERE lastmessage is null" );
executeSql( "ALTER TABLE message DROP COLUMN messagesubject" );
executeSql( "ALTER TABLE message DROP COLUMN messagekey" );
executeSql( "ALTER TABLE message DROP COLUMN sentdate" );
executeSql( "ALTER TABLE usermessage DROP COLUMN messagedate" );
executeSql( "UPDATE usermessage SET isfollowup=false WHERE isfollowup is null" );
executeSql( "DROP TABLE message_usermessages" );
// create code unique constraints
executeSql( "ALTER TABLE dataelement ADD CONSTRAINT dataelement_code_key UNIQUE(code)" );
executeSql( "ALTER TABLE indicator ADD CONSTRAINT indicator_code_key UNIQUE(code)" );
executeSql( "ALTER TABLE organisationunit ADD CONSTRAINT organisationunit_code_key UNIQUE(code)" );
executeSql( "ALTER TABLE organisationunit ALTER COLUMN code TYPE varchar(50)" );
executeSql( "ALTER TABLE indicator ALTER COLUMN code TYPE varchar(50)" );
// remove uuid
executeSql( "ALTER TABLE attribute DROP COLUMN uuid" );
executeSql( "ALTER TABLE categorycombo DROP COLUMN uuid" );
executeSql( "ALTER TABLE categoryoptioncombo DROP COLUMN uuid" );
executeSql( "ALTER TABLE chart DROP COLUMN uuid" );
executeSql( "ALTER TABLE concept DROP COLUMN uuid" );
executeSql( "ALTER TABLE constant DROP COLUMN uuid" );
executeSql( "ALTER TABLE dataelement DROP COLUMN uuid" );
executeSql( "ALTER TABLE dataelementcategory DROP COLUMN uuid" );
executeSql( "ALTER TABLE dataelementcategoryoption DROP COLUMN uuid" );
executeSql( "ALTER TABLE dataelementgroup DROP COLUMN uuid" );
executeSql( "ALTER TABLE dataelementgroupset DROP COLUMN uuid" );
executeSql( "ALTER TABLE dataset DROP COLUMN uuid" );
executeSql( "ALTER TABLE indicator DROP COLUMN uuid" );
executeSql( "ALTER TABLE indicatorgroup DROP COLUMN uuid" );
executeSql( "ALTER TABLE indicatorgroupset DROP COLUMN uuid" );
executeSql( "ALTER TABLE indicatortype DROP COLUMN uuid" );
// executeSql( "ALTER TABLE organisationunit DROP COLUMN uuid" );
executeSql( "ALTER TABLE orgunitgroup DROP COLUMN uuid" );
executeSql( "ALTER TABLE orgunitgroupset DROP COLUMN uuid" );
executeSql( "ALTER TABLE orgunitlevel DROP COLUMN uuid" );
executeSql( "ALTER TABLE report DROP COLUMN uuid" );
executeSql( "ALTER TABLE validationrule DROP COLUMN uuid" );
executeSql( "ALTER TABLE validationrulegroup DROP COLUMN uuid" );
// replace null with false for boolean fields
executeSql( "update dataset set fieldcombinationrequired = false where fieldcombinationrequired is null" );
executeSql( "update chart set hidelegend = false where hidelegend is null" );
executeSql( "update chart set regression = false where regression is null" );
executeSql( "update chart set hidesubtitle = false where hidesubtitle is null" );
executeSql( "update chart set userorganisationunit = false where userorganisationunit is null" );
executeSql( "update chart set percentstackedvalues = false where percentstackedvalues is null" );
executeSql( "update chart set cumulativevalues = false where cumulativevalues is null" );
executeSql( "update chart set nospacebetweencolumns = false where nospacebetweencolumns is null" );
executeSql( "update indicator set annualized = false where annualized is null" );
executeSql( "update indicatortype set indicatornumber = false where indicatornumber is null" );
executeSql( "update dataset set mobile = false where mobile is null" );
executeSql( "update dataset set allowfutureperiods = false where allowfutureperiods is null" );
executeSql( "update dataset set validcompleteonly = false where validcompleteonly is null" );
executeSql( "update dataset set notifycompletinguser = false where notifycompletinguser is null" );
executeSql( "update dataset set approvedata = false where approvedata is null" );
executeSql( "update dataelement set zeroissignificant = false where zeroissignificant is null" );
executeSql( "update organisationunit set haspatients = false where haspatients is null" );
executeSql( "update organisationunit set openingdate = '1970-01-01' where openingdate is null" );
executeSql( "update dataset set expirydays = 0 where expirydays is null" );
executeSql( "update eventchart set hidelegend = false where hidelegend is null" );
executeSql( "update eventchart set regression = false where regression is null" );
executeSql( "update eventchart set hidetitle = false where hidetitle is null" );
executeSql( "update eventchart set hidesubtitle = false where hidesubtitle is null" );
executeSql( "update eventchart set hidenadata = false where hidenadata is null" );
executeSql( "update eventchart set percentstackedvalues = false where percentstackedvalues is null" );
executeSql( "update eventchart set cumulativevalues = false where cumulativevalues is null" );
executeSql( "update eventchart set nospacebetweencolumns = false where nospacebetweencolumns is null" );
executeSql( "update reporttable set showdimensionlabels = false where showdimensionlabels is null" );
executeSql( "update eventreport set showdimensionlabels = false where showdimensionlabels is null" );
executeSql( "update reporttable set skiprounding = false where skiprounding is null" );
executeSql( "update validationrule set skipformvalidation = false where skipformvalidation is null" );
executeSql( "update validationnotificationtemplate set sendstrategy = 'COLLECTIVE_SUMMARY' where sendstrategy is null" );
// move timelydays from system setting => dataset property
executeSql( "update dataset set timelydays = 15 where timelydays is null" );
executeSql( "delete from systemsetting where name='completenessOffset'" );
executeSql( "update report set paramreportingmonth = false where paramreportingmonth is null" );
executeSql( "update report set paramparentorganisationunit = false where paramorganisationunit is null" );
executeSql( "update reporttable set paramreportingmonth = false where paramreportingmonth is null" );
executeSql( "update reporttable set paramparentorganisationunit = false where paramparentorganisationunit is null" );
executeSql( "update reporttable set paramorganisationunit = false where paramorganisationunit is null" );
executeSql( "update reporttable set paramgrandparentorganisationunit = false where paramgrandparentorganisationunit is null" );
executeSql( "update reporttable set reportingmonth = false where reportingmonth is null" );
executeSql( "update reporttable set reportingbimonth = false where reportingbimonth is null" );
executeSql( "update reporttable set reportingquarter = false where reportingquarter is null" );
executeSql( "update reporttable set monthsthisyear = false where monthsthisyear is null" );
executeSql( "update reporttable set quartersthisyear = false where quartersthisyear is null" );
executeSql( "update reporttable set thisyear = false where thisyear is null" );
executeSql( "update reporttable set monthslastyear = false where monthslastyear is null" );
executeSql( "update reporttable set quarterslastyear = false where quarterslastyear is null" );
executeSql( "update reporttable set lastyear = false where lastyear is null" );
executeSql( "update reporttable set last5years = false where last5years is null" );
executeSql( "update reporttable set lastsixmonth = false where lastsixmonth is null" );
executeSql( "update reporttable set last4quarters = false where last4quarters is null" );
executeSql( "update reporttable set last12months = false where last12months is null" );
executeSql( "update reporttable set last3months = false where last3months is null" );
executeSql( "update reporttable set last6bimonths = false where last6bimonths is null" );
executeSql( "update reporttable set last4quarters = false where last4quarters is null" );
executeSql( "update reporttable set last2sixmonths = false where last2sixmonths is null" );
executeSql( "update reporttable set thisfinancialyear = false where thisfinancialyear is null" );
executeSql( "update reporttable set lastfinancialyear = false where lastfinancialyear is null" );
executeSql( "update reporttable set last5financialyears = false where last5financialyears is null" );
executeSql( "update reporttable set cumulative = false where cumulative is null" );
executeSql( "update reporttable set userorganisationunit = false where userorganisationunit is null" );
executeSql( "update reporttable set userorganisationunitchildren = false where userorganisationunitchildren is null" );
executeSql( "update reporttable set userorganisationunitgrandchildren = false where userorganisationunitgrandchildren is null" );
executeSql( "update reporttable set subtotals = true where subtotals is null" );
executeSql( "update reporttable set hideemptyrows = false where hideemptyrows is null" );
executeSql( "update reporttable set hideemptycolumns = false where hideemptycolumns is null" );
executeSql( "update reporttable set displaydensity = 'normal' where displaydensity is null" );
executeSql( "update reporttable set fontsize = 'normal' where fontsize is null" );
executeSql( "update reporttable set digitgroupseparator = 'space' where digitgroupseparator is null" );
executeSql( "update reporttable set sortorder = 0 where sortorder is null" );
executeSql( "update reporttable set toplimit = 0 where toplimit is null" );
executeSql( "update reporttable set showhierarchy = false where showhierarchy is null" );
executeSql( "update reporttable set legenddisplaystyle = 'FILL' where legenddisplaystyle is null" );
executeSql( "update reporttable set legenddisplaystrategy = 'FIXED' where legenddisplaystrategy is null" );
executeSql( "update reporttable set hidetitle = false where hidetitle is null" );
executeSql( "update reporttable set hidesubtitle = false where hidesubtitle is null" );
// reporttable col/row totals = keep existing || copy from totals || true
executeSql( "update reporttable set totals = true where totals is null" );
executeSql( "update reporttable set coltotals = totals where coltotals is null" );
executeSql( "update reporttable set coltotals = true where coltotals is null" );
executeSql( "update reporttable set rowtotals = totals where rowtotals is null" );
executeSql( "update reporttable set rowtotals = true where rowtotals is null" );
executeSql( "alter table reporttable drop column totals" );
// reporttable col/row subtotals
executeSql( "update reporttable set colsubtotals = subtotals where colsubtotals is null" );
executeSql( "update reporttable set rowsubtotals = subtotals where rowsubtotals is null" );
// reporttable upgrade counttype to outputtype
executeSql( "update eventreport set outputtype = 'EVENT' where outputtype is null and counttype = 'events'" );
executeSql( "update eventreport set outputtype = 'TRACKED_ENTITY_INSTANCE' where outputtype is null and counttype = 'tracked_entity_instances'" );
executeSql( "update eventreport set hidetitle = false where hidetitle is null" );
executeSql( "update eventreport set hidesubtitle = false where hidesubtitle is null" );
executeSql( "update eventreport set outputtype = 'EVENT' where outputtype is null" );
executeSql( "alter table eventreport drop column counttype" );
executeSql( "update chart set reportingmonth = false where reportingmonth is null" );
executeSql( "update chart set reportingbimonth = false where reportingbimonth is null" );
executeSql( "update chart set reportingquarter = false where reportingquarter is null" );
executeSql( "update chart set monthsthisyear = false where monthsthisyear is null" );
executeSql( "update chart set quartersthisyear = false where quartersthisyear is null" );
executeSql( "update chart set thisyear = false where thisyear is null" );
executeSql( "update chart set monthslastyear = false where monthslastyear is null" );
executeSql( "update chart set quarterslastyear = false where quarterslastyear is null" );
executeSql( "update chart set lastyear = false where lastyear is null" );
executeSql( "update chart set lastsixmonth = false where lastsixmonth is null" );
executeSql( "update chart set last12months = false where last12months is null" );
executeSql( "update chart set last3months = false where last3months is null" );
executeSql( "update chart set last5years = false where last5years is null" );
executeSql( "update chart set last4quarters = false where last4quarters is null" );
executeSql( "update chart set last6bimonths = false where last6bimonths is null" );
executeSql( "update chart set last4quarters = false where last4quarters is null" );
executeSql( "update chart set last2sixmonths = false where last2sixmonths is null" );
executeSql( "update chart set showdata = false where showdata is null" );
executeSql( "update chart set userorganisationunit = false where userorganisationunit is null" );
executeSql( "update chart set userorganisationunitchildren = false where userorganisationunitchildren is null" );
executeSql( "update chart set userorganisationunitgrandchildren = false where userorganisationunitgrandchildren is null" );
executeSql( "update chart set hidetitle = false where hidetitle is null" );
executeSql( "update chart set sortorder = 0 where sortorder is null" );
executeSql( "update eventreport set showhierarchy = false where showhierarchy is null" );
executeSql( "update eventreport set counttype = 'events' where counttype is null" );
executeSql( "update eventreport set hidenadata = false where hidenadata is null" );
// eventreport col/rowtotals = keep existing || copy from totals || true
executeSql( "update eventreport set totals = true where totals is null" );
executeSql( "update eventreport set coltotals = totals where coltotals is null" );
executeSql( "update eventreport set coltotals = true where coltotals is null" );
executeSql( "update eventreport set rowtotals = totals where rowtotals is null" );
executeSql( "update eventreport set rowtotals = true where rowtotals is null" );
executeSql( "alter table eventreport drop column totals" );
// eventreport col/row subtotals
executeSql( "update eventreport set colsubtotals = subtotals where colsubtotals is null" );
executeSql( "update eventreport set rowsubtotals = subtotals where rowsubtotals is null" );
// eventchart upgrade counttype to outputtype
executeSql( "update eventchart set outputtype = 'EVENT' where outputtype is null and counttype = 'events'" );
executeSql( "update eventchart set outputtype = 'TRACKED_ENTITY_INSTANCE' where outputtype is null and counttype = 'tracked_entity_instances'" );
executeSql( "update eventchart set outputtype = 'EVENT' where outputtype is null" );
executeSql( "alter table eventchart drop column counttype" );
executeSql( "update eventchart set sortorder = 0 where sortorder is null" );
// Move chart filters to chart_filters table
executeSql( "insert into chart_filters (chartid, sort_order, filter) select chartid, 0, filter from chart" );
executeSql( "alter table chart drop column filter" );
// Upgrade chart dimension identifiers
executeSql( "update chart set series = 'dx' where series = 'data'" );
executeSql( "update chart set series = 'pe' where series = 'period'" );
executeSql( "update chart set series = 'ou' where series = 'organisationunit'" );
executeSql( "update chart set category = 'dx' where category = 'data'" );
executeSql( "update chart set category = 'pe' where category = 'period'" );
executeSql( "update chart set category = 'ou' where category = 'organisationunit'" );
executeSql( "update chart_filters set filter = 'dx' where filter = 'data'" );
executeSql( "update chart_filters set filter = 'pe' where filter = 'period'" );
executeSql( "update chart_filters set filter = 'ou' where filter = 'organisationunit'" );
executeSql( "update dataentryform set format = 1 where format is null" );
executeSql( "update dataelementgroup set shortname=name where shortname is null and length(name)<=50" );
executeSql( "update orgunitgroup set shortname=name where shortname is null and length(name)<=50" );
// report, reporttable, chart groups
executeSql( "DROP TABLE reportgroupmembers" );
executeSql( "DROP TABLE reportgroup" );
executeSql( "DROP TABLE reporttablegroupmembers" );
executeSql( "DROP TABLE reporttablegroup" );
executeSql( "DROP TABLE chartgroupmembers" );
executeSql( "DROP TABLE chartgroup" );
executeSql( "delete from usersetting where name='currentStyle' and value like '%blue/blue.css'" );
executeSql( "delete from systemsetting where name='currentStyle' and value like '%blue/blue.css'" );
executeSql( "update dataentryform set style='regular' where style is null" );
executeSql( "UPDATE dataset SET skipaggregation = false WHERE skipaggregation IS NULL" );
executeSql( "UPDATE dataset SET skipoffline = false WHERE skipoffline IS NULL" );
executeSql( "UPDATE dataset SET renderastabs = false WHERE renderastabs IS NULL" );
executeSql( "UPDATE dataset SET renderhorizontally = false WHERE renderhorizontally IS NULL" );
executeSql( "UPDATE dataset SET novaluerequirescomment = false WHERE novaluerequirescomment IS NULL" );
executeSql( "UPDATE dataset SET openfutureperiods = 12 where allowfutureperiods is true" );
executeSql( "UPDATE dataset SET openfutureperiods = 0 where allowfutureperiods is false" );
executeSql( "update dataset SET compulsoryfieldscompleteonly = false WHERE compulsoryfieldscompleteonly IS NULL" );
executeSql( "ALTER TABLE dataset DROP COLUMN allowfutureperiods" );
executeSql( "UPDATE categorycombo SET skiptotal = false WHERE skiptotal IS NULL" );
// short names
executeSql( "ALTER TABLE dataelement ALTER COLUMN shortname TYPE character varying(50)" );
executeSql( "ALTER TABLE indicator ALTER COLUMN shortname TYPE character varying(50)" );
executeSql( "ALTER TABLE dataset ALTER COLUMN shortname TYPE character varying(50)" );
executeSql( "ALTER TABLE organisationunit ALTER COLUMN shortname TYPE character varying(50)" );
executeSql( "update report set type='jasperReportTable' where type is null and reporttableid is not null" );
executeSql( "update report set type='jasperJdbc' where type is null and reporttableid is null" );
// upgrade authorities
executeSql( "UPDATE userroleauthorities SET authority='F_DOCUMENT_PUBLIC_ADD' WHERE authority='F_DOCUMENT_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_REPORT_PUBLIC_ADD' WHERE authority='F_REPORT_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_REPORTTABLE_PUBLIC_ADD' WHERE authority='F_REPORTTABLE_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_DATASET_PUBLIC_ADD' WHERE authority='F_DATASET_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_DATAELEMENT_PUBLIC_ADD' WHERE authority='F_DATAELEMENT_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_DATAELEMENTGROUP_PUBLIC_ADD' WHERE authority='F_DATAELEMENTGROUP_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_DATAELEMENTGROUPSET_PUBLIC_ADD' WHERE authority='F_DATAELEMENTGROUPSET_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_ORGUNITGROUP_PUBLIC_ADD' WHERE authority='F_ORGUNITGROUP_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_ORGUNITGROUPSET_PUBLIC_ADD' WHERE authority='F_ORGUNITGROUPSET_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_INDICATOR_PUBLIC_ADD' WHERE authority='F_INDICATOR_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_INDICATORGROUP_PUBLIC_ADD' WHERE authority='F_INDICATORGROUP_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_INDICATORGROUPSET_PUBLIC_ADD' WHERE authority='F_INDICATORGROUPSET_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_USERROLE_PUBLIC_ADD' WHERE authority='F_USERROLE_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_USERGROUP_PUBLIC_ADD' WHERE authority='F_USER_GRUP_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_USERGROUP_UPDATE' WHERE authority='F_USER_GRUP_UPDATE'" );
executeSql( "UPDATE userroleauthorities SET authority='F_USERGROUP_DELETE' WHERE authority='F_USER_GRUP_DELETE'" );
executeSql( "UPDATE userroleauthorities SET authority='F_USERGROUP_LIST' WHERE authority='F_USER_GRUP_LIST'" );
executeSql( "UPDATE userroleauthorities SET authority='F_SQLVIEW_PUBLIC_ADD' WHERE authority='F_SQLVIEW_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_OPTIONSET_PUBLIC_ADD' WHERE authority='F_OPTIONSET_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_VALIDATIONRULEGROUP_PUBLIC_ADD' WHERE authority='F_VALIDATIONRULEGROUP_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_TRACKED_ENTITY_ATTRIBUTE_PUBLIC_ADD' WHERE authority='F_TRACKED_ENTITY_ATTRIBUTE_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_PROGRAM_INDICATOR_PUBLIC_ADD' WHERE authority='F_ADD_PROGRAM_INDICATOR'" );
executeSql( "UPDATE userroleauthorities SET authority='F_LEGEND_SET_PUBLIC_ADD' WHERE authority='F_LEGEND_SET_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_VALIDATIONRULE_PUBLIC_ADD' WHERE authority='F_VALIDATIONRULE_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='F_ATTRIBUTE_PUBLIC_ADD' WHERE authority='F_ATTRIBUTE_ADD'" );
executeSql( "UPDATE userroleauthorities SET authority='M_dhis-web-dashboard' WHERE authority='M_dhis-web-dashboard-integration'" );
// remove unused authorities
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_CONCEPT_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_CONSTANT_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_DATAELEMENT_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_DATAELEMENTGROUP_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_DATAELEMENTGROUPSET_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_DATAELEMENT_MINMAX_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_DATASET_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_SECTION_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_DATAVALUE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_INDICATOR_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_INDICATORTYPE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_INDICATORGROUP_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_INDICATORGROUPSET_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_ORGANISATIONUNIT_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_ORGUNITGROUP_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_ORGUNITGROUPSET_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_USERROLE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_USERGROUP_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_VALIDATIONRULE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_VALIDATIONRULEGROUP_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_REPORT_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_SQLVIEW_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_VALIDATIONCRITERIA_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_OPTIONSET_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_ATTRIBUTE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PATIENTATTRIBUTE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PATIENT_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_UPDATE_PROGRAM_INDICATOR'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PROGRAM_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PROGRAMSTAGE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PROGRAMSTAGE_SECTION_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PATIENTIDENTIFIERTYPE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PROGRAM_ATTRIBUTE_UPDATE'" );
executeSql( "DELETE FROM userroleauthorities WHERE authority='F_PATIENT_DATAVALUE_UPDATE'" );
// remove unused configurations
executeSql( "delete from systemsetting where name='keySmsConfig'" );
executeSql( "delete from systemsetting where name='keySmsConfiguration'" );
executeSql( "delete from systemsetting where name='keySmsConfigurations'" );
// update denominator of indicator which has indicatortype as 'number'
executeSql( "UPDATE indicator SET denominator = 1, denominatordescription = '' WHERE indicatortypeid IN (SELECT DISTINCT indicatortypeid FROM indicatortype WHERE indicatornumber = true) AND denominator IS NULL" );
// remove name/shortName uniqueness
executeSql( "ALTER TABLE organisationunit DROP CONSTRAINT organisationunit_name_key" );
executeSql( "ALTER TABLE orgunitgroup ADD CONSTRAINT orgunitgroup_name_key UNIQUE (name)" );
executeSql( "ALTER TABLE orgunitgroupset ADD CONSTRAINT orgunitgroupset_name_key UNIQUE (name)" );
executeSql( "ALTER TABLE indicator DROP CONSTRAINT indicator_name_key" );
executeSql( "ALTER TABLE indicator DROP CONSTRAINT indicator_shortname_key" );
executeSql( "ALTER TABLE indicatorgroup DROP CONSTRAINT indicatorgroup_name_key" );
executeSql( "ALTER TABLE indicatorgroupset DROP CONSTRAINT indicatorgroupset_name_key" );
executeSql( "ALTER TABLE dataset DROP CONSTRAINT dataset_name_key" );
executeSql( "ALTER TABLE dataset DROP CONSTRAINT dataset_shortname_key" );
executeSql( "ALTER TABLE document DROP CONSTRAINT document_name_key" );
executeSql( "ALTER TABLE reporttable DROP CONSTRAINT reporttable_name_key" );
executeSql( "ALTER TABLE report DROP CONSTRAINT report_name_key" );
executeSql( "ALTER TABLE usergroup DROP CONSTRAINT usergroup_name_key" );
executeSql( "ALTER TABLE dataelementcategory DROP COLUMN conceptid" );
executeSql( "ALTER TABLE dataelementcategoryoption DROP COLUMN conceptid" );
// upgrade system charts/maps to public read-only sharing
executeSql( "UPDATE chart SET publicaccess='r
executeSql( "UPDATE map SET publicaccess='r
executeSql( "UPDATE chart SET publicaccess='
executeSql( "UPDATE map SET publicaccess='
executeSql( "update dataelementcategory set datadimension = false where datadimension is null" );
executeSql( "UPDATE dataset SET dataelementdecoration=false WHERE dataelementdecoration is null" );
executeSql( "update sqlview set sqlviewid=viweid" );
executeSql( "alter table sqlview drop column viewid" );
executeSql( "update sqlview set type = 'QUERY' where query is true" );
executeSql( "update sqlview set type = 'VIEW' where type is null" );
executeSql( "alter table sqlview drop column query" );
executeSql( "UPDATE dashboard SET publicaccess='
executeSql( "UPDATE optionset SET version=0 WHERE version IS NULL" );
executeSql( "UPDATE dataset SET version=0 WHERE version IS NULL" );
executeSql( "UPDATE program SET version=0 WHERE version IS NULL" );
executeSql( "update program set shortname = substring(name,0,50) where shortname is null" );
executeSql( "update programstageinstance set attributeoptioncomboid = " + defaultOptionComboId + " where attributeoptioncomboid is null" );
executeSql( "update programstageinstance set storedby=completedby where storedby is null and completedby is not null" );
executeSql( "ALTER TABLE datavalue ALTER COLUMN lastupdated TYPE timestamp" );
executeSql( "ALTER TABLE completedatasetregistration ALTER COLUMN date TYPE timestamp" );
executeSql( "ALTER TABLE message ALTER COLUMN userid DROP NOT NULL" );
executeSql( "ALTER TABLE message ALTER COLUMN messagetext TYPE text" );
executeSql( "drop index crosstab" );
executeSql( "delete from usersetting where name = 'dashboardConfig' or name = 'dashboardConfiguration'" );
executeSql( "update usersetting set name = 'keyUiLocale' where name = 'currentLocale'" );
executeSql( "update usersetting set name = 'keyDbLocale' where name = 'keyLocaleUserSetting'" );
executeSql( "update usersetting set name = 'keyStyle' where name = 'currentStyle'" );
executeSql( "ALTER TABLE interpretation ALTER COLUMN userid DROP NOT NULL" );
executeSql( "UPDATE interpretation SET publicaccess='r
executeSql( "ALTER TABLE dataset DROP COLUMN symbol" );
executeSql( "ALTER TABLE users ALTER COLUMN password DROP NOT NULL" );
executeSql( "UPDATE users SET twofa = false WHERE twofa IS NULL" );
// set default dataDimension on orgUnitGroupSet and deGroupSet
executeSql( "UPDATE dataelementgroupset SET datadimension=true WHERE datadimension IS NULL" );
executeSql( "ALTER TABLE dataelementgroupset ALTER COLUMN datadimension SET NOT NULL" );
executeSql( "UPDATE orgunitgroupset SET datadimension=true WHERE datadimension IS NULL" );
executeSql( "ALTER TABLE orgunitgroupset ALTER COLUMN datadimension SET NOT NULL" );
executeSql( "ALTER TABLE validationnotificationtemplate ALTER COLUMN sendstrategy SET NOT NULL" );
// set attribute defaults
executeSql( "UPDATE attribute SET dataelementattribute=false WHERE dataelementattribute IS NULL" );
executeSql( "UPDATE attribute SET dataelementgroupattribute=false WHERE dataelementgroupattribute IS NULL" );
executeSql( "UPDATE attribute SET indicatorattribute=false WHERE indicatorattribute IS NULL" );
executeSql( "UPDATE attribute SET indicatorgroupattribute=false WHERE indicatorgroupattribute IS NULL" );
executeSql( "UPDATE attribute SET organisationunitattribute=false WHERE organisationunitattribute IS NULL" );
executeSql( "UPDATE attribute SET organisationunitgroupattribute=false WHERE organisationunitgroupattribute IS NULL" );
executeSql( "UPDATE attribute SET organisationunitgroupsetattribute=false WHERE organisationunitgroupsetattribute IS NULL" );
executeSql( "UPDATE attribute SET userattribute=false WHERE userattribute IS NULL" );
executeSql( "UPDATE attribute SET usergroupattribute=false WHERE usergroupattribute IS NULL" );
executeSql( "UPDATE attribute SET datasetattribute=false WHERE datasetattribute IS NULL" );
executeSql( "UPDATE attribute SET programattribute=false WHERE programattribute IS NULL" );
executeSql( "UPDATE attribute SET programstageattribute=false WHERE programstageattribute IS NULL" );
executeSql( "UPDATE attribute SET trackedentityattribute=false WHERE trackedentityattribute IS NULL" );
executeSql( "UPDATE attribute SET trackedentityattributeattribute=false WHERE trackedentityattributeattribute IS NULL" );
executeSql( "UPDATE attribute SET categoryoptionattribute=false WHERE categoryoptionattribute IS NULL" );
executeSql( "UPDATE attribute SET categoryoptiongroupattribute=false WHERE categoryoptiongroupattribute IS NULL" );
executeSql( "UPDATE attribute SET documentattribute=false WHERE documentattribute IS NULL" );
executeSql( "UPDATE attribute SET optionattribute=false WHERE optionattribute IS NULL" );
executeSql( "UPDATE attribute SET optionsetattribute=false WHERE optionsetattribute IS NULL" );
executeSql( "UPDATE attribute SET constantattribute=false WHERE constantattribute IS NULL" );
executeSql( "UPDATE attribute SET legendsetattribute=false WHERE legendsetattribute IS NULL" );
executeSql( "UPDATE attribute SET programindicatorattribute=false WHERE programindicatorattribute IS NULL" );
executeSql( "UPDATE attribute SET sqlViewAttribute=false WHERE sqlViewAttribute IS NULL" );
executeSql( "UPDATE attribute SET sectionAttribute=false WHERE sectionAttribute IS NULL" );
executeSql( "UPDATE attribute SET categoryoptioncomboattribute=false WHERE categoryoptioncomboattribute IS NULL" );
executeSql( "update attribute set isunique=false where isunique is null" );
executeSql( "ALTER TABLE trackedentityattributedimension DROP COLUMN operator" );
executeSql( "ALTER TABLE trackedentitydataelementdimension DROP COLUMN operator" );
// update attribute.code, set to null if code=''
executeSql( "UPDATE attribute SET code=NULL WHERE code=''" );
//update programruleaction:
executeSql( "ALTER TABLE programruleaction DROP COLUMN name" );
//update programrule
executeSql( "UPDATE programrule SET rulecondition = condition WHERE rulecondition IS NULL" );
executeSql( "ALTER TABLE programrule DROP COLUMN condition" );
// data approval
executeSql( "UPDATE dataapproval SET accepted=false WHERE accepted IS NULL" );
executeSql( "ALTER TABLE dataapproval ALTER COLUMN accepted SET NOT NULL" );
executeSql( "DELETE FROM dataapproval WHERE categoryoptiongroupid IS NOT NULL" );
executeSql( "ALTER TABLE dataapproval DROP COLUMN categoryoptiongroupid" );
executeSql( "UPDATE dataapproval SET attributeoptioncomboid=categoryoptioncomboid WHERE categoryoptioncomboid IS NOT NULL" );
executeSql( "ALTER TABLE dataapproval DROP COLUMN categoryoptioncomboid" );
executeSql( "UPDATE dataapproval SET attributeoptioncomboid=" + defaultCategoryComboId + " WHERE attributeoptioncomboid IS NULL" );
executeSql( "ALTER TABLE dataapproval ALTER COLUMN attributeoptioncomboid SET NOT NULL" );
// validation rule group, new column alertbyorgunits
executeSql( "UPDATE validationrulegroup SET alertbyorgunits=false WHERE alertbyorgunits IS NULL" );
executeSql( "update expression set missingvaluestrategy = 'SKIP_IF_ANY_VALUE_MISSING' where missingvaluestrategy is null and (nullifblank is true or nullifblank is null)" );
executeSql( "update expression set missingvaluestrategy = 'NEVER_SKIP' where missingvaluestrategy is null nullifblank is false" );
executeSql( "alter table expression alter column missingvaluestrategy set not null" );
executeSql( "alter table expression drop column nullifblank" );
executeSql( "drop table expressiondataelement" );
executeSql( "drop table expressionsampleelement" );
executeSql( "alter table dataelementcategoryoption alter column startdate type date" );
executeSql( "alter table dataelementcategoryoption alter column enddate type date" );
executeSql( "alter table dataelement drop column sortorder" );
executeSql( "alter table indicator drop column sortorder" );
executeSql( "alter table dataset drop column sortorder" );
executeSql( "alter table dataelement drop column active" );
executeSql( "alter table datavalue alter column value type varchar(50000)" );
executeSql( "alter table datavalue alter column comment type varchar(50000)" );
executeSql( "alter table datavalueaudit alter column value type varchar(50000)" );
executeSql( "alter table trackedentitydatavalue alter column value type varchar(50000)" );
executeSql( "alter table trackedentityattributevalue alter column value type varchar(50000)" );
executeSql( "update trackedentitydatavalue set providedelsewhere=false where providedelsewhere is null" );
executeSql( "update datavalueaudit set attributeoptioncomboid = " + defaultOptionComboId + " where attributeoptioncomboid is null" );
executeSql( "alter table datavalueaudit alter column attributeoptioncomboid set not null;" );
executeSql( "update dataelementcategoryoption set shortname = substring(name,0,50) where shortname is null" );
// AttributeValue
executeSql( "UPDATE attributevalue SET created=now() WHERE created IS NULL" );
executeSql( "UPDATE attributevalue SET lastupdated=now() WHERE lastupdated IS NULL" );
executeSql( "ALTER TABLE attributevalue ALTER value TYPE text" );
executeSql( "DELETE FROM attributevalue where value IS NULL or value=''" );
executeSql( "update dashboarditem set shape = 'normal' where shape is null" );
executeSql( "update categoryoptioncombo set ignoreapproval = false where ignoreapproval is null" );
executeSql( "alter table version alter column versionkey set not null" );
executeSql( "alter table version add constraint version_versionkey_key unique(versionkey)" );
// Cacheable
executeSql( "UPDATE report set cachestrategy='RESPECT_SYSTEM_SETTING' where cachestrategy is null" );
executeSql( "UPDATE sqlview set cachestrategy='RESPECT_SYSTEM_SETTING' where cachestrategy is null" );
executeSql( "update categorycombo set datadimensiontype = 'DISAGGREGATION' where dimensiontype = 'disaggregation'" );
executeSql( "update categorycombo set datadimensiontype = 'ATTRIBUTE' where dimensiontype = 'attribute'" );
executeSql( "update categorycombo set datadimensiontype = 'DISAGGREGATION' where datadimensiontype is null" );
executeSql( "alter table categorycombo drop column dimensiontype" );
executeSql( "update dataelementcategory set datadimensiontype = 'DISAGGREGATION' where dimensiontype = 'disaggregation'" );
executeSql( "update dataelementcategory set datadimensiontype = 'ATTRIBUTE' where dimensiontype = 'attribute'" );
executeSql( "update dataelementcategory set datadimensiontype = 'DISAGGREGATION' where datadimensiontype is null" );
executeSql( "alter table dataelementcategory drop column dimensiontype" );
executeSql( "update categoryoptiongroupset set datadimensiontype = 'ATTRIBUTE' where datadimensiontype is null" );
executeSql( "update categoryoptiongroup set datadimensiontype = 'ATTRIBUTE' where datadimensiontype is null" );
executeSql( "update reporttable set completedonly = false where completedonly is null" );
executeSql( "update chart set completedonly = false where completedonly is null" );
executeSql( "update eventreport set completedonly = false where completedonly is null" );
executeSql( "update eventchart set completedonly = false where completedonly is null" );
executeSql( "update program set enrollmentdatelabel = dateofenrollmentdescription where enrollmentdatelabel is null" );
executeSql( "update program set incidentdatelabel = dateofincidentdescription where incidentdatelabel is null" );
executeSql( "update programinstance set incidentdate = dateofincident where incidentdate is null" );
executeSql( "alter table programinstance alter column incidentdate drop not null" );
executeSql( "alter table program drop column dateofenrollmentdescription" );
executeSql( "alter table program drop column dateofincidentdescription" );
executeSql( "alter table programinstance drop column dateofincident" );
executeSql( "update programstage set reportdatetouse = 'indicentDate' where reportdatetouse='dateOfIncident'" );
executeSql( "update programstage set repeatable = irregular where repeatable is null" );
executeSql( "update programstage set repeatable = false where repeatable is null" );
executeSql( "alter table programstage drop column reportdatedescription" );
executeSql( "alter table programstage drop column irregular" );
executeSql( "update smscodes set compulsory = false where compulsory is null" );
executeSql( "alter table programmessage drop column storecopy" );
executeSql( "alter table programindicator drop column missingvaluereplacement" );
executeSql( "update keyjsonvalue set namespacekey = key where namespacekey is null" );
executeSql( "alter table keyjsonvalue alter column namespacekey set not null" );
executeSql( "alter table keyjsonvalue drop column key" );
executeSql( "alter table trackedentityattributevalue drop column encrypted_value" );
executeSql( "alter table predictor drop column predictororglevels" );
// Remove data mart
executeSql( "drop table aggregateddatasetcompleteness" );
executeSql( "drop table aggregateddatasetcompleteness_temp" );
executeSql( "drop table aggregateddatavalue" );
executeSql( "drop table aggregateddatavalue_temp" );
executeSql( "drop table aggregatedindicatorvalue" );
executeSql( "drop table aggregatedindicatorvalue_temp" );
executeSql( "drop table aggregatedorgunitdatasetcompleteness" );
executeSql( "drop table aggregatedorgunitdatasetcompleteness_temp" );
executeSql( "drop table aggregatedorgunitdatavalue" );
executeSql( "drop table aggregatedorgunitdatavalue_temp" );
executeSql( "drop table aggregatedorgunitindicatorvalue" );
executeSql( "drop table aggregatedorgunitindicatorvalue_temp" );
executeSql( "alter table trackedentitydatavalue alter column storedby TYPE character varying(255)" );
executeSql( "alter table datavalue alter column storedby TYPE character varying(255)" );
executeSql( "alter table datastatisticsevent alter column eventtype type character varying" );
executeSql( "alter table orgunitlevel drop constraint orgunitlevel_name_key" );
executeSql( "update interpretation set likes = 0 where likes is null" );
executeSql( "create index in_interpretationcomment_mentions_username on interpretationcomment using GIN((mentions->'username') jsonb_path_ops)" );
executeSql( "create index in_interpretation_mentions_username on interpretation using GIN((mentions->'username') jsonb_path_ops)" );
executeSql( "update chart set regressiontype = 'NONE' where regression is false or regression is null" );
executeSql( "update chart set regressiontype = 'LINEAR' where regression is true" );
executeSql( "alter table chart alter column regressiontype set not null" );
executeSql( "alter table chart drop column regression" );
executeSql( "update eventchart set regressiontype = 'NONE' where regression is false or regression is null" );
executeSql( "update eventchart set regressiontype = 'LINEAR' where regression is true" );
executeSql( "alter table eventchart alter column regressiontype set not null" );
executeSql( "alter table eventchart drop column regression" );
executeSql( "alter table validationrule drop column ruletype" );
executeSql( "alter table validationrule drop column skiptestexpressionid" );
executeSql( "alter table validationrule drop column organisationunitlevel" );
executeSql( "alter table validationrule drop column sequentialsamplecount" );
executeSql( "alter table validationrule drop column annualsamplecount" );
executeSql( "alter table validationrule drop column sequentialskipcount" );
// remove TrackedEntityAttributeGroup
executeSql( "alter table trackedentityattribute drop column trackedentityattributegroupid" );
executeSql( "ALTER TABLE trackedentityattribute DROP CONSTRAINT fk_trackedentityattribute_attributegroupid" );
// remove id object parts from embedded objects
upgradeEmbeddedObject( "datainputperiod" );
upgradeEmbeddedObject( "datasetelement" );
updateEnums();
upgradeDataValueSoftDelete();
initOauth2();
upgradeDataValuesWithAttributeOptionCombo();
upgradeCompleteDataSetRegistrationsWithAttributeOptionCombo();
upgradeMapViewsToAnalyticalObject();
upgradeTranslations();
upgradeToDataApprovalWorkflows();
executeSql( "alter table dataapproval alter column workflowid set not null" );
executeSql( "alter table dataapproval add constraint dataapproval_unique_key unique (dataapprovallevelid,workflowid,periodid,organisationunitid,attributeoptioncomboid)" );
upgradeImplicitAverageMonitoringRules();
updateOptions();
upgradeAggregationType( "reporttable" );
upgradeAggregationType( "chart" );
updateRelativePeriods();
updateNameColumnLengths();
upgradeMapViewsToColumns();
upgradeDataDimensionsToEmbeddedOperand();
upgradeDataDimensionItemsToReportingRateMetric();
upgradeDataDimensionItemToEmbeddedProgramAttribute();
upgradeDataDimensionItemToEmbeddedProgramDataElement();
updateObjectTranslation();
upgradeDataSetElements();
removeOutdatedTranslationProperties();
updateLegendRelationship();
updateHideEmptyRows();
executeSql( "update programindicator set analyticstype = 'EVENT' where analyticstype is null" );
executeSql( "alter table programindicator alter column analyticstype set not null" );
//TODO: remove - not needed in release 2.26.
executeSql( "update programindicator set analyticstype = programindicatoranalyticstype" );
executeSql( "alter table programindicator drop programindicatoranalyticstype" );
// Scheduler fixes for 2.29
executeSql( "delete from systemsetting where name='keyScheduledTasks'" );
executeSql( "delete from systemsetting where name='keyDataMartTask'" );
executeSql( "delete from systemsetting where name='dataSyncCron'" );
executeSql( "delete from systemsetting where name='metaDataSyncCron'" );
updateDimensionFilterToText();
insertDefaultBoundariesForBoundlessProgramIndicators();
executeSql( "UPDATE trackedentitytype SET publicaccess='rwrw----' WHERE publicaccess IS NULL;" );
executeSql( "UPDATE programstage SET publicaccess='rw
executeSql("alter table jobconfiguration drop column configurable;");
// 2FA fixes for 2.30
executeSql( "ALTER TABLE users alter column secret set not null" );
executeSql( "drop table userroleprogram");
log.info( "Tables updated" );
}
private void upgradeEmbeddedObject( String table )
{
executeSql( "ALTER TABLE " + table + " DROP COLUMN uid" );
executeSql( "ALTER TABLE " + table + " DROP COLUMN created" );
executeSql( "ALTER TABLE " + table + " DROP COLUMN lastupdated" );
executeSql( "ALTER TABLE " + table + " DROP COLUMN code" );
}
private void removeOutdatedTranslationProperties()
{
executeSql( "delete from indicatortranslations where objecttranslationid in (select objecttranslationid from objecttranslation where property in ('numeratorDescription', 'denominatorDescription'))" );
executeSql( "delete from objecttranslation where property in ('numeratorDescription', 'denominatorDescription')" );
}
private void upgradeDataValueSoftDelete()
{
executeSql( "update datavalue set deleted = false where deleted is null" );
executeSql( "alter table datavalue alter column deleted set not null" );
executeSql( "create index in_datavalue_deleted on datavalue(deleted)" );
}
private void initOauth2()
{
// OAuth2
executeSql( "CREATE TABLE oauth_code (" +
" code VARCHAR(256), authentication " + statementBuilder.getLongVarBinaryType() +
")" );
executeSql( "CREATE TABLE oauth_access_token (" +
" token_id VARCHAR(256)," +
" token " + statementBuilder.getLongVarBinaryType() + "," +
" authentication_id VARCHAR(256) PRIMARY KEY," +
" user_name VARCHAR(256)," +
" client_id VARCHAR(256)," +
" authentication " + statementBuilder.getLongVarBinaryType() + "," +
" refresh_token VARCHAR(256)" +
")" );
executeSql( "CREATE TABLE oauth_refresh_token (" +
" token_id VARCHAR(256)," +
" token " + statementBuilder.getLongVarBinaryType() + "," +
" authentication " + statementBuilder.getLongVarBinaryType() +
")" );
}
private void updateEnums()
{
executeSql( "update report set type='JASPER_REPORT_TABLE' where type='jasperReportTable'" );
executeSql( "update report set type='JASPER_JDBC' where type='jasperJdbc'" );
executeSql( "update report set type='HTML' where type='html'" );
executeSql( "update dashboarditem set shape='NORMAL' where shape ='normal'" );
executeSql( "update dashboarditem set shape='DOUBLE_WIDTH' where shape ='double_width'" );
executeSql( "update dashboarditem set shape='FULL_WIDTH' where shape ='full_width'" );
executeSql( "update reporttable set displaydensity='COMFORTABLE' where displaydensity='comfortable'" );
executeSql( "update reporttable set displaydensity='NORMAL' where displaydensity='normal'" );
executeSql( "update reporttable set displaydensity='COMPACT' where displaydensity='compact'" );
executeSql( "update eventreport set displaydensity='COMFORTABLE' where displaydensity='comfortable'" );
executeSql( "update eventreport set displaydensity='NORMAL' where displaydensity='normal'" );
executeSql( "update eventreport set displaydensity='COMPACT' where displaydensity='compact'" );
executeSql( "update reporttable set fontsize='LARGE' where fontsize='large'" );
executeSql( "update reporttable set fontsize='NORMAL' where fontsize='normal'" );
executeSql( "update reporttable set fontsize='SMALL' where fontsize='small'" );
executeSql( "update eventreport set fontsize='LARGE' where fontsize='large'" );
executeSql( "update eventreport set fontsize='NORMAL' where fontsize='normal'" );
executeSql( "update eventreport set fontsize='SMALL' where fontsize='small'" );
executeSql( "update reporttable set digitgroupseparator='NONE' where digitgroupseparator='none'" );
executeSql( "update reporttable set digitgroupseparator='SPACE' where digitgroupseparator='space'" );
executeSql( "update reporttable set digitgroupseparator='COMMA' where digitgroupseparator='comma'" );
executeSql( "update eventreport set digitgroupseparator='NONE' where digitgroupseparator='none'" );
executeSql( "update eventreport set digitgroupseparator='SPACE' where digitgroupseparator='space'" );
executeSql( "update eventreport set digitgroupseparator='COMMA' where digitgroupseparator='comma'" );
executeSql( "update eventreport set datatype='AGGREGATED_VALUES' where datatype='aggregated_values'" );
executeSql( "update eventreport set datatype='EVENTS' where datatype='individual_cases'" );
executeSql( "update chart set type='COLUMN' where type='column'" );
executeSql( "update chart set type='STACKED_COLUMN' where type='stackedcolumn'" );
executeSql( "update chart set type='STACKED_COLUMN' where type='stackedColumn'" );
executeSql( "update chart set type='BAR' where type='bar'" );
executeSql( "update chart set type='STACKED_BAR' where type='stackedbar'" );
executeSql( "update chart set type='STACKED_BAR' where type='stackedBar'" );
executeSql( "update chart set type='LINE' where type='line'" );
executeSql( "update chart set type='AREA' where type='area'" );
executeSql( "update chart set type='PIE' where type='pie'" );
executeSql( "update chart set type='RADAR' where type='radar'" );
executeSql( "update chart set type='GAUGE' where type='gauge'" );
executeSql( "update eventchart set type='COLUMN' where type='column'" );
executeSql( "update eventchart set type='STACKED_COLUMN' where type='stackedcolumn'" );
executeSql( "update eventchart set type='STACKED_COLUMN' where type='stackedColumn'" );
executeSql( "update eventchart set type='BAR' where type='bar'" );
executeSql( "update eventchart set type='STACKED_BAR' where type='stackedbar'" );
executeSql( "update eventchart set type='STACKED_BAR' where type='stackedBar'" );
executeSql( "update eventchart set type='LINE' where type='line'" );
executeSql( "update eventchart set type='AREA' where type='area'" );
executeSql( "update eventchart set type='PIE' where type='pie'" );
executeSql( "update eventchart set type='RADAR' where type='radar'" );
executeSql( "update eventchart set type='GAUGE' where type='gauge'" );
executeSql( "update dataentryform set style='COMFORTABLE' where style='comfortable'" );
executeSql( "update dataentryform set style='NORMAL' where style='regular'" );
executeSql( "update dataentryform set style='COMPACT' where style='compact'" );
executeSql( "update dataentryform set style='NONE' where style='none'" );
}
private void upgradeDataSetElements()
{
String autoIncr = statementBuilder.getAutoIncrementValue();
String uid = statementBuilder.getUid();
String insertSql =
"insert into datasetelement(datasetelementid,uid,datasetid,dataelementid,created,lastupdated) " +
"select " + autoIncr + " as datasetelementid, " +
uid + " as uid, " +
"dsm.datasetid as datasetid, " +
"dsm.dataelementid as dataelementid, " +
"now() as created, " +
"now() as lastupdated " +
"from datasetmembers dsm; " +
"drop table datasetmembers; ";
executeSql( insertSql );
executeSql( "alter table datasetelement alter column uid set not null" );
executeSql( "alter table datasetelement alter column created set not null" );
executeSql( "alter table datasetelement alter column lastupdated set not null" );
executeSql( "alter table datasetelement alter column datasetid drop not null" );
}
private void upgradeAggregationType( String table )
{
executeSql( "update " + table + " set aggregationtype='SUM' where aggregationtype='sum'" );
executeSql( "update " + table + " set aggregationtype='COUNT' where aggregationtype='count'" );
executeSql( "update " + table + " set aggregationtype='STDDEV' where aggregationtype='stddev'" );
executeSql( "update " + table + " set aggregationtype='VARIANCE' where aggregationtype='variance'" );
executeSql( "update " + table + " set aggregationtype='MIN' where aggregationtype='min'" );
executeSql( "update " + table + " set aggregationtype='MAX' where aggregationtype='max'" );
executeSql( "update " + table + " set aggregationtype='DEFAULT' where aggregationtype='default' or aggregationtype is null" );
}
private void updateRelativePeriods()
{
executeSql( "update relativeperiods set thismonth=reportingmonth" );
executeSql( "update relativeperiods set thisbimonth=reportingbimonth" );
executeSql( "update relativeperiods set thisquarter=reportingquarter" );
executeSql( "update relativeperiods set lastweek = false where lastweek is null" );
executeSql( "update relativeperiods set weeksthisyear = false where weeksthisyear is null" );
executeSql( "update relativeperiods set bimonthsthisyear = false where bimonthsthisyear is null" );
executeSql( "update relativeperiods set last4weeks = false where last4weeks is null" );
executeSql( "update relativeperiods set last12weeks = false where last12weeks is null" );
executeSql( "update relativeperiods set last6months = false where last6months is null" );
executeSql( "update relativeperiods set thismonth = false where thismonth is null" );
executeSql( "update relativeperiods set thisbimonth = false where thisbimonth is null" );
executeSql( "update relativeperiods set thisquarter = false where thisquarter is null" );
executeSql( "update relativeperiods set thissixmonth = false where thissixmonth is null" );
executeSql( "update relativeperiods set thisweek = false where thisweek is null" );
executeSql( "update relativeperiods set lastmonth = false where lastmonth is null" );
executeSql( "update relativeperiods set lastbimonth = false where lastbimonth is null" );
executeSql( "update relativeperiods set lastquarter = false where lastquarter is null" );
executeSql( "update relativeperiods set lastsixmonth = false where lastsixmonth is null" );
executeSql( "update relativeperiods set lastweek = false where lastweek is null" );
executeSql( "update relativeperiods set thisday = false where thisday is null" );
executeSql( "update relativeperiods set yesterday = false where yesterday is null" );
executeSql( "update relativeperiods set last3days = false where last3days is null" );
executeSql( "update relativeperiods set last7days = false where last7days is null" );
executeSql( "update relativeperiods set last14days = false where last14days is null" );
// Set non-null constraint on fields
executeSql( "alter table relativeperiods alter column thisday set not null" );
executeSql( "alter table relativeperiods alter column yesterday set not null" );
executeSql( "alter table relativeperiods alter column last3Days set not null" );
executeSql( "alter table relativeperiods alter column last7Days set not null" );
executeSql( "alter table relativeperiods alter column last14Days set not null" );
executeSql( "alter table relativeperiods alter column thisMonth set not null" );
executeSql( "alter table relativeperiods alter column lastMonth set not null" );
executeSql( "alter table relativeperiods alter column thisBimonth set not null" );
executeSql( "alter table relativeperiods alter column lastBimonth set not null" );
executeSql( "alter table relativeperiods alter column thisQuarter set not null" );
executeSql( "alter table relativeperiods alter column lastQuarter set not null" );
executeSql( "alter table relativeperiods alter column thisSixMonth set not null" );
executeSql( "alter table relativeperiods alter column lastSixMonth set not null" );
executeSql( "alter table relativeperiods alter column monthsThisYear set not null" );
executeSql( "alter table relativeperiods alter column quartersThisYear set not null" );
executeSql( "alter table relativeperiods alter column thisYear set not null" );
executeSql( "alter table relativeperiods alter column monthsLastYear set not null" );
executeSql( "alter table relativeperiods alter column quartersLastYear set not null" );
executeSql( "alter table relativeperiods alter column lastYear set not null" );
executeSql( "alter table relativeperiods alter column last5Years set not null" );
executeSql( "alter table relativeperiods alter column last12Months set not null" );
executeSql( "alter table relativeperiods alter column last6Months set not null" );
executeSql( "alter table relativeperiods alter column last3Months set not null" );
executeSql( "alter table relativeperiods alter column last6BiMonths set not null" );
executeSql( "alter table relativeperiods alter column last4Quarters set not null" );
executeSql( "alter table relativeperiods alter column last2SixMonths set not null" );
executeSql( "alter table relativeperiods alter column thisFinancialYear set not null" );
executeSql( "alter table relativeperiods alter column lastFinancialYear set not null" );
executeSql( "alter table relativeperiods alter column last5FinancialYears set not null" );
executeSql( "alter table relativeperiods alter column thisWeek set not null" );
executeSql( "alter table relativeperiods alter column lastWeek set not null" );
executeSql( "alter table relativeperiods alter column last4Weeks set not null" );
executeSql( "alter table relativeperiods alter column last12Weeks set not null" );
executeSql( "alter table relativeperiods alter column last52Weeks set not null" );
}
private void updateNameColumnLengths()
{
List<String> tables = Lists.newArrayList( "user", "usergroup", "organisationunit", "orgunitgroup", "orgunitgroupset",
"section", "dataset", "sqlview", "dataelement", "dataelementgroup", "dataelementgroupset", "categorycombo",
"dataelementcategory", "dataelementcategoryoption", "indicator", "indicatorgroup", "indicatorgroupset", "indicatortype",
"validationrule", "validationrulegroup", "constant", "attribute", "attributegroup",
"program", "programstage", "programindicator", "trackedentitytype", "trackedentityattribute" );
for ( String table : tables )
{
executeSql( "alter table " + table + " alter column name type character varying(230)" );
}
}
private void upgradeDataValuesWithAttributeOptionCombo()
{
final String sql = statementBuilder.getNumberOfColumnsInPrimaryKey( "datavalue" );
Integer no = statementManager.getHolder().queryForInteger( sql );
if ( no >= 5 )
{
return; // attributeoptioncomboid already part of pkey
}
int optionComboId = getDefaultOptionCombo();
executeSql( "alter table datavalue drop constraint datavalue_pkey;" );
executeSql( "alter table datavalue add column attributeoptioncomboid integer;" );
executeSql( "update datavalue set attributeoptioncomboid = " + optionComboId + " where attributeoptioncomboid is null;" );
executeSql( "alter table datavalue alter column attributeoptioncomboid set not null;" );
executeSql( "alter table datavalue add constraint fk_datavalue_attributeoptioncomboid foreign key (attributeoptioncomboid) references categoryoptioncombo (categoryoptioncomboid) match simple;" );
executeSql( "alter table datavalue add constraint datavalue_pkey primary key(dataelementid, periodid, sourceid, categoryoptioncomboid, attributeoptioncomboid);" );
log.info( "Data value table upgraded with attributeoptioncomboid column" );
}
private void upgradeCompleteDataSetRegistrationsWithAttributeOptionCombo()
{
final String sql = statementBuilder.getNumberOfColumnsInPrimaryKey( "completedatasetregistration" );
Integer no = statementManager.getHolder().queryForInteger( sql );
if ( no >= 4 )
{
return; // attributeoptioncomboid already part of pkey
}
int optionComboId = getDefaultOptionCombo();
executeSql( "alter table completedatasetregistration drop constraint completedatasetregistration_pkey" );
executeSql( "alter table completedatasetregistration add column attributeoptioncomboid integer;" );
executeSql( "update completedatasetregistration set attributeoptioncomboid = " + optionComboId
+ " where attributeoptioncomboid is null;" );
executeSql( "alter table completedatasetregistration alter column attributeoptioncomboid set not null;" );
executeSql( "alter table completedatasetregistration add constraint fk_completedatasetregistration_attributeoptioncomboid foreign key (attributeoptioncomboid) references categoryoptioncombo (categoryoptioncomboid) match simple;" );
executeSql( "alter table completedatasetregistration add constraint completedatasetregistration_pkey primary key(datasetid, periodid, sourceid, attributeoptioncomboid);" );
log.info( "Complete data set registration table upgraded with attributeoptioncomboid column" );
}
private void upgradeMapViewsToAnalyticalObject()
{
executeSql( "insert into mapview_dataelements ( mapviewid, sort_order, dataelementid ) select mapviewid, 0, dataelementid from mapview where dataelementid is not null" );
executeSql( "alter table mapview drop column dataelementid" );
executeSql( "insert into mapview_dataelementoperands ( mapviewid, sort_order, dataelementoperandid ) select mapviewid, 0, dataelementoperandid from mapview where dataelementoperandid is not null" );
executeSql( "alter table mapview drop column dataelementoperandid" );
executeSql( "insert into mapview_indicators ( mapviewid, sort_order, indicatorid ) select mapviewid, 0, indicatorid from mapview where indicatorid is not null" );
executeSql( "alter table mapview drop column indicatorid" );
executeSql( "insert into mapview_organisationunits ( mapviewid, sort_order, organisationunitid ) select mapviewid, 0, parentorganisationunitid from mapview where parentorganisationunitid is not null" );
executeSql( "alter table mapview drop column parentorganisationunitid" );
executeSql( "insert into mapview_periods ( mapviewid, sort_order, periodid ) select mapviewid, 0, periodid from mapview where periodid is not null" );
executeSql( "alter table mapview drop column periodid" );
executeSql( "insert into mapview_orgunitlevels ( mapviewid, sort_order, orgunitlevel ) select m.mapviewid, 0, o.level "
+ "from mapview m join orgunitlevel o on (m.organisationunitlevelid=o.orgunitlevelid) where m.organisationunitlevelid is not null" );
executeSql( "alter table mapview drop column organisationunitlevelid" );
executeSql( "alter table mapview drop column dataelementgroupid" );
executeSql( "alter table mapview drop column indicatorgroupid" );
executeSql( "update mapview set userorganisationunit = false where userorganisationunit is null" );
executeSql( "update mapview set userorganisationunitchildren = false where userorganisationunitchildren is null" );
executeSql( "update mapview set userorganisationunitgrandchildren = false where userorganisationunitgrandchildren is null" );
}
private void upgradeTranslations()
{
final String sql = statementBuilder.getNumberOfColumnsInPrimaryKey( "translation" );
Integer no = statementManager.getHolder().queryForInteger( sql );
if ( no == 1 )
{
return; // translationid already set as single pkey
}
executeSql( statementBuilder.getDropPrimaryKey( "translation" ) );
executeSql( statementBuilder.getAddPrimaryKeyToExistingTable( "translation", "translationid" ) );
executeSql( statementBuilder.getDropNotNullConstraint( "translation", "objectid", "integer" ) );
}
/**
* Convert from older releases where dataApproval referenced dataset
* instead of workflow:
* <p>
* For every dataset that has either ("approve data" == true) *or*
* (existing data approval database records referencing it), a workflow will
* be created with the same name as the data set. This workflow will be
* associated with all approval levels in the system and have a period type
* equal to the data set's period type. If the data set's approvedata ==
* true, then the data set will be associated with this workflow.
* If there are existing data approval records that reference this data set,
* then they will be changed to reference the associated workflow instead.
*/
private void upgradeToDataApprovalWorkflows()
{
if ( executeSql( "update dataset set approvedata = approvedata where datasetid < 0" ) < 0 )
{
return; // Already converted because dataset.approvedata no longer exists.
}
executeSql( "insert into dataapprovalworkflow ( workflowid, uid, created, lastupdated, name, periodtypeid, userid, publicaccess ) "
+ "select " + statementBuilder.getAutoIncrementValue() + ", " + statementBuilder.getUid() + ", now(), now(), ds.name, ds.periodtypeid, ds.userid, ds.publicaccess "
+ "from (select datasetid from dataset where approvedata = true union select distinct datasetid from dataapproval) as a "
+ "join dataset ds on ds.datasetid = a.datasetid" );
executeSql( "insert into dataapprovalworkflowlevels (workflowid, dataapprovallevelid) "
+ "select w.workflowid, l.dataapprovallevelid from dataapprovalworkflow w "
+ "cross join dataapprovallevel l" );
executeSql( "update dataset set workflowid = ( select w.workflowid from dataapprovalworkflow w where w.name = dataset.name)" );
executeSql( "alter table dataset drop column approvedata cascade" ); // Cascade to SQL Views, if any.
executeSql( "update dataapproval set workflowid = ( select ds.workflowid from dataset ds where ds.datasetid = dataapproval.datasetid)" );
executeSql( "alter table dataapproval drop constraint dataapproval_unique_key" );
executeSql( "alter table dataapproval drop column datasetid cascade" ); // Cascade to SQL Views, if any.
log.info( "Added any workflows needed for approvble datasets and/or approved data." );
}
/**
* Convert from pre-2.22 releases where the right hand sides of surveillance rules were
* implicitly averaged. This just wraps the previous expression in a call to AVG().
* <p>
* We use the presence of the lowoutliers column to determine whether we need to make the
* change. Just to be extra sure, our rewrite SQL won't rewrite rules which already have
* references to AVG or STDDEV.
*/
private void upgradeImplicitAverageMonitoringRules()
{
if ( executeSql( "update validationrule set lowoutliers = lowoutliers where validationruleid < 0" ) < 0 )
{
return; // Already converted because lowoutlier fields are gone
}
// Just to be extra sure, we don't modify any expressions which already contain a call to AVG or STDDEV
executeSql( "INSERT INTO expressionsampleelement (expressionid, dataelementid) " +
"SELECT ede.expressionid, ede.dataelementid " +
"FROM expressiondataelement ede " +
"JOIN expression e ON e.expressionid = ede.expressionid " +
"JOIN validationrule v ON v.rightexpressionid = e.expressionid " +
"WHERE v.ruletype='SURVEILLANCE' " +
"AND e.expression NOT LIKE '%AVG%' and e.expression NOT LIKE '%STDDEV%';" );
executeSql( "update expression set expression=" + statementBuilder.concatenate( "'AVG('", "expression", "')'" ) +
" from validationrule where ruletype='SURVEILLANCE' AND rightexpressionid=expressionid " +
"AND expression NOT LIKE '%AVG%' and expression NOT LIKE '%STDDEV%';" );
executeSql( "ALTER TABLE validationrule DROP COLUMN highoutliers" );
executeSql( "ALTER TABLE validationrule DROP COLUMN lowoutliers" );
log.info( "Added explicit AVG calls to olid-style implicit average surveillance rules" );
}
private List<Integer> getDistinctIdList( String table, String col1 )
{
StatementHolder holder = statementManager.getHolder();
List<Integer> distinctIds = new ArrayList<>();
try
{
Statement statement = holder.getStatement();
ResultSet resultSet = statement.executeQuery( "SELECT DISTINCT " + col1 + " FROM " + table );
while ( resultSet.next() )
{
distinctIds.add( resultSet.getInt( 1 ) );
}
}
catch ( Exception ex )
{
log.error( ex );
}
finally
{
holder.close();
}
return distinctIds;
}
private Map<Integer, List<Integer>> getIdMap( String table, String col1, String col2, List<Integer> distinctIds )
{
StatementHolder holder = statementManager.getHolder();
Map<Integer, List<Integer>> idMap = new HashMap<>();
try
{
Statement statement = holder.getStatement();
for ( Integer distinctId : distinctIds )
{
List<Integer> foreignIds = new ArrayList<>();
ResultSet resultSet = statement.executeQuery( "SELECT " + col2 + " FROM " + table + " WHERE " + col1
+ "=" + distinctId );
while ( resultSet.next() )
{
foreignIds.add( resultSet.getInt( 1 ) );
}
idMap.put( distinctId, foreignIds );
}
}
catch ( Exception ex )
{
log.error( ex );
}
finally
{
holder.close();
}
return idMap;
}
private void updateHideEmptyRows()
{
executeSql(
"update chart set hideemptyrowitems = 'NONE' where hideemptyrows is false or hideemptyrows is null; " +
"update chart set hideemptyrowitems = 'ALL' where hideemptyrows is true; " +
"alter table chart alter column hideemptyrowitems set not null; " +
"alter table chart drop column hideemptyrows;" );
executeSql(
"update eventchart set hideemptyrowitems = 'NONE' where hideemptyrows is false or hideemptyrows is null; " +
"update eventchart set hideemptyrowitems = 'ALL' where hideemptyrows is true; " +
"alter table eventchart alter column hideemptyrowitems set not null; " +
"alter table eventchart drop column hideemptyrows;" );
}
private void updateSortOrder( String table, String col1, String col2 )
{
List<Integer> distinctIds = getDistinctIdList( table, col1 );
log.info( "Got distinct ids: " + distinctIds.size() );
Map<Integer, List<Integer>> idMap = getIdMap( table, col1, col2, distinctIds );
log.info( "Got id map: " + idMap.size() );
for ( Integer distinctId : idMap.keySet() )
{
int sortOrder = 1;
for ( Integer foreignId : idMap.get( distinctId ) )
{
String sql = "UPDATE " + table + " SET sort_order=" + sortOrder++ + " WHERE " + col1 + "=" + distinctId
+ " AND " + col2 + "=" + foreignId;
int count = executeSql( sql );
log.info( "Executed: " + count + " - " + sql );
}
}
}
private Integer getDefaultOptionCombo()
{
String sql = "select coc.categoryoptioncomboid from categoryoptioncombo coc "
+ "inner join categorycombos_optioncombos cco on coc.categoryoptioncomboid=cco.categoryoptioncomboid "
+ "inner join categorycombo cc on cco.categorycomboid=cc.categorycomboid " + "where cc.name='default';";
return statementManager.getHolder().queryForInteger( sql );
}
private Integer getDefaultCategoryCombo()
{
String sql = "select categorycomboid from categorycombo where name = 'default'";
return statementManager.getHolder().queryForInteger( sql );
}
private void updateOptions()
{
String sql = "insert into optionvalue(optionvalueid, code, name, optionsetid, sort_order) "
+ "select " + statementBuilder.getAutoIncrementValue() + ", optionvalue, optionvalue, optionsetid, ( sort_order + 1 ) "
+ "from optionsetmembers";
int result = executeSql( sql );
if ( result != -1 )
{
executeSql( "drop table optionsetmembers" );
}
}
/**
* Upgrades existing map views to use mapview_columns for multiple column
* dimensions.
*/
private void upgradeMapViewsToColumns()
{
String sql =
"insert into mapview_columns(mapviewid, sort_order, dimension) " +
"select mapviewid, 0, 'dx' " +
"from mapview mv " +
"where not exists (" +
"select mc.mapviewid " +
"from mapview_columns mc " +
"where mv.mapviewid = mc.mapviewid)";
executeSql( sql );
}
/**
* Upgrades data dimension items to use embedded data element operands.
*/
private void upgradeDataDimensionsToEmbeddedOperand()
{
String sql =
"update datadimensionitem di " +
"set dataelementoperand_dataelementid = ( " +
"select op.dataelementid " +
"from dataelementoperand op " +
"where di.dataelementoperandid=op.dataelementoperandid " +
"), " +
"dataelementoperand_categoryoptioncomboid = ( " +
"select op.categoryoptioncomboid " +
"from dataelementoperand op " +
"where di.dataelementoperandid=op.dataelementoperandid " +
") " +
"where di.dataelementoperandid is not null; " +
"alter table datadimensionitem drop column dataelementoperandid;";
executeSql( sql );
}
/**
* Upgrade data dimension items for legacy data sets to use REPORTING_RATE
* as metric.
*/
private void upgradeDataDimensionItemsToReportingRateMetric()
{
String sql = "update datadimensionitem " +
"set metric='REPORTING_RATE' " +
"where datasetid is not null " +
"and metric is null;";
executeSql( sql );
}
/**
* Upgrades data dimension items to use embedded
* ProgramTrackedEntityAttributeDimensionItem class.
*/
private void upgradeDataDimensionItemToEmbeddedProgramAttribute()
{
String sql =
"update datadimensionitem di " +
"set programattribute_programid = (select programid from program_attributes where programtrackedentityattributeid=di.programattributeid), " +
"programattribute_attributeid = (select trackedentityattributeid from program_attributes where programtrackedentityattributeid=di.programattributeid) " +
"where programattributeid is not null " +
"and (programattribute_programid is null and programattribute_attributeid is null); " +
"alter table datadimensionitem drop column programattributeid;";
executeSql( sql );
}
/**
* Upgrades data dimension items to use embedded
* ProgramDataElementDimensionItem class.
*/
private void upgradeDataDimensionItemToEmbeddedProgramDataElement()
{
String sql =
"update datadimensionitem di " +
"set programdataelement_programid = (select programid from programdataelement where programdataelementid=di.programdataelementid), " +
"programdataelement_dataelementid = (select dataelementid from programdataelement where programdataelementid=di.programdataelementid) " +
"where di.programdataelementid is not null " +
"and (programdataelement_programid is null and programdataelement_dataelementid is null); " +
"alter table datadimensionitem drop column programdataelementid; " +
"drop table programdataelementtranslations; " +
"drop table programdataelement;"; // Remove if program data element is to be reintroduced
executeSql( sql );
}
/**
* Creates an utility function in the database for generating uid values in select statements.
* Example usage: select uid();
*/
private void insertUidDbFunction()
{
String uidFunction =
"CREATE OR REPLACE FUNCTION uid() RETURNS text AS $$ SELECT substring('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' " +
"FROM (random()*51)::int +1 for 1) || array_to_string(ARRAY(SELECT substring('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' " +
" FROM (random()*61)::int + 1 FOR 1) FROM generate_series(1,10)), '') $$ LANGUAGE sql;";
executeSql( uidFunction );
}
/**
* Inserts default {@link AnalyticsPeriodBoundary} objects for program indicators that has no boundaries defined.
* Based on the analyticsType if the program indicator, the insert is made
*/
private void insertDefaultBoundariesForBoundlessProgramIndicators()
{
String findBoundlessAndInsertDefaultBoundaries =
"create temporary table temp_unbounded_programindicators (programindicatorid integer,analyticstype varchar(10)) on commit drop;" +
"insert into temp_unbounded_programindicators (programindicatorid,analyticstype ) select pi.programindicatorid,pi.analyticstype " +
"from programindicator pi left join analyticsperiodboundary apb on apb.programindicatorid = pi.programindicatorid group by pi.programindicatorid " +
"having count(apb.*) = 0;" +
"insert into analyticsperiodboundary (analyticsperiodboundaryid, uid, created, lastupdated, boundarytarget,analyticsperiodboundarytype, programindicatorid) " +
"select nextval('hibernate_sequence'), uid(), now(), now(), 'EVENT_DATE', 'AFTER_START_OF_REPORTING_PERIOD', ubpi.programindicatorid " +
"from temp_unbounded_programindicators ubpi where ubpi.analyticstype = 'EVENT';" +
"insert into analyticsperiodboundary (analyticsperiodboundaryid, uid, created, lastupdated, boundarytarget,analyticsperiodboundarytype, programindicatorid) " +
"select nextval('hibernate_sequence'), uid(), now(), now(), 'EVENT_DATE', 'BEFORE_END_OF_REPORTING_PERIOD', ubpi.programindicatorid " +
"from temp_unbounded_programindicators ubpi where ubpi.analyticstype = 'EVENT';" +
"insert into analyticsperiodboundary (analyticsperiodboundaryid, uid, created, lastupdated, boundarytarget,analyticsperiodboundarytype, programindicatorid) " +
"select nextval('hibernate_sequence'), uid(), now(), now(), 'ENROLLMENT_DATE', 'AFTER_START_OF_REPORTING_PERIOD', ubpi.programindicatorid " +
"from temp_unbounded_programindicators ubpi where ubpi.analyticstype = 'ENROLLMENT';" +
"insert into analyticsperiodboundary (analyticsperiodboundaryid, uid, created, lastupdated, boundarytarget,analyticsperiodboundarytype, programindicatorid) " +
"select nextval('hibernate_sequence'), uid(), now(), now(), 'ENROLLMENT_DATE', 'BEFORE_END_OF_REPORTING_PERIOD', ubpi.programindicatorid " +
"from temp_unbounded_programindicators ubpi where ubpi.analyticstype = 'ENROLLMENT';";
executeSql( findBoundlessAndInsertDefaultBoundaries );
}
private int executeSql( String sql )
{
try
{
// TODO use jdbcTemplate
return statementManager.getHolder().executeUpdate( sql );
}
catch ( Exception ex )
{
log.debug( ex );
return -1;
}
}
private void addTranslationTable( List<Map<String, String>> listTables,
String className, String translationTable, String objectTable, String objectId )
{
Map<String, String> mapTables = new HashMap<>();
mapTables.put( "className", className );
mapTables.put( "translationTable", translationTable );
mapTables.put( "objectTable", objectTable );
mapTables.put( "objectId", objectId );
listTables.add( mapTables );
}
private void updateObjectTranslation()
{
List<Map<String, String>> listTables = new ArrayList<>();
addTranslationTable( listTables, "DataElement", "dataelementtranslations", "dataelement", "dataelementid" );
addTranslationTable( listTables, "Category", "dataelementcategorytranslations", "dataelementcategory", "categoryid" );
addTranslationTable( listTables, "Attribute", "attributetranslations", "attribute", "attributeid" );
addTranslationTable( listTables, "Indicator", "indicatortranslations", "indicator", "indicatorid" );
addTranslationTable( listTables, "OrganisationUnit", "organisationUnittranslations", "organisationunit", "organisationunitid" );
addTranslationTable( listTables, "CategoryCombo", "categorycombotranslations", "categorycombo", "categorycomboid" );
addTranslationTable( listTables, "OrganisationUnit", "organisationUnittranslations", "organisationunit", "organisationunitid" );
addTranslationTable( listTables, "DataElementGroup", "dataelementgrouptranslations", "dataelementgroup", "dataelementgroupid" );
addTranslationTable( listTables, "DataSet", "datasettranslations", "dataset", "datasetid" );
addTranslationTable( listTables, "IndicatorType", "indicatortypetranslations", "indicatortype", "indicatortypeid" );
addTranslationTable( listTables, "Section", "datasetsectiontranslations", "section", "sectionid" );
addTranslationTable( listTables, "Chart", "charttranslations", "chart", "chartid" );
addTranslationTable( listTables, "Color", "colortranslations", "color", "colorid" );
addTranslationTable( listTables, "ColorSet", "colorsettranslations", "colorset", "colorsetid" );
addTranslationTable( listTables, "Constant", "constanttranslations", "constant", "constantid" );
addTranslationTable( listTables, "Dashboard", "dashboardtranslations", "dashboard", "dashboardid" );
addTranslationTable( listTables, "DashboardItem", "dashboarditemtranslations", "dashboarditemid", "dashboarditemid" );
addTranslationTable( listTables, "DataApprovalLevel", "dataapprovalleveltranslations", "dataapprovallevel", "dataapprovallevelid" );
addTranslationTable( listTables, "DataApprovalWorkflow", "dataapprovalworkflowtranslations", "dataapprovalworkflow", "workflowid" );
addTranslationTable( listTables, "CategoryOptionGroup", "categoryoptiongrouptranslations", "categoryoptiongroup", "categoryoptiongroupid" );
addTranslationTable( listTables, "CategoryOptionGroupSet", "categoryoptiongroupsettranslations", "categoryoptiongroupset", "categoryoptiongroupsetid" );
addTranslationTable( listTables, "CategoryOption", "categoryoptiontranslations", "dataelementcategoryoption", "categoryoptionid" );
addTranslationTable( listTables, "CategoryOptionCombo", "categoryoptioncombotranslations", "categoryoptioncombo", "categoryoptioncomboid" );
addTranslationTable( listTables, "DataElementGroupSet", "dataelementgroupsettranslations", "dataelementgroupset", "dataelementgroupsetid" );
addTranslationTable( listTables, "DataElementOperand", "dataelementoperandtranslations", "dataelementoperand", "dataelementoperandid" );
addTranslationTable( listTables, "DataEntryForm", "dataentryformtranslations", "dataentryform", "dataentryformid" );
addTranslationTable( listTables, "DataStatistics", "statisticstranslations", "datastatistics", "statisticsid" );
addTranslationTable( listTables, "Document", "documenttranslations", "document", "documentid" );
addTranslationTable( listTables, "EventChart", "eventcharttranslations", "eventchart", "eventchartid" );
addTranslationTable( listTables, "EventReport", "eventreporttranslations", "eventreport", "eventreportid" );
addTranslationTable( listTables, "IndicatorGroup", "indicatorgrouptranslations", "indicatorgroup", "indicatorgroupid" );
addTranslationTable( listTables, "IndicatorGroupSet", "indicatorgroupsettranslations", "indicatorgroupset", "indicatorgroupsetid" );
addTranslationTable( listTables, "Interpretation", "interpretationtranslations", "interpretation", "interpretationid" );
addTranslationTable( listTables, "InterpretationComment", "interpretationcommenttranslations", "interpretationcomment", "interpretationcommentid" );
addTranslationTable( listTables, "Legend", "maplegendtranslations", "maplegend", "maplegendid" );
addTranslationTable( listTables, "LegendSet", "maplegendsettranslations", "maplegendset", "maplegendsetid" );
addTranslationTable( listTables, "Map", "maptranslations", "map", "mapid" );
addTranslationTable( listTables, "MapLayer", "maplayertranslations", "maplayer", "maplayerid" );
addTranslationTable( listTables, "MapView", "mapviewtranslations", "mapview", "mapviewid" );
addTranslationTable( listTables, "Message", "messagetranslations", "message", "messageid" );
addTranslationTable( listTables, "MessageConversation", "messageconversationtranslations", "messageconversation", "messageconversationid" );
addTranslationTable( listTables, "Option", "optionvaluetranslations", "optionvalue", "optionvalueid" );
addTranslationTable( listTables, "OptionSet", "optionsettranslations", "optionset", "optionsetid" );
addTranslationTable( listTables, "OrganisationUnit", "organisationunittranslations", "organisationunit", "organisationunitid" );
addTranslationTable( listTables, "OrganisationUnitGroup", "orgunitgrouptranslations", "orgunitgroup", "orgunitgroupid" );
addTranslationTable( listTables, "OrganisationUnitGroupSet", "orgunitgroupsettranslations", "orgunitgroupset", "orgunitgroupsetid" );
addTranslationTable( listTables, "OrganisationUnitLevel", "orgunitleveltranslations", "orgunitlevel", "orgunitlevelid" );
addTranslationTable( listTables, "Period", "periodtranslations", "period", "periodid" );
addTranslationTable( listTables, "Program", "programtranslations", "program", "programid" );
addTranslationTable( listTables, "ProgramDataElement", "programdataelementtranslations", "programdataelement", "programdataelementid" );
addTranslationTable( listTables, "ProgramIndicator", "programindicatortranslations", "programindicator", "programindicatorid" );
addTranslationTable( listTables, "ProgramInstance", "programinstancetranslations", "programinstance", "programinstanceid" );
addTranslationTable( listTables, "ProgramMessage", "programmessagetranslations", "programmessage", "id" );
addTranslationTable( listTables, "ProgramStage", "programstagetranslations", "programstage", "programstageid" );
addTranslationTable( listTables, "ProgramStageDataElement", "programstagedataelementtranslations", "programstagedataelement", "programstagedataelementid" );
addTranslationTable( listTables, "ProgramStageInstance", "programstageinstancetranslations", "programstageinstance", "programstageinstanceid" );
addTranslationTable( listTables, "ProgramStageSection", "programstagesectiontranslations", "programstagesection", "programstagesectionid" );
addTranslationTable( listTables, "ProgramTrackedEntityAttribute", "programattributestranslations", "programtrackedentityattribute", "programtrackedentityattributeid" );
addTranslationTable( listTables, "ProgramRule", "programruletranslations", "programrule", "programruleid" );
addTranslationTable( listTables, "ProgramRuleAction", "programruleactiontranslations", "programruleaction", "programruleactionid" );
addTranslationTable( listTables, "ProgramRuleVariable", "programrulevariabletranslations", "programrulevariable", "programrulevariableid" );
addTranslationTable( listTables, "RelationshipType", "relationshiptypetranslations", "relationshiptype", "relationshiptypeid" );
addTranslationTable( listTables, "Report", "reporttranslations", "report", "reportid" );
addTranslationTable( listTables, "ReportTable", "reporttabletranslations", "reporttable", "reporttableid" );
addTranslationTable( listTables, "TrackedEntityType", "trackedentitytranslations", "trackedentitytype", "trackedentitytypeid" );
addTranslationTable( listTables, "TrackedEntityAttribute", "trackedentityattributetranslations", "trackedentityattribute", "trackedentityattributeid" );
addTranslationTable( listTables, "TrackedEntityInstance", "trackedentityinstancetranslations", "trackedentityinstance", "trackedentityinstanceid" );
addTranslationTable( listTables, "User", "userinfotranslations", "userinfo", "userinfoid" );
addTranslationTable( listTables, "UserAuthorityGroup", "userroletranslations", "userrole", "userroleid" );
addTranslationTable( listTables, "UserCredentials", "usertranslations", "users", "userid" );
addTranslationTable( listTables, "UserGroup", "usergrouptranslations", "usergroup", "usergroupid" );
addTranslationTable( listTables, "ValidationCriteria", "validationcriteriatranslations", "validationcriteria", "validationcriteriaid" );
addTranslationTable( listTables, "ValidationRule", "validationruletranslations", "validationrule", "validationruleid" );
addTranslationTable( listTables, "ValidationRuleGroup", "validationrulegrouptranslations", "validationrulegroup", "validationrulegroupid" );
executeSql( "alter table translation add column objectid integer;" );
String sql;
for ( Map<String, String> table : listTables )
{
sql =
" insert into objecttranslation ( objecttranslationid, locale , property , value ) " +
" select t.translationid, t.locale, " +
" case when t.objectproperty = 'shortName' then 'SHORT_NAME' " +
" when t.objectproperty = 'formName' then 'FORM_NAME' " +
" when t.objectproperty = 'name' then 'NAME' " +
" when t.objectproperty = 'description' then'DESCRIPTION'" +
" else t.objectproperty " +
" end ," +
" t.value " +
" from translation as t " +
" where t.objectclass = '" + table.get( "className" ) + "'" +
" and t.objectproperty is not null " +
" and t.locale is not null " +
" and t.value is not null " +
" and not exists ( select 1 from objecttranslation where objecttranslationid = t.translationid ) " +
" and ( " +
" exists ( select 1 from " + table.get( "objectTable" ) + " where " + table.get( "objectId" ) + " = t.objectid ) " +
" or exists ( select 1 from " + table.get( "objectTable" ) + " where uid = t.objectuid ) " +
" ) ;";
executeSql( sql );
sql =
" insert into " + table.get( "translationTable" ) + " ( " + table.get( "objectId" ) + ", objecttranslationid ) " +
" select " +
" case when t.objectid is not null then t.objectid " +
" else ( select " + table.get( "objectId" ) + " from " + table.get( "objectTable" ) + " where uid = t.objectuid ) " +
" end," +
" o.objecttranslationid " +
" from objecttranslation o inner join translation t on o.objecttranslationid = t.translationid and t.objectclass = '" + table.get( "className" ) + "'" +
" and not exists ( select 1 from " + table.get( "translationTable" ) + " where objecttranslationid = o.objecttranslationid) ;";
executeSql( sql );
}
}
private void updateLegendRelationship()
{
String sql = "update maplegend l set maplegendsetid = (select legendsetid from maplegendsetmaplegend m where m.maplegendid = l.maplegendid);";
executeSql( sql );
sql = " drop table maplegendsetmaplegend";
executeSql( sql );
}
private void updateDimensionFilterToText()
{
executeSql( "alter table trackedentityattributedimension alter column \"filter\" type text;" );
executeSql( "alter table trackedentitydataelementdimension alter column \"filter\" type text;" );
executeSql( "alter table trackedentityprogramindicatordimension alter column \"filter\" type text;" );
}
}
|
package org.drools.examples;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.definition.KnowledgePackage;
import org.drools.event.rule.DebugAgendaEventListener;
import org.drools.event.rule.DebugWorkingMemoryEventListener;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;
/**
* This is a sample file to launch a rule package from a rule source file.
*/
public class HelloWorldExample {
public static final void main(final String[] args) throws Exception {
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
.newKnowledgeBuilder();
// this will parse and compile in one step
kbuilder.add(ResourceFactory.newClassPathResource("HelloWorld.drl",
HelloWorldExample.class), ResourceType.DRL);
// Check the builder for errors
if (kbuilder.hasErrors()) {
System.out.println(kbuilder.getErrors().toString());
throw new RuntimeException("Unable to compile \"HelloWorld.drl\".");
}
// get the compiled packages (which are serializable)
final Collection<KnowledgePackage> pkgs = kbuilder
.getKnowledgePackages();
// add the packages to a knowledgebase (deploy the knowledge packages).
final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(pkgs);
final StatefulKnowledgeSession ksession = kbase
.newStatefulKnowledgeSession();
ksession.setGlobal("list", new ArrayList<Object>());
ksession.addEventListener(new DebugAgendaEventListener());
ksession.addEventListener(new DebugWorkingMemoryEventListener());
// setup the audit logging
KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory
.newFileLogger(ksession, "log/helloworld");
final Message message = new Message();
message.setMessage("Hello World");
message.setStatus(Message.HELLO);
ksession.insert(message);
ksession.fireAllRules();
logger.close();
ksession.dispose();
}
public static class Message {
public static final int HELLO = 0;
public static final int GOODBYE = 1;
private String message;
private int status;
public Message() {
}
public String getMessage() {
return this.message;
}
public void setMessage(final String message) {
this.message = message;
}
public int getStatus() {
return this.status;
}
public void setStatus(final int status) {
this.status = status;
}
public static Message doSomething(Message message) {
return message;
}
public boolean isSomething(String msg, List<Object> list) {
list.add(this);
return this.message.equals(msg);
}
}
}
|
package edu.oregonstate.cope.eclipse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SnapshotManagerTest extends PopulatedWorkspaceTest {
private SnapshotManager snapshotManager;
@Before
public void setUp() throws Exception {
File file = new File(COPEPlugin.getLocalStorage(), "known-projects");
file.createNewFile();
Files.write(file.toPath(), "known1\nknown2\n".getBytes(), StandardOpenOption.WRITE);
snapshotManager = new SnapshotManager(COPEPlugin.getLocalStorage().getAbsolutePath());
}
@After
public void tearDown() throws Exception {
File[] zipFiles = listZipFilesInDir(COPEPlugin.getLocalStorage());
for (File zipFile : zipFiles) {
zipFile.delete();
}
}
@Test
public void testNotKnowProject() {
assertFalse(snapshotManager.isProjectKnown("test"));
}
@Test
public void testIsProjectKnown() {
assertTrue(snapshotManager.isProjectKnown("known1"));
assertTrue(snapshotManager.isProjectKnown("known2"));
}
@Test
public void testKnowProject() throws Exception {
snapshotManager.knowProject("known3");
assertTrue(snapshotManager.isProjectKnown("known3"));
assertEquals("known1\nknown2\nlibrariesTest\nknown3\n",new String(Files.readAllBytes(Paths.get(COPEPlugin.getLocalStorage().getAbsolutePath(), "known-projects"))));
}
@Test
public void testTouchProjectInSession() throws Exception {
String projectName = javaProject.getProject().getName();
snapshotManager.isProjectKnown(projectName);
snapshotManager.takeSnapshotOfKnownProjects();
File fileDir = COPEPlugin.getLocalStorage();
assertTrue(fileDir.isDirectory());
File[] listFiles = listZipFilesInDir(fileDir);
assertEquals(1,listFiles.length);
assertTrue(listFiles[0].getName().matches(projectName + "-[0-9]*\\.zip"));
assertZipFileContentsIsNotEmpty(listFiles[0]);
}
private void assertZipFileContentsIsNotEmpty(File zipFile) throws Exception {
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
while (zipInputStream.available() == 1) {
ZipEntry nextEntry = zipInputStream.getNextEntry();
if (nextEntry == null)
break;
int count = 0;
ArrayList<Byte> contents = new ArrayList<Byte>();
do {
byte[] block = new byte[1024];
int read = zipInputStream.read(block, 0, 1024);
if (read != -1) {
count += read;
contents.addAll(Arrays.asList(boxByteArray(block)));
} else {
assertContentsAreTheSameAsTheOriginal(contents, nextEntry.getName());
break;
}
} while(true);
System.out.println(count);
assertTrue(count != 0);
}
zipInputStream.close();
}
private Byte[] boxByteArray(byte[] block) {
Byte[] boxedBlock = new Byte[1024];
for (int i=0; i< 1024; i++) {
boxedBlock[i] = block[i];
}
return boxedBlock;
}
private void assertContentsAreTheSameAsTheOriginal(ArrayList<Byte> contents, String fileName) throws Exception {
IFile file = javaProject.getProject().getFile(fileName);
byte[] actualFileContents = null;
try {
actualFileContents = Files.readAllBytes(Paths.get(file.getLocation().toPortableString()));
} catch (NoSuchFileException e) {
return;
}
assertEquals(actualFileContents, contents);
}
private File[] listZipFilesInDir(File fileDir) {
File[] listFiles = fileDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".zip");
}
});
return listFiles;
}
@Test
public void testCompleteSnapshot() throws Exception {
String snapshotFile = snapshotManager.takeSnapshot(javaProject.getProject());
ZipFileStructureProvider structureProvider = new ZipFileStructureProvider(new ZipFile(snapshotFile));
ZipEntry rootEntry = structureProvider.getRoot();
List children = structureProvider.getChildren(rootEntry);
ZipEntry projectRoot = getProjectEntry(children);
assertEntryMatchesDir(structureProvider, javaProject.getProject(), projectRoot);
}
private ZipEntry getProjectEntry(List children) {
ZipEntry projectRoot = null;
for (Object child : children) {
if(((ZipEntry) child).getName().equals("librariesTest/"))
projectRoot = (ZipEntry) child;
}
return projectRoot;
}
private void assertEntryMatchesDir(ZipFileStructureProvider structureProvider, IContainer folder, ZipEntry parentEntry) throws Exception {
List unexportedItems = Arrays.asList("bin");
IResource[] members = folder.members();
List children = structureProvider.getChildren(parentEntry);
for (IResource member : members) {
String memberName = member.getName();
if (unexportedItems.contains(memberName))
continue;
boolean found = false;
for (Object child : children) {
ZipEntry entry = (ZipEntry) child;
String entryName = getEntryName(entry);
if (entryName.equals(memberName)) {
found = true;
if (member instanceof IFolder)
if (entry.isDirectory())
assertEntryMatchesDir(structureProvider, (IContainer) member, entry);
else
fail("Directories don't match");
}
}
assertTrue(found);
}
}
private String getEntryName(ZipEntry entry) {
String entryName = entry.getName();
if (entryName.endsWith("/"))
entryName = entryName.substring(0, entryName.length() - 1);
entryName = entryName.substring(entryName.lastIndexOf("/") + 1);
return entryName;
}
}
|
package com.stratio.streaming.service;
import com.stratio.streaming.commons.constants.ColumnType;
import com.stratio.streaming.commons.constants.STREAMING;
import com.stratio.streaming.commons.constants.StreamAction;
import com.stratio.streaming.commons.messages.ColumnNameTypeValue;
import com.stratio.streaming.commons.messages.StratioStreamingMessage;
import com.stratio.streaming.commons.messages.StreamQuery;
import com.stratio.streaming.dao.StreamStatusDao;
import com.stratio.streaming.exception.ServiceException;
import com.stratio.streaming.streams.QueryDTO;
import com.stratio.streaming.streams.StreamStatusDTO;
import com.stratio.streaming.utils.SiddhiUtils;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.query.api.QueryFactory;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.definition.StreamDefinition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class StreamOperationServiceWithoutMetrics {
private final SiddhiManager siddhiManager;
private final StreamStatusDao streamStatusDao;
private final CallbackService callbackService;
public StreamOperationServiceWithoutMetrics(SiddhiManager siddhiManager, StreamStatusDao streamStatusDao,
CallbackService callbackService) {
this.siddhiManager = siddhiManager;
this.streamStatusDao = streamStatusDao;
this.callbackService = callbackService;
}
public void createInternalStream(String streamName, List<ColumnNameTypeValue> columns) {
StreamDefinition newStream = QueryFactory.createStreamDefinition().name(streamName);
for (ColumnNameTypeValue column : columns) {
newStream.attribute(column.getColumn(), getSiddhiType(column.getType()));
}
siddhiManager.defineStream(newStream);
streamStatusDao.createInferredStream(streamName, columns);
}
public void createStream(String streamName, List<ColumnNameTypeValue> columns) {
StreamDefinition newStream = QueryFactory.createStreamDefinition().name(streamName);
for (ColumnNameTypeValue column : columns) {
newStream.attribute(column.getColumn(), getSiddhiType(column.getType()));
}
siddhiManager.defineStream(newStream);
streamStatusDao.create(streamName, columns);
}
public boolean streamExist(String streamName) {
return streamStatusDao.get(streamName) != null ? true : false;
}
public boolean isUserDefined(String streamName) {
StreamStatusDTO streamStatus = streamStatusDao.get(streamName);
return streamStatus != null ? streamStatus.getUserDefined() : false;
}
public int enlargeStream(String streamName, List<ColumnNameTypeValue> columns) throws ServiceException {
int addedColumns = 0;
StreamDefinition streamMetaData = siddhiManager.getStreamDefinition(streamName);
for (ColumnNameTypeValue columnNameTypeValue : columns) {
if (!SiddhiUtils.columnAlreadyExistsInStream(columnNameTypeValue.getColumn(), streamMetaData)) {
addedColumns++;
streamMetaData.attribute(columnNameTypeValue.getColumn(), getSiddhiType(columnNameTypeValue.getType()));
} else {
throw new ServiceException(String.format("Alter stream error, Column %s already exists.",
columnNameTypeValue.getColumn()));
}
}
return addedColumns;
}
public void dropStream(String streamName) {
Map<String, QueryDTO> attachedQueries = streamStatusDao.get(streamName).getAddedQueries();
for (String queryId : attachedQueries.keySet()) {
siddhiManager.removeQuery(queryId);
}
siddhiManager.removeStream(streamName);
streamStatusDao.remove(streamName);
}
public void addQuery(String streamName, String queryString) {
String queryId = siddhiManager.addQuery(queryString);
streamStatusDao.addQuery(streamName, queryId, queryString);
for (StreamDefinition streamDefinition : siddhiManager.getStreamDefinitions()) {
// XXX refactor to obtain exactly siddhi inferred streams.
streamStatusDao.createInferredStream(streamDefinition.getStreamId(), castToColumnNameTypeValue(streamDefinition.getAttributeList()));
}
}
private List<ColumnNameTypeValue> castToColumnNameTypeValue(List<Attribute> attributeList) {
List<ColumnNameTypeValue> result = new ArrayList<>();
for (Attribute attribute : attributeList) {
result.add(new ColumnNameTypeValue(attribute.getName(), getStreamingType(attribute.getType()), null));
}
return result;
}
public void removeQuery(String queryId, String streamName) {
siddhiManager.removeQuery(queryId);
streamStatusDao.removeQuery(streamName, queryId);
for (Map.Entry<String, StreamStatusDTO> streamStatus : streamStatusDao.getAll().entrySet()) {
String temporalStreamName = streamStatus.getKey();
if (siddhiManager.getStreamDefinition(temporalStreamName) == null) {
this.dropStream(temporalStreamName);
}
}
}
public boolean queryIdExists(String streamName, String queryId) {
StreamStatusDTO streamStatus = streamStatusDao.get(streamName);
if (streamStatus != null) {
return streamStatus.getAddedQueries().containsKey(queryId);
} else {
return false;
}
}
public boolean queryRawExists(String streamName, String queryRaw) {
StreamStatusDTO streamStatus = streamStatusDao.get(streamName);
if (streamStatus != null) {
return streamStatus.getAddedQueries().containsValue(new QueryDTO(queryRaw));
} else {
return false;
}
}
public void enableAction(String streamName, StreamAction action) {
if (streamStatusDao.getEnabledActions(streamName).size() == 0) {
String actionQueryId = siddhiManager.addQuery(QueryFactory.createQuery()
.from(QueryFactory.inputStream(streamName))
.insertInto(STREAMING.STATS_NAMES.SINK_STREAM_PREFIX.concat(streamName)));
streamStatusDao.setActionQuery(streamName, actionQueryId);
siddhiManager.addCallback(actionQueryId,
callbackService.add(streamName, streamStatusDao.getEnabledActions(streamName)));
}
streamStatusDao.enableAction(streamName, action);
}
public void disableAction(String streamName, StreamAction action) {
streamStatusDao.disableAction(streamName, action);
if (streamStatusDao.getEnabledActions(streamName).size() == 0) {
String actionQueryId = streamStatusDao.getActionQuery(streamName);
if (actionQueryId != null) {
siddhiManager.removeQuery(actionQueryId);
}
callbackService.remove(streamName);
}
}
public boolean isActionEnabled(String streamName, StreamAction action) {
return streamStatusDao.getEnabledActions(streamName).contains(action);
}
public List<StratioStreamingMessage> list() {
List<StratioStreamingMessage> result = new ArrayList<>();
for (StreamDefinition streamDefinition : siddhiManager.getStreamDefinitions()) {
if (suitableToList(streamDefinition.getStreamId())) {
StratioStreamingMessage message = new StratioStreamingMessage();
for (Attribute attribute : streamDefinition.getAttributeList()) {
message.addColumn(new ColumnNameTypeValue(attribute.getName(), this.getStreamingType(attribute
.getType()), null));
}
StreamStatusDTO streamStatus = streamStatusDao.get(streamDefinition.getStreamId());
if (streamStatus != null) {
Map<String, QueryDTO> attachedQueries = streamStatus.getAddedQueries();
for (Map.Entry<String, QueryDTO> entry : attachedQueries.entrySet()) {
message.addQuery(new StreamQuery(entry.getKey(), entry.getValue().getQueryRaw()));
}
message.setUserDefined(streamStatus.getUserDefined());
message.setActiveActions(streamStatusDao.getEnabledActions(streamDefinition.getStreamId()));
}
message.setStreamName(streamDefinition.getStreamId());
result.add(message);
}
}
return result;
}
private boolean suitableToList(String streamName) {
boolean startWithSinkPrefix = streamName.startsWith(STREAMING.STATS_NAMES.SINK_STREAM_PREFIX);
boolean isAStatStream = Arrays.asList(STREAMING.STATS_NAMES.STATS_STREAMS).contains(streamName);
return !startWithSinkPrefix && !isAStatStream;
}
public void send(String streamName, List<ColumnNameTypeValue> columns) throws ServiceException {
try {
siddhiManager.getInputHandler(streamName).send(
SiddhiUtils.getOrderedValues(siddhiManager.getStreamDefinition(streamName), columns));
} catch (InterruptedException e) {
throw new ServiceException(String.format("Error sending data to stream %s, column data: %s", streamName,
columns), e);
}
}
private Attribute.Type getSiddhiType(ColumnType originalType) {
switch (originalType) {
case STRING:
return Attribute.Type.STRING;
case BOOLEAN:
return Attribute.Type.BOOL;
case DOUBLE:
return Attribute.Type.DOUBLE;
case INTEGER:
return Attribute.Type.INT;
case LONG:
return Attribute.Type.LONG;
case FLOAT:
return Attribute.Type.FLOAT;
default:
throw new RuntimeException("Unsupported Column type: " + originalType);
}
}
private ColumnType getStreamingType(Attribute.Type type) {
switch (type) {
case STRING:
return ColumnType.STRING;
case BOOL:
return ColumnType.BOOLEAN;
case DOUBLE:
return ColumnType.DOUBLE;
case INT:
return ColumnType.INTEGER;
case LONG:
return ColumnType.LONG;
case FLOAT:
return ColumnType.FLOAT;
default:
throw new RuntimeException("Unsupported Column type: " + type);
}
}
}
|
package es.tid.fiware.fiwareconnectors.cygnus.backends.hdfs;
import es.tid.fiware.fiwareconnectors.cygnus.errors.CygnusPersistenceError;
import es.tid.fiware.fiwareconnectors.cygnus.errors.CygnusRuntimeError;
import java.io.IOException;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.log4j.Logger;
/**
*
* @author frb
*
* HDFS persistence based on the HttpFS service (TCP/14000). HttpFS is an alternative implementation of the WebHDFS
* API which hides the cluster details by forwarding directly to the Master node instead of to the Data node.
*/
public class HDFSBackendImpl extends HDFSBackend {
private final Logger logger;
/**
*
* @param cosmosHost
* @param cosmosPort
* @param cosmosDefaultUsername
* @param cosmosDefaultPassword
* @param hiveHost
* @param hivePort
* @param krb5
* @param krb5User
* @param krb5Password
* @param krb5LoginConfFile
* @param krb5ConfFile
*/
public HDFSBackendImpl(String[] cosmosHost, String cosmosPort, String cosmosDefaultUsername,
String cosmosDefaultPassword, String hiveHost, String hivePort, boolean krb5, String krb5User,
String krb5Password, String krb5LoginConfFile, String krb5ConfFile) {
super(cosmosHost, cosmosPort, cosmosDefaultUsername, cosmosDefaultPassword, hiveHost, hivePort, krb5,
krb5User, krb5Password, krb5LoginConfFile, krb5ConfFile);
logger = Logger.getLogger(HDFSBackendImpl.class);
} // HDFSBackendImpl
@Override
public void createDir(String username, String dirPath) throws Exception {
String relativeURL = "/webhdfs/v1/user/" + username + "/" + dirPath + "?op=mkdirs&user.name=" + username;
HttpResponse response = doHDFSRequest("PUT", relativeURL, true, null, null);
// check the status
if (response.getStatusLine().getStatusCode() != 200) {
throw new CygnusPersistenceError("The " + dirPath + " directory could not be created in HDFS. "
+ "HttpFS response: " + response.getStatusLine().getStatusCode() + " "
+ response.getStatusLine().getReasonPhrase());
}
} // createDir
@Override
public void createFile(String username, String filePath, String data)
throws Exception {
String relativeURL = "/webhdfs/v1/user/" + username + "/" + filePath + "?op=create&user.name=" + username;
HttpResponse response = doHDFSRequest("PUT", relativeURL, true, null, null);
// check the status
if (response.getStatusLine().getStatusCode() != 307) {
throw new CygnusPersistenceError("The " + filePath + " file could not be created in HDFS. "
+ "HttpFS response: " + response.getStatusLine().getStatusCode() + " "
+ response.getStatusLine().getReasonPhrase());
}
// get the redirection location
Header header = response.getHeaders("Location")[0];
String absoluteURL = header.getValue();
// do second step
ArrayList<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("Content-Type", "application/octet-stream"));
response = doHDFSRequest("PUT", absoluteURL, false, headers, new StringEntity(data + "\n"));
// check the status
if (response.getStatusLine().getStatusCode() != 201) {
throw new CygnusPersistenceError(filePath + " file created in HDFS, but could not write the "
+ "data. HttpFS response: " + response.getStatusLine().getStatusCode() + " "
+ response.getStatusLine().getReasonPhrase());
}
} // createFile
@Override
public void append(String username, String filePath, String data) throws Exception {
String relativeURL = "/webhdfs/v1/user/" + username + "/" + filePath + "?op=append&user.name=" + username;
HttpResponse response = doHDFSRequest("POST", relativeURL, true, null, null);
// check the status
if (response.getStatusLine().getStatusCode() != 307) {
throw new CygnusPersistenceError("The " + filePath + " file seems to not exist in HDFS. "
+ "HttpFS response: " + response.getStatusLine().getStatusCode() + " "
+ response.getStatusLine().getReasonPhrase());
}
// get the redirection location
Header header = response.getHeaders("Location")[0];
String absoluteURL = header.getValue();
// do second step
ArrayList<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("Content-Type", "application/octet-stream"));
response = doHDFSRequest("POST", absoluteURL, false, headers, new StringEntity(data + "\n"));
// check the status
if (response.getStatusLine().getStatusCode() != 200) {
throw new CygnusPersistenceError(filePath + " file exists in HDFS, but could not write the "
+ "data. HttpFS response: " + response.getStatusLine().getStatusCode() + " "
+ response.getStatusLine().getReasonPhrase());
}
} // append
@Override
public boolean exists(String username, String filePath) throws Exception {
String relativeURL = "/webhdfs/v1/user/" + username + "/" + filePath + "?op=getfilestatus&user.name="
+ username;
HttpResponse response = doHDFSRequest("GET", relativeURL, true, null, null);
// check the status
return (response.getStatusLine().getStatusCode() == 200);
} // exists
/**
* Does a HDFS request given a HTTP client, a method and a relative URL (the final URL will be composed by using
* this relative URL and the active HDFS endpoint).
* @param method
* @param relativeURL
* @return
* @throws Exception
*/
private HttpResponse doHDFSRequest(String method, String url, boolean relative, ArrayList<Header> headers,
StringEntity entity) throws Exception {
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_SERVICE_UNAVAILABLE,
"Service unavailable");
if (relative) {
// iterate on the hosts
for (String host : cosmosHost) {
// create the HttpFS URL
String effectiveURL = "http://" + host + ":" + cosmosPort + url;
try {
if (krb5) {
response = doPrivilegedHDFSRequest(method, effectiveURL, headers, entity);
} else {
response = doHDFSRequest(method, effectiveURL, headers, entity);
} // if else
} catch (Exception e) {
logger.debug("The used HDFS endpoint is not active, trying another one (host=" + host + ")");
continue;
} // try catch
int status = response.getStatusLine().getStatusCode();
if (status != 200 && status != 307 && status != 404 && status != 201) {
logger.debug("The used HDFS endpoint is not active, trying another one (host=" + host + ")");
continue;
}
// place the current host in the first place (if not yet placed), since it is currently working
if (!cosmosHost.getFirst().equals(host)) {
cosmosHost.remove(host);
cosmosHost.add(0, host);
logger.debug("Placing the host in the first place of the list (host=" + host + ")");
}
break;
} // for
} else {
if (krb5) {
response = doPrivilegedHDFSRequest(method, url, headers, entity);
} else {
response = doHDFSRequest(method, url, headers, entity);
} // if else
} // if else
return response;
} // doHDFSRequest
private HttpResponse doHDFSRequest(String method, String url, ArrayList<Header> headers, StringEntity entity)
throws Exception {
HttpResponse response = null;
HttpRequestBase request = null;
if (method.equals("PUT")) {
HttpPut req = new HttpPut(url);
if (entity != null) {
req.setEntity(entity);
}
request = req;
} else if (method.equals("POST")) {
HttpPost req = new HttpPost(url);
if (entity != null) {
req.setEntity(entity);
}
request = req;
} else if (method.equals("GET")) {
request = new HttpGet(url);
} else {
throw new CygnusRuntimeError("HTTP method not supported: " + method);
} // if else
if (headers != null) {
for (Header header : headers) {
request.setHeader(header);
} // for
}
logger.debug("HDFS request: " + request.toString());
try {
response = httpClient.execute(request);
} catch (IOException e) {
throw new CygnusPersistenceError(e.getMessage());
} // try catch
request.releaseConnection();
logger.debug("HDFS response: " + response.getStatusLine().toString());
return response;
} // doHDFSRequest
// from here on, consider this link:
private HttpResponse doPrivilegedHDFSRequest(String method, String url, ArrayList<Header> headers,
StringEntity entity) throws Exception {
try {
LoginContext loginContext = new LoginContext("cygnus_krb5_login",
new KerberosCallBackHandler(krb5User, krb5Password));
loginContext.login();
PrivilegedHDFSRequest req = new PrivilegedHDFSRequest(method, url, headers, entity);
return (HttpResponse) Subject.doAs(loginContext.getSubject(), req);
} catch (LoginException e) {
logger.error(e.getMessage());
return null;
} // try catch
} // doPrivilegedHDFSRequest
/**
* PrivilegedHDFSRequest class.
*/
private class PrivilegedHDFSRequest implements PrivilegedAction {
private final Logger logger;
private final String method;
private final String url;
private final ArrayList<Header> headers;
private final StringEntity entity;
/**
* Constructor.
* @param mrthod
* @param url
* @param headers
* @param entity
*/
public PrivilegedHDFSRequest(String method, String url, ArrayList<Header> headers, StringEntity entity) {
this.logger = Logger.getLogger(PrivilegedHDFSRequest.class);
this.method = method;
this.url = url;
this.headers = headers;
this.entity = entity;
} // PrivilegedHDFSRequest
@Override
public Object run() {
try {
Subject current = Subject.getSubject(AccessController.getContext());
Set<Principal> principals = current.getPrincipals();
for (Principal next : principals) {
logger.info("DOAS Principal: " + next.getName());
} // for
return doHDFSRequest(method, url, headers, entity);
} catch (Exception e) {
logger.error(e.getMessage());
return null;
} // try catch
} // run
} // PrivilegedHDFSRequest
/**
* KerberosCallBackHandler class.
*/
private class KerberosCallBackHandler implements CallbackHandler {
private final String user;
private final String password;
public KerberosCallBackHandler(String user, String password) {
this.user = user;
this.password = password;
} // KerberosCallBackHandler
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
NameCallback nc = (NameCallback) callback;
nc.setName(user);
} else if (callback instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callback;
pc.setPassword(password.toCharArray());
} else {
throw new UnsupportedCallbackException(callback, "Unknown Callback");
} // if else if
} // for
} // handle
} // KerberosCallBackHandler
} // HDFSBackendImpl
|
package com.example.helloworld.db.jdbi;
import org.jdbi.v3.core.Jdbi;
import com.example.helloworld.db.WorldDAO;
import com.example.helloworld.db.model.World;
import com.example.helloworld.resources.Helper;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class WorldRepository implements WorldDAO {
private final Jdbi jdbi;
public WorldRepository(Jdbi jdbi) {
this.jdbi = jdbi;
}
@Override
public World findById(int id) {
return jdbi.withExtension(WorldJDBIImpl.class, dao -> dao.findById(id));
}
@Override
public World findAndModify(int id, int newRandomNumber) {
throw new RuntimeException("Don't call this");
}
@Override
public World[] updatesQueries(int totalQueries) {
return jdbi.withExtension(WorldJDBIImpl.class, dao -> {
final List<World> updates = new ArrayList<>(totalQueries);
for (int i = 0; i < totalQueries; i++) {
final World world = dao.findById(Helper.randomWorld());
world.setRandomNumber(Helper.randomWorld());
updates.add(i, world);
}
updates.sort(Comparator.comparingInt(World::getId));
final World[] updatesArray = updates.toArray(new World[totalQueries]);
dao.update(updatesArray);
return updatesArray;
});
}
}
|
package uk.ac.ebi.spot.goci;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import uk.ac.ebi.spot.goci.model.*;
import uk.ac.ebi.spot.goci.model.deposition.*;
import uk.ac.ebi.spot.goci.repository.*;
import uk.ac.ebi.spot.goci.service.DepositionPublicationService;
import uk.ac.ebi.spot.goci.service.DepositionSubmissionService;
import uk.ac.ebi.spot.goci.service.PublicationService;
import java.util.*;
@Service
@Transactional
public class DepositionSyncService {
private final CurationStatus curationComplete;
private final Curator levelOneCurator;
private final CurationStatus awaitingCuration;
private final CurationStatus awaitingLiterature;
private final DepositionSubmissionService submissionService;
private final BodyOfWorkRepository bodyOfWorkRepository;
private final UnpublishedStudyRepository unpublishedRepository;
private final UnpublishedAncestryRepository unpublishedAncestryRepo;
private PublicationService publicationService;
private DepositionPublicationService depositionPublicationService;
private CurationStatusRepository statusRepository;
private CuratorRepository curatorRepository;
public DepositionSyncService(@Autowired PublicationService publicationService,
@Autowired DepositionPublicationService depositionPublicationService,
@Autowired CurationStatusRepository statusRepository,
@Autowired CuratorRepository curatorRepository,
@Autowired DepositionSubmissionService submissionService,
@Autowired BodyOfWorkRepository bodyOfWorkRepository,
@Autowired UnpublishedStudyRepository unpublishedRepository,
@Autowired UnpublishedAncestryRepository unpublishedAncestryRepo) {
this.curatorRepository = curatorRepository;
this.statusRepository = statusRepository;
this.depositionPublicationService = depositionPublicationService;
this.publicationService = publicationService;
this.submissionService = submissionService;
this.bodyOfWorkRepository = bodyOfWorkRepository;
this.unpublishedRepository = unpublishedRepository;
this.unpublishedAncestryRepo = unpublishedAncestryRepo;
curationComplete = statusRepository.findByStatus("Publish study");
levelOneCurator = curatorRepository.findByLastName("Level 1 Curator");
awaitingCuration = statusRepository.findByStatus("Awaiting Curation");
awaitingLiterature = statusRepository.findByStatus("Awaiting literature");
}
private boolean isPublished(Publication publication) {
for (Study study : publication.getStudies()) {
boolean studyPublished = false;
Housekeeping housekeeping = study.getHousekeeping();
if (housekeeping.getIsPublished()) {
studyPublished = true;
}else if (!housekeeping.getIsPublished() || housekeeping.getCatalogUnpublishDate() != null) {
studyPublished = true;
}else if(housekeeping.getCurationStatus().getStatus().equals("Curation Abandoned")
|| housekeeping.getCurationStatus().getStatus().equals("Unpublished from catalog")){
studyPublished = true;
}
if(!studyPublished){
return false;
}
}
return true;
}
// private boolean isAvailable(Publication publication) {
// for (Study study : publication.getStudies()) {
// Housekeeping housekeeping = study.getHousekeeping();
// CurationStatus curationStatus = housekeeping.getCurationStatus();
// Curator curator = housekeeping.getCurator();
// if (curationStatus == null) {
// return false;
// } else if (!curationStatus.getId().equals(awaitingCuration.getId()) &&
// !curationStatus.getId().equals(curationComplete.getId()) &&
// !curationStatus.getId().equals(awaitingLiterature.getId())) {
// return false;
// } else if (!curator.getId().equals(levelOneCurator.getId())) {
// return false;
// return true;
// private boolean isWaiting(Publication publication) {
// for (Study study : publication.getStudies()) {
// Housekeeping housekeeping = study.getHousekeeping();
// CurationStatus curationStatus = housekeeping.getCurationStatus();
// Curator curator = housekeeping.getCurator();
// if (curationStatus == null) {
// return false;
// } else if (!curationStatus.getId().equals(awaitingLiterature.getId())) {
// return false;
// } else if (!curator.getId().equals(levelOneCurator.getId())) {
// return false;
// return true;
/**
* syncPublications intends to keep publications syned between GOCI and Deposition. It checks the GOCI catalog
* against Deposition. If a publication is in GOCI but not in Deposition, it checks the state of the studies in
* GOCI.
* If the study is awaiting curation (assigned to Level 1 Curator + Awating Curation status), the publication is
* sent
* to Deposition as AVAILABLE. If the study is published (Publish Study status) the publication is sent to
* Deposition
* as EXPORTED and a submission is created containing the study data from GOCI.
* This is the reverse of the Import endpoint, where a submission is received from Curation and added into GOCI.
*/
public void syncPublications(boolean initialSync) {
//read all publications from GOCI
List<String> newPubs = new ArrayList<>();
List<String> updatePubs = new ArrayList<>();
List<String> sumStatsPubs = new ArrayList<>();
List<Publication> gociPublications = publicationService.findAll();
//if publication not in Deposition, insert
Map<String, DepositionPublication> depositionPublications = depositionPublicationService.getAllPublications();
Map<String, BodyOfWorkDto> bomMap = depositionPublicationService.getAllBodyOfWork();
for (Publication p : gociPublications) {
String pubmedId = p.getPubmedId();
//System.out.println("checking pmid " + pubmedId);
boolean isPublished = isPublished(p);
// boolean isAvailable = isAvailable(p);
DepositionPublication newPublication = createPublication(p);
DepositionPublication depositionPublication = depositionPublications.get(pubmedId);
if(initialSync) { // add all publications to mongo
if (newPublication != null && depositionPublication == null) {
if(isPublished) {
System.out.println("adding published publication " + pubmedId + " to mongo");
if(addSummaryStatsData(newPublication, p)){
newPublication.setStatus("PUBLISHED_WITH_SS");
}
}else if(isUnpublished(p, bomMap.values())){//check if this pubmed id is associated with a
// prepublished submission
newPublication.setStatus("UNDER_SUBMISSION");
}else {
newPublication.setStatus("ELIGIBLE");
}
depositionPublicationService.addPublication(newPublication);
}
}else {
if(depositionPublication == null && newPublication != null) { // add new publication
if(isPublished) {
if(addSummaryStatsData(newPublication, p)) {
System.out.println("adding published publication w/ sumstats " + pubmedId);
newPublication.setStatus("PUBLISHED_WITH_SS");
newPublication.setFirstAuthor(p.getFirstAuthor().getFullnameStandard());
}else if(isUnpublished(p, bomMap.values())){//check if this pubmed id is associated with a
// prepublished submission
newPublication.setStatus("UNDER_SUBMISSION");
}else {
System.out.println("adding published publication " + pubmedId + " to mongo");
}
}else {
newPublication.setStatus("ELIGIBLE");
System.out.println("adding eligible publication " + pubmedId + " to mongo");
}
depositionPublicationService.addPublication(newPublication);
newPubs.add(newPublication.getPmid());
}else if(newPublication != null){//check publication status, update if needed
if (isPublished && (depositionPublication.getStatus().equals("ELIGIBLE") || depositionPublication.getStatus().equals("CURATION_STARTED"))) { //sync newly
// published publications
newPublication.setStatus("PUBLISHED");
addSummaryStatsData(newPublication, p);
System.out.println("setting publication status to " + newPublication.getStatus() + " for " +
" " + pubmedId);
newPublication.setFirstAuthor(p.getFirstAuthor().getFullnameStandard());
depositionPublicationService.updatePublication(newPublication);
updatePubs.add(newPublication.getPmid());
}else if (isPublished && depositionPublication.getStatus().equals("PUBLISHED")) { //sync newly
//published summary stats
if(addSummaryStatsData(newPublication, p)) {
System.out.println("setting publication status to PUBLISHED_WITH_SS for " + pubmedId);
newPublication.setStatus("PUBLISHED_WITH_SS");
newPublication.setFirstAuthor(p.getFirstAuthor().getFullnameStandard());
depositionPublicationService.updatePublication(newPublication);
sumStatsPubs.add(newPublication.getPmid());
}
}
}
}
}
System.out.println("created " + newPubs.size());
System.out.println(Arrays.toString(newPubs.toArray()));
System.out.println("published " + updatePubs.size());
System.out.println(Arrays.toString(updatePubs.toArray()));
System.out.println("added sum stats " + sumStatsPubs.size());
System.out.println(Arrays.toString(sumStatsPubs.toArray()));
}
/**
* method to import new studies from deposition that do not have a PubMed ID. We want to keep them separate from
* existing studies to indicate the different level of review. But we do want them stored in GOCI so they can be
* searched and displayed.
*/
public void syncUnpublishedStudies(){
List<String> newPubs = new ArrayList<>();
List<String> updatePubs = new ArrayList<>();
Map<String, DepositionSubmission> submissions = submissionService.getSubmissions();
//if unpublished_studies does not have accession, add
//check body of work, if not found, add
//else if accession exists, check publication for change, update
//curation import will need to prune unpublished_studies, ancestry and body_of_work
submissions.forEach((s, submission) -> {
if(submission.getStatus().equals("SUBMITTED") && submission.getPublication() == null){
BodyOfWorkDto bodyOfWorkDto = submission.getBodyOfWork();
if(isEligible(bodyOfWorkDto)) {
Set<UnpublishedStudy> studies = new HashSet<>();
submission.getStudies().forEach(studyDto -> {
String studyTag = studyDto.getStudyTag();
UnpublishedStudy unpublishedStudy = unpublishedRepository.findByAccession(studyDto.getAccession());
if (unpublishedStudy == null) {
unpublishedStudy =
unpublishedRepository.save(UnpublishedStudy.createFromStudy(studyDto, submission));
studies.add(unpublishedStudy);
//add ancestries
List<DepositionSampleDto> sampleDtoList = getSamples(submission, studyTag);
List<UnpublishedAncestry> ancestryList = new ArrayList<>();
for (DepositionSampleDto sampleDto : sampleDtoList) {
UnpublishedAncestry ancestry = UnpublishedAncestry.create(sampleDto, unpublishedStudy);
ancestryList.add(ancestry);
}
unpublishedAncestryRepo.save(ancestryList);
unpublishedStudy.setAncestries(ancestryList);
unpublishedRepository.save(unpublishedStudy);
}
});
BodyOfWork bom = bodyOfWorkRepository.findByPublicationId(bodyOfWorkDto.getBodyOfWorkId());
if(bom == null) {
//add bodies of work
BodyOfWork bodyOfWork = BodyOfWork.create(bodyOfWorkDto);
bodyOfWork.setStudies(studies);
bodyOfWorkRepository.save(bodyOfWork);
newPubs.add(bodyOfWorkDto.getBodyOfWorkId());
}
}
}
});
Map<String, BodyOfWorkDto> bomMap = depositionPublicationService.getAllBodyOfWork();
bomMap.entrySet().stream().forEach(e->{
String bomId = e.getKey();
BodyOfWorkDto dto = e.getValue();
BodyOfWork bom = bodyOfWorkRepository.findByPublicationId(bomId);
BodyOfWork newBom = BodyOfWork.create(dto);
if(bom != null && isEligible(dto) && !bom.equals(newBom)){
bom.update(newBom);
bodyOfWorkRepository.save(bom);
updatePubs.add(dto.getBodyOfWorkId());
}
});
System.out.println("created " + newPubs.size());
System.out.println(Arrays.toString(newPubs.toArray()));
System.out.println("updated " + updatePubs.size());
System.out.println(Arrays.toString(updatePubs.toArray()));
}
private List<DepositionSampleDto> getSamples(DepositionSubmission submission, String studyTag){
List<DepositionSampleDto> sampleDtoList = new ArrayList<>();
submission.getSamples().forEach(depositionSampleDto -> {
if(depositionSampleDto.getStudyTag().equals(studyTag)){
sampleDtoList.add(depositionSampleDto);
}
});
return sampleDtoList;
}
private boolean addSummaryStatsData(DepositionPublication depositionPublication, Publication publication){
return addSummaryStatsData(depositionPublication, publication, true);
}
private boolean addSummaryStatsData(DepositionPublication depositionPublication, Publication publication,
boolean setStatus){
boolean hasFiles = false;
List<DepositionSummaryStatsDto> summaryStatsDtoList = new ArrayList<>();
Collection<Study> studies = publication.getStudies();
for(Study study: studies){
if(study.getAccessionId() != null) {
DepositionSummaryStatsDto summaryStatsDto = new DepositionSummaryStatsDto();
summaryStatsDto.setStudyAccession(study.getAccessionId());
summaryStatsDto.setSampleDescription(study.getInitialSampleSize());
if (study.getDiseaseTrait() != null) {
summaryStatsDto.setTrait(study.getDiseaseTrait().getTrait());
}
summaryStatsDto.setStudyTag(study.getStudyTag());
if (study.getFullPvalueSet()) {
hasFiles = true;
}
summaryStatsDto.setHasSummaryStats(study.getFullPvalueSet());
summaryStatsDtoList.add(summaryStatsDto);
}
}
if(summaryStatsDtoList.size() != 0) {
depositionPublication.setSummaryStatsDtoList(summaryStatsDtoList);
}
if(hasFiles && setStatus){
depositionPublication.setStatus("PUBLISHED_WITH_SS");
}
return hasFiles;
}
/**
* fix publications is intended as a one-off execution to correct errors with loaded data, not as part of the
* daily sync
*/
public void fixPublications() {
List<String> fixedPubs = new ArrayList<>();
//read all publications from GOCI
List<Publication> gociPublications = publicationService.findAll();
//check status, set to PUBLISHED_SS if hasSummaryStats
Map<String, DepositionSubmission> submissions = submissionService.getSubmissions();
Map<String, DepositionPublication> publicationMap = buildPublicationMap(submissions);
Map<String, List<String>> sumStatsMap = buildSumStatsMap(submissions);
System.out.println("pmid\tis published\tdepo sum stats size\tgoci sum stats size");
for (Publication p : gociPublications) {
String pubmedId = p.getPubmedId();
List<String> accessionList = sumStatsMap.get(pubmedId);
DepositionPublication depositionPublication = publicationMap.get(pubmedId);
boolean isPublished = isPublished(p);
if(depositionPublication != null) {
addSummaryStatsData(depositionPublication, p, false);
int newSumStatsSize = depositionPublication.getSummaryStatsDtoList() != null ?
depositionPublication.getSummaryStatsDtoList().size() : 0;
System.out.println(pubmedId + "\t" + isPublished + "\t" + accessionList.size() + "\t" + newSumStatsSize);
if (accessionList.size() != newSumStatsSize) {
System.out.println("adding summary stats to " + depositionPublication.getPmid());
depositionPublicationService.updatePublication(depositionPublication);
fixedPubs.add(pubmedId);
}
}
}
System.out.println("fixed " + fixedPubs.size());
System.out.println(Arrays.toString(fixedPubs.toArray()));
}
private Map<String, DepositionPublication> buildPublicationMap(Map<String, DepositionSubmission> submissions) {
Map<String, DepositionPublication> publicationMap = new HashMap<>();
submissions.forEach((s, submission) ->{
if(submission.getPublication() != null){
publicationMap.put(submission.getPublication().getPmid(),
submission.getPublication());
}
});
return publicationMap;
}
private Map<String, List<String>> buildSumStatsMap(Map<String, DepositionSubmission> submissions) {
Map<String, List<String>> sumStatsMap = new HashMap<>();
submissions.forEach((s, submission) ->{
if(submission.getPublication() != null){
List<String> sumStatsList = new ArrayList<>();
submission.getStudies().forEach(studyDto->{
if(studyDto.getAccession() != null) {
sumStatsList.add(studyDto.getAccession());
}
});
sumStatsMap.put(submission.getPublication().getPmid(), sumStatsList);
}
});
return sumStatsMap;
}
private DepositionPublication createPublication(Publication p) {
Author author = p.getFirstAuthor();
DepositionPublication newPublication = null;
if (author != null) { //error check for invalid publications
newPublication = new DepositionPublication();
newPublication.setPmid(p.getPubmedId());
String authorName = null;
Author firstAuthor = p.getFirstAuthor();
if(firstAuthor.getLastName() == null || firstAuthor.getInitials() == null){
authorName = firstAuthor.getFullname();
}else {
authorName = firstAuthor.getLastName() + " " + firstAuthor.getInitials();
}
newPublication.setFirstAuthor(authorName);
newPublication.setPublicationDate(new LocalDate(p.getPublicationDate()));
newPublication.setPublicationId(p.getId().toString());
newPublication.setTitle(p.getTitle());
newPublication.setJournal(p.getPublication());
newPublication.setStatus("PUBLISHED");
} else {
System.out.println("error: publication " + p.getPubmedId() + " has no authors");
}
return newPublication;
}
private boolean isEligible(BodyOfWorkDto bodyOfWorkDto) {
if(!bodyOfWorkDto.getStatus().equals("UNDER_SUBMISSION")){
return false;
}if (bodyOfWorkDto.getEmbargoUntilPublished() != null && bodyOfWorkDto.getEmbargoUntilPublished() == true && bodyOfWorkDto.getPmids() == null){
return false;
}if(bodyOfWorkDto.getEmbargoDate() != null && new LocalDate().isBefore(bodyOfWorkDto.getEmbargoDate())) {
return false;
} else {
return true;
}
}
private boolean isUnpublished(Publication publication, Collection<BodyOfWorkDto> bomList){
if(bodyOfWorkRepository.findByPubMedId(publication.getPubmedId()) != null){
return true;
}else{
List<BodyOfWork> bodiesOfWork = bodyOfWorkRepository.findAll();
for (BodyOfWork bom : bodiesOfWork) {
if (publication.getPubmedId().equals(bom.getPubMedId())) {
return true;
}else if(bom.getPubMedId() != null && bom.getPubMedId().contains(publication.getPubmedId())){
return true;
}
}
for(BodyOfWorkDto bom: bomList){
String bomId = String.join(",", bom.getPmids());
if (bomId.contains(publication.getPubmedId())){
return true;
}
}
}
return false;
}
}
|
package com.tinkerpop.gremlin.process.graph.step.util;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.process.graph.marker.PathConsumer;
import com.tinkerpop.gremlin.process.graph.step.sideEffect.SideEffectStep;
public class AsIdentityStep<S> extends SideEffectStep<S> {
public AsIdentityStep(final Traversal traversal) {
super(traversal);
}
}
|
package com.tinkerpop.gremlin.process.graph.strategy;
import com.tinkerpop.gremlin.process.Step;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.process.TraversalEngine;
import com.tinkerpop.gremlin.process.TraversalStrategy;
import com.tinkerpop.gremlin.process.graph.step.sideEffect.ProfileStep;
import com.tinkerpop.gremlin.process.util.TraversalHelper;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ProfileStrategy extends AbstractTraversalStrategy {
private static final ProfileStrategy INSTANCE = new ProfileStrategy();
private static final Set<Class<? extends TraversalStrategy>> PRIORS = new HashSet<>();
static {
// Ensure that this strategy is applied last.
PRIORS.add(TraverserSourceStrategy.class);
}
private ProfileStrategy() {
}
@Override
public void apply(final Traversal<?, ?> traversal, final TraversalEngine engine) {
if (!TraversalHelper.hasStepOfClass(ProfileStep.class, traversal))
return;
// Remove user-specified .profile() steps
List<ProfileStep> profileSteps = TraversalHelper.getStepsOfClass(ProfileStep.class, traversal);
for (ProfileStep step : profileSteps) {
TraversalHelper.removeStep(step, traversal);
}
// Add .profile() step after every pre-existing step.
final List<Step> steps = traversal.asAdmin().getSteps();
for (int ii = 0; ii < steps.size(); ii++) {
TraversalHelper.insertStep(new ProfileStep(traversal, steps.get(ii)), ii + 1, traversal);
ii++;
}
}
@Override
public Set<Class<? extends TraversalStrategy>> applyPrior() {
return PRIORS;
}
public static ProfileStrategy instance() {
return INSTANCE;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.