answer
stringlengths 17
10.2M
|
|---|
package blog.common.numerical;
/**
* Creates MatrixLib objects.
*
* All code should use this class to create new MatrixLib objects, instead
* of importing JamaMatrixLib directly. This allows us to easily change the
* underlying implementation in the future.
*/
public class MatrixFactory {
static public MatrixLib fromArray(double[][] array) {
return new JamaMatrixLib(array);
}
static public MatrixLib createRowVector(double... args) {
double[][] ary = new double[1][args.length];
for (int i = 0; i < args.length; i++) {
ary[0][i] = args[i];
}
return MatrixFactory.fromArray(ary);
}
static public MatrixLib eye(int size) {
double[][] result = new double[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == j) {
result[i][j] = 1;
} else {
result[i][j] = 0;
}
}
}
return fromArray(result);
}
static public MatrixLib zeros(int rows, int cols) {
double[][] result = new double[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = 0;
}
}
return fromArray(result);
}
static public MatrixLib ones(int rows, int cols) {
double[][] result = new double[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = 1;
}
}
return fromArray(result);
}
static public MatrixLib vstack(MatrixLib a, MatrixLib b) {
if (a.numCols() != b.numCols()) {
throw new RuntimeException("matrices should have equal number of columns");
}
double[][] result = new double[a.numRows() + b.numRows()][a.numCols()];
for (int i = 0; i < a.numRows(); i++) {
for (int j = 0; j < a.numCols(); j++) {
result[i][j] = a.elementAt(i, j);
}
}
for (int i = 0; i < b.numRows(); i++) {
for (int j = 0; j < b.numCols(); j++) {
result[a.numRows() + i][j] = b.elementAt(i, j);
}
}
return fromArray(result);
}
static public MatrixLib hstack(MatrixLib a, MatrixLib b) {
if (a.numRows() != b.numRows()) {
throw new RuntimeException("matrices should have equal number of rows");
}
double[][] result = new double[a.numRows()][a.numCols() + b.numCols()];
for (int i = 0; i < a.numRows(); i++) {
for (int j = 0; j < a.numCols(); j++) {
result[i][j] = a.elementAt(i, j);
}
}
for (int i = 0; i < b.numRows(); i++) {
for (int j = 0; j < b.numCols(); j++) {
result[i][a.numCols() + j] = b.elementAt(i, j);
}
}
return fromArray(result);
}
}
|
// Unless required by applicable law or agreed to in writing, software /
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
package br.shura.venus.compiler;
import br.shura.venus.component.AsyncContainer;
import br.shura.venus.component.Component;
import br.shura.venus.component.Container;
import br.shura.venus.component.Script;
import br.shura.venus.component.SimpleComponent;
import br.shura.venus.component.SimpleContainer;
import br.shura.venus.component.branch.Break;
import br.shura.venus.component.branch.Breakable;
import br.shura.venus.component.branch.Continue;
import br.shura.venus.component.branch.DoWhileContainer;
import br.shura.venus.component.branch.ElseContainer;
import br.shura.venus.component.branch.ElseIfContainer;
import br.shura.venus.component.branch.ForEachContainer;
import br.shura.venus.component.branch.ForRangeContainer;
import br.shura.venus.component.branch.IfContainer;
import br.shura.venus.component.branch.Return;
import br.shura.venus.component.branch.WhileContainer;
import br.shura.venus.component.object.Attribute;
import br.shura.venus.component.object.ObjectDefinition;
import br.shura.venus.exception.compile.ScriptCompileException;
import br.shura.venus.exception.compile.UnexpectedTokenException;
import br.shura.venus.expression.ArrayAccess;
import br.shura.venus.expression.ArrayAttribution;
import br.shura.venus.expression.ArrayDefine;
import br.shura.venus.expression.Attribution;
import br.shura.venus.expression.BinaryOperation;
import br.shura.venus.expression.Constant;
import br.shura.venus.expression.Expression;
import br.shura.venus.expression.FunctionCall;
import br.shura.venus.expression.NewObject;
import br.shura.venus.expression.Variable;
import br.shura.venus.function.Argument;
import br.shura.venus.function.Definition;
import br.shura.venus.library.VenusLibrary;
import br.shura.venus.operator.BinaryOperator;
import br.shura.venus.operator.Operator;
import br.shura.venus.operator.OperatorList;
import br.shura.venus.type.PrimitiveType;
import br.shura.venus.type.Type;
import br.shura.venus.value.BoolValue;
import br.shura.venus.value.DecimalValue;
import br.shura.venus.value.FunctionRefValue;
import br.shura.venus.value.IntegerValue;
import br.shura.venus.value.StringValue;
import br.shura.venus.value.TypeValue;
import br.shura.venus.value.Value;
import br.shura.venus.value.VariableRefValue;
import br.shura.x.charset.build.TextBuilder;
import br.shura.x.collection.list.List;
import br.shura.x.collection.list.impl.ArrayList;
import br.shura.x.collection.map.Map;
import br.shura.x.collection.map.impl.LinkedMap;
import br.shura.x.math.number.BaseConverter;
import br.shura.x.util.Pool;
import br.shura.x.worker.ParseWorker;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class VenusParser {
private Container container;
private VenusLexer lexer;
private boolean nextAsyncable;
private boolean nextDaemon;
private final Script script;
public VenusParser(Script script) {
this.script = script;
}
public synchronized void parse(VenusLexer lexer, Container target) throws ScriptCompileException {
this.container = target;
this.lexer = lexer;
Token token;
boolean justExitedIfContainer = false;
while ((token = lexer.nextToken()) != null) {
if (container instanceof ObjectDefinition) {
if (token.getType() == Token.Type.NAME_DEFINITION) {
if (token.getValue().equals(KeywordDefinitions.DEFINE)) {
parseDefinition(false);
}
continue;
}
else if (token.getType() != Token.Type.CLOSE_BRACE && token.getType() != Token.Type.NEW_LINE) {
bye(token, "expected a definition");
}
}
if (token.getType() == Token.Type.GLOBAL_ACCESS) {
lexer.reRead(token);
addComponent(readExpression(Token.Type.NEW_LINE), true);
}
else if (token.getType() == Token.Type.NAME_DEFINITION) {
if (token.getValue().equals(KeywordDefinitions.ASYNC)) {
if (nextAsyncable) {
bye(token, "duplicated 'async' keyword");
}
this.nextAsyncable = true;
}
else if (token.getValue().equals(KeywordDefinitions.BREAK) || token.getValue().equals(KeywordDefinitions.CONTINUE)) {
requireToken(Token.Type.NEW_LINE, "expected a new line");
Container lookup = container;
boolean foundContinuable = false;
while (lookup != null) {
if (lookup instanceof Breakable) {
foundContinuable = true;
break;
}
// If there is a definition, at run-time it will be in a single context,
// so do not let lookuping a definition's parents
if (lookup instanceof Definition) {
break;
}
lookup = lookup.getParent();
}
if (foundContinuable) {
addComponent(token.getValue().equals(KeywordDefinitions.BREAK) ? new Break() : new Continue(), false);
}
else {
bye(token, "there is no parent container available");
}
}
else if (token.getValue().equals(KeywordDefinitions.DAEMON)) {
if (nextAsyncable) {
if (nextDaemon) {
bye(token, "duplicated 'daemon' keyword");
}
this.nextDaemon = true;
}
else {
bye(token, "'daemon' keyword must come after an 'async' keyword");
}
}
else if (token.getValue().equals(KeywordDefinitions.DEFINE)) {
parseDefinition(true);
}
else if (token.getValue().equals(KeywordDefinitions.DO)) {
requireToken(Token.Type.OPEN_BRACE, "expected an open brace");
addContainer(new DoWhileContainer(null), true);
}
else if (token.getValue().equals(KeywordDefinitions.ELSE)) {
if (justExitedIfContainer) {
parseElse();
}
else {
bye(token, "no previous 'if' container");
}
}
else if (token.getValue().equals(KeywordDefinitions.EXPORT)) {
if (container == script) {
parseExport();
}
else {
bye(token, "cannot use 'export' keyword inside container");
}
}
else if (token.getValue().equals(KeywordDefinitions.FOR)) {
parseFor();
}
else if (token.getValue().equals(KeywordDefinitions.IF)) {
parseIf(false);
}
else if (token.getValue().equals(KeywordDefinitions.INCLUDE)) {
if (container == script) {
parseInclude();
}
else {
bye(token, "cannot use 'import' keyword inside container");
}
}
else if (token.getValue().equals(KeywordDefinitions.OBJECT)) {
parseObject();
}
else if (token.getValue().equals(KeywordDefinitions.RETURN)) {
parseReturn();
}
else if (token.getValue().equals(KeywordDefinitions.USING)) {
if (container == script) {
parseUsing();
}
else {
bye(token, "cannot use 'using' keyword inside container");
}
}
else if (token.getValue().equals(KeywordDefinitions.WHILE)) {
parseWhile();
}
else {
lexer.reRead(token);
addComponent(readExpression(Token.Type.NEW_LINE), true);
}
justExitedIfContainer = false;
}
else if (token.getType() == Token.Type.OPEN_BRACE) {
addContainer(new SimpleContainer(), true);
}
else if (token.getType() == Token.Type.CLOSE_BRACE) {
if (container != script) {
if (container instanceof IfContainer) {
justExitedIfContainer = true;
}
if (container instanceof DoWhileContainer) {
DoWhileContainer doWhileContainer = (DoWhileContainer) container;
Token test = lexer.nextToken();
if (test.getType() == Token.Type.NEW_LINE) {
test = lexer.nextToken();
}
if (test.getType() == Token.Type.NAME_DEFINITION && test.getValue().equals(KeywordDefinitions.WHILE)) {
Expression expression = readExpression(Token.Type.NEW_LINE);
doWhileContainer.setCondition(expression);
}
else {
lexer.reRead(test);
}
}
do {
this.container = container.getParent();
}
while (container instanceof AsyncContainer);
}
else {
bye(token, "no container to close");
}
}
else if (token.getType() != Token.Type.NEW_LINE) {
lexer.reRead(token);
addComponent(readExpression(Token.Type.NEW_LINE), true);
}
}
}
protected void addComponent(Component component, boolean asyncable) throws UnexpectedTokenException {
if (nextAsyncable && !asyncable) {
this.nextAsyncable = false;
bye("Cannot apply 'async' keyword to component " + component);
}
if (asyncable && nextAsyncable) {
AsyncContainer asyncContainer = new AsyncContainer(nextDaemon);
asyncContainer.setSourceLine(lexer.currentLine());
container.getChildren().add(asyncContainer);
asyncContainer.getChildren().add(component);
this.nextAsyncable = false;
this.nextDaemon = false;
}
else {
component.setSourceLine(lexer.currentLine());
container.getChildren().add(component);
}
}
protected void addComponent(Expression expression, boolean asyncable) throws UnexpectedTokenException {
addComponent(new SimpleComponent(expression), asyncable);
}
protected void addContainer(Container container, boolean asyncable) throws UnexpectedTokenException {
addComponent(container, asyncable);
this.container = container;
}
protected void bye(String message) throws UnexpectedTokenException {
throw new UnexpectedTokenException(script.getDisplayName(), lexer.currentLine(), message);
}
// Do not call other bye() method, for better stacktrace
protected void bye(Token token, String message) throws UnexpectedTokenException {
throw new UnexpectedTokenException(script.getDisplayName(), lexer.currentLine(), "Invalid token \"" + token + "\"; " + message);
}
protected Value getValueOf(Token token) throws ScriptCompileException {
String value = token.getValue();
if (token.getType() == Token.Type.FUNC_REF) {
Token next = requireToken();
if (next.getType() == Token.Type.NAME_DEFINITION) {
return new FunctionRefValue(next.getValue());
}
lexer.reRead(next);
}
if (token.getType() == Token.Type.BINARY_LITERAL) {
try {
return new IntegerValue(BaseConverter.encodeToLong(value, BaseConverter.BINARY));
}
catch (NumberFormatException exception) {
bye(token, "illegal binary value \"" + value + "\"");
}
}
if (token.getType() == Token.Type.COLON) {
Token next = requireToken();
if (next.getType() == Token.Type.GLOBAL_ACCESS) {
Token next2 = requireToken();
if (next2.getType() == Token.Type.NAME_DEFINITION) {
return new VariableRefValue(next.getValue() + next2.getValue());
}
lexer.reRead(next2);
}
else if (next.getType() == Token.Type.NAME_DEFINITION) {
return new VariableRefValue(next.getValue());
}
lexer.reRead(next);
}
if (token.getType() == Token.Type.CHAR_LITERAL || token.getType() == Token.Type.STRING_LITERAL) {
return new StringValue(value);
}
if (token.getType() == Token.Type.DECIMAL_LITERAL) {
if (ParseWorker.isLong(value)) {
return new IntegerValue(ParseWorker.toLong(value));
}
if (ParseWorker.isDouble(value)) {
return new DecimalValue(ParseWorker.toDouble(value));
}
bye(token, "illegal decimal value \"" + value + "\"");
}
if (token.getType() == Token.Type.HEXADECIMAL_LITERAL) {
try {
return new IntegerValue(BaseConverter.encodeToLong(value, BaseConverter.HEXADECIMAL));
}
catch (NumberFormatException exception) {
bye(token, "illegal hexadecimal value \"" + value + "\"");
}
}
if (token.getType() == Token.Type.NAME_DEFINITION) {
if (value.equals(KeywordDefinitions.TRUE)) {
return new BoolValue(true);
}
if (value.equals(KeywordDefinitions.FALSE)) {
return new BoolValue(false);
}
}
if (token.getType() == Token.Type.OPERATOR && token.getValue().equals("*")) {
Token next = requireToken();
if (next.getType() == Token.Type.NAME_DEFINITION) {
String keyword = next.getValue();
Type type = PrimitiveType.forIdentifier(keyword);
if (type != null) {
return new TypeValue(type);
}
}
lexer.reRead(next);
}
return null;
}
protected Object parseArrayElementOperation(String currentNameDef, Expression index, String operatorStr, Token errorToken, boolean mustBeUnary) throws ScriptCompileException {
if (operatorStr.equals("=")) {
Expression expression = readExpression(token -> token.getType() != Token.Type.NEW_LINE && token.getType() != Token.Type.CLOSE_PARENTHESE,
token -> true);
return new ArrayAttribution(currentNameDef, index, expression);
}
Operator opr = OperatorList.forIdentifier(operatorStr, mustBeUnary);
if (opr != null) {
return opr;
}
// Is attribution
if (operatorStr.endsWith("=")) {
String operatorIdentifier = operatorStr.substring(0, operatorStr.length() - 1);
Operator operator = OperatorList.forIdentifier(operatorIdentifier, false); // false for bye(excepted bin opr)
if (operator != null) {
if (operator instanceof BinaryOperator) {
Expression expression = readExpression(token -> token.getType() != Token.Type.NEW_LINE && token.getType() != Token.Type.CLOSE_PARENTHESE,
token -> true);
BinaryOperation operation = new BinaryOperation((BinaryOperator) operator,
new ArrayAccess(currentNameDef, index), expression);
return new ArrayAttribution(currentNameDef, index, operation);
}
bye(errorToken, "expected an attribution with binary operator (+=, -=, ...)");
}
else {
bye(errorToken, "expected a valid attribution operator (=, +=, -=, ...)");
}
}
bye(errorToken, "expected a valid " + (mustBeUnary ? "unary operator" : "operator") + " (+, -, *, /, %, ...)");
return null; // Will not happen
}
protected void parseDefinition(boolean isGlobal) throws ScriptCompileException {
Token typeToken = requireToken(Token.Type.NAME_DEFINITION, "expected a return type");
String definitionName = typeToken.getValue();
List<Argument> arguments = new ArrayList<>();
requireToken(Token.Type.OPEN_PARENTHESE, "expected an open parenthese");
Token reading;
while ((reading = requireToken()).getType() != Token.Type.CLOSE_PARENTHESE) { // Reads definition arguments
if (reading.getType() == Token.Type.NAME_DEFINITION) {
Type argumentType = PrimitiveType.forIdentifier(reading.getValue());
if (argumentType != null) {
Token argumentToken = requireToken(Token.Type.NAME_DEFINITION, "expected an argument name");
String argumentName = argumentToken.getValue();
if (!KeywordDefinitions.isKeyword(argumentName)) {
arguments.add(new Argument(argumentName, argumentType));
Token commaOrClose = requireToken();
if (commaOrClose.getType() == Token.Type.CLOSE_PARENTHESE) {
break;
}
if (commaOrClose.getType() != Token.Type.COMMA) {
bye(commaOrClose, "expected an argument separator (comma) or close parenthese");
}
}
else {
bye(reading, "argument name cannot be a keyword");
}
}
else {
bye(reading, "expected an argument value type (" + PrimitiveType.valuesView().toString(", ") + ") or object type");
}
}
else {
bye(reading, "expected an argument name");
}
}
requireToken(Token.Type.OPEN_BRACE, "expected an open brace");
addContainer(new Definition(definitionName, arguments, isGlobal), false);
}
protected void parseElse() throws ScriptCompileException {
Token next = requireToken();
if (next.getType() == Token.Type.NAME_DEFINITION && next.getValue().equals(KeywordDefinitions.IF)) {
parseIf(true);
}
else {
lexer.reRead(next);
requireToken(Token.Type.OPEN_BRACE, "expected an open brace");
addContainer(new ElseContainer(), false);
}
}
protected void parseExport() throws ScriptCompileException {
Token nameToken = requireToken(Token.Type.NAME_DEFINITION, "expected a variable name");
String variableName = nameToken.getValue();
if (!KeywordDefinitions.isKeyword(variableName)) {
Token attributionToken = requireToken();
if (attributionToken.getType() == Token.Type.OPERATOR && attributionToken.getValue().equals("=")) {
Value value = readValue();
script.getApplicationContext().setVar(variableName, value);
requireNewLine();
}
else {
bye(attributionToken, "expected an attribution character '='");
}
}
else {
bye(nameToken, "variable name cannot be a keyword");
}
}
protected void parseFor() throws ScriptCompileException {
Token varNameToken = requireToken(Token.Type.NAME_DEFINITION, "expected a variable name");
requireToken(Token.Type.NAME_DEFINITION, "expected 'in' token");
Token next = requireToken();
if (next.getType() == Token.Type.OPEN_PARENTHESE) {
Expression[] arguments = readFunctionArguments();
requireToken(Token.Type.OPEN_BRACE, "expected an open brace");
if (arguments.length == 2 || arguments.length == 3) {
String varName = varNameToken.getValue();
ForRangeContainer forContainer = new ForRangeContainer(varName, arguments[0], arguments[1],
arguments.length == 3 ? arguments[2] : new BinaryOperation(OperatorList.PLUS, new Variable(varName),
new Constant(new IntegerValue(1))));
addContainer(forContainer, true);
}
else {
bye("Expected 2 arguments to for definition; received " + arguments.length);
}
}
else {
lexer.reRead(next);
Expression iterable = readExpression(Token.Type.OPEN_BRACE);
String varName = varNameToken.getValue();
ForEachContainer forContainer = new ForEachContainer(varName, iterable);
addContainer(forContainer, true);
}
}
protected void parseIf(boolean isElseIf) throws ScriptCompileException {
Expression expression = readExpression(Token.Type.OPEN_BRACE);
IfContainer ifContainer = isElseIf ? new ElseIfContainer(expression) : new IfContainer(expression);
addContainer(ifContainer, false);
}
protected void parseInclude() throws ScriptCompileException {
Token next = requireToken(Token.Type.STRING_LITERAL, "expected a string literal as including script");
String includeName = next.getValue();
boolean maybe = false;
Token maybeOrNewLine = requireToken();
if (maybeOrNewLine.getType() == Token.Type.NAME_DEFINITION) {
if (maybeOrNewLine.getValue().equals("maybe")) {
maybe = true;
requireToken(Token.Type.NEW_LINE, "expected new line");
}
else {
bye(maybeOrNewLine, "expected 'maybe' or new line");
}
}
else if (maybeOrNewLine.getType() != Token.Type.NEW_LINE) {
bye(maybeOrNewLine, "expected 'maybe' or new line");
}
try {
script.include(includeName, maybe);
}
catch (ScriptCompileException exception) {
bye('"' + exception.getMessage() + '"');
}
}
protected void parseObject() throws ScriptCompileException {
Token nameToken = requireToken(Token.Type.NAME_DEFINITION, "expected an object name");
requireToken(Token.Type.OPEN_PARENTHESE, "expected an open parenthese");
ObjectDefinition definition = new ObjectDefinition(nameToken.getValue());
Token next;
while ((next = requireToken()).getType() != Token.Type.CLOSE_PARENTHESE) {
if (next.getType() == Token.Type.NAME_DEFINITION) {
Token test = requireToken();
Expression defaultExpression = null;
if (test.getType() == Token.Type.COLON) {
defaultExpression = readExpression(token -> token.getType() != Token.Type.COMMA &&
token.getType() != Token.Type.CLOSE_PARENTHESE, token -> token.getType() == Token.Type.CLOSE_PARENTHESE);
}
else {
lexer.reRead(test);
}
definition.getAttributes().add(new Attribute(next.getValue(), defaultExpression));
}
else if (next.getType() != Token.Type.COMMA) {
bye(next, "expected an attribute name or close parenthese");
}
}
next = lexer.nextToken();
if (next != null) {
if (next.getType() == Token.Type.OPEN_BRACE) {
addContainer(definition, false);
return;
}
lexer.reRead(next);
}
addContainer(definition, false);
do {
this.container = container.getParent();
}
while (container instanceof AsyncContainer);
}
protected Object parseOperation(String currentNameDef, String operatorStr, Token errorToken, boolean mustBeUnary) throws ScriptCompileException {
if (operatorStr.equals("=")) {
Expression expression = readExpression(token -> token.getType() != Token.Type.NEW_LINE && token.getType() != Token.Type.CLOSE_PARENTHESE,
token -> true);
return new Attribution(currentNameDef, expression);
}
Operator opr = OperatorList.forIdentifier(operatorStr, mustBeUnary);
if (opr != null) {
return opr;
}
// Is attribution
if (operatorStr.endsWith("=")) {
String operatorIdentifier = operatorStr.substring(0, operatorStr.length() - 1);
Operator operator = OperatorList.forIdentifier(operatorIdentifier, false); // false for bye(excepted bin opr)
if (operator != null) {
if (operator instanceof BinaryOperator) {
Expression expression = readExpression(token -> token.getType() != Token.Type.NEW_LINE && token.getType() != Token.Type.CLOSE_PARENTHESE,
token -> true);
BinaryOperation operation = new BinaryOperation((BinaryOperator) operator, new Variable(currentNameDef), expression);
return new Attribution(currentNameDef, operation);
}
bye(errorToken, "expected an attribution with binary operator (+=, -=, ...)");
}
else {
bye(errorToken, "expected a valid attribution operator (=, +=, -=, ...)");
}
}
bye(errorToken, "expected a valid " + (mustBeUnary ? "unary operator" : "operator") + " (+, -, *, /, %, ...)");
return null; // Will not happen
}
protected void parseReturn() throws ScriptCompileException {
Token test = lexer.nextToken();
if (test == null || test.getType() == Token.Type.NEW_LINE) {
addComponent(new Return(null), false);
}
else {
lexer.reRead(test);
addComponent(new Return(readExpression(Token.Type.NEW_LINE)), false);
}
}
protected void parseUsing() throws ScriptCompileException {
Token nameToken = requireToken(Token.Type.NAME_DEFINITION, "expected a library name (without quotes)");
requireNewLine();
String libraryName = nameToken.getValue();
Supplier<VenusLibrary> supplier = script.getApplicationContext().getLibrarySuppliers().get(libraryName);
VenusLibrary library;
if (supplier != null && (library = supplier.get()) != null) {
script.getLibraryList().add(library);
}
else {
bye(nameToken, "could not find a library named \"" + libraryName + "\"");
}
}
protected void parseWhile() throws ScriptCompileException {
Expression expression = readExpression(Token.Type.OPEN_BRACE);
WhileContainer whileContainer = new WhileContainer(expression);
addContainer(whileContainer, true);
}
protected Expression readExpression(Predicate<Token> process) throws ScriptCompileException {
return readExpression(process, token -> false);
}
protected Expression readExpression(Predicate<Token> process, Predicate<Token> reReadLast) throws ScriptCompileException {
BuildingExpression expression = new BuildingExpression();
String nameDef = null;
Expression arrayIndex = null;
Token nameDefToken = null;
Token token;
while (process.test(token = requireToken())) {
if (nameDef == null) {
Value value;
try {
value = getValueOf(token);
if (value != null) {
expression.addExpression(this, token, new Constant(value));
continue;
}
}
catch (UnexpectedTokenException exception) {
}
}
if (token.getType() == Token.Type.OBJECT_ACCESS) {
if (nameDef != null) {
expression.addInContext(this, nameDefToken, nameDef);
arrayIndex = null;
nameDef = null;
}
else {
bye(token, "expected a name definition before object access");
}
}
else if (token.getType() == Token.Type.GLOBAL_ACCESS) {
if (nameDef != null) {
bye(token, "expected open parenthese (function) or operator after a name definition");
}
Token next = requireToken(Token.Type.NAME_DEFINITION, "expected a variable name");
nameDef = token.getValue() + next.getValue();
nameDefToken = next;
}
else if (token.getType() == Token.Type.OPERATOR) {
String operator = readOperator(token.getValue());
if (nameDef != null) {
Object r;
if (arrayIndex != null) {
r = parseArrayElementOperation(nameDef, arrayIndex, operator, token, false);
}
else {
r = parseOperation(nameDef, operator, token, false);
}
if (r instanceof Expression) {
expression.addExpression(this, token, (Expression) r);
}
else if (r instanceof Operator) {
expression.addExpression(this, nameDefToken, arrayIndex != null ? new ArrayAccess(nameDef, arrayIndex) : new Variable(nameDef));
expression.addOperator(this, token, (Operator) r);
}
else {
bye(token, "unknown type " + r.getClass().getName());
}
arrayIndex = null;
nameDef = null;
}
else {
Object r = parseOperation(null, operator, token, !expression.hasResultor() || expression.hasOperator());
if (r instanceof Operator) {
expression.addOperator(this, token, (Operator) r);
}
else {
bye(token, "unknown type " + r.getClass().getName());
}
}
}
else if (token.getType() == Token.Type.OPEN_BRACKET) {
if (nameDef != null) {
if (arrayIndex == null) {
arrayIndex = readExpression(Token.Type.CLOSE_BRACKET);
}
else {
bye(token, "already has index expression");
}
}
else {
Expression[] expressions = readResultors(Token.Type.COMMA, Token.Type.CLOSE_BRACKET);
expression.addExpression(this, token, new ArrayDefine(expressions));
}
}
else if (token.getType() == Token.Type.OPEN_PARENTHESE) {
if (nameDef != null) {
Expression[] arguments = readFunctionArguments();
expression.addExpression(this, nameDefToken, new FunctionCall(nameDef, arguments));
nameDef = null;
}
else {
expression.addExpression(this, token, readExpression(Token.Type.CLOSE_PARENTHESE));
}
}
else if (nameDef != null) {
bye(token, "expected open parenthese (function) or operator after a name definition");
}
else if (token.getType() == Token.Type.NAME_DEFINITION) {
if (token.getValue().equals(KeywordDefinitions.NEW)) {
Token objectTypeToken = requireToken(Token.Type.NAME_DEFINITION, "expected an object name");
requireToken(Token.Type.OPEN_PARENTHESE, "expected an open parenthese");
Map<String, Expression> attributes = new LinkedMap<>();
while (true) {
Token t = requireToken();
if (t.getType() == Token.Type.CLOSE_PARENTHESE) {
break;
}
if (t.getType() == Token.Type.NAME_DEFINITION) {
requireToken(Token.Type.COLON, "expected an attribute separator (colon)");
Expression attribExpression = readExpression(o -> o.getType() != Token.Type.COMMA && o.getType() != Token.Type.CLOSE_PARENTHESE,
o -> o.getType() == Token.Type.CLOSE_PARENTHESE);
attributes.add(t.getValue(), attribExpression);
}
else {
bye(t, "expected an attribute name");
}
}
expression.addExpression(this, token, new NewObject(objectTypeToken.getValue(), attributes));
}
else {
nameDef = token.getValue();
nameDefToken = token;
}
}
else if (token.getType() != Token.Type.NEW_LINE) {
bye(token, "unexpected token");
}
}
if (nameDef != null) {
if (arrayIndex != null) {
expression.addExpression(this, nameDefToken, new ArrayAccess(nameDef, arrayIndex));
}
else {
expression.addExpression(this, nameDefToken, new Variable(nameDef));
}
}
if (reReadLast.test(token)) {
lexer.reRead(token);
}
Expression result = expression.build();
if (result == null) {
bye(token, "expected an expression/value");
}
return result;
}
protected Expression readExpression(Token.Type stopAt) throws ScriptCompileException {
return readExpression(stopAt, token -> false);
}
protected Expression readExpression(Token.Type stopAt, Predicate<Token> reReadLast) throws ScriptCompileException {
return readExpression(token -> token.getType() != stopAt, reReadLast);
}
protected Expression[] readFunctionArguments() throws ScriptCompileException {
return readResultors(Token.Type.COMMA, Token.Type.CLOSE_PARENTHESE);
}
protected String readOperator(String start) throws ScriptCompileException {
TextBuilder operatorStr = Pool.newBuilder();
Token operatorToken;
if (start != null) {
operatorStr.append(start);
}
while ((operatorToken = requireToken()).getType() == Token.Type.OPERATOR) {
String op = operatorToken.getValue();
if (OperatorList.forIdentifier(op, true) != null && !operatorStr.isEmpty()) {
break;
}
operatorStr.append(operatorToken.getValue());
}
lexer.reRead(operatorToken); // Last token have type != OPERATOR
return operatorStr.toStringAndClear();
}
// This also consumes the last 'end' token
protected Expression[] readResultors(Token.Type separator, Token.Type end) throws ScriptCompileException {
List<Expression> result = new ArrayList<>();
Token token;
while ((token = requireToken()).getType() != end) {
lexer.reRead(token);
result.add(readExpression(
t -> t.getType() != end && t.getType() != separator,
t -> t.getType() == end));
}
return result.toArray();
}
protected Value readValue() throws ScriptCompileException {
Token token = requireToken();
Value value = getValueOf(token);
if (value == null) {
bye(token, "expected a value literal (array/boolean/char/number/string/type)");
}
return value;
}
protected void requireNewLine() throws ScriptCompileException {
Token token = requireToken();
if (token.getType() != Token.Type.NEW_LINE) {
bye(token, "expected a new line");
}
}
protected Token requireToken() throws ScriptCompileException {
Token token = lexer.nextToken();
if (token == null) {
bye("Unexpected end of file");
}
return token;
}
protected Token requireToken(Token.Type type, String errorMessage) throws ScriptCompileException {
Token token = requireToken();
if (token.getType() != type) {
bye(token, errorMessage);
}
return token;
}
}
|
package br.ufrj.cos.redes.receiver;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Timer;
import java.util.TimerTask;
import br.ufrj.cos.redes.delayLossSimulator.DelayLossSimulator;
import br.ufrj.cos.redes.fileAccess.Chunk;
import br.ufrj.cos.redes.packet.InitPacket;
public class Receiver {
private Buffer buffer;
private String requestedFilename;
private Player player;
private DelayLossSimulator simulator;
public Receiver(Buffer buffer, String requestedFilename, DelayLossSimulator sim, Player player) {
this.buffer = buffer;
this.requestedFilename = requestedFilename;
this.player = player;
this.simulator = sim;
}
public void startReceiver(DatagramSocket clientSocket, InetAddress serverAddrress, int serverPort) throws IOException {
Thread simulatorThread = new Thread(new Runnable() {
@Override
public void run() {
try {
simulator.receive(clientSocket);
} catch (ClassNotFoundException e) {
System.out.println("Error in simulator, ClassNotFoundException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error in simulator, IOException");
e.printStackTrace();
}
}
});
simulatorThread.start();
ByteArrayOutputStream byteOstream = new ByteArrayOutputStream();
new ObjectOutputStream(byteOstream).writeObject(new InitPacket(InitPacket.INIT_MSG, requestedFilename));
byte[] sendBytes = byteOstream.toByteArray();
DatagramPacket initDatagram = new DatagramPacket(sendBytes, sendBytes.length, serverAddrress, serverPort);
clientSocket.send(initDatagram);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (buffer.isOver()) {
System.out.println("Buffer is over.");
timer.cancel();
System.exit(0);
return;
}
Chunk chunk = buffer.get();
try {
player.play(chunk);
} catch (IOException e) {
System.out.println("Player Timer Task: ERROR! Could not play chunk with seqNum " + chunk.getSeqNum());
e.printStackTrace();
}
}
}, 20, 20);
}
}
|
package cc.mallet.topics;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.zip.*;
import java.io.*;
import java.text.NumberFormat;
import cc.mallet.types.*;
import cc.mallet.util.Randoms;
/**
* A parallel topic model runnable task.
*
* @author David Mimno, Andrew McCallum
*/
/* Travese all non-zero document-topic distribution */
/* for (const auto& k : n_mks[m])
{
psum += k.second * trees[w].getComponent(k.first);
p[ii++] = psum; //cumulative array for binary search
}
double u = d_unif01(urng) * (psum + alpha*trees[w].w[1]);
if (u < psum) //binary search in non zero topics
{
int temp = std::lower_bound(p,p+ii,u) - p; // position of related non zero topic
topic = n_mks[m][temp].first; //actual topic
}
else //sample in F tree
{
topic = trees[w].sample(d_unif01(urng));
}
// add newly estimated z_i to count variables
if (topic!=old_topic)
{
if(nd_m[topic] == 0)
{
rev_mapper[topic] = n_mks[m].size();
n_mks[m].push_back(std::pair<int, int>(topic, 1));
}
else
{
n_mks[m][rev_mapper[topic]].second += 1;
}
nd_m[topic] += 1;
if (nd_m[old_topic] == 0)
{
n_mks[m][rev_mapper[old_topic]].first = n_mks[m].back().first;
n_mks[m][rev_mapper[old_topic]].second = n_mks[m].back().second;
rev_mapper[n_mks[m].back().first] = rev_mapper[old_topic];
n_mks[m].pop_back();
rev_mapper[old_topic] = -1;
}
cbuff[nst*(w%ntt)+i].push(delta(w,old_topic,topic));
}
else
{
n_mks[m][rev_mapper[topic]].second += 1;
nd_m[topic] += 1;
}
z[m][n] = topic;
}
for (const auto& k : n_mks[m])
{
nd_m[k.first] = 0;
rev_mapper[k.first] = -1;
}
}
tn = std::chrono::high_resolution_clock::now();
std::cout << "In thread " << i << " at iteration " << iter << " ..."
<< "Time: " << std::chrono::duration_cast<std::chrono::milliseconds>(tn - ts).count() << std::endl;
}
std::cout<<"Returning from "<<i<<std::endl;
delete[] p;
delete[] nd_m;
delete[] rev_mapper;
return 0;
}
*/
public class FastWorkerRunnable implements Runnable {
boolean isFinished = true;
ArrayList<TopicAssignment> data;
int startDoc, numDocs;
protected int numTopics; // Number of topics to be fit
// These values are used to encode type/topic counts as
// count/topic pairs in a single int.
protected int topicMask;
protected int topicBits;
protected int numTypes;
protected double[] alpha; // Dirichlet(alpha,alpha,...) is the distribution over topics
protected double alphaSum;
protected double beta; // Prior on per-topic multinomial distribution over words
protected double betaSum;
public static final double DEFAULT_BETA = 0.01;
protected double smoothingOnlyMass = 0.0;
protected double[] cachedCoefficients;
protected int[][] typeTopicCounts; // indexed by <feature index, topic index>
protected int[] tokensPerTopic; // indexed by <topic index>
// for dirichlet estimation
protected int[] docLengthCounts; // histogram of document sizes
protected int[][] topicDocCounts; // histogram of document/topic counts, indexed by <topic index, sequence position index>
boolean shouldSaveState = false;
boolean shouldBuildLocalCounts = true;
protected FTree[] trees; //store
protected Randoms random;
public FastWorkerRunnable(int numTopics,
double[] alpha, double alphaSum,
double beta, Randoms random,
ArrayList<TopicAssignment> data,
int[][] typeTopicCounts,
int[] tokensPerTopic,
int startDoc, int numDocs) {
this.data = data;
this.numTopics = numTopics;
this.numTypes = typeTopicCounts.length;
trees = new FTree[this.numTypes];
if (Integer.bitCount(numTopics) == 1) {
// exact power of 2
topicMask = numTopics - 1;
topicBits = Integer.bitCount(topicMask);
} else {
// otherwise add an extra bit
topicMask = Integer.highestOneBit(numTopics) * 2 - 1;
topicBits = Integer.bitCount(topicMask);
}
this.typeTopicCounts = typeTopicCounts;
this.tokensPerTopic = tokensPerTopic;
this.alphaSum = alphaSum;
this.alpha = alpha;
this.beta = beta;
this.betaSum = beta * numTypes;
this.random = random;
this.startDoc = startDoc;
this.numDocs = numDocs;
cachedCoefficients = new double[numTopics];
//System.err.println("WorkerRunnable Thread: " + numTopics + " topics, " + topicBits + " topic bits, " +
// Integer.toBinaryString(topicMask) + " topic mask");
}
/**
* If there is only one thread, we don't need to go through communication
* overhead. This method asks this worker not to prepare local type-topic
* counts. The method should be called when we are using this code in a
* non-threaded environment.
*/
public void makeOnlyThread() {
shouldBuildLocalCounts = false;
}
public int[] getTokensPerTopic() {
return tokensPerTopic;
}
public int[][] getTypeTopicCounts() {
return typeTopicCounts;
}
public int[] getDocLengthCounts() {
return docLengthCounts;
}
public int[][] getTopicDocCounts() {
return topicDocCounts;
}
public void initializeAlphaStatistics(int size) {
docLengthCounts = new int[size];
topicDocCounts = new int[numTopics][size];
}
public void collectAlphaStatistics() {
shouldSaveState = true;
}
public void resetBeta(double beta, double betaSum) {
this.beta = beta;
this.betaSum = betaSum;
}
/**
* Once we have sampled the local counts, trash the "global" type topic
* counts and reuse the space to build a summary of the type topic counts
* specific to this worker's section of the corpus.
*/
public void buildLocalTypeTopicCounts() {
// Clear the topic totals
Arrays.fill(tokensPerTopic, 0);
// Clear the type/topic counts, only
// looking at the entries before the first 0 entry.
for (int type = 0; type < typeTopicCounts.length; type++) {
int[] topicCounts = typeTopicCounts[type];
int position = 0;
while (position < topicCounts.length
&& topicCounts[position] > 0) {
topicCounts[position] = 0;
position++;
}
}
for (int doc = startDoc;
doc < data.size() && doc < startDoc + numDocs;
doc++) {
TopicAssignment document = data.get(doc);
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
FeatureSequence topicSequence = (FeatureSequence) document.topicSequence;
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.size(); position++) {
int topic = topics[position];
if (topic == ParallelTopicModel.UNASSIGNED_TOPIC) {
continue;
}
tokensPerTopic[topic]++;
// The format for these arrays is
// the topic in the rightmost bits
// the count in the remaining (left) bits.
// Since the count is in the high bits, sorting (desc)
// by the numeric value of the int guarantees that
// higher counts will be before the lower counts.
int type = tokens.getIndexAtPosition(position);
int[] currentTypeTopicCounts = typeTopicCounts[type];
// Start by assuming that the array is either empty
// or is in sorted (descending) order.
// Here we are only adding counts, so if we find
// an existing location with the topic, we only need
// to ensure that it is not larger than its left neighbor.
int index = 0;
int currentTopic = currentTypeTopicCounts[index] & topicMask;
int currentValue;
while (currentTypeTopicCounts[index] > 0 && currentTopic != topic) {
index++;
if (index == currentTypeTopicCounts.length) {
System.out.println("overflow on type " + type);
}
currentTopic = currentTypeTopicCounts[index] & topicMask;
}
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (currentValue == 0) {
// new value is 1, so we don't have to worry about sorting
// (except by topic suffix, which doesn't matter)
currentTypeTopicCounts[index]
= (1 << topicBits) + topic;
} else {
currentTypeTopicCounts[index]
= ((currentValue + 1) << topicBits) + topic;
// Now ensure that the array is still sorted by
// bubbling this value up.
while (index > 0
&& currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
int temp = currentTypeTopicCounts[index];
currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
currentTypeTopicCounts[index - 1] = temp;
index
}
}
}
}
}
public void run() {
try {
if (!isFinished) {
System.out.println("already running!");
return;
}
isFinished = false;
// Initialize the smoothing-only sampling bucket
smoothingOnlyMass = 0;
// Initialize the cached coefficients, using only smoothing.
// These values will be selectively replaced in documents with
// non-zero counts in particular topics.
for (int topic = 0; topic < numTopics; topic++) {
smoothingOnlyMass += alpha[topic] * beta / (tokensPerTopic[topic] + betaSum);
cachedCoefficients[topic] = alpha[topic] / (tokensPerTopic[topic] + betaSum);
}
double[] temp = new double[numTopics];
//smooth for all topics
for (int topic = 0; topic < numTopics; topic++) {
temp[topic] = beta / (tokensPerTopic[topic] + betaSum);
}
for (int w = 0; w < numTypes - 1; ++w) {
int index = 0;
int[] currentTypeTopicCounts = typeTopicCounts[w];
//non zero topics per word
while (index < currentTypeTopicCounts.length) {
int currentTopic = currentTypeTopicCounts[index] & topicMask;
int currentValue = currentTypeTopicCounts[index] >> topicBits;
temp[currentTopic] = (currentValue + beta) / (tokensPerTopic[currentTopic] + betaSum);
index++;
}
trees[w].init(numTopics);
trees[w].constructTree(temp);
//reset temp
while (index < currentTypeTopicCounts.length) {
int currentTopic = currentTypeTopicCounts[index] & topicMask;
temp[currentTopic] = beta / (tokensPerTopic[currentTopic] + betaSum);
index++;
}
}
for (int doc = startDoc;
doc < data.size() && doc < startDoc + numDocs;
doc++) {
// if (doc % 10 == 0) {
// System.out.println("processing doc " + doc);
FeatureSequence tokenSequence
= (FeatureSequence) data.get(doc).instance.getData();
LabelSequence topicSequence
= (LabelSequence) data.get(doc).topicSequence;
sampleTopicsForOneDoc(tokenSequence, topicSequence,
true);
}
if (shouldBuildLocalCounts) {
buildLocalTypeTopicCounts();
}
shouldSaveState = false;
isFinished = true;
} catch (Exception e) {
e.printStackTrace();
}
}
public static int lower_bound(Comparable[] arr, Comparable key) {
int len = arr.length;
int lo = 0;
int hi = len - 1;
int mid = (lo + hi) / 2;
while (true) {
int cmp = arr[mid].compareTo(key);
if (cmp == 0 || cmp > 0) {
hi = mid - 1;
if (hi < lo) {
return mid;
}
} else {
lo = mid + 1;
if (hi < lo) {
return mid < len - 1 ? mid + 1 : -1;
}
}
mid = (lo + hi) / 2; //(hi-lo)/2+lo in order not to overflow? or (lo + hi) >>> 1
}
}
protected void sampleTopicsForOneDoc(FeatureSequence tokenSequence,
FeatureSequence topicSequence,
boolean readjustTopicsAndStats /* currently ignored */) {
int[] oneDocTopics = topicSequence.getFeatures();
int[] currentTypeTopicCounts;
int type, oldTopic, newTopic;
int docLength = tokenSequence.getLength();
int[] localTopicCounts = new int[numTopics];
int[] localTopicIndex = new int[numTopics];
// populate topic counts
for (int position = 0; position < docLength; position++) {
if (oneDocTopics[position] == ParallelTopicModel.UNASSIGNED_TOPIC) {
continue;
}
localTopicCounts[oneDocTopics[position]]++;
}
// Build an array that densely lists the topics that
// have non-zero counts.
int denseIndex = 0;
for (int topic = 0; topic < numTopics; topic++) {
if (localTopicCounts[topic] != 0) {
localTopicIndex[denseIndex] = topic;
denseIndex++;
}
}
// Record the total number of non-zero topics
int nonZeroTopics = denseIndex;
// Initialize the topic count/beta sampling bucket
double topicBetaMass = 0.0;
// Initialize cached coefficients and the topic/beta
// normalizing constant.
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
int topic = localTopicIndex[denseIndex];
int n = localTopicCounts[topic];
// initialize the normalization constant for the (B * n_{t|d}) term
topicBetaMass += beta * n / (tokensPerTopic[topic] + betaSum);
// update the coefficients for the non-zero topics
cachedCoefficients[topic] = (alpha[topic] + n) / (tokensPerTopic[topic] + betaSum);
}
double topicTermMass = 0.0;
double[] topicTermScores = new double[numTopics];
int[] topicTermIndices;
int[] topicTermValues;
int i;
double score;
// Iterate over the positions (words) in the document
for (int position = 0; position < docLength; position++) {
type = tokenSequence.getIndexAtPosition(position);
oldTopic = oneDocTopics[position];
currentTypeTopicCounts = typeTopicCounts[type];
if (oldTopic != ParallelTopicModel.UNASSIGNED_TOPIC) {
// Remove this token from all counts.
// Remove this topic's contribution to the
// normalizing constants
smoothingOnlyMass -= alpha[oldTopic] * beta
/ (tokensPerTopic[oldTopic] + betaSum);
topicBetaMass -= beta * localTopicCounts[oldTopic]
/ (tokensPerTopic[oldTopic] + betaSum);
// Decrement the local doc/topic counts
localTopicCounts[oldTopic]
// Maintain the dense index, if we are deleting
// the old topic
if (localTopicCounts[oldTopic] == 0) {
// First get to the dense location associated with
// the old topic.
denseIndex = 0;
// We know it's in there somewhere, so we don't
// need bounds checking.
while (localTopicIndex[denseIndex] != oldTopic) {
denseIndex++;
}
// shift all remaining dense indices to the left.
while (denseIndex < nonZeroTopics) {
if (denseIndex < localTopicIndex.length - 1) {
localTopicIndex[denseIndex]
= localTopicIndex[denseIndex + 1];
}
denseIndex++;
}
nonZeroTopics
}
// Decrement the global topic count totals
tokensPerTopic[oldTopic]
assert (tokensPerTopic[oldTopic] >= 0) : "old Topic " + oldTopic + " below 0";
// Add the old topic's contribution back into the
// normalizing constants.
smoothingOnlyMass += alpha[oldTopic] * beta
/ (tokensPerTopic[oldTopic] + betaSum);
topicBetaMass += beta * localTopicCounts[oldTopic]
/ (tokensPerTopic[oldTopic] + betaSum);
// Reset the cached coefficient for this topic
cachedCoefficients[oldTopic]
= (alpha[oldTopic] + localTopicCounts[oldTopic])
/ (tokensPerTopic[oldTopic] + betaSum);
}
// Now go over the type/topic counts, decrementing
// where appropriate, and calculating the score
// for each topic at the same time.
int index = 0;
int currentTopic, currentValue;
boolean alreadyDecremented = (oldTopic == ParallelTopicModel.UNASSIGNED_TOPIC);
topicTermMass = 0.0;
while (index < currentTypeTopicCounts.length
&& currentTypeTopicCounts[index] > 0) {
currentTopic = currentTypeTopicCounts[index] & topicMask;
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (!alreadyDecremented
&& currentTopic == oldTopic) {
// We're decrementing and adding up the
// sampling weights at the same time, but
// decrementing may require us to reorder
// the topics, so after we're done here,
// look at this cell in the array again.
currentValue
if (currentValue == 0) {
currentTypeTopicCounts[index] = 0;
} else {
currentTypeTopicCounts[index]
= (currentValue << topicBits) + oldTopic;
}
// Shift the reduced value to the right, if necessary.
int subIndex = index;
while (subIndex < currentTypeTopicCounts.length - 1
&& currentTypeTopicCounts[subIndex] < currentTypeTopicCounts[subIndex + 1]) {
int temp = currentTypeTopicCounts[subIndex];
currentTypeTopicCounts[subIndex] = currentTypeTopicCounts[subIndex + 1];
currentTypeTopicCounts[subIndex + 1] = temp;
subIndex++;
}
alreadyDecremented = true;
} else {
score
= cachedCoefficients[currentTopic] * currentValue;
topicTermMass += score;
topicTermScores[index] = score;
index++;
}
}
double sample = random.nextUniform() * (smoothingOnlyMass + topicBetaMass + topicTermMass);
double origSample = sample;
// Make sure it actually gets set
newTopic = -1;
if (sample < topicTermMass) {
//topicTermCount++;
i = -1;
while (sample > 0) {
i++;
sample -= topicTermScores[i];
}
newTopic = currentTypeTopicCounts[i] & topicMask;
currentValue = currentTypeTopicCounts[i] >> topicBits;
currentTypeTopicCounts[i] = ((currentValue + 1) << topicBits) + newTopic;
// Bubble the new value up, if necessary
while (i > 0
&& currentTypeTopicCounts[i] > currentTypeTopicCounts[i - 1]) {
int temp = currentTypeTopicCounts[i];
currentTypeTopicCounts[i] = currentTypeTopicCounts[i - 1];
currentTypeTopicCounts[i - 1] = temp;
i
}
} else {
sample -= topicTermMass;
if (sample < topicBetaMass) {
//betaTopicCount++;
sample /= beta;
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
int topic = localTopicIndex[denseIndex];
sample -= localTopicCounts[topic]
/ (tokensPerTopic[topic] + betaSum);
if (sample <= 0.0) {
newTopic = topic;
break;
}
}
} else {
//smoothingOnlyCount++;
sample -= topicBetaMass;
sample /= beta;
newTopic = 0;
sample -= alpha[newTopic]
/ (tokensPerTopic[newTopic] + betaSum);
while (sample > 0.0) {
newTopic++;
sample -= alpha[newTopic]
/ (tokensPerTopic[newTopic] + betaSum);
}
}
// Move to the position for the new topic,
// which may be the first empty position if this
// is a new topic for this word.
index = 0;
while (currentTypeTopicCounts[index] > 0
&& (currentTypeTopicCounts[index] & topicMask) != newTopic) {
index++;
if (index == currentTypeTopicCounts.length) {
System.err.println("type: " + type + " new topic: " + newTopic);
for (int k = 0; k < currentTypeTopicCounts.length; k++) {
System.err.print((currentTypeTopicCounts[k] & topicMask) + ":"
+ (currentTypeTopicCounts[k] >> topicBits) + " ");
}
System.err.println();
}
}
// index should now be set to the position of the new topic,
// which may be an empty cell at the end of the list.
if (currentTypeTopicCounts[index] == 0) {
// inserting a new topic, guaranteed to be in
// order w.r.t. count, if not topic.
currentTypeTopicCounts[index] = (1 << topicBits) + newTopic;
} else {
currentValue = currentTypeTopicCounts[index] >> topicBits;
currentTypeTopicCounts[index] = ((currentValue + 1) << topicBits) + newTopic;
// Bubble the increased value left, if necessary
while (index > 0
&& currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
int temp = currentTypeTopicCounts[index];
currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
currentTypeTopicCounts[index - 1] = temp;
index
}
}
}
if (newTopic == -1) {
System.err.println("WorkerRunnable sampling error: " + origSample + " " + sample + " " + smoothingOnlyMass + " "
+ topicBetaMass + " " + topicTermMass);
newTopic = numTopics - 1; // TODO is this appropriate
}
//assert(newTopic != -1);
// Put that new topic into the counts
oneDocTopics[position] = newTopic;
smoothingOnlyMass -= alpha[newTopic] * beta
/ (tokensPerTopic[newTopic] + betaSum);
topicBetaMass -= beta * localTopicCounts[newTopic]
/ (tokensPerTopic[newTopic] + betaSum);
localTopicCounts[newTopic]++;
// If this is a new topic for this document,
// add the topic to the dense index.
if (localTopicCounts[newTopic] == 1) {
// First find the point where we
// should insert the new topic by going to
// the end (which is the only reason we're keeping
// track of the number of non-zero
// topics) and working backwards
denseIndex = nonZeroTopics;
while (denseIndex > 0
&& localTopicIndex[denseIndex - 1] > newTopic) {
localTopicIndex[denseIndex]
= localTopicIndex[denseIndex - 1];
denseIndex
}
localTopicIndex[denseIndex] = newTopic;
nonZeroTopics++;
}
tokensPerTopic[newTopic]++;
// update the coefficients for the non-zero topics
cachedCoefficients[newTopic]
= (alpha[newTopic] + localTopicCounts[newTopic])
/ (tokensPerTopic[newTopic] + betaSum);
smoothingOnlyMass += alpha[newTopic] * beta
/ (tokensPerTopic[newTopic] + betaSum);
topicBetaMass += beta * localTopicCounts[newTopic]
/ (tokensPerTopic[newTopic] + betaSum);
}
if (shouldSaveState) {
// Update the document-topic count histogram,
// for dirichlet estimation
docLengthCounts[docLength]++;
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
int topic = localTopicIndex[denseIndex];
topicDocCounts[topic][localTopicCounts[topic]]++;
}
}
// Clean up our mess: reset the coefficients to values with only
// smoothing. The next doc will update its own non-zero topics...
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
int topic = localTopicIndex[denseIndex];
cachedCoefficients[topic]
= alpha[topic] / (tokensPerTopic[topic] + betaSum);
}
}
}
|
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JOptionPane;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.BorderFactory;
import java.io.Serializable;
/**
* The entry point and glue code for the game. It also contains some helpful
* global utility methods.
* @author Geoffrey Washburn <<a href="mailto:geoffw@cis.upenn.edu">geoffw@cis.upenn.edu</a>>
* @version $Id: Mazewar.java 371 2004-02-10 21:55:32Z geoffw $
*/
public class Mazewar extends JFrame {
/**
* The default width of the {@link Maze}.
*/
private final int mazeWidth = 20;
/**
* The default height of the {@link Maze}.
*/
private final int mazeHeight = 10;
/**
* The default random seed for the {@link Maze}.
* All implementations of the same protocol must use
* the same seed value, or your mazes will be different.
*/
private final int mazeSeed = 42;
/**
* The {@link Maze} that the game uses.
*/
private Maze maze = null;
/**
* The {@link GUIClient} for the game.
*/
private GUIClient guiClient = null;
/**
* The panel that displays the {@link Maze}.
*/
private OverheadMazePanel overheadPanel = null;
/**
* The table the displays the scores.
*/
private JTable scoreTable = null;
/**
* Create the textpane statically so that we can
* write to it globally using
* the static consolePrint methods
*/
private static final JTextPane console = new JTextPane();
/**
* Write a message to the console followed by a newline.
* @param msg The {@link String} to print.
*/
public static synchronized void consolePrintLn(String msg) {
console.setText(console.getText()+msg+"\n");
}
/**
* Write a message to the console.
* @param msg The {@link String} to print.
*/
public static synchronized void consolePrint(String msg) {
console.setText(console.getText()+msg);
}
/**
* Clear the console.
*/
public static synchronized void clearConsole() {
console.setText("");
}
/**
* Static method for performing cleanup before exiting the game.
*/
public static void quit() {
// Put any network clean-up code you might have here.
// (inform other implementations on the network that you have
// left, etc.)
System.exit(0);
}
/**
* The place where all the pieces are put together.
*/
public Mazewar(String host, int port_num) {
super("ECE419 Mazewar");
consolePrintLn("ECE419 Mazewar started!");
// Create the maze
maze = new MazeImpl(new Point(mazeWidth, mazeHeight), mazeSeed);
assert(maze != null);
// Have the ScoreTableModel listen to the maze to find
// out how to adjust scores.
ScoreTableModel scoreModel = new ScoreTableModel();
assert(scoreModel != null);
maze.addMazeListener(scoreModel);
// Throw up a dialog to get the GUIClient name.
String name = JOptionPane.showInputDialog("Enter your name");
if((name == null) || (name.length() == 0)) {
Mazewar.quit();
}
// Create the GUI client
String serv_hostname = host; // Machine that hosts the server
int serv_port = port_num; // Port number of the server
int localType = 25; // GUI client is a local type
guiClient = new GUIClient(name,localType,host,port_num);
maze.addClient(guiClient);
this.addKeyListener(guiClient);
guiClient.clients.put(guiClient.getName(), guiClient);
guiClient.joinOtherClients();
// Use braces to force constructors not to be called at the beginning of the
// constructor.
/*{
maze.addClient(new RobotClient("Norby"));
maze.addClient(new RobotClient("Robbie"));
maze.addClient(new RobotClient("Clango"));
maze.addClient(new RobotClient("Marvin"));
}*/
// Create the panel that will display the maze.
overheadPanel = new OverheadMazePanel(maze, guiClient);
assert(overheadPanel != null);
maze.addMazeListener(overheadPanel);
// Don't allow editing the console from the GUI
console.setEditable(false);
console.setFocusable(false);
console.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder()));
// Allow the console to scroll by putting it in a scrollpane
JScrollPane consoleScrollPane = new JScrollPane(console);
assert(consoleScrollPane != null);
consoleScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Console"));
// Create the score table
scoreTable = new JTable(scoreModel);
assert(scoreTable != null);
scoreTable.setFocusable(false);
scoreTable.setRowSelectionAllowed(false);
// Allow the score table to scroll too.
JScrollPane scoreScrollPane = new JScrollPane(scoreTable);
assert(scoreScrollPane != null);
scoreScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Scores"));
// Create the layout manager
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
getContentPane().setLayout(layout);
// Define the constraints on the components.
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 3.0;
c.gridwidth = GridBagConstraints.REMAINDER;
layout.setConstraints(overheadPanel, c);
c.gridwidth = GridBagConstraints.RELATIVE;
c.weightx = 2.0;
c.weighty = 1.0;
layout.setConstraints(consoleScrollPane, c);
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1.0;
layout.setConstraints(scoreScrollPane, c);
// Add the components
getContentPane().add(overheadPanel);
getContentPane().add(consoleScrollPane);
getContentPane().add(scoreScrollPane);
// Pack everything neatly.
pack();
// Let the magic begin.
setVisible(true);
overheadPanel.repaint();
this.requestFocusInWindow();
}
/**
* Entry point for the game.
* @param args Command-line arguments.
*/
public static void main(String args[]) {
String hostname;
int port;
if(args.length == 2){
hostname = args[0];
port = Integer.parseInt(args[1]);
}
/* Create the GUI */
new Mazewar(hostname,port);
}
}
|
package cc.mallet.topics;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.Iterator;
import java.util.Formatter;
import java.util.Locale;
import java.util.concurrent.*;
import java.util.logging.*;
import java.util.zip.*;
import java.io.*;
import java.text.NumberFormat;
import cc.mallet.types.*;
import cc.mallet.topics.TopicAssignment;
import cc.mallet.util.Randoms;
import cc.mallet.util.MalletLogger;
/**
* Simple parallel threaded implementation of LDA,
* following Newman, Asuncion, Smyth and Welling, Distributed Algorithms for Topic Models
* JMLR (2009), with SparseLDA sampling scheme and data structure from
* Yao, Mimno and McCallum, Efficient Methods for Topic Model Inference on Streaming Document Collections, KDD (2009).
*
* @author David Mimno, Andrew McCallum
*/
public class ParallelTopicModel implements Serializable {
public static final int UNASSIGNED_TOPIC = -1;
public static Logger logger = MalletLogger.getLogger(ParallelTopicModel.class.getName());
public ArrayList<TopicAssignment> data; // the training instances and their topic assignments
public Alphabet alphabet; // the alphabet for the input data
public LabelAlphabet topicAlphabet; // the alphabet for the topics
public int numTopics; // Number of topics to be fit
// These values are used to encode type/topic counts as
// count/topic pairs in a single int.
public int topicMask;
public int topicBits;
public int numTypes;
public int totalTokens;
public double[] alpha; // Dirichlet(alpha,alpha,...) is the distribution over topics
public double alphaSum;
public double beta; // Prior on per-topic multinomial distribution over words
public double betaSum;
public boolean usingSymmetricAlpha = false;
public static final double DEFAULT_BETA = 0.01;
public int[][] typeTopicCounts; // indexed by <feature index, topic index>
public int[] tokensPerTopic; // indexed by <topic index>
// for dirichlet estimation
public int[] docLengthCounts; // histogram of document sizes
public int[][] topicDocCounts; // histogram of document/topic counts, indexed by <topic index, sequence position index>
public int numIterations = 1000;
public int burninPeriod = 200;
public int saveSampleInterval = 10;
public int optimizeInterval = 50;
public int temperingInterval = 0;
public int showTopicsInterval = 50;
public int wordsPerTopic = 7;
public int saveStateInterval = 0;
public String stateFilename = null;
public int saveModelInterval = 0;
public String modelFilename = null;
public int randomSeed = -1;
public NumberFormat formatter;
public boolean printLogLikelihood = true;
// The number of times each type appears in the corpus
int[] typeTotals;
// The max over typeTotals, used for beta optimization
int maxTypeCount;
int numThreads = 1;
public ParallelTopicModel (int numberOfTopics) {
this (numberOfTopics, numberOfTopics, DEFAULT_BETA);
}
public ParallelTopicModel (int numberOfTopics, double alphaSum, double beta) {
this (newLabelAlphabet (numberOfTopics), alphaSum, beta);
}
private static LabelAlphabet newLabelAlphabet (int numTopics) {
LabelAlphabet ret = new LabelAlphabet();
for (int i = 0; i < numTopics; i++)
ret.lookupIndex("topic"+i);
return ret;
}
public ParallelTopicModel (LabelAlphabet topicAlphabet, double alphaSum, double beta)
{
this.data = new ArrayList<TopicAssignment>();
this.topicAlphabet = topicAlphabet;
this.numTopics = topicAlphabet.size();
if (Integer.bitCount(numTopics) == 1) {
// exact power of 2
topicMask = numTopics - 1;
topicBits = Integer.bitCount(topicMask);
}
else {
// otherwise add an extra bit
topicMask = Integer.highestOneBit(numTopics) * 2 - 1;
topicBits = Integer.bitCount(topicMask);
}
this.alphaSum = alphaSum;
this.alpha = new double[numTopics];
Arrays.fill(alpha, alphaSum / numTopics);
this.beta = beta;
tokensPerTopic = new int[numTopics];
formatter = NumberFormat.getInstance();
formatter.setMaximumFractionDigits(5);
logger.info("Coded LDA: " + numTopics + " topics, " + topicBits + " topic bits, " +
Integer.toBinaryString(topicMask) + " topic mask");
}
public Alphabet getAlphabet() { return alphabet; }
public LabelAlphabet getTopicAlphabet() { return topicAlphabet; }
public int getNumTopics() { return numTopics; }
public ArrayList<TopicAssignment> getData() { return data; }
public void setNumIterations (int numIterations) {
this.numIterations = numIterations;
}
public void setBurninPeriod (int burninPeriod) {
this.burninPeriod = burninPeriod;
}
public void setTopicDisplay(int interval, int n) {
this.showTopicsInterval = interval;
this.wordsPerTopic = n;
}
public void setRandomSeed(int seed) {
randomSeed = seed;
}
/** Interval for optimizing Dirichlet hyperparameters */
public void setOptimizeInterval(int interval) {
this.optimizeInterval = interval;
// Make sure we always have at least one sample
// before optimizing hyperparameters
if (saveSampleInterval > optimizeInterval) {
saveSampleInterval = optimizeInterval;
}
}
public void setSymmetricAlpha(boolean b) {
usingSymmetricAlpha = b;
}
public void setTemperingInterval(int interval) {
temperingInterval = interval;
}
public void setNumThreads(int threads) {
this.numThreads = threads;
}
/** Define how often and where to save a text representation of the current state.
* Files are GZipped.
*
* @param interval Save a copy of the state every <code>interval</code> iterations.
* @param filename Save the state to this file, with the iteration number as a suffix
*/
public void setSaveState(int interval, String filename) {
this.saveStateInterval = interval;
this.stateFilename = filename;
}
/** Define how often and where to save a serialized model.
*
* @param interval Save a serialized model every <code>interval</code> iterations.
* @param filename Save to this file, with the iteration number as a suffix
*/
public void setSaveSerializedModel(int interval, String filename) {
this.saveModelInterval = interval;
this.modelFilename = filename;
}
public void addInstances (InstanceList training) {
alphabet = training.getDataAlphabet();
numTypes = alphabet.size();
betaSum = beta * numTypes;
typeTopicCounts = new int[numTypes][];
// Get the total number of occurrences of each word type
//int[] typeTotals = new int[numTypes];
typeTotals = new int[numTypes];
int doc = 0;
for (Instance instance : training) {
doc++;
FeatureSequence tokens = (FeatureSequence) instance.getData();
for (int position = 0; position < tokens.getLength(); position++) {
int type = tokens.getIndexAtPosition(position);
typeTotals[ type ]++;
}
}
maxTypeCount = 0;
// Allocate enough space so that we never have to worry about
// overflows: either the number of topics or the number of times
// the type occurs.
for (int type = 0; type < numTypes; type++) {
if (typeTotals[type] > maxTypeCount) { maxTypeCount = typeTotals[type]; }
typeTopicCounts[type] = new int[ Math.min(numTopics, typeTotals[type]) ];
}
doc = 0;
Randoms random = null;
if (randomSeed == -1) {
random = new Randoms();
}
else {
random = new Randoms(randomSeed);
}
for (Instance instance : training) {
doc++;
FeatureSequence tokens = (FeatureSequence) instance.getData();
LabelSequence topicSequence =
new LabelSequence(topicAlphabet, new int[ tokens.size() ]);
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < topics.length; position++) {
int topic = random.nextInt(numTopics);
topics[position] = topic;
}
TopicAssignment t = new TopicAssignment (instance, topicSequence);
data.add (t);
}
buildInitialTypeTopicCounts();
initializeHistograms();
}
public void initializeFromState(File stateFile) throws IOException {
String line;
String[] fields;
BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(stateFile))));
line = reader.readLine();
// Skip some lines starting with "#" that describe the format and specify hyperparameters
while (line.startsWith("
line = reader.readLine();
}
fields = line.split(" ");
for (TopicAssignment document: data) {
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
FeatureSequence topicSequence = (FeatureSequence) document.topicSequence;
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.size(); position++) {
int type = tokens.getIndexAtPosition(position);
if (type == Integer.parseInt(fields[3])) {
topics[position] = Integer.parseInt(fields[5]);
}
else {
System.err.println("instance list and state do not match: " + line);
throw new IllegalStateException();
}
line = reader.readLine();
if (line != null) {
fields = line.split(" ");
}
}
}
buildInitialTypeTopicCounts();
initializeHistograms();
}
public void buildInitialTypeTopicCounts () {
// Clear the topic totals
Arrays.fill(tokensPerTopic, 0);
// Clear the type/topic counts, only
// looking at the entries before the first 0 entry.
for (int type = 0; type < numTypes; type++) {
int[] topicCounts = typeTopicCounts[type];
int position = 0;
while (position < topicCounts.length &&
topicCounts[position] > 0) {
topicCounts[position] = 0;
position++;
}
}
for (TopicAssignment document : data) {
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
FeatureSequence topicSequence = (FeatureSequence) document.topicSequence;
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.size(); position++) {
int topic = topics[position];
if (topic == UNASSIGNED_TOPIC) { continue; }
tokensPerTopic[topic]++;
// The format for these arrays is
// the topic in the rightmost bits
// the count in the remaining (left) bits.
// Since the count is in the high bits, sorting (desc)
// by the numeric value of the int guarantees that
// higher counts will be before the lower counts.
int type = tokens.getIndexAtPosition(position);
int[] currentTypeTopicCounts = typeTopicCounts[ type ];
// Start by assuming that the array is either empty
// or is in sorted (descending) order.
// Here we are only adding counts, so if we find
// an existing location with the topic, we only need
// to ensure that it is not larger than its left neighbor.
int index = 0;
int currentTopic = currentTypeTopicCounts[index] & topicMask;
int currentValue;
while (currentTypeTopicCounts[index] > 0 && currentTopic != topic) {
index++;
if (index == currentTypeTopicCounts.length) {
logger.info("overflow on type " + type);
}
currentTopic = currentTypeTopicCounts[index] & topicMask;
}
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (currentValue == 0) {
// new value is 1, so we don't have to worry about sorting
// (except by topic suffix, which doesn't matter)
currentTypeTopicCounts[index] =
(1 << topicBits) + topic;
}
else {
currentTypeTopicCounts[index] =
((currentValue + 1) << topicBits) + topic;
// Now ensure that the array is still sorted by
// bubbling this value up.
while (index > 0 &&
currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
int temp = currentTypeTopicCounts[index];
currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
currentTypeTopicCounts[index - 1] = temp;
index
}
}
}
}
}
public void sumTypeTopicCounts (WorkerRunnable[] runnables) {
// Clear the topic totals
Arrays.fill(tokensPerTopic, 0);
// Clear the type/topic counts, only
// looking at the entries before the first 0 entry.
for (int type = 0; type < numTypes; type++) {
int[] targetCounts = typeTopicCounts[type];
int position = 0;
while (position < targetCounts.length &&
targetCounts[position] > 0) {
targetCounts[position] = 0;
position++;
}
}
for (int thread = 0; thread < numThreads; thread++) {
// Handle the total-tokens-per-topic array
int[] sourceTotals = runnables[thread].getTokensPerTopic();
for (int topic = 0; topic < numTopics; topic++) {
tokensPerTopic[topic] += sourceTotals[topic];
}
// Now handle the individual type topic counts
int[][] sourceTypeTopicCounts =
runnables[thread].getTypeTopicCounts();
for (int type = 0; type < numTypes; type++) {
// Here the source is the individual thread counts,
// and the target is the global counts.
int[] sourceCounts = sourceTypeTopicCounts[type];
int[] targetCounts = typeTopicCounts[type];
int sourceIndex = 0;
while (sourceIndex < sourceCounts.length &&
sourceCounts[sourceIndex] > 0) {
int topic = sourceCounts[sourceIndex] & topicMask;
int count = sourceCounts[sourceIndex] >> topicBits;
int targetIndex = 0;
int currentTopic = targetCounts[targetIndex] & topicMask;
int currentCount;
while (targetCounts[targetIndex] > 0 && currentTopic != topic) {
targetIndex++;
if (targetIndex == targetCounts.length) {
logger.info("overflow in merging on type " + type);
}
currentTopic = targetCounts[targetIndex] & topicMask;
}
currentCount = targetCounts[targetIndex] >> topicBits;
targetCounts[targetIndex] =
((currentCount + count) << topicBits) + topic;
// Now ensure that the array is still sorted by
// bubbling this value up.
while (targetIndex > 0 &&
targetCounts[targetIndex] > targetCounts[targetIndex - 1]) {
int temp = targetCounts[targetIndex];
targetCounts[targetIndex] = targetCounts[targetIndex - 1];
targetCounts[targetIndex - 1] = temp;
targetIndex
}
sourceIndex++;
}
}
}
/* // Debuggging code to ensure counts are being
// reconstructed correctly.
for (int type = 0; type < numTypes; type++) {
int[] targetCounts = typeTopicCounts[type];
int index = 0;
int count = 0;
while (index < targetCounts.length &&
targetCounts[index] > 0) {
count += targetCounts[index] >> topicBits;
index++;
}
if (count != typeTotals[type]) {
System.err.println("Expected " + typeTotals[type] + ", found " + count);
}
}
*/
}
/**
* Gather statistics on the size of documents
* and create histograms for use in Dirichlet hyperparameter
* optimization.
*/
private void initializeHistograms() {
int maxTokens = 0;
totalTokens = 0;
int seqLen;
for (int doc = 0; doc < data.size(); doc++) {
FeatureSequence fs = (FeatureSequence) data.get(doc).instance.getData();
seqLen = fs.getLength();
if (seqLen > maxTokens)
maxTokens = seqLen;
totalTokens += seqLen;
}
logger.info("max tokens: " + maxTokens);
logger.info("total tokens: " + totalTokens);
docLengthCounts = new int[maxTokens + 1];
topicDocCounts = new int[numTopics][maxTokens + 1];
}
public void optimizeAlpha(WorkerRunnable[] runnables) {
// First clear the sufficient statistic histograms
Arrays.fill(docLengthCounts, 0);
for (int topic = 0; topic < topicDocCounts.length; topic++) {
Arrays.fill(topicDocCounts[topic], 0);
}
for (int thread = 0; thread < numThreads; thread++) {
int[] sourceLengthCounts = runnables[thread].getDocLengthCounts();
int[][] sourceTopicCounts = runnables[thread].getTopicDocCounts();
for (int count=0; count < sourceLengthCounts.length; count++) {
if (sourceLengthCounts[count] > 0) {
docLengthCounts[count] += sourceLengthCounts[count];
sourceLengthCounts[count] = 0;
}
}
for (int topic=0; topic < numTopics; topic++) {
if (! usingSymmetricAlpha) {
for (int count=0; count < sourceTopicCounts[topic].length; count++) {
if (sourceTopicCounts[topic][count] > 0) {
topicDocCounts[topic][count] += sourceTopicCounts[topic][count];
sourceTopicCounts[topic][count] = 0;
}
}
}
else {
// For the symmetric version, we only need one
// count array, which I'm putting in the same
// data structure, but for topic 0. All other
// topic histograms will be empty.
// I'm duplicating this for loop, which
// isn't the best thing, but it means only checking
// whether we are symmetric or not numTopics times,
// instead of numTopics * longest document length.
for (int count=0; count < sourceTopicCounts[topic].length; count++) {
if (sourceTopicCounts[topic][count] > 0) {
topicDocCounts[0][count] += sourceTopicCounts[topic][count];
// ^ the only change
sourceTopicCounts[topic][count] = 0;
}
}
}
}
}
if (usingSymmetricAlpha) {
alphaSum = Dirichlet.learnSymmetricConcentration(topicDocCounts[0],
docLengthCounts,
numTopics,
alphaSum);
for (int topic = 0; topic < numTopics; topic++) {
alpha[topic] = alphaSum / numTopics;
}
}
else {
alphaSum = Dirichlet.learnParameters(alpha, topicDocCounts, docLengthCounts, 1.001, 1.0, 1);
}
}
public void temperAlpha(WorkerRunnable[] runnables) {
// First clear the sufficient statistic histograms
Arrays.fill(docLengthCounts, 0);
for (int topic = 0; topic < topicDocCounts.length; topic++) {
Arrays.fill(topicDocCounts[topic], 0);
}
for (int thread = 0; thread < numThreads; thread++) {
int[] sourceLengthCounts = runnables[thread].getDocLengthCounts();
int[][] sourceTopicCounts = runnables[thread].getTopicDocCounts();
for (int count=0; count < sourceLengthCounts.length; count++) {
if (sourceLengthCounts[count] > 0) {
sourceLengthCounts[count] = 0;
}
}
for (int topic=0; topic < numTopics; topic++) {
for (int count=0; count < sourceTopicCounts[topic].length; count++) {
if (sourceTopicCounts[topic][count] > 0) {
sourceTopicCounts[topic][count] = 0;
}
}
}
}
for (int topic = 0; topic < numTopics; topic++) {
alpha[topic] = 1.0;
}
alphaSum = numTopics;
}
public void optimizeBeta(WorkerRunnable[] runnables) {
// The histogram starts at count 0, so if all of the
// tokens of the most frequent type were assigned to one topic,
// we would need to store a maxTypeCount + 1 count.
int[] countHistogram = new int[maxTypeCount + 1];
// Now count the number of type/topic pairs that have
// each number of tokens.
int index;
for (int type = 0; type < numTypes; type++) {
int[] counts = typeTopicCounts[type];
index = 0;
while (index < counts.length &&
counts[index] > 0) {
int count = counts[index] >> topicBits;
countHistogram[count]++;
index++;
}
}
// Figure out how large we need to make the "observation lengths"
// histogram.
int maxTopicSize = 0;
for (int topic = 0; topic < numTopics; topic++) {
if (tokensPerTopic[topic] > maxTopicSize) {
maxTopicSize = tokensPerTopic[topic];
}
}
// Now allocate it and populate it.
int[] topicSizeHistogram = new int[maxTopicSize + 1];
for (int topic = 0; topic < numTopics; topic++) {
topicSizeHistogram[ tokensPerTopic[topic] ]++;
}
betaSum = Dirichlet.learnSymmetricConcentration(countHistogram,
topicSizeHistogram,
numTypes,
betaSum);
beta = betaSum / numTypes;
logger.info("[beta: " + formatter.format(beta) + "] ");
// Now publish the new value
for (int thread = 0; thread < numThreads; thread++) {
runnables[thread].resetBeta(beta, betaSum);
}
}
public void estimate () throws IOException {
long startTime = System.currentTimeMillis();
WorkerRunnable[] runnables = new WorkerRunnable[numThreads];
int docsPerThread = data.size() / numThreads;
int offset = 0;
if (numThreads > 1) {
for (int thread = 0; thread < numThreads; thread++) {
int[] runnableTotals = new int[numTopics];
System.arraycopy(tokensPerTopic, 0, runnableTotals, 0, numTopics);
int[][] runnableCounts = new int[numTypes][];
for (int type = 0; type < numTypes; type++) {
int[] counts = new int[typeTopicCounts[type].length];
System.arraycopy(typeTopicCounts[type], 0, counts, 0, counts.length);
runnableCounts[type] = counts;
}
// some docs may be missing at the end due to integer division
if (thread == numThreads - 1) {
docsPerThread = data.size() - offset;
}
Randoms random = null;
if (randomSeed == -1) {
random = new Randoms();
}
else {
random = new Randoms(randomSeed);
}
runnables[thread] = new WorkerRunnable(numTopics,
alpha, alphaSum, beta,
random, data,
runnableCounts, runnableTotals,
offset, docsPerThread);
runnables[thread].initializeAlphaStatistics(docLengthCounts.length);
offset += docsPerThread;
}
}
else {
// If there is only one thread, copy the typeTopicCounts
// arrays directly, rather than allocating new memory.
Randoms random = null;
if (randomSeed == -1) {
random = new Randoms();
}
else {
random = new Randoms(randomSeed);
}
runnables[0] = new WorkerRunnable(numTopics,
alpha, alphaSum, beta,
random, data,
typeTopicCounts, tokensPerTopic,
offset, docsPerThread);
runnables[0].initializeAlphaStatistics(docLengthCounts.length);
// If there is only one thread, we
// can avoid communications overhead.
// This switch informs the thread not to
// gather statistics for its portion of the data.
runnables[0].makeOnlyThread();
}
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int iteration = 1; iteration <= numIterations; iteration++) {
long iterationStart = System.currentTimeMillis();
if (showTopicsInterval != 0 && iteration != 0 && iteration % showTopicsInterval == 0) {
logger.info("\n" + displayTopWords (wordsPerTopic, false));
}
if (saveStateInterval != 0 && iteration % saveStateInterval == 0) {
this.printState(new File(stateFilename + '.' + iteration));
}
if (saveModelInterval != 0 && iteration % saveModelInterval == 0) {
this.write(new File(modelFilename + '.' + iteration));
}
if (numThreads > 1) {
// Submit runnables to thread pool
for (int thread = 0; thread < numThreads; thread++) {
if (iteration > burninPeriod && optimizeInterval != 0 &&
iteration % saveSampleInterval == 0) {
runnables[thread].collectAlphaStatistics();
}
logger.fine("submitting thread " + thread);
executor.submit(runnables[thread]);
//runnables[thread].run();
}
// I'm getting some problems that look like
// a thread hasn't started yet when it is first
// polled, so it appears to be finished.
// This only occurs in very short corpora.
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
boolean finished = false;
while (! finished) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
finished = true;
// Are all the threads done?
for (int thread = 0; thread < numThreads; thread++) {
//logger.info("thread " + thread + " done? " + runnables[thread].isFinished);
finished = finished && runnables[thread].isFinished;
}
}
//System.out.print("[" + (System.currentTimeMillis() - iterationStart) + "] ");
sumTypeTopicCounts(runnables);
//System.out.print("[" + (System.currentTimeMillis() - iterationStart) + "] ");
for (int thread = 0; thread < numThreads; thread++) {
int[] runnableTotals = runnables[thread].getTokensPerTopic();
System.arraycopy(tokensPerTopic, 0, runnableTotals, 0, numTopics);
int[][] runnableCounts = runnables[thread].getTypeTopicCounts();
for (int type = 0; type < numTypes; type++) {
int[] targetCounts = runnableCounts[type];
int[] sourceCounts = typeTopicCounts[type];
int index = 0;
while (index < sourceCounts.length) {
if (sourceCounts[index] != 0) {
targetCounts[index] = sourceCounts[index];
}
else if (targetCounts[index] != 0) {
targetCounts[index] = 0;
}
else {
break;
}
index++;
}
//System.arraycopy(typeTopicCounts[type], 0, counts, 0, counts.length);
}
}
}
else {
if (iteration > burninPeriod && optimizeInterval != 0 &&
iteration % saveSampleInterval == 0) {
runnables[0].collectAlphaStatistics();
}
runnables[0].run();
}
long elapsedMillis = System.currentTimeMillis() - iterationStart;
if (elapsedMillis < 1000) {
logger.fine(elapsedMillis + "ms ");
}
else {
logger.fine((elapsedMillis/1000) + "s ");
}
if (iteration > burninPeriod && optimizeInterval != 0 &&
iteration % optimizeInterval == 0) {
optimizeAlpha(runnables);
optimizeBeta(runnables);
logger.fine("[O " + (System.currentTimeMillis() - iterationStart) + "] ");
}
if (iteration % 10 == 0) {
if (printLogLikelihood) {
logger.info ("<" + iteration + "> LL/token: " + formatter.format(modelLogLikelihood() / totalTokens));
}
else {
logger.info ("<" + iteration + ">");
}
}
}
executor.shutdownNow();
long seconds = Math.round((System.currentTimeMillis() - startTime)/1000.0);
long minutes = seconds / 60; seconds %= 60;
long hours = minutes / 60; minutes %= 60;
long days = hours / 24; hours %= 24;
StringBuilder timeReport = new StringBuilder();
timeReport.append("\nTotal time: ");
if (days != 0) { timeReport.append(days); timeReport.append(" days "); }
if (hours != 0) { timeReport.append(hours); timeReport.append(" hours "); }
if (minutes != 0) { timeReport.append(minutes); timeReport.append(" minutes "); }
timeReport.append(seconds); timeReport.append(" seconds");
logger.info(timeReport.toString());
}
public void printTopWords (File file, int numWords, boolean useNewLines) throws IOException {
PrintStream out = new PrintStream (file);
printTopWords(out, numWords, useNewLines);
out.close();
}
/**
* Return an array of sorted sets (one set per topic). Each set
* contains IDSorter objects with integer keys into the alphabet.
* To get direct access to the Strings, use getTopWords().
*/
public ArrayList<TreeSet<IDSorter>> getSortedWords () {
ArrayList<TreeSet<IDSorter>> topicSortedWords = new ArrayList<TreeSet<IDSorter>>(numTopics);
// Initialize the tree sets
for (int topic = 0; topic < numTopics; topic++) {
topicSortedWords.add(new TreeSet<IDSorter>());
}
// Collect counts
for (int type = 0; type < numTypes; type++) {
int[] topicCounts = typeTopicCounts[type];
int index = 0;
while (index < topicCounts.length &&
topicCounts[index] > 0) {
int topic = topicCounts[index] & topicMask;
int count = topicCounts[index] >> topicBits;
topicSortedWords.get(topic).add(new IDSorter(type, count));
index++;
}
}
return topicSortedWords;
}
/** Return an array (one element for each topic) of arrays of words, which
* are the most probable words for that topic in descending order. These
* are returned as Objects, but will probably be Strings.
*
* @param numWords The maximum length of each topic's array of words (may be less).
*/
public Object[][] getTopWords(int numWords) {
ArrayList<TreeSet<IDSorter>> topicSortedWords = getSortedWords();
Object[][] result = new Object[ numTopics ][];
for (int topic = 0; topic < numTopics; topic++) {
TreeSet<IDSorter> sortedWords = topicSortedWords.get(topic);
// How many words should we report? Some topics may have fewer than
// the default number of words with non-zero weight.
int limit = numWords;
if (sortedWords.size() < numWords) { limit = sortedWords.size(); }
result[topic] = new Object[limit];
Iterator<IDSorter> iterator = sortedWords.iterator();
for (int i=0; i < limit; i++) {
IDSorter info = iterator.next();
result[topic][i] = alphabet.lookupObject(info.getID());
}
}
return result;
}
public void printTopWords (PrintStream out, int numWords, boolean usingNewLines) {
out.print(displayTopWords(numWords, usingNewLines));
}
public String displayTopWords (int numWords, boolean usingNewLines) {
StringBuilder out = new StringBuilder();
ArrayList<TreeSet<IDSorter>> topicSortedWords = getSortedWords();
// Print results for each topic
for (int topic = 0; topic < numTopics; topic++) {
TreeSet<IDSorter> sortedWords = topicSortedWords.get(topic);
int word = 1;
Iterator<IDSorter> iterator = sortedWords.iterator();
if (usingNewLines) {
out.append (topic + "\t" + formatter.format(alpha[topic]) + "\n");
while (iterator.hasNext() && word < numWords) {
IDSorter info = iterator.next();
out.append(alphabet.lookupObject(info.getID()) + "\t" + formatter.format(info.getWeight()) + "\n");
word++;
}
}
else {
out.append (topic + "\t" + formatter.format(alpha[topic]) + "\t");
while (iterator.hasNext() && word < numWords) {
IDSorter info = iterator.next();
out.append(alphabet.lookupObject(info.getID()) + " ");
word++;
}
out.append ("\n");
}
}
return out.toString();
}
public void topicXMLReport (PrintWriter out, int numWords) {
ArrayList<TreeSet<IDSorter>> topicSortedWords = getSortedWords();
out.println("<?xml version='1.0' ?>");
out.println("<topicModel>");
for (int topic = 0; topic < numTopics; topic++) {
out.println(" <topic id='" + topic + "' alpha='" + alpha[topic] +
"' totalTokens='" + tokensPerTopic[topic] + "'>");
int word = 1;
Iterator<IDSorter> iterator = topicSortedWords.get(topic).iterator();
while (iterator.hasNext() && word < numWords) {
IDSorter info = iterator.next();
out.println(" <word rank='" + word + "'>" +
alphabet.lookupObject(info.getID()) +
"</word>");
word++;
}
out.println(" </topic>");
}
out.println("</topicModel>");
}
public void topicPhraseXMLReport(PrintWriter out, int numWords) {
int numTopics = this.getNumTopics();
gnu.trove.TObjectIntHashMap<String>[] phrases = new gnu.trove.TObjectIntHashMap[numTopics];
Alphabet alphabet = this.getAlphabet();
// Get counts of phrases
for (int ti = 0; ti < numTopics; ti++)
phrases[ti] = new gnu.trove.TObjectIntHashMap<String>();
for (int di = 0; di < this.getData().size(); di++) {
TopicAssignment t = this.getData().get(di);
Instance instance = t.instance;
FeatureSequence fvs = (FeatureSequence) instance.getData();
boolean withBigrams = false;
if (fvs instanceof FeatureSequenceWithBigrams) withBigrams = true;
int prevtopic = -1;
int prevfeature = -1;
int topic = -1;
StringBuffer sb = null;
int feature = -1;
int doclen = fvs.size();
for (int pi = 0; pi < doclen; pi++) {
feature = fvs.getIndexAtPosition(pi);
topic = this.getData().get(di).topicSequence.getIndexAtPosition(pi);
if (topic == prevtopic && (!withBigrams || ((FeatureSequenceWithBigrams)fvs).getBiIndexAtPosition(pi) != -1)) {
if (sb == null)
sb = new StringBuffer (alphabet.lookupObject(prevfeature).toString() + " " + alphabet.lookupObject(feature));
else {
sb.append (" ");
sb.append (alphabet.lookupObject(feature));
}
} else if (sb != null) {
String sbs = sb.toString();
//logger.info ("phrase:"+sbs);
if (phrases[prevtopic].get(sbs) == 0)
phrases[prevtopic].put(sbs,0);
phrases[prevtopic].increment(sbs);
prevtopic = prevfeature = -1;
sb = null;
} else {
prevtopic = topic;
prevfeature = feature;
}
}
}
// phrases[] now filled with counts
// Now start printing the XML
out.println("<?xml version='1.0' ?>");
out.println("<topics>");
ArrayList<TreeSet<IDSorter>> topicSortedWords = getSortedWords();
double[] probs = new double[alphabet.size()];
for (int ti = 0; ti < numTopics; ti++) {
out.print(" <topic id=\"" + ti + "\" alpha=\"" + alpha[ti] +
"\" totalTokens=\"" + tokensPerTopic[ti] + "\" ");
// For gathering <term> and <phrase> output temporarily
// so that we can get topic-title information before printing it to "out".
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream pout = new PrintStream (bout);
// For holding candidate topic titles
AugmentableFeatureVector titles = new AugmentableFeatureVector (new Alphabet());
// Print words
int word = 1;
Iterator<IDSorter> iterator = topicSortedWords.get(ti).iterator();
while (iterator.hasNext() && word < numWords) {
IDSorter info = iterator.next();
pout.println(" <word weight=\""+(info.getWeight()/tokensPerTopic[ti])+"\" count=\""+Math.round(info.getWeight())+"\">"
+ alphabet.lookupObject(info.getID()) +
"</word>");
word++;
if (word < 20) // consider top 20 individual words as candidate titles
titles.add(alphabet.lookupObject(info.getID()), info.getWeight());
}
/*
for (int type = 0; type < alphabet.size(); type++)
probs[type] = this.getCountFeatureTopic(type, ti) / (double)this.getCountTokensPerTopic(ti);
RankedFeatureVector rfv = new RankedFeatureVector (alphabet, probs);
for (int ri = 0; ri < numWords; ri++) {
int fi = rfv.getIndexAtRank(ri);
pout.println (" <term weight=\""+probs[fi]+"\" count=\""+this.getCountFeatureTopic(fi,ti)+"\">"+alphabet.lookupObject(fi)+ "</term>");
if (ri < 20) // consider top 20 individual words as candidate titles
titles.add(alphabet.lookupObject(fi), this.getCountFeatureTopic(fi,ti));
}
*/
// Print phrases
Object[] keys = phrases[ti].keys();
int[] values = phrases[ti].getValues();
double counts[] = new double[keys.length];
for (int i = 0; i < counts.length; i++) counts[i] = values[i];
double countssum = MatrixOps.sum (counts);
Alphabet alph = new Alphabet(keys);
RankedFeatureVector rfv = new RankedFeatureVector (alph, counts);
int max = rfv.numLocations() < numWords ? rfv.numLocations() : numWords;
for (int ri = 0; ri < max; ri++) {
int fi = rfv.getIndexAtRank(ri);
pout.println (" <phrase weight=\""+counts[fi]/countssum+"\" count=\""+values[fi]+"\">"+alph.lookupObject(fi)+ "</phrase>");
// Any phrase count less than 20 is simply unreliable
if (ri < 20 && values[fi] > 20)
titles.add(alph.lookupObject(fi), 100*values[fi]); // prefer phrases with a factor of 100
}
// Select candidate titles
StringBuffer titlesStringBuffer = new StringBuffer();
rfv = new RankedFeatureVector (titles.getAlphabet(), titles);
int numTitles = 10;
for (int ri = 0; ri < numTitles && ri < rfv.numLocations(); ri++) {
// Don't add redundant titles
if (titlesStringBuffer.indexOf(rfv.getObjectAtRank(ri).toString()) == -1) {
titlesStringBuffer.append (rfv.getObjectAtRank(ri));
if (ri < numTitles-1)
titlesStringBuffer.append (", ");
} else
numTitles++;
}
out.println("titles=\"" + titlesStringBuffer.toString() + "\">");
out.print(bout.toString());
out.println(" </topic>");
}
out.println("</topics>");
}
/**
* Write the internal representation of type-topic counts
* (count/topic pairs in descending order by count) to a file.
*/
public void printTypeTopicCounts(File file) throws IOException {
PrintWriter out = new PrintWriter (new FileWriter (file) );
for (int type = 0; type < numTypes; type++) {
StringBuilder buffer = new StringBuilder();
buffer.append(type + " " + alphabet.lookupObject(type));
int[] topicCounts = typeTopicCounts[type];
int index = 0;
while (index < topicCounts.length &&
topicCounts[index] > 0) {
int topic = topicCounts[index] & topicMask;
int count = topicCounts[index] >> topicBits;
buffer.append(" " + topic + ":" + count);
index++;
}
out.println(buffer);
}
out.close();
}
public void printTopicWordWeights(File file) throws IOException {
PrintWriter out = new PrintWriter (new FileWriter (file) );
printTopicWordWeights(out);
out.close();
}
/**
* Print an unnormalized weight for every word in every topic.
* Most of these will be equal to the smoothing parameter beta.
*/
public void printTopicWordWeights(PrintWriter out) throws IOException {
// Probably not the most efficient way to do this...
for (int topic = 0; topic < numTopics; topic++) {
for (int type = 0; type < numTypes; type++) {
int[] topicCounts = typeTopicCounts[type];
double weight = beta;
int index = 0;
while (index < topicCounts.length &&
topicCounts[index] > 0) {
int currentTopic = topicCounts[index] & topicMask;
if (currentTopic == topic) {
weight += topicCounts[index] >> topicBits;
break;
}
index++;
}
out.println(topic + "\t" + alphabet.lookupObject(type) + "\t" + weight);
}
}
}
/** Get the smoothed distribution over topics for a training instance.
*/
public double[] getTopicProbabilities(int instanceID) {
LabelSequence topics = data.get(instanceID).topicSequence;
return getTopicProbabilities(topics);
}
/** Get the smoothed distribution over topics for a topic sequence,
* which may be from the training set or from a new instance with topics
* assigned by an inferencer.
*/
public double[] getTopicProbabilities(LabelSequence topics) {
double[] topicDistribution = new double[numTopics];
// Loop over the tokens in the document, counting the current topic
// assignments.
for (int position = 0; position < topics.getLength(); position++) {
topicDistribution[ topics.getIndexAtPosition(position) ]++;
}
// Add the smoothing parameters and normalize
double sum = 0.0;
for (int topic = 0; topic < numTopics; topic++) {
topicDistribution[topic] += alpha[topic];
sum += topicDistribution[topic];
}
// And normalize
for (int topic = 0; topic < numTopics; topic++) {
topicDistribution[topic] /= sum;
}
return topicDistribution;
}
public void printDocumentTopics (File file) throws IOException {
PrintWriter out = new PrintWriter (new FileWriter (file) );
printDocumentTopics (out);
out.close();
}
public void printDocumentTopics (PrintWriter out) {
printDocumentTopics (out, 0.0, -1);
}
/**
* @param out A print writer
* @param threshold Only print topics with proportion greater than this number
* @param max Print no more than this many topics
*/
public void printDocumentTopics (PrintWriter out, double threshold, int max) {
out.print ("#doc name topic proportion ...\n");
int docLen;
int[] topicCounts = new int[ numTopics ];
IDSorter[] sortedTopics = new IDSorter[ numTopics ];
for (int topic = 0; topic < numTopics; topic++) {
// Initialize the sorters with dummy values
sortedTopics[topic] = new IDSorter(topic, topic);
}
if (max < 0 || max > numTopics) {
max = numTopics;
}
for (int doc = 0; doc < data.size(); doc++) {
LabelSequence topicSequence = (LabelSequence) data.get(doc).topicSequence;
int[] currentDocTopics = topicSequence.getFeatures();
StringBuilder builder = new StringBuilder();
builder.append(doc);
builder.append("\t");
if (data.get(doc).instance.getName() != null) {
builder.append(data.get(doc).instance.getName());
}
else {
builder.append("no-name");
}
builder.append("\t");
docLen = currentDocTopics.length;
// Count up the tokens
for (int token=0; token < docLen; token++) {
topicCounts[ currentDocTopics[token] ]++;
}
// And normalize
for (int topic = 0; topic < numTopics; topic++) {
sortedTopics[topic].set(topic, (alpha[topic] + topicCounts[topic]) / (docLen + alphaSum) );
}
Arrays.sort(sortedTopics);
for (int i = 0; i < max; i++) {
if (sortedTopics[i].getWeight() < threshold) { break; }
builder.append(sortedTopics[i].getID() + "\t" +
sortedTopics[i].getWeight() + "\t");
}
out.println(builder);
Arrays.fill(topicCounts, 0);
}
}
public void printState (File f) throws IOException {
PrintStream out =
new PrintStream(new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(f))));
printState(out);
out.close();
}
public void printState (PrintStream out) {
out.println ("#doc source pos typeindex type topic");
out.print("#alpha : ");
for (int topic = 0; topic < numTopics; topic++) {
out.print(alpha[topic] + " ");
}
out.println();
out.println("#beta : " + beta);
for (int doc = 0; doc < data.size(); doc++) {
FeatureSequence tokenSequence = (FeatureSequence) data.get(doc).instance.getData();
LabelSequence topicSequence = (LabelSequence) data.get(doc).topicSequence;
String source = "NA";
if (data.get(doc).instance.getSource() != null) {
source = data.get(doc).instance.getSource().toString();
}
Formatter output = new Formatter(new StringBuilder(), Locale.US);
for (int pi = 0; pi < topicSequence.getLength(); pi++) {
int type = tokenSequence.getIndexAtPosition(pi);
int topic = topicSequence.getIndexAtPosition(pi);
output.format("%d %s %d %d %s %d\n", doc, source, pi, type, alphabet.lookupObject(type), topic);
/*
out.print(doc); out.print(' ');
out.print(source); out.print(' ');
out.print(pi); out.print(' ');
out.print(type); out.print(' ');
out.print(alphabet.lookupObject(type)); out.print(' ');
out.print(topic); out.println();
*/
}
out.print(output);
}
}
public double modelLogLikelihood() {
double logLikelihood = 0.0;
int nonZeroTopics;
// The likelihood of the model is a combination of a
// Dirichlet-multinomial for the words in each topic
// and a Dirichlet-multinomial for the topics in each
// document.
// The likelihood function of a dirichlet multinomial is
// Gamma( sum_i alpha_i ) prod_i Gamma( alpha_i + N_i )
// prod_i Gamma( alpha_i ) Gamma( sum_i (alpha_i + N_i) )
// So the log likelihood is
// logGamma ( sum_i alpha_i ) - logGamma ( sum_i (alpha_i + N_i) ) +
// sum_i [ logGamma( alpha_i + N_i) - logGamma( alpha_i ) ]
// Do the documents first
int[] topicCounts = new int[numTopics];
double[] topicLogGammas = new double[numTopics];
int[] docTopics;
for (int topic=0; topic < numTopics; topic++) {
topicLogGammas[ topic ] = Dirichlet.logGammaStirling( alpha[topic] );
}
for (int doc=0; doc < data.size(); doc++) {
LabelSequence topicSequence = (LabelSequence) data.get(doc).topicSequence;
docTopics = topicSequence.getFeatures();
for (int token=0; token < docTopics.length; token++) {
topicCounts[ docTopics[token] ]++;
}
for (int topic=0; topic < numTopics; topic++) {
if (topicCounts[topic] > 0) {
logLikelihood += (Dirichlet.logGammaStirling(alpha[topic] + topicCounts[topic]) -
topicLogGammas[ topic ]);
}
}
// subtract the (count + parameter) sum term
logLikelihood -= Dirichlet.logGammaStirling(alphaSum + docTopics.length);
Arrays.fill(topicCounts, 0);
}
// add the parameter sum term
logLikelihood += data.size() * Dirichlet.logGammaStirling(alphaSum);
// And the topics
// Count the number of type-topic pairs that are not just (logGamma(beta) - logGamma(beta))
int nonZeroTypeTopics = 0;
for (int type=0; type < numTypes; type++) {
// reuse this array as a pointer
topicCounts = typeTopicCounts[type];
int index = 0;
while (index < topicCounts.length &&
topicCounts[index] > 0) {
int topic = topicCounts[index] & topicMask;
int count = topicCounts[index] >> topicBits;
nonZeroTypeTopics++;
logLikelihood += Dirichlet.logGammaStirling(beta + count);
if (Double.isNaN(logLikelihood)) {
logger.warning("NaN in log likelihood calculation");
return 0;
}
else if (Double.isInfinite(logLikelihood)) {
logger.warning("infinite log likelihood");
return 0;
}
index++;
}
}
for (int topic=0; topic < numTopics; topic++) {
logLikelihood -=
Dirichlet.logGammaStirling( (beta * numTypes) +
tokensPerTopic[ topic ] );
if (Double.isNaN(logLikelihood)) {
logger.info("NaN after topic " + topic + " " + tokensPerTopic[ topic ]);
return 0;
}
else if (Double.isInfinite(logLikelihood)) {
logger.info("Infinite value after topic " + topic + " " + tokensPerTopic[ topic ]);
return 0;
}
}
// logGamma(|V|*beta) for every topic
logLikelihood +=
Dirichlet.logGammaStirling(beta * numTypes) * numTopics;
// logGamma(beta) for all type/topic pairs with non-zero count
logLikelihood -=
Dirichlet.logGammaStirling(beta) * nonZeroTypeTopics;
if (Double.isNaN(logLikelihood)) {
logger.info("at the end");
}
else if (Double.isInfinite(logLikelihood)) {
logger.info("Infinite value beta " + beta + " * " + numTypes);
return 0;
}
return logLikelihood;
}
/** Return a tool for estimating topic distributions for new documents */
public TopicInferencer getInferencer() {
return new TopicInferencer(typeTopicCounts, tokensPerTopic,
data.get(0).instance.getDataAlphabet(),
alpha, beta, betaSum);
}
/** Return a tool for evaluating the marginal probability of new documents
* under this model */
public MarginalProbEstimator getProbEstimator() {
return new MarginalProbEstimator(numTopics, alpha, alphaSum, beta,
typeTopicCounts, tokensPerTopic);
}
// Serialization
private static final long serialVersionUID = 1;
private static final int CURRENT_SERIAL_VERSION = 0;
private static final int NULL_INTEGER = -1;
private void writeObject (ObjectOutputStream out) throws IOException {
out.writeInt (CURRENT_SERIAL_VERSION);
out.writeObject(data);
out.writeObject(alphabet);
out.writeObject(topicAlphabet);
out.writeInt(numTopics);
out.writeInt(topicMask);
out.writeInt(topicBits);
out.writeInt(numTypes);
out.writeObject(alpha);
out.writeDouble(alphaSum);
out.writeDouble(beta);
out.writeDouble(betaSum);
out.writeObject(typeTopicCounts);
out.writeObject(tokensPerTopic);
out.writeObject(docLengthCounts);
out.writeObject(topicDocCounts);
out.writeInt(numIterations);
out.writeInt(burninPeriod);
out.writeInt(saveSampleInterval);
out.writeInt(optimizeInterval);
out.writeInt(showTopicsInterval);
out.writeInt(wordsPerTopic);
out.writeInt(saveStateInterval);
out.writeObject(stateFilename);
out.writeInt(saveModelInterval);
out.writeObject(modelFilename);
out.writeInt(randomSeed);
out.writeObject(formatter);
out.writeBoolean(printLogLikelihood);
out.writeInt(numThreads);
}
private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {
int version = in.readInt ();
data = (ArrayList<TopicAssignment>) in.readObject ();
alphabet = (Alphabet) in.readObject();
topicAlphabet = (LabelAlphabet) in.readObject();
numTopics = in.readInt();
topicMask = in.readInt();
topicBits = in.readInt();
numTypes = in.readInt();
alpha = (double[]) in.readObject();
alphaSum = in.readDouble();
beta = in.readDouble();
betaSum = in.readDouble();
typeTopicCounts = (int[][]) in.readObject();
tokensPerTopic = (int[]) in.readObject();
docLengthCounts = (int[]) in.readObject();
topicDocCounts = (int[][]) in.readObject();
numIterations = in.readInt();
burninPeriod = in.readInt();
saveSampleInterval = in.readInt();
optimizeInterval = in.readInt();
showTopicsInterval = in.readInt();
wordsPerTopic = in.readInt();
saveStateInterval = in.readInt();
stateFilename = (String) in.readObject();
saveModelInterval = in.readInt();
modelFilename = (String) in.readObject();
randomSeed = in.readInt();
formatter = (NumberFormat) in.readObject();
printLogLikelihood = in.readBoolean();
numThreads = in.readInt();
}
public void write (File serializedModelFile) {
try {
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream(serializedModelFile));
oos.writeObject(this);
oos.close();
} catch (IOException e) {
System.err.println("Problem serializing ParallelTopicModel to file " +
serializedModelFile + ": " + e);
}
}
public static ParallelTopicModel read (File f) throws Exception {
ParallelTopicModel topicModel = null;
ObjectInputStream ois = new ObjectInputStream (new FileInputStream(f));
topicModel = (ParallelTopicModel) ois.readObject();
ois.close();
topicModel.initializeHistograms();
return topicModel;
}
public static void main (String[] args) {
try {
InstanceList training = InstanceList.load (new File(args[0]));
int numTopics = args.length > 1 ? Integer.parseInt(args[1]) : 200;
ParallelTopicModel lda = new ParallelTopicModel (numTopics, 50.0, 0.01);
lda.printLogLikelihood = true;
lda.setTopicDisplay(50, 7);
lda.addInstances(training);
lda.setNumThreads(Integer.parseInt(args[2]));
lda.estimate();
logger.info("printing state");
lda.printState(new File("state.gz"));
logger.info("finished printing");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.android.email.activity;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import android.app.AlertDialog;
import android.app.Dialog;
import com.android.email.K9ListActivity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import com.android.email.Account;
import com.android.email.Email;
import com.android.email.MessagingController;
import com.android.email.MessagingListener;
import com.android.email.Preferences;
import com.android.email.R;
import com.android.email.activity.setup.Prefs;
import com.android.email.activity.setup.AccountSettings;
import com.android.email.activity.setup.AccountSetupBasics;
import com.android.email.activity.setup.AccountSetupCheckSettings;
import com.android.email.mail.Folder;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Store;
import com.android.email.mail.store.LocalStore;
import com.android.email.mail.store.LocalStore.LocalFolder;
public class Accounts extends K9ListActivity implements OnItemClickListener, OnClickListener {
private static final int DIALOG_REMOVE_ACCOUNT = 1;
private ConcurrentHashMap<String, Integer> unreadMessageCounts = new ConcurrentHashMap<String, Integer>();
private ConcurrentHashMap<Account, String> pendingWork = new ConcurrentHashMap<Account, String>();
/**
* Key codes used to open a debug settings screen.
*/
private static int[] secretKeyCodes = {
KeyEvent.KEYCODE_D, KeyEvent.KEYCODE_E, KeyEvent.KEYCODE_B, KeyEvent.KEYCODE_U,
KeyEvent.KEYCODE_G
};
private int mSecretKeyCodeIndex = 0;
private Account mSelectedContextAccount;
private AccountsHandler mHandler = new AccountsHandler();
private AccountsAdapter mAdapter;
private class AccountSizeChangedHolder {
Account account;
long oldSize;
long newSize;
}
class AccountsHandler extends Handler
{
private static final int DATA_CHANGED = 1;
private static final int MSG_ACCOUNT_SIZE_CHANGED = 2;
private static final int MSG_WORKING_ACCOUNT = 3;
private static final int MSG_PROGRESS = 4;
private static final int MSG_FOLDER_SYNCING = 5;
private static final int MSG_DEFINITE_PROGRESS = 6;
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case DATA_CHANGED:
if (mAdapter != null)
{
mAdapter.notifyDataSetChanged();
}
break;
case MSG_WORKING_ACCOUNT:
{
Account account = (Account)msg.obj;
int res = msg.arg1;
String toastText = getString(res, account.getDescription());
Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT);
toast.show();
break;
}
case MSG_ACCOUNT_SIZE_CHANGED:
{
AccountSizeChangedHolder holder = (AccountSizeChangedHolder)msg.obj;
Account account = holder.account;
Long oldSize = holder.oldSize;
Long newSize = holder.newSize;
String toastText = getString(R.string.account_size_changed, account.getDescription(),
SizeFormatter.formatSize(getApplication(), oldSize), SizeFormatter.formatSize(getApplication(), newSize));;
Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG);
toast.show();
break;
}
case MSG_FOLDER_SYNCING:
{
String folderName = (String) ((Object[]) msg.obj)[0];
String dispString;
dispString = getString(R.string.accounts_title);
if (folderName != null)
{
dispString += " (" + getString(R.string.status_loading)
+ folderName + ")";
}
setTitle(dispString);
break;
}
case MSG_PROGRESS:
setProgressBarIndeterminateVisibility(msg.arg1 != 0);
//setProgressBarVisibility(msg.arg1 != 0);
break;
case MSG_DEFINITE_PROGRESS:
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
public void dataChanged()
{
sendEmptyMessage(DATA_CHANGED);
}
public void workingAccount(Account account, int res)
{
android.os.Message msg = new android.os.Message();
msg.what = MSG_WORKING_ACCOUNT;
msg.obj = account;
msg.arg1 = res;
sendMessage(msg);
}
public void accountSizeChanged(Account account, long oldSize, long newSize)
{
android.os.Message msg = new android.os.Message();
msg.what = MSG_ACCOUNT_SIZE_CHANGED;
AccountSizeChangedHolder holder = new AccountSizeChangedHolder();
holder.account = account;
holder.oldSize = oldSize;
holder.newSize = newSize;
msg.obj = holder;
sendMessage(msg);
}
public void progress(boolean progress)
{
android.os.Message msg = new android.os.Message();
msg.what = MSG_PROGRESS;
msg.arg1 = progress ? 1 : 0;
sendMessage(msg);
}
public void progress(int progress)
{
android.os.Message msg = new android.os.Message();
msg.what = MSG_DEFINITE_PROGRESS;
msg.arg1 = progress ;
sendMessage(msg);
}
public void folderSyncing(String folder)
{
android.os.Message msg = new android.os.Message();
msg.what = MSG_FOLDER_SYNCING;
msg.obj = new String[]
{ folder };
sendMessage(msg);
}
}
MessagingListener mListener = new MessagingListener() {
@Override
public void accountStatusChanged(Account account, int unreadMessageCount)
{
unreadMessageCounts.put(account.getUuid(), unreadMessageCount);
mHandler.dataChanged();
pendingWork.remove(account);
if (pendingWork.isEmpty())
{
mHandler.progress(Window.PROGRESS_END);
}
else {
int level = (Window.PROGRESS_END / mAdapter.getCount()) * (mAdapter.getCount() - pendingWork.size()) ;
mHandler.progress(level);
}
}
@Override
public void accountSizeChanged(Account account, long oldSize, long newSize)
{
mHandler.accountSizeChanged(account, oldSize, newSize);
}
@Override
public void synchronizeMailboxFinished(
Account account,
String folder,
int totalMessagesInMailbox,
int numNewMessages) {
MessagingController.getInstance(getApplication()).getAccountUnreadCount(Accounts.this, account, mListener);
mHandler.progress(false);
mHandler.folderSyncing(null);
}
@Override
public void synchronizeMailboxStarted(Account account, String folder)
{
mHandler.progress(true);
mHandler.folderSyncing(account.getDescription()
+ getString(R.string.notification_bg_title_separator) + folder);
}
@Override
public void synchronizeMailboxFailed(Account account, String folder,
String message)
{
mHandler.progress(false);
mHandler.folderSyncing(null);
}
};
private static String UNREAD_MESSAGE_COUNTS = "unreadMessageCounts";
private static String SELECTED_CONTEXT_ACCOUNT = "selectedContextAccount";
public static final String EXTRA_STARTUP = "startup";
public static void actionLaunch(Context context) {
Intent intent = new Intent(context, Accounts.class);
intent.putExtra(EXTRA_STARTUP, true);
context.startActivity(intent);
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Account[] accounts = Preferences.getPreferences(this).getAccounts();
Intent intent = getIntent();
boolean startup = (boolean)intent.getBooleanExtra(EXTRA_STARTUP, false);
if (startup && accounts.length == 1) {
FolderList.actionHandleAccount(this, accounts[0], accounts[0].getAutoExpandFolderName());
finish();
}
else {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.accounts);
ListView listView = getListView();
listView.setOnItemClickListener(this);
listView.setItemsCanFocus(false);
listView.setEmptyView(findViewById(R.id.empty));
findViewById(R.id.add_new_account).setOnClickListener(this);
registerForContextMenu(listView);
if (icicle != null && icicle.containsKey(SELECTED_CONTEXT_ACCOUNT)) {
mSelectedContextAccount = (Account) icicle.getSerializable("selectedContextAccount");
}
if (icicle != null) {
Map<String, Integer> oldUnreadMessageCounts = (Map<String, Integer>)icicle.get(UNREAD_MESSAGE_COUNTS);
if (oldUnreadMessageCounts != null) {
unreadMessageCounts.putAll(oldUnreadMessageCounts);
}
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSelectedContextAccount != null) {
outState.putSerializable(SELECTED_CONTEXT_ACCOUNT, mSelectedContextAccount);
}
outState.putSerializable(UNREAD_MESSAGE_COUNTS, unreadMessageCounts);
}
@Override
public void onResume() {
super.onResume();
refresh();
MessagingController.getInstance(getApplication()).addListener(mListener);
}
@Override
public void onPause() {
super.onPause();
MessagingController.getInstance(getApplication()).removeListener(mListener);
}
private void refresh() {
Account[] accounts = Preferences.getPreferences(this).getAccounts();
mAdapter = new AccountsAdapter(accounts);
getListView().setAdapter(mAdapter);
if (accounts.length > 0) {
mHandler.progress(Window.PROGRESS_START);
}
for (Account account : accounts) {
MessagingController.getInstance(getApplication()).getAccountUnreadCount(Accounts.this, account, mListener);
pendingWork.put(account, "true");
}
}
private void onAddNewAccount() {
AccountSetupBasics.actionNewAccount(this);
}
private void onEditAccount(Account account) {
AccountSettings.actionSettings(this, account);
}
private void onEditPrefs() {
Prefs.actionPrefs(this);
}
private void onCheckMail(Account account) {
MessagingController.getInstance(getApplication()).checkMail(this, account, true, true, null);
}
private void onClearCommands(Account account) {
MessagingController.getInstance(getApplication()).clearAllPending(account);
}
private void onEmptyTrash(Account account) {
MessagingController.getInstance(getApplication()).emptyTrash(account, null);
}
private void onCompose() {
Account defaultAccount = Preferences.getPreferences(this).getDefaultAccount();
if (defaultAccount != null) {
MessageCompose.actionCompose(this, defaultAccount);
}
else {
onAddNewAccount();
}
}
private void onOpenAccount(Account account) {
FolderList.actionHandleAccount(this, account, true);
}
public void onClick(View view) {
if (view.getId() == R.id.add_new_account) {
onAddNewAccount();
}
}
private void onDeleteAccount(Account account) {
mSelectedContextAccount = account;
showDialog(DIALOG_REMOVE_ACCOUNT);
}
@Override
public Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_REMOVE_ACCOUNT:
return createRemoveAccountDialog();
}
return super.onCreateDialog(id);
}
private Dialog createRemoveAccountDialog() {
return new AlertDialog.Builder(this)
.setTitle(R.string.account_delete_dlg_title)
.setMessage(getString(R.string.account_delete_dlg_instructions_fmt, mSelectedContextAccount.getDescription()))
.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_REMOVE_ACCOUNT);
try {
((LocalStore)Store.getInstance( mSelectedContextAccount.getLocalStoreUri(), getApplication())).delete();
} catch (Exception e) {
// Ignore
}
mSelectedContextAccount.delete(Preferences.getPreferences(Accounts.this));
Email.setServicesEnabled(Accounts.this);
refresh();
}
})
.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_REMOVE_ACCOUNT);
}
})
.create();
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
Account account = (Account)getListView().getItemAtPosition(menuInfo.position);
switch (item.getItemId()) {
case R.id.edit_prefs:
onEditPrefs();
break;
case R.id.delete_account:
onDeleteAccount(account);
break;
case R.id.edit_account:
onEditAccount(account);
break;
case R.id.open:
onOpenAccount(account);
break;
case R.id.check_mail:
onCheckMail(account);
break;
case R.id.clear_pending:
onClearCommands(account);
break;
case R.id.empty_trash:
onEmptyTrash(account);
break;
case R.id.compact:
onCompact(account);
break;
case R.id.clear:
onClear(account);
break;
}
return true;
}
private void onCompact(Account account) {
mHandler.workingAccount(account, R.string.compacting_account);
MessagingController.getInstance(getApplication()).compact(account, null);
}
private void onClear(Account account) {
mHandler.workingAccount(account, R.string.clearing_account);
MessagingController.getInstance(getApplication()).clear(account, null);
}
public void onItemClick(AdapterView parent, View view, int position, long id) {
Account account = (Account)parent.getItemAtPosition(position);
onOpenAccount(account);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_new_account:
onAddNewAccount();
break;
case R.id.edit_prefs:
onEditPrefs();
break;
case R.id.check_mail:
onCheckMail(null);
break;
case R.id.compose:
onCompose();
break;
case R.id.about:
onAbout();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
private void onAbout() {
String appName = getString(R.string.app_name);
WebView wv = new WebView(this);
String html = "<h1>" + String.format(getString(R.string.about_title_fmt).toString(),
"<a href=\"" + getString(R.string.app_webpage_url) + "\">" + appName + "</a>") + "</h1>" +
"<p>" + appName + " " +
String.format(getString(R.string.debug_version_fmt).toString(),
getVersionNumber()) + "</p>" +
"<p>" + String.format(getString(R.string.app_authors_fmt).toString(),
getString(R.string.app_authors)) + "</p>" +
"<p>" + String.format(getString(R.string.app_revision_fmt).toString(),
"<a href=\"" + getString(R.string.app_revision_url) + "\">" +
getString(R.string.app_revision_url) + "</a></p>");
wv.loadData(html, "text/html", "utf-8");
new AlertDialog.Builder(this)
.setView(wv)
.setCancelable(true)
.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener () {
public void onClick(DialogInterface d, int c) {
d.dismiss();
}
})
.show();
}
/**
* Get current version number.
*
* @return String version
*/
private String getVersionNumber() {
String version = "?";
try {
PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
version = pi.versionName;
} catch (PackageManager.NameNotFoundException e) {
//Log.e(TAG, "Package name not found", e);
};
return version;
}
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.accounts_option, menu);
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(R.string.accounts_context_menu_title);
getMenuInflater().inflate(R.menu.accounts_context, menu);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == secretKeyCodes[mSecretKeyCodeIndex]) {
mSecretKeyCodeIndex++;
if (mSecretKeyCodeIndex == secretKeyCodes.length) {
mSecretKeyCodeIndex = 0;
startActivity(new Intent(this, Debug.class));
}
} else {
mSecretKeyCodeIndex = 0;
}
return super.onKeyDown(keyCode, event);
}
class AccountsAdapter extends ArrayAdapter<Account> {
public AccountsAdapter(Account[] accounts) {
super(Accounts.this, 0, accounts);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Account account = getItem(position);
View view;
if (convertView != null) {
view = convertView;
}
else {
view = getLayoutInflater().inflate(R.layout.accounts_item, parent, false);
}
AccountViewHolder holder = (AccountViewHolder) view.getTag();
if (holder == null) {
holder = new AccountViewHolder();
holder.description = (TextView) view.findViewById(R.id.description);
holder.email = (TextView) view.findViewById(R.id.email);
holder.newMessageCount = (TextView) view.findViewById(R.id.new_message_count);
view.setTag(holder);
}
holder.description.setText(account.getDescription());
holder.email.setText(account.getEmail());
if (account.getEmail().equals(account.getDescription())) {
holder.email.setVisibility(View.GONE);
}
Integer unreadMessageCount = unreadMessageCounts.get(account.getUuid());
if (unreadMessageCount != null) {
holder.newMessageCount.setText(Integer.toString(unreadMessageCount));
holder.newMessageCount.setVisibility(unreadMessageCount > 0 ? View.VISIBLE : View.GONE);
}
else {
//holder.newMessageCount.setText("-");
holder.newMessageCount.setVisibility(View.GONE);
}
return view;
}
class AccountViewHolder {
public TextView description;
public TextView email;
public TextView newMessageCount;
}
}
}
|
package com.chromium.fontinstaller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.content.Intent;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.view.*;
public class FontList extends Activity {
private ListView lv;
static ProgressDialog downloadProgress;
String fontName, selectedFromList;
static int dlLeft;
//Font url strings
String urlRobotoBold, urlRobotoBoldItalic, urlRobotoItalic,
urlRobotoLight, urlRobotoLightItalic, urlRobotoRegular, urlRobotoThin,
urlRobotoThinItalic, urlRobotoCondensedBold, urlRobotoCondensedBoldItalic,
urlRobotoCondensedItalic, urlRobotoCondensedRegular;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.font_list);
lv = (ListView) findViewById(R.id.listView1);
ArrayList<String> fontList = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("fonts.txt")));
String line = br.readLine();
while (line != null) {
fontList.add(line);
line = br.readLine();
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fontList);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View clickView, int position, long id) {
selectedFromList = (lv.getItemAtPosition(position).toString());
fontName = removeSpaces(selectedFromList); //remove the spaces from the item so that it can later be passed into the URL string
urlRobotoBold = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-Bold.ttf";
urlRobotoBoldItalic = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-BoldItalic.ttf";
urlRobotoRegular = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-Regular.ttf";
urlRobotoItalic = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-Italic.ttf";
urlRobotoLight = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-Light.ttf";
urlRobotoLightItalic = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-LightItalic.ttf";
urlRobotoThin = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-Thin.ttf";
urlRobotoThinItalic = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/Roboto-ThinItalic.ttf";
urlRobotoCondensedBold = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/RobotoCondensed-Bold.ttf";
urlRobotoCondensedBoldItalic = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/RobotoCondensed-BoldItalic.ttf";
urlRobotoCondensedRegular = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/RobotoCondensed-Regular.ttf";
urlRobotoCondensedItalic = "https://github.com/Chromium1/Fonts/raw/master/" + fontName + "FontPack/RobotoCondensed-Italic.ttf";
// 12 requests for all font styles
DownloadManager.Request request1 = new DownloadManager.Request(Uri.parse(urlRobotoBold));
request1.allowScanningByMediaScanner();
request1.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-Bold.ttf");
request1.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request2 = new DownloadManager.Request(Uri.parse(urlRobotoBoldItalic));
request2.allowScanningByMediaScanner();
request2.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-BoldItalic.ttf");
request2.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request3 = new DownloadManager.Request(Uri.parse(urlRobotoRegular));
request3.allowScanningByMediaScanner();
request3.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-Regular.ttf");
request3.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request4 = new DownloadManager.Request(Uri.parse(urlRobotoItalic));
request4.allowScanningByMediaScanner();
request4.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-Italic.ttf");
request4.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request5 = new DownloadManager.Request(Uri.parse(urlRobotoLight));
request5.allowScanningByMediaScanner();
request5.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-Light.ttf");
request5.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request6 = new DownloadManager.Request(Uri.parse(urlRobotoLightItalic));
request6.allowScanningByMediaScanner();
request6.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-LightItalic.ttf");
request6.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request7 = new DownloadManager.Request(Uri.parse(urlRobotoThin));
request7.allowScanningByMediaScanner();
request7.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-Thin.ttf");
request7.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request8 = new DownloadManager.Request(Uri.parse(urlRobotoThinItalic));
request8.allowScanningByMediaScanner();
request8.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "Roboto-ThinItalic.ttf");
request8.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request9 = new DownloadManager.Request(Uri.parse(urlRobotoCondensedBold));
request9.allowScanningByMediaScanner();
request9.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "RobotoCondensed-Bold.ttf");
request9.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request10 = new DownloadManager.Request(Uri.parse(urlRobotoCondensedBoldItalic));
request10.allowScanningByMediaScanner();
request10.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "RobotoCondensed-BoldItalic.ttf");
request10.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request11 = new DownloadManager.Request(Uri.parse(urlRobotoCondensedRegular));
request11.allowScanningByMediaScanner();
request11.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "RobotoCondensed-Regular.ttf");
request11.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager.Request request12 = new DownloadManager.Request(Uri.parse(urlRobotoCondensedItalic));
request12.allowScanningByMediaScanner();
request12.setDestinationInExternalPublicDir("/DownloadedFonts/"+fontName, "RobotoCondensed-Italic.ttf");
request12.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
File file = new File("/sdcard/DownloadedFonts/"+fontName + "/Roboto-BoldItalic.ttf");
if (file.exists()) {
AlertDialog.Builder builder = new AlertDialog.Builder(FontList.this);
builder.setMessage("You have already previously downloaded this font. Press OK to install.")
.setTitle ("Fonts already downloaded")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Process mountSystem = Runtime.getRuntime().exec(new String[] { "su", "-c", "mount -o rw,remount /system"});
Process process1 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Bold.ttf /system"});
Process process2 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-BoldItalic.ttf /system"});
Process process3 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Regular.ttf /system"});
Process process4 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Italic.ttf /system"});
Process process5 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Light.ttf /system"});
Process process6 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-LightItalic.ttf /system"});
Process process7 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Thin.ttf /system"});
Process process8 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-ThinItalic.ttf /system"});
Process process9 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-Bold.ttf /system"});
Process process10 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-BoldItalic.ttf /system"});
Process process11 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-Regular.ttf /system"});
Process process12 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-Italic.ttf /system"});
}
catch (IOException e) {
Toast.makeText(getApplicationContext(), "not found",
Toast.LENGTH_LONG).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
else {
//display a progress dialog just before the request for downloads are sent
downloadProgress = ProgressDialog.show(FontList.this, "Downloading", "Downloading " + selectedFromList + ".", true);
downloadProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
manager.enqueue(request1);
manager.enqueue(request2);
manager.enqueue(request3);
manager.enqueue(request4);
manager.enqueue(request5);
manager.enqueue(request6);
manager.enqueue(request7);
manager.enqueue(request8);
manager.enqueue(request9);
manager.enqueue(request10);
manager.enqueue(request11);
manager.enqueue(request12);
dlLeft = 12;
}
// listen for download completion, and close the progress dialog once it is detected
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
dlLeft--; //every time a font is downloaded decrement this integer with an initial value of 12
}
if (dlLeft == 0){ //once it reaches 0 (meaning all fonts were downloaded), display an alert
downloadProgress.dismiss();
AlertDialog.Builder builder2 = new AlertDialog.Builder(FontList.this);
builder2.setMessage(fontName + " successfully downloaded. Press OK to install.")
.setTitle ("Fonts downloaded")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Process mountSystem = Runtime.getRuntime().exec(new String[] { "su", "-c", "mount -o rw,remount /system"});
Process process1 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Bold.ttf /system"});
Process process2 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-BoldItalic.ttf /system"});
Process process3 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Regular.ttf /system"});
Process process4 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Italic.ttf /system"});
Process process5 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Light.ttf /system"});
Process process6 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-LightItalic.ttf /system"});
Process process7 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-Thin.ttf /system"});
Process process8 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/Roboto-ThinItalic.ttf /system"});
Process process9 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-Bold.ttf /system"});
Process process10 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-BoldItalic.ttf /system"});
Process process11 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-Regular.ttf /system"});
Process process12 = Runtime.getRuntime().exec(new String[] { "su", "-c", "cp /sdcard/DownloadedFonts/"+fontName + "/RobotoCondensed-Italic.ttf /system"});
}
catch (IOException e) {
Toast.makeText(getApplicationContext(), "not found",
Toast.LENGTH_LONG).show();
}
}
});
AlertDialog alert2 = builder2.create();
alert2.show();
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
});
}
public static String removeSpaces (String line)
{//method to remove spaces
for (int x = 0 ; x < line.length () ; x++)
{
if (line.charAt (x) == ' ')
{
String newLine = line.substring (0, x) + line.substring (x+1);
return removeSpaces (newLine);
}
}
return line;
}
}
|
package com.dmdirc.installer;
import com.dmdirc.installer.cliparser.CLIParser;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
/**
* Installs DMDirc on linux
*
* @author Shane Mc Cormack
*/
public class LinuxInstaller extends Installer {
/**
* Are we running as root?
*/
private boolean isRoot() {
return (CLIParser.getCLIParser().getParamNumber("-isroot") > 0);
}
/**
* Is the given file name vaild to copy to the installation directory?
*
* @param filename File to check
* @return true If the file should be copied, else false.
*/
@Override
public boolean validFile(final String filename) {
return (!filename.equalsIgnoreCase("setup.sh") &&
!filename.equalsIgnoreCase("getjre.sh") &&
!filename.equalsIgnoreCase("progressbar.sh") &&
!filename.equalsIgnoreCase("installjre.sh"));
}
/** {@inheritDoc} */
@Override
public String defaultInstallLocation() {
String result = "";
if (CLIParser.getCLIParser().getParamNumber("-directory") > 0) {
return CLIParser.getCLIParser().getParam("-directory").getStringValue();
}
if (result.isEmpty()) {
if (isRoot()) {
result = "/opt/dmdirc";
} else {
result = System.getProperty("user.home") + "/DMDirc";
}
}
return result;
}
/**
* Check if this OS supports a given shortcut Type
*
* @param shortcutType Type of shortcut to check
* @return True if this OS supports a given shortcut Type
*/
@Override
public boolean supportsShortcut(final ShortcutType shortcutType) {
switch (shortcutType) {
case QUICKLAUNCH:
return false;
case DESKTOP:
// No desktop for root
return !isRoot();
case PROTOCOL:
case UNINSTALLER:
case MENU:
// Both root and non-root have a menu, uninstaller, and protocol
return true;
default:
// Anything else that gets added should be false until the relevent
// code is added
return false;
}
}
/**
* Setup shortcut.
*
* @param location Location where app will be installed to.
* @param shortcutType Type of shortcut to add.
*/
public void setupShortcut(final String location, final ShortcutType shortcutType) {
if (!supportsShortcut(shortcutType)) {
step.addText(" - Error creating shortcut. Not applicable to this Operating System");
return;
}
PrintWriter writer = null;
try {
String filename = "";
String command = "";
switch (shortcutType) {
case DESKTOP:
filename = System.getProperty("user.home")+"/Desktop/DMDirc.desktop";
break;
case MENU:
if (isRoot()) {
filename = "/usr/share/applications/DMDirc.desktop";
} else {
filename = System.getProperty("user.home")+"/.local/share/applications/DMDirc.desktop";
}
break;
case UNINSTALLER:
writer = new PrintWriter(location+"/uninstall.sh");
writer.println("#!/bin/sh");
writer.println("# DMDirc Uninstaller");
writer.println("PIDOF=`which pidof`");
writer.println("if [ -z \"${PIDOF}\" ]; then");
writer.println(" # For some reason some distros hide pidof...");
writer.println(" if [ -e /sbin/pidof ]; then");
writer.println(" PIDOF=/sbin/pidof");
writer.println(" elif [ -e /usr/sbin/pidof ]; then");
writer.println(" PIDOF=/usr/sbin/pidof");
writer.println(" fi;");
writer.println("fi;");
writer.println("");
writer.println("## Helper Functions");
writer.println("if [ -n \"${PIDOF}\" ]; then");
writer.println(" ISKDE=`${PIDOF} -x -s kdeinit`");
writer.println(" ISGNOME=`${PIDOF} -x -s gnome-panel`");
writer.println("else");
writer.println(" ISKDE=`pgrep kdeinit`");
writer.println(" ISGNOME=`pgrep gnome-panel`");
writer.println("fi;");
writer.println("KDIALOG=`which kdialog`");
writer.println("ZENITY=`which zenity`");
writer.println("DIALOG=`which dialog`");
writer.println("JAVA=`which java`");
writer.println("messagedialog() {");
writer.println(" # Send message to console.");
writer.println(" echo \"\"");
writer.println(" echo \"
writer.println(" echo \"DMDirc: ${1}\"");
writer.println(" echo \"
writer.println(" echo \"${2}\"");
writer.println(" echo \"
writer.println();
writer.println(" if [ \"\" != \"${ISKDE}\" -a \"\" != \"${KDIALOG}\" -a \"\" != \"${DISPLAY}\" ]; then");
writer.println(" echo \"Dialog on Display: ${DISPLAY}\"");
writer.println(" ${KDIALOG} --title \"DMDirc: ${1}\" --msgbox \"${2}\"");
writer.println(" elif [ \"\" != \"${ISGNOME}\" -a \"\" != \"${ZENITY}\" -a \"\" != \"${DISPLAY}\" ]; then");
writer.println(" echo \"Dialog on Display: ${DISPLAY}\"");
writer.println(" ${ZENITY} --info --title \"DMDirc: ${1}\" --text \"${2}\"");
writer.println(" elif [ \"\" != \"${DIALOG}\" ]; then");
writer.println(" ${DIALOG} --title \"DMDirc: ${1}\" --msgbox \"${2}\" 8 40");
writer.println(" fi");
writer.println("}");
writer.println("questiondialog() {");
writer.println(" # Send question to console.");
writer.println(" echo \"\"");
writer.println(" echo \"
writer.println(" echo \"DMDirc: ${1}\"");
writer.println(" echo \"
writer.println(" echo \"${2}\"");
writer.println(" echo \"
writer.println();
writer.println(" if [ \"\" != \"${ISKDE}\" -a \"\" != \"${KDIALOG}\" -a \"\" != \"${DISPLAY}\" ]; then");
writer.println(" echo \"Dialog on Display: ${DISPLAY}\"");
writer.println(" ${KDIALOG} --title \"DMDirc: ${1}\" --yesno \"${2}\"");
writer.println(" elif [ \"\" != \"${ISGNOME}\" -a \"\" != \"${ZENITY}\" -a \"\" != \"${DISPLAY}\" ]; then");
writer.println(" echo \"Dialog on Display: ${DISPLAY}\"");
writer.println(" ${ZENITY} --question --title \"DMDirc: ${1}\" --text \"${2}\"");
writer.println(" elif [ \"\" != \"${DIALOG}\" ]; then");
writer.println(" ${DIALOG} --title \"DMDirc: ${1}\" --yesno \"${2}\" 8 40");
writer.println(" else");
writer.println(" echo \"Unable to show Dialog for question, assuming no\"");
writer.println(" return 1");
writer.println(" fi");
writer.println("}");
writer.println("errordialog() {");
writer.println(" # Send error to console.");
writer.println(" echo \"\"");
writer.println(" echo \"
writer.println(" echo \"[Error] DMDirc: ${1}\"");
writer.println(" echo \"
writer.println(" echo \"${2}\"");
writer.println(" echo \"
writer.println();
writer.println(" if [ \"\" != \"${ISKDE}\" -a \"\" != \"${KDIALOG}\" -a \"\" != \"${DISPLAY}\" ]; then");
writer.println(" echo \"Dialog on Display: ${DISPLAY}\"");
writer.println(" ${KDIALOG} --title \"DMDirc: ${1}\" --error \"${2}\"");
writer.println(" elif [ \"\" != \"${ISGNOME}\" -a \"\" != \"${ZENITY}\" -a \"\" != \"${DISPLAY}\" ]; then");
writer.println(" echo \"Dialog on Display: ${DISPLAY}\"");
writer.println(" ${ZENITY} --error --title \"DMDirc: ${1}\" --text \"${2}\"");
writer.println(" elif [ \"\" != \"${DIALOG}\" ]; then");
writer.println(" ${DIALOG} --title \"[Error] DMDirc: ${1}\" --msgbox \"${2}\" 8 40");
writer.println(" fi");
writer.println("}");
if (isRoot()) {
writer.println("USER=`whoami`");
writer.println("if [ \"${USER}\" != \"root\" ]; then");
writer.println(" errordialog \"Uninstaller\" \"Uninstall Aborted. Only root can use this script\"");
writer.println(" exit 1;");
writer.println("fi");
}
writer.println("questiondialog \"Uninstaller\" \"Are you sure you want to uninstall DMDirc?\"");
writer.println("if [ $? -ne 0 ]; then");
writer.println(" messagedialog \"Uninstaller\" \"Uninstall Aborted.\"");
writer.println(" echo \"Uninstall Aborted\"");
writer.println(" exit 1;");
writer.println("fi");
writer.println("RUNNING=`${JAVA} -jar " + location + "/DMDirc.jar -e -v 2>&1 1>/dev/null | grep 'Unable to connect'`");
writer.println("if [ -z \"${RUNNING}\" ]; then");
writer.println(" errordialog \"Uninstaller\" \"Uninstall Aborted - DMDirc is still running.\nPlease close DMDirc before continuing\"");
writer.println(" echo \"Uninstall Aborted - DMDirc already running.\"");
writer.println(" exit 1;");
writer.println("fi");
writer.println("echo \"Uninstalling dmdirc\"");
writer.println("echo \"Removing Shortcuts..\"");
if (isRoot()) {
command = "${TOOL} --config-source=`${TOOL} --get-default-source`";
filename = "/usr/share/services/irc.protocol";
writer.println("rm -Rfv /usr/share/applications/DMDirc.desktop");
} else {
command = "${TOOL}";
filename = "~/.kde/share/services/irc.protocol";
writer.println("rm -Rfv "+System.getProperty("user.home")+"/.local/share/applications/DMDirc.desktop");
writer.println("rm -Rfv "+System.getProperty("user.home")+"/Desktop/DMDirc.desktop");
}
writer.println("TOOL=`which gconftool-2`");
writer.println("if [ \"${TOOL}\" != \"\" ]; then");
writer.println(" CURRENT=`"+command+" --get /desktop/gnome/url-handlers/irc/command`");
writer.println(" if [ \"${CURRENT}\" = \"\\\""+location+"/DMDirc.sh\\\" -e -c %s\" ]; then");
writer.println(" echo \"Removing Gnome Protocol Handler\"");
writer.println(" "+command+" --unset /desktop/gnome/url-handlers/irc/enabled");
writer.println(" "+command+" --unset /desktop/gnome/url-handlers/irc/command");
writer.println(" else");
writer.println(" echo \"Not Removing Gnome Protocol Handler\"");
writer.println(" fi");
writer.println("fi");
writer.println("if [ -e \""+filename+"\" ]; then");
writer.println(" CURRENT=`grep DMDirc "+filename+"`");
writer.println(" if [ \"\" != \"${CURRENT}\" ]; then");
writer.println(" echo \"Removing KDE Protocol Handler\"");
writer.println(" rm -Rfv "+filename);
writer.println(" else");
writer.println(" echo \"Not Removing KDE Protocol Handler\"");
writer.println(" fi");
writer.println("fi");
writer.println("echo \"Removing Installation Directory\"");
writer.println("rm -Rfv \""+location+"\"");
writer.println("PROFILEDIR=\"${HOME}/.DMDirc\"");
writer.println("if [ -e ${PROFILEDIR}/dmdirc.config ]; then");
writer.println(" questiondialog \"Uninstaller\" \"A dmdirc profile has been detected (${PROFILEDIR})\n Do you want to delete it aswell?\"");
writer.println(" if [ $? -eq 0 ]; then");
writer.println(" rm -Rfv \"${PROFILEDIR}\"");
writer.println(" fi");
writer.println("fi");
writer.println("messagedialog \"Uninstaller\" \"DMDirc Uninstalled Successfully\"");
writer.println("echo \"Done.\"");
new File(location+"/uninstall.sh").setExecutable(true);
return;
case PROTOCOL:
if (isRoot()) {
command = "${TOOL} --config-source=`${TOOL} --get-default-source`";
filename = "/usr/share/services/";
} else {
command = "${TOOL}";
filename = "${HOME}/.kde/share/services/";
}
writer = new PrintWriter(location+"/protocolHandlers.sh");
writer.println("#!/bin/sh");
writer.println("TOOL=`which gconftool-2`");
writer.println("if [ \"${TOOL}\" != \"\" ]; then");
writer.println("\t"+command+" --set --type=bool /desktop/gnome/url-handlers/irc/enabled true");
writer.println("\t"+command+" --set --type=string /desktop/gnome/url-handlers/irc/command \"\\\""+location+"/DMDirc.sh\\\" -e -c %s\"");
writer.println("\t"+command+" --set --type=bool /desktop/gnome/url-handlers/irc/need-terminal false");
writer.println("fi");
writer.println("if [ -e \""+filename+"\" ]; then");
writer.println("\techo \"[Protocol]\" > "+filename+"irc.protocol");
writer.println("\techo \"exec=\""+location+"/DMDirc.sh\" -e -c %u\" >> "+filename+"irc.protocol");
writer.println("\techo \"protocol=irc\" >> "+filename+"irc.protocol");
writer.println("\techo \"input=none\" >> "+filename+"irc.protocol");
writer.println("\techo \"output=none\" >> "+filename+"irc.protocol");
writer.println("\techo \"helper=true\" >> "+filename+"irc.protocol");
writer.println("\techo \"listing=false\" >> "+filename+"irc.protocol");
writer.println("\techo \"reading=false\" >> "+filename+"irc.protocol");
writer.println("\techo \"writing=false\" >> "+filename+"irc.protocol");
writer.println("\techo \"makedir=false\" >> "+filename+"irc.protocol");
writer.println("\techo \"deleting=false\" >> "+filename+"irc.protocol");
writer.println("fi");
writer.println("exit 0;");
writer.close();
final File protocolFile = new File(location+"/protocolHandlers.sh");
protocolFile.setExecutable(true);
try {
final Process gconfProcess = Runtime.getRuntime().exec(new String[]{"/bin/sh", location+"/protocolHandlers.sh"});
new StreamReader(gconfProcess.getInputStream()).start();
new StreamReader(gconfProcess.getErrorStream()).start();
try {
gconfProcess.waitFor();
} catch (InterruptedException e) { }
protocolFile.delete();
} catch (SecurityException e) {
step.addText(" - Error adding Protocol Handler: "+e.getMessage());
} catch (IOException e) {
step.addText(" - Error adding Protocol Handler: "+e.getMessage());
}
return;
default:
step.addText(" - Error creating shortcut. Not applicable to this Operating System");
return;
}
File temp = new File(filename);
if (!temp.getParentFile().exists()) {
temp.getParentFile().mkdir();
}
writer = new PrintWriter(filename);
writeFile(writer, location);
} catch (IOException e) {
step.addText(" - Error creating shortcut: "+e.toString());
} catch (SecurityException e) {
step.addText(" - Error creating shortcut: "+e.toString());
} finally {
if (writer != null) {
writer.close();
}
}
}
/**
* Write the .desktop file
*
* @param writer PrintWriter to write to
* @param location Location of installed files
* @throws IOException if an error occurs when writing
*/
private void writeFile(final PrintWriter writer, final String location) throws IOException {
writer.println("[Desktop Entry]");
writer.println("Categories=Network;IRCClient;");
writer.println("Comment=DMDirc IRC Client");
writer.println("Encoding=UTF-8");
// writer.println("Exec=java -jar "+location+"/DMDirc.jar");
writer.println("Exec="+location+"/DMDirc.sh");
writer.println("GenericName=IRC Client");
writer.println("Icon="+location+"/icon.svg");
if (isRoot()) {
writer.println("Name=DMDirc (Global)");
} else {
writer.println("Name=DMDirc");
}
writer.println("StartupNotify=true");
writer.println("Terminal=false");
writer.println("TerminalOptions=");
writer.println("Type=Application");
}
/**
* Any post-install tasks should be done here.
*
* @param location Location where app was installed to.
*/
public void postInstall(final String location) {
new File(location+"/DMDirc.sh").setExecutable(true, !isRoot());
}
}
|
package com.ecyrd.jspwiki.xmlrpc;
import java.io.*;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.*;
import java.util.*;
/**
* Provides handlers for all RPC routines.
*
* @author Janne Jalkanen
* @since 1.6.6
*/
// We could use WikiEngine directly, but because of introspection it would
// show just too many methods to be safe.
public class RPCHandler
{
private WikiEngine m_engine;
public RPCHandler( WikiEngine engine )
{
m_engine = engine;
}
public String getApplicationName()
{
return m_engine.getApplicationName();
}
public Vector getAllPages()
{
Collection pages = m_engine.getRecentChanges();
Vector result = new Vector();
int count = 0;
for( Iterator i = pages.iterator(); i.hasNext(); )
{
result.add( ((WikiPage)i.next()).getName() );
}
return result;
}
private Hashtable encodeWikiPage( WikiPage page )
{
Hashtable ht = new Hashtable();
ht.put( "name", page.getName() );
ht.put( "lastModified", page.getLastModified() );
ht.put( "version", new Integer(page.getVersion()) );
ht.put( "author", page.getAuthor() );
return ht;
}
public Vector getRecentChanges( Date since )
{
Collection pages = m_engine.getRecentChanges();
Vector result = new Vector();
for( Iterator i = pages.iterator(); i.hasNext(); )
{
WikiPage page = (WikiPage)i.next();
if( page.getLastModified().after( since ) )
{
result.add( encodeWikiPage( page ) );
}
}
return result;
}
public Hashtable getPageInfo( String pagename )
{
return encodeWikiPage( m_engine.getPage(pagename) );
}
public Hashtable getPageInfo( String pagename, int version )
{
return encodeWikiPage( m_engine.getPage( pagename, version ) );
}
public String getPage( String pagename )
{
return m_engine.getPureText( pagename, -1 );
}
public String getPage( String pagename, int version )
{
return m_engine.getPureText( pagename, version );
}
public String getPageHTML( String pagename )
{
return m_engine.getHTML( pagename );
}
public String getPageHTML( String pagename, int version )
{
return m_engine.getHTML( pagename, version );
}
}
|
package com.esotericsoftware.kryo.util;
import static com.esotericsoftware.minlog.Log.*;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.SerializerFactory;
import com.esotericsoftware.kryo.serializers.FieldSerializer;
import com.esotericsoftware.kryo.util.Generics.GenericType;
import java.lang.reflect.Type;
/** A few utility methods, mostly for private use.
* @author Nathan Sweet */
public class Util {
static public final boolean isAndroid = "Dalvik".equals(System.getProperty("java.vm.name"));
/** True if Unsafe is available. */
static public final boolean unsafe;
static {
boolean found = false;
try {
found = Class.forName("com.esotericsoftware.kryo.unsafe.UnsafeUtil", true, FieldSerializer.class.getClassLoader())
.getField("unsafe").get(null) != null;
} catch (Throwable ex) {
if (TRACE) trace("kryo", "Unsafe is unavailable.", ex);
}
unsafe = found;
}
static public final int maxArraySize = Integer.MAX_VALUE - 8;
static public boolean isClassAvailable (String className) {
try {
Class.forName(className);
return true;
} catch (Exception ex) {
debug("kryo", "Class not available: " + className);
return false;
}
}
/** Returns the primitive wrapper class for a primitive class.
* @param type Must be a primitive class. */
static public Class getWrapperClass (Class type) {
if (type == int.class) return Integer.class;
if (type == float.class) return Float.class;
if (type == boolean.class) return Boolean.class;
if (type == byte.class) return Byte.class;
if (type == long.class) return Long.class;
if (type == char.class) return Character.class;
if (type == double.class) return Double.class;
if (type == short.class) return Short.class;
return Void.class;
}
/** Returns the primitive class for a primitive wrapper class. Otherwise returns the type parameter.
* @param type Must be a wrapper class. */
static public Class getPrimitiveClass (Class type) {
if (type == Integer.class) return int.class;
if (type == Float.class) return float.class;
if (type == Boolean.class) return boolean.class;
if (type == Byte.class) return byte.class;
if (type == Long.class) return long.class;
if (type == Character.class) return char.class;
if (type == Double.class) return double.class;
if (type == Short.class) return short.class;
if (type == Void.class) return void.class;
return type;
}
static public boolean isWrapperClass (Class type) {
return type == Integer.class || type == Float.class || type == Boolean.class || type == Byte.class || type == Long.class
|| type == Character.class || type == Double.class || type == Short.class;
}
static public boolean isEnum (Class type) {
// Use this rather than type.isEnum() to return true for an enum value that is an inner class, eg: enum A {b{}}
return Enum.class.isAssignableFrom(type) && type != Enum.class;
}
/** Logs a message about an object. The log level and the string format of the object depend on the object type. */
static public void log (String message, Object object, int position) {
if (object == null) {
if (TRACE) trace("kryo", message + ": null" + pos(position));
return;
}
Class type = object.getClass();
if (type.isPrimitive() || isWrapperClass(type) || type == String.class) {
if (TRACE) trace("kryo", message + ": " + string(object) + pos(position));
} else
debug("kryo", message + ": " + string(object) + pos(position));
}
static public String pos (int position) {
return position == -1 ? "" : " [" + position + "]";
}
/** Returns the object formatted as a string. The format depends on the object's type and whether {@link Object#toString()} has
* been overridden. */
static public String string (Object object) {
if (object == null) return "null";
Class type = object.getClass();
if (type.isArray()) return className(type);
String className = TRACE ? className(type) : type.getSimpleName();
try {
if (type.getMethod("toString", new Class[0]).getDeclaringClass() == Object.class) return className;
} catch (Exception ignored) {
}
try {
String value = String.valueOf(object) + " (" + className + ")";
return value.length() > 97 ? value.substring(0, 97) + "..." : value;
} catch (Throwable ex) {
return className + " (toString exception: " + ex + ")";
}
}
/** Returns the class formatted as a string. The format varies depending on the type. */
static public String className (Class type) {
if (type == null) return "null";
if (type.isArray()) {
Class elementClass = getElementClass(type);
StringBuilder buffer = new StringBuilder(16);
for (int i = 0, n = getDimensionCount(type); i < n; i++)
buffer.append("[]");
return className(elementClass) + buffer;
}
if (type.isPrimitive() || type == Object.class || type == Boolean.class || type == Byte.class || type == Character.class
|| type == Short.class || type == Integer.class || type == Long.class || type == Float.class || type == Double.class
|| type == String.class) {
return type.getSimpleName();
}
return type.getName();
}
/** Returns the classes formatted as a string. The format varies depending on the type. */
static public String classNames (Class[] types) {
StringBuilder buffer = new StringBuilder(32);
for (int i = 0, n = types.length; i < n; i++) {
if (i > 0) buffer.append(", ");
buffer.append(className(types[i]));
}
return buffer.toString();
}
static public String simpleName (Type type) {
if (type instanceof Class) return ((Class)type).getSimpleName();
return type.toString(); // Java 8: getTypeName
}
static public String simpleName (Class type, GenericType genericType) {
StringBuilder buffer = new StringBuilder(32);
buffer.append((type.isArray() ? getElementClass(type) : type).getSimpleName());
if (genericType.arguments != null) {
buffer.append('<');
for (int i = 0, n = genericType.arguments.length; i < n; i++) {
if (i > 0) buffer.append(", ");
buffer.append(genericType.arguments[i].toString());
}
buffer.append('>');
}
if (type.isArray()) {
for (int i = 0, n = getDimensionCount(type); i < n; i++)
buffer.append("[]");
}
return buffer.toString();
}
/** Returns the number of dimensions of an array. */
static public int getDimensionCount (Class arrayClass) {
int depth = 0;
Class nextClass = arrayClass.getComponentType();
while (nextClass != null) {
depth++;
nextClass = nextClass.getComponentType();
}
return depth;
}
/** Returns the base element type of an n-dimensional array class. */
static public Class getElementClass (Class arrayClass) {
Class elementClass = arrayClass;
while (elementClass.getComponentType() != null)
elementClass = elementClass.getComponentType();
return elementClass;
}
static public boolean isAscii (String value) {
for (int i = 0, n = value.length(); i < n; i++)
if (value.charAt(i) > 127) return false;
return true;
}
/** @param factoryClass Must have a constructor that takes a serializer class, or a zero argument constructor.
* @param serializerClass May be null if the factory already knows the serializer class to create. */
static public <T extends SerializerFactory> T newFactory (Class<T> factoryClass, Class<? extends Serializer> serializerClass) {
try {
if (serializerClass != null) {
try {
return factoryClass.getConstructor(Class.class).newInstance(serializerClass);
} catch (NoSuchMethodException ex) {
}
}
return factoryClass.newInstance();
} catch (Exception ex) {
if (serializerClass == null)
throw new IllegalArgumentException("Unable to create serializer factory: " + factoryClass.getName(), ex);
else {
throw new IllegalArgumentException("Unable to create serializer factory \"" + factoryClass.getName()
+ "\" for serializer class: " + className(serializerClass), ex);
}
}
}
}
|
package com.hp.hpl.jena.util;
import java.io.InputStream;
import java.util.*;
import com.hp.hpl.jena.JenaRuntime;
import com.hp.hpl.jena.vocabulary.LocationMappingVocab;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.shared.JenaException;
import org.apache.commons.logging.*;
/**
* Alternative locations for URIs. Maintains two maps:
* single item alternatives and alternative prefixes.
* To suggest an alternative location, first check the single items,
* then check the prefixes.
*
* A LocationMapper can be configured by an RDF file. The default for this
* is "etc/location-mapping.n3".
*
* There is a default LocationMapper which is used by the global @link{FileManager}.
*
* @see FileManager
*
* @author Andy Seaborne
* @version $Id: LocationMapper.java,v 1.8 2005-03-18 21:34:50 andy_seaborne Exp $
*/
public class LocationMapper
{
static Log log = LogFactory.getLog(LocationMapper.class) ;
/** The default path for searching for the location mapper */
public static final String DEFAULT_PATH =
"file:location-mapping.rdf;file:location-mapping.n3;" +
"file:etc/location-mapping.rdf;file:etc/location-mapping.n3;" ;
public static final String GlobalMapperSystemProperty1 = "http://jena.hpl.hp.com/2004/08/LocationMap" ;
public static final String GlobalMapperSystemProperty2 = "LocationMap" ;
static String s_globalMapperPath = null ;
Map altLocations = new HashMap() ;
Map altPrefixes = new HashMap() ;
static LocationMapper theMapper = null ;
/** Get the global LocationMapper */
public static LocationMapper get()
{
if ( theMapper == null )
{
theMapper = new LocationMapper() ;
if ( getGlobalConfigPath() != null )
theMapper.initFromPath(getGlobalConfigPath(), false) ;
}
return theMapper ;
}
/** Create a LocationMapper with no mapping yet */
public LocationMapper() { }
/** Create a LocationMapper from an existing model
* @see com.hp.hpl.jena.vocabulary.LocationMappingVocab;
*/
public LocationMapper(Model model)
{
processConfig(model) ;
}
/** Create a LocationMapper from a config file */
public LocationMapper(String config)
{
initFromPath(config, true) ;
}
private void initFromPath(String configPath, boolean configMustExist)
{
if ( configPath == null )
{
log.warn("Null configuration") ;
return ;
}
// Make a file manager to look for the location mapping file
FileManager fm = new FileManager() ;
fm.addLocatorFile() ;
fm.addLocatorClassLoader(fm.getClass().getClassLoader()) ;
try {
String uriConfig = null ;
InputStream in = null ;
StringTokenizer pathElems = new StringTokenizer( configPath, FileManager.PATH_DELIMITER );
while (pathElems.hasMoreTokens()) {
String uri = pathElems.nextToken();
in = fm.openNoMap(uri) ;
if ( in != null )
{
uriConfig = uri ;
break ;
}
}
if ( in == null )
{
if ( ! configMustExist )
log.debug("Failed to find configuration: "+configPath) ;
return ;
}
String syntax = FileUtils.guessLang(uriConfig) ;
Model model = ModelFactory.createDefaultModel() ;
model.read(in, null, syntax) ;
processConfig(model) ;
} catch (JenaException ex)
{
LogFactory.getLog(LocationMapper.class).warn("Error in configuration file: "+ex.getMessage()) ;
}
}
public String altMapping(String uri)
{
return altMapping(uri, uri) ;
}
/** Apply mappings: first try for an exact alternative location, then
* try to remap by prefix, finally, try the special case of filenames
* in a specific base directory.
* @param uri
* @param otherwise
* @return The alternative location choosen
*/
public String altMapping(String uri, String otherwise)
{
if ( altLocations.containsKey(uri))
return (String)altLocations.get(uri) ;
String newStart = null ;
String oldStart = null ;
for ( Iterator iter = altPrefixes.keySet().iterator() ; iter.hasNext() ;)
{
String prefix = (String)iter.next() ;
if ( uri.startsWith(prefix) )
{
String s = (String)altPrefixes.get(prefix) ;
if ( newStart == null || newStart.length() < s.length() )
{
oldStart = prefix ;
newStart = s ;
}
}
}
if ( newStart != null )
return newStart+uri.substring(oldStart.length()) ;
return otherwise ;
}
public void addAltEntry(String uri, String alt)
{
altLocations.put(uri, alt) ;
}
public void addAltPrefix(String uriPrefix, String altPrefix)
{
altPrefixes.put(uriPrefix, altPrefix) ;
}
/** Iterate over all the entries registered */
public Iterator listAltEntries() { return altLocations.keySet().iterator() ; }
/** Iterate over all the prefixes registered */
public Iterator listAltPrefixes() { return altPrefixes.keySet().iterator() ; }
public void removeAltEntry(String uri)
{
altLocations.remove(uri) ;
}
public void removeAltPrefix(String uriPrefix)
{
altPrefixes.remove(uriPrefix) ;
}
public String getAltEntry(String uri)
{
return (String)altLocations.get(uri) ;
}
public String getAltPrefix(String uriPrefix)
{
return (String)altPrefixes.get(uriPrefix) ;
}
static private String getGlobalConfigPath()
{
if ( s_globalMapperPath == null )
s_globalMapperPath = JenaRuntime.getSystemProperty(GlobalMapperSystemProperty1,null) ;
if ( s_globalMapperPath == null )
s_globalMapperPath = JenaRuntime.getSystemProperty(GlobalMapperSystemProperty2,null) ;
if ( s_globalMapperPath == null )
s_globalMapperPath = DEFAULT_PATH ;
return s_globalMapperPath ;
}
public String toString()
{
String s = "" ;
for ( Iterator iter = altLocations.keySet().iterator() ; iter.hasNext() ; )
{
String k = (String)iter.next() ;
String v = (String)altLocations.get(k) ;
s = s+"(Loc:"+k+"=>"+v+") " ;
}
for ( Iterator iter = altPrefixes.keySet().iterator() ; iter.hasNext() ; )
{
String k = (String)iter.next() ;
String v = (String)altLocations.get(k) ;
s = s+"(Prefix:"+k+"=>"+v+") " ;
}
return s ;
}
private void processConfig(Model m)
{
StmtIterator mappings =
m.listStatements(null, LocationMappingVocab.mapping, (RDFNode)null) ;
for (; mappings.hasNext();)
{
Statement s = mappings.nextStatement() ;
Resource mapping = s.getResource() ;
if ( mapping.hasProperty(LocationMappingVocab.name) )
{
try
{
String name = mapping.getRequiredProperty(LocationMappingVocab.name)
.getString() ;
String altName = mapping.getRequiredProperty(LocationMappingVocab.altName)
.getString() ;
addAltEntry(name, altName) ;
log.debug("Mapping: "+name+" => "+altName) ;
} catch (JenaException ex)
{
log.warn("Error processing name mapping: "+ex.getMessage()) ;
return ;
}
}
if ( mapping.hasProperty(LocationMappingVocab.prefix) )
{
try
{
String prefix = mapping.getRequiredProperty(LocationMappingVocab.prefix)
.getString() ;
String altPrefix = mapping.getRequiredProperty(LocationMappingVocab.altPrefix)
.getString() ;
addAltPrefix(prefix, altPrefix) ;
log.debug("Prefix mapping: "+prefix+" => "+altPrefix) ;
} catch (JenaException ex)
{
log.warn("Error processing prefix mapping: "+ex.getMessage()) ;
return ;
}
}
}
}
}
|
package com.opencms.core;
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import javax.servlet.*;
import javax.servlet.http.*;
import source.org.apache.java.io.*;
import source.org.apache.java.util.*;
import com.opencms.boot.*;
import com.opencms.file.*;
import com.opencms.util.*;
public class OpenCmsHttpServlet extends HttpServlet implements I_CmsConstants,I_CmsLogChannels {
/**
* Debug-switch
*/
static final boolean C_DEBUG = false;
/**
* The name of the redirect entry in the configuration file.
*/
static final String C_PROPERTY_REDIRECT = "redirect";
/**
* The name of the redirect location entry in the configuration file.
*/
static final String C_PROPERTY_REDIRECTLOCATION = "redirectlocation";
/**
* The configuration for the OpenCms servlet.
*/
private Configurations m_configurations;
/**
* The session storage for all active users.
*/
private CmsCoreSession m_sessionStorage;
/**
* The reference to the OpenCms system.
*/
private A_OpenCms m_opencms;
/**
* Storage for redirects.
*/
private Vector m_redirect = new Vector();
/**
* Storage for redirect locations.
*/
private Vector m_redirectlocation = new Vector();
/**
* Storage for the clusterurl
*/
private String m_clusterurl = null;
/**
* The total amount of concurrent requests.
*/
private int m_currentRequestAmount = 0;
/**
* Checks if the requested resource must be redirected to the server docroot and
* excecutes the redirect if nescessary.
* @param cms The CmsObject
* @exeption Throws CmsException if something goes wrong.
*/
private void checkRelocation(CmsObject cms) throws CmsException {
CmsRequestContext context = cms.getRequestContext();
// check the if the current project is the online project. Only in this project,
// a redirect is nescessary.
if(context.currentProject().equals(cms.onlineProject())) {
String filename = context.getUri();
// check all redirect locations
for(int i = 0;i < m_redirect.size();i++) {
String redirect = (String)m_redirect.elementAt(i);
// found a match, so redirect
if(filename.startsWith(redirect)) {
String redirectlocation = (String)m_redirectlocation.elementAt(i);
String doRedirect = redirectlocation + filename.substring(redirect.length());
// try to redirect
try {
((HttpServletResponse)context.getResponse().getOriginalResponse()).sendRedirect(doRedirect);
}
catch(Exception e) {
throw new CmsException("Redirect fails :" + doRedirect, CmsException.C_UNKNOWN_EXCEPTION, e);
}
}
}
}
}
/**
* Generates a formated exception output. <br>
* Because the exception could be thrown while accessing the system files,
* the complete HTML code must be added here!
* @param e The caught CmsException.
* @return String containing the HTML code of the error message.
*/
private String createErrorBox(CmsException e, CmsObject cms) {
StringBuffer output = new StringBuffer();
output.append("<HTML>\n");
output.append("<script language=JavaScript>\n");
output.append("<!
output.append("function show_help()\n");
output.append("{\n");
output.append("return '2_2_2_2_5_5_1.html';\n");
output.append("}\n");
output.append("var shown=false;\n");
output.append("function checkBrowser(){\n");
output.append("this.ver=navigator.appVersion\n");
output.append("this.dom=document.getElementById?1:0\n");
output.append("this.ie5=(this.ver.indexOf(\"MSIE 5\")>-1 && this.dom)?1:0;\n");
output.append("this.ie4=(document.all && !this.dom)?1:0;\n");
output.append("this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;\n");
output.append("this.ns4=(document.layers && !this.dom)?1:0;\n");
output.append("this.bw=(this.ie5 || this.ie4 || this.ns4 || this.ns5)\n");
output.append("return this\n");
output.append("}\n");
output.append("bw=new checkBrowser();\n");
output.append("function makeObj(obj,nest){\n");
output.append("nest=(!nest) ? '':'document.'+nest+'.';\n");
output.append("this.el=bw.dom?document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?eval(nest+'document.'+obj):0;\n");
output.append("this.css=bw.dom?document.getElementById(obj).style:bw.ie4?document.all[obj].style:bw.ns4?eval(nest+'document.'+obj):0;\n");
output.append("this.scrollHeight=bw.ns4?this.css.document.height:this.el.offsetHeight; \n");
output.append("this.clipHeight=bw.ns4?this.css.clip.height:this.el.offsetHeight;\n");
output.append("this.obj = obj + \"Object\";\n");
output.append("eval(this.obj + \"=this\");\n");
output.append("return this;\n");
output.append("}\n");
output.append("ns = (document.layers)? true:false;\n");
output.append("ie = (document.all)? true:false;\n");
output.append("if(ns)\n");
output.append("{\n");
output.append("var layerzeigen_01= 'document.layers.';\n");
output.append("var layerzeigen_02= '.visibility=\"show\"';\n");
output.append("var layerverstecken_01= 'document.layers.';\n");
output.append("var layerverstecken_02= '.visibility=\"hide\"';\n");
output.append("}\n");
output.append("else\n");
output.append("{\n");
output.append("var layerzeigen_01= 'document.all.';\n");
output.append("var layerzeigen_02= '.style.visibility=\"visible\"';\n");
output.append("var layerverstecken_01= 'document.all.';\n");
output.append("var layerverstecken_02= '.style.visibility=\"hidden\"';\n");
output.append("}\n");
output.append("function getWindowWidth() {\n");
output.append("if( ns==true ) {\n");
output.append("windowWidth = innerWidth;\n");
output.append("}\n");
output.append("else if( ie==true ) {\n");
output.append("windowWidth = document.body.clientWidth;\n");
output.append("}\n");
output.append("return windowWidth;\n");
output.append("}\n");
output.append("function centerLayer(layerName){\n");
output.append("totalWidth=getWindowWidth();\n");
output.append("if (ie) {\n");
output.append("eval('lyrWidth = document.all[\"'+ layerName +'\"].offsetWidth');\n");
output.append("eval('document.all[\"'+ layerName +'\"].style.left=Math.round((totalWidth-lyrWidth)/2)');\n");
output.append("}\n");
output.append("else if (ns) {\n");
output.append("eval('lyrWidth = document[\"'+ layerName +'\"].clip.width');\n");
output.append("eval('document[\"'+ layerName +'\"].left=Math.round((totalWidth-lyrWidth)/2)');\n");
output.append("}\n");
output.append("}\n");
output.append("function justifyLayers(lyr1,lyr2) {\n");
output.append("if (ie) {\n");
output.append("eval('y1 = document.all[\"'+ lyr1 +'\"].offsetTop');\n");
output.append("eval('lyrHeight = document.all[\"'+ lyr1 +'\"].offsetHeight');\n");
output.append("y2 = y1 + lyrHeight;\n");
output.append("eval('document.all[\"'+ lyr2 +'\"].style.top = y2-22');\n");
output.append("}\n");
output.append("else if (ns) {\n");
output.append("eval('y1 = document[\"'+ lyr1 +'\"].top');\n");
output.append("eval('lyrHeight = document[\"'+ lyr1 +'\"].clip.height');\n");
output.append("y2 = y1 + lyrHeight; \n");
output.append("eval('document[\"'+ lyr2 +'\"].top = y2-22');\n");
output.append("}\n");
output.append("}\n");
output.append("function chInputTxt(formName,field,txt,layerName)\n");
output.append("{\n");
output.append("if (ie || layerName==null)\n");
output.append("eval('document.' + formName +'.'+ field + '.value=\"'+ txt +'\";');\n");
output.append("else if (ns && layerName!=null) \n");
output.append("eval('document[\"'+layerName+'\"].document.forms[\"'+formName+'\"].'+ field + '.value=\"'+ txt +'\";');\n");
output.append("}\n");
output.append("function chButtonTxt(formName,field,txt1,txt2,layerName)\n");
output.append("{\n");
output.append("if (shown)\n");
output.append("chInputTxt(formName,field,txt2,layerName);\n");
output.append("else\n");
output.append("chInputTxt(formName,field,txt1,layerName);\n");
output.append("}\n");
output.append("function newObj(layerName,visibility){\n");
output.append("eval('oCont=new makeObj(\"'+ layerName +'\")');\n");
output.append("eval('oCont.css.visibility=\"'+ visibility +'\"');\n");
output.append("eval('centerLayer(\"'+ layerName +'\")');\n");
output.append("}\n");
output.append("function showlyr(welche)\n");
output.append("{\n");
output.append("eval(layerzeigen_01+welche+layerzeigen_02);\n");
output.append("}\n");
output.append("function hidelyr(welche)\n");
output.append("{\n");
output.append("eval(layerverstecken_01+welche+layerverstecken_02);\n");
output.append("}\n");
output.append("function toggleLayer(layerName)\n");
output.append("{\n");
output.append("if (shown) {\n");
output.append("eval('hidelyr(\"'+ layerName +'\")');\n");
output.append("shown=false;\n");
output.append("}\n");
output.append("else {\n");
output.append("eval('showlyr(\"'+ layerName +'\")');\n");
output.append("shown=true;\n");
output.append("}\n");
output.append("}\n");
output.append("function resized(){\n");
output.append("pageWidth2=bw.ns4?innerWidth:document.body.offsetWidth;\n");
output.append("pageHeight2=bw.ns4?innerHeight:document.body.offsetHeight;\n");
output.append("if(pageWidth!=pageWidth2 || pageHeight!=pageHeight2) location.reload();\n");
output.append("}\n");
output.append("function errorinit() {\n");
output.append("newObj('errormain','hidden');\n");
output.append("newObj('errordetails','hidden');\n");
output.append("justifyLayers('errormain','errordetails');\n");
output.append("showlyr('errormain');\n");
output.append("pageWidth=bw.ns4?innerWidth:document.body.offsetWidth;\n");
output.append("pageHeight=bw.ns4?innerHeight:document.body.offsetHeight;\n");
output.append("window.onresize=resized;\n");
output.append("}\n");
output.append("
output.append("</script>\n");
output.append("<head>\n");
output.append("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">\n");
output.append("<title>OpenCms-Systemfehler</title>\n");
output.append("<style type=\"text/css\">\n");
output.append("TD.dialogtxt\n");
output.append("{\n");
output.append("BACKGROUND-COLOR: #c0c0c0;\n");
output.append("COLOR: #000000;\n");
output.append("FONT-FAMILY: MS sans serif,arial,helvetica,sans-serif;\n");
output.append("FONT-SIZE: 8px;\n");
output.append("FONT-WEIGHT: normal\n");
output.append("}\n");
output.append("TD.head\n");
output.append("{\n");
output.append("BACKGROUND-COLOR: #000066;\n");
output.append("COLOR: white;\n");
output.append("FONT-FAMILY: MS Sans Serif, Arial, helevitca, sans-serif;\n");
output.append("FONT-SIZE: 8px;\n");
output.append("FONT-WEIGHT: bold\n");
output.append("}\n");
output.append("TD.leerzeile\n");
output.append("{\n");
output.append("BACKGROUND-COLOR: #c0c0c0;\n");
output.append("HEIGHT: 3px;\n");
output.append("PADDING-BOTTOM: 0px;\n");
output.append("PADDING-LEFT: 10px;\n");
output.append("PADDING-RIGHT: 10px\n");
output.append("}\n");
output.append("TD.formular\n");
output.append("{\n");
output.append("BACKGROUND-COLOR: #c0c0c0;\n");
output.append("COLOR: black;\n");
output.append("FONT-FAMILY: MS Sans Serif, Arial, helvetica, sans-serif;\n");
output.append("FONT-SIZE: 8px;\n");
output.append("FONT-WEIGHT: bold\n");
output.append("}\n");
output.append("INPUT.button\n");
output.append("{\n");
output.append("COLOR: black;\n");
output.append("FONT-FAMILY: MS Sans Serif, Arial, helvetica, sans-serif;\n");
output.append("FONT-SIZE: 8px;\n");
output.append("FONT-WEIGHT: normal;\n");
output.append("WIDTH: 100px;\n");
output.append("}\n");
output.append("TEXTAREA.textarea\n");
output.append("{\n");
output.append("COLOR: #000000;\n");
output.append("FONT-FAMILY: MS Sans Serif, Arial, helvetica, sans-serif;\n");
output.append("FONT-SIZE: 8px;\n");
output.append("WIDTH: 300px\n");
output.append("}\n");
output.append("#errormain{position:absolute; top:78; left:0; width:350; visibility:hidden; z-index:10; }\n");
output.append("#errordetails{position:absolute; top:78; left:0; width:350; visibility:hidden; z-index:100}\n");
output.append("</style>\n");
output.append("</HEAD>\n");
output.append("<BODY onLoad=\"errorinit();\" bgcolor=\"#ffffff\" marginwidth = 0 marginheight = 0 topmargin=0 leftmargin=0>\n");
output.append("<div id=\"errormain\">\n");
output.append("<!-- Tabellenaufbau f?r Dialog mit OK und Abbrechen-->\n");
output.append("<form id=ERROR name=ERROR>\n");
output.append("<table cellspacing=0 cellpadding=0 border=2 width=350>\n");
output.append("<tr><td class=dialogtxt>\n");
output.append("<table cellspacing=0 cellpadding=5 border=0 width=100% height=100%>\n");
output.append("<!-- Beginn Tabellenkopf blau-->\n");
output.append("<tr> \n");
output.append("<td colspan=2 class=\"head\">Systemfehler</td>\n");
output.append("</tr>\n");
output.append("<!-- Ende Tabellenkopf blau-->\n");
output.append("<!-- Beginn Leerzeile-->\n");
output.append("<tr> <td colspan=2 class=\"leerzeile\"> </td></tr>\n");
output.append("<!-- Ende Leerzeile-->\n");
output.append("<tr> \n");
output.append("<td class=\"dialogtxt\" rowspan=3 valign=top><IMG border=0 src=\"" + cms.getRequestContext().getRequest().getWebAppUrl() + "/pics/system/ic_caution.gif\" width=32 height=32></td>\n");
output.append("<td class=dialogtxt>Ein Systemfehler ist aufgetreten.</td>\n");
output.append("</tr> \n");
output.append("<tr><td class=dialogtxt>Für weitere Informationen klicken Sie auf \"Details anzeigen\" oder kontaktieren Sie Ihren Systemadministrator.</td></tr>\n");
output.append("<!-- Beginn Leerzeile-->\n");
output.append("<tr> <td class=\"leerzeile\"> </td></tr>\n");
output.append("<!-- Ende Leerzeile-->\n");
output.append("<!-- Beginn Buttonleisete-->\n");
output.append("<tr><td class=dialogtxt colspan=2>\n");
output.append("<table cellspacing=0 cellpadding=5 width=100%>\n");
output.append("<tr>\n");
output.append("<td class=formular align=center><INPUT class=button width = 100 type=\"button\" value=\"OK\" id=OK name=OK onClick=\"history.back();\"></td>\n");
output.append("<td class=formular align=center><INPUT class=button width = 100 type=\"button\" value=\"Details anzeigen\" id=details name=details onClick=\"toggleLayer('errordetails');chButtonTxt('ERROR','details','Details anzeigen','Details verbergen','errormain')\"></td>\n");
output.append("</tr>\n");
output.append("</table>\n");
output.append("</td>\n");
output.append("</tr>\n");
output.append("</table>\n");
output.append("<!-- Ende Buttonleisete--> \n");
output.append("</td></tr>\n");
output.append("</table>\n");
output.append("</form>\n");
output.append("</div>\n");
output.append("<div id=\"errordetails\">\n");
output.append("<form id=DETAILS name=DETAILS>\n");
output.append("<table cellspacing=0 cellpadding=0 border=2 width=350>\n");
output.append("<tr><td class=dialogtxt>\n");
output.append("<table cellspacing=1 cellpadding=5 border=0 width=100% height=100%>\n");
output.append("<tr><td class=formular>Fehlermeldung:</td>\n");
output.append("<tr><td align=center class=dialogtxt>\n");
output.append("<textarea wrap=off cols=33 rows=6 style=\"width:330\" class=\"textarea\" onfocus=\"this.blur();\" id=EXCEPTION name=EXCEPTION>");
output.append(Utils.getStackTrace(e));
output.append("</textarea>\n");
output.append("</td></tr>\n");
output.append("</table>\n");
output.append("</td></tr>\n");
output.append("</table>\n");
output.append("</form>\n");
output.append("</div> \n");
output.append("</BODY>\n");
output.append("</html>\n");
return output.toString();
}
/**
* Destroys all running threads before closing the VM.
*/
public void destroy() {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] Performing Shutdown....");
}
try {
m_opencms.destroy();
}
catch(CmsException e) {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[OpenCmsServlet]" + e.toString());
}
}
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[OpenCmsServlet] Shutdown Completed");
}
}
/**
* Method invoked on each HTML GET request.
* <p>
* (Overloaded Servlet API method, requesting a document).
* Reads the URI received from the client and invokes the appropiate action.
*
* @param req The clints request.
* @param res The servlets response.
* @exception ServletException Thrown if request fails.
* @exception IOException Thrown if user autherization fails.
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
// start time of this request
if(C_DEBUG) {
long reqStartTime = System.currentTimeMillis();
}
if(req.getRequestURI().indexOf("system/workplace/action/login.html") > 0) {
HttpSession session = req.getSession(false);
if(session != null) {
session.invalidate();
}
}
CmsObject cms = null;
CmsRequestHttpServlet cmsReq = new CmsRequestHttpServlet(req);
CmsResponseHttpServlet cmsRes = new CmsResponseHttpServlet(req, res, m_clusterurl);
try {
cms = initUser(cmsReq, cmsRes);
checkRelocation(cms);
CmsFile file = m_opencms.initResource(cms);
if(file != null) {
// If the CmsFile object is null, the resource could not be found.
// Stop processing in this case to avoid NullPointerExceptions
m_opencms.setResponse(cms, file);
m_opencms.showResource(cms, file);
updateUser(cms, cmsReq, cmsRes);
}
}
catch(CmsException e) {
errorHandling(cms, cmsReq, cmsRes, e);
}
// create debug informations
if(C_DEBUG) {
long total = Runtime.getRuntime().totalMemory() / 1024;
long free = Runtime.getRuntime().freeMemory() / 1024;
System.err.print(new Date() + " doGet() reqAm:" + m_currentRequestAmount + " users:" + m_sessionStorage.size());
System.err.print((" [" + total + "/" + free + "/" + (total - free) + "] "));
System.err.print("threads:" + Thread.activeCount() + " ");
System.err.println(cmsReq.getRequestedResource() + " " + cms.getRequestContext().currentUser().getName());
}
}
/**
* Method invoked on each HTML POST request.
* <p>
* (Overloaded Servlet API method, posting a document)
* The OpenCmsMultipartRequest is invoked to upload a new document into OpenCms.
*
* @param req The clints request.
* @param res The servlets response.
* @exception ServletException Thrown if request fails.
* @exception IOException Thrown if user autherization fails.
*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
// start time of this request
if(C_DEBUG) {
long reqStartTime = System.currentTimeMillis();
}
//Check for content type "form/multipart" and decode it
String type = req.getHeader("content-type");
CmsObject cms = null;
if((type != null) && type.startsWith("multipart/form-data")) {
// req = new CmsMultipartRequest(req);
}
CmsRequestHttpServlet cmsReq = new CmsRequestHttpServlet(req);
CmsResponseHttpServlet cmsRes = new CmsResponseHttpServlet(req, res, m_clusterurl);
try {
cms = initUser(cmsReq, cmsRes);
checkRelocation(cms);
CmsFile file = m_opencms.initResource(cms);
if(file != null) {
// If the CmsFile object is null, the resource could not be found.
// Stop processing in this case to avoid NullPointerExceptions
m_opencms.setResponse(cms, file);
m_opencms.showResource(cms, file);
updateUser(cms, cmsReq, cmsRes);
}
}
catch(CmsException e) {
errorHandling(cms, cmsReq, cmsRes, e);
}
// create debug informations
if(C_DEBUG) {
long total = Runtime.getRuntime().totalMemory() / 1024;
long free = Runtime.getRuntime().freeMemory() / 1024;
System.err.print(new Date() + " doPost() reqAm:" + m_currentRequestAmount + " users:" + m_sessionStorage.size());
System.err.print((" [" + total + "/" + free + "/" + (total - free) + "] "));
System.err.print("threads:" + Thread.activeCount() + " ");
System.err.println(cmsReq.getRequestedResource() + " " + cms.getRequestContext().currentUser().getName());
}
}
/**
* This method performs the error handling for the OpenCms.
* All CmsExetions throns in the OpenCms are forwared to this method and are
* processed here.
*
* @param cms The CmsObject
* @param cmsReq The clints request.
* @param cmsRes The servlets response.
* @param e The CmsException to be processed.
*/
private void errorHandling(CmsObject cms, I_CmsRequest cmsReq, I_CmsResponse cmsRes, CmsException e) {
int errorType = e.getType();
HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
HttpServletResponse res = (HttpServletResponse)cmsRes.getOriginalResponse();
boolean canWrite = ((!cmsRes.isRedirected()) && (!cmsRes.isOutputWritten()));
try {
switch(errorType) {
// access denied error - display login dialog
case CmsException.C_ACCESS_DENIED:
if(canWrite) {
requestAuthorization(req, res);
}
break;
// file not found - display 404 error.
case CmsException.C_NOT_FOUND:
if(canWrite) {
res.setContentType("text/HTML");
//res.getWriter().print(createErrorBox(e));
res.sendError(res.SC_NOT_FOUND);
}
break;
case CmsException.C_SERVICE_UNAVAILABLE:
if(canWrite) {
res.sendError(res.SC_SERVICE_UNAVAILABLE, e.toString());
}
break;
default:
if(canWrite) {
// send errorbox, but only if the request was not redirected
res.setContentType("text/HTML");
// set some HTTP headers preventing proxy servers from caching the error box
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Pragma", "no-cache");
res.getWriter().print(createErrorBox(e, cms));
}
//res.sendError(res.SC_INTERNAL_SERVER_ERROR);
}
}
catch(IOException ex) {
}
}
/**
* Initialization of the OpenCms servlet.
* Used instead of a constructor (Overloaded Servlet API method)
* <p>
* The connection information for the property database is read from the configuration
* file and all resource brokers are initialized via the initalizer.
*
* @param config Configuration of OpenCms.
* @exception ServletException Thrown when sevlet initalization fails.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Collect the configurations
try {
ExtendedProperties p = new ExtendedProperties(CmsBase.getPropertiesPath(true));
// Change path to log file, if given path is not absolute
String logFile = (String)p.get("log.file");
if(logFile != null) {
p.put("log.file", CmsBase.getAbsolutePath(logFile));
}
// m_configurations = new Configurations(new ExtendedProperties(CmsBase.getPropertiesPath(true)));
m_configurations = new Configurations(p);
}
catch(Exception e) {
throw new ServletException(e.getMessage() + ". Properties file is: " + CmsBase.getBasePath() + "opencms.properties");
}
// Initialize the logging
A_OpenCms.initializeServletLogging(m_configurations);
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] logging started");
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] Server Info: " + config.getServletContext().getServerInfo());
String jdkinfo = System.getProperty("java.vm.name") + " ";
jdkinfo += System.getProperty("java.vm.version") + " ";
jdkinfo += System.getProperty("java.vm.info") + " ";
jdkinfo += System.getProperty("java.vm.vendor") + " ";
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] JDK Info: " + jdkinfo);
String osinfo = System.getProperty("os.name") + " ";
osinfo += System.getProperty("os.version") + " ";
osinfo += System.getProperty("os.arch") + " ";
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] OS Info: " + osinfo);
}
// initialize the redirect information
int count = 0;
String redirect;
String redirectlocation;
while((redirect = (String)m_configurations.getString(C_PROPERTY_REDIRECT + "." + count)) != null) {
redirectlocation = (String)m_configurations.getString(C_PROPERTY_REDIRECTLOCATION + "." + count);
m_redirect.addElement(redirect);
m_redirectlocation.addElement(redirectlocation);
count++;
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] redirect-rule: " + redirect + " -> " + redirectlocation);
}
}
m_clusterurl = (String)m_configurations.getString(C_CLUSTERURL, "");
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] Clusterurl: " + m_clusterurl);
}
try {
// invoke the OpenCms
m_opencms = new OpenCms(m_configurations);
}
catch(Exception exc) {
throw new ServletException(exc.getMessage());
}
//initalize the session storage
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] initializing session storage");
}
m_sessionStorage = new CmsCoreSession();
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] initializing... DONE");
}
// create the cms-object for the class-loader to read classes from the vfs
CmsObject cms = new CmsObject();
try {
m_opencms.initUser(cms, null, null, C_USER_GUEST, C_GROUP_GUEST, C_PROJECT_ONLINE_ID);
} catch (CmsException exc) {
throw new ServletException("Error while initializing the cms-object for the classloader", exc);
}
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] initializing CmsClassLoader ");
}
// get the repositories for the classloader
Vector repositories = new Vector();
String[] repositoriesFromConfigFile = null;
String[] repositoriesFromRegistry = null;
// add repositories from the configuration file
repositoriesFromConfigFile = cms.getConfigurations().getStringArray("repositories");
for(int i = 0;i < repositoriesFromConfigFile.length;i++) {
repositories.addElement(repositoriesFromConfigFile[i]);
}
// add the repositories from the registry, if it is available
I_CmsRegistry reg = null;
try{
reg = cms.getRegistry();
}catch(CmsException e){
throw new ServletException(e.getMessage());
}
CmsClassLoader loader = (CmsClassLoader) (getClass().getClassLoader());
if(reg != null) {
repositoriesFromRegistry = reg.getRepositories();
for(int i = 0;i < repositoriesFromRegistry.length;i++) {
try {
cms.readFileHeader(repositoriesFromRegistry[i]);
//repositories.addElement(repositoriesFromRegistry[i]);
loader.addRepository(repositoriesFromRegistry[i], CmsClassLoader.C_REPOSITORY_VIRTUAL_FS);
}
catch(CmsException e) {
// this repository was not found, do do not add it to the repository list
// no exception handling is nescessary here.
}
}
}
// give the guest-loggedin cms-object and the repositories to the classloader
// CmsClassLoader loader = new CmsClassLoader();
//CmsClassLoader loader = (CmsClassLoader) (getClass().getClassLoader());
//loader.init(cms, repositories);
loader.init(cms);
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] initializing CmsClassLoader... DONE");
}
}
/**
* This method handled the user authentification for each request sent to the
* OpenCms. <p>
*
* User authentification is done in three steps:
* <ul>
* <li> Session Authentification: OpenCms stores all active sessions of authentificated
* users in an internal storage. During the session authetification phase, it is checked
* if the session of the active user is stored there. </li>
* <li> HTTP Autheification: If session authentification fails, it is checked if the current
* user has loged in using HTTP authentification. If this check is positive, the user account is
* checked. </li>
* <li> Default user: When both authentification methods fail, the current user is
* set to the default (guest) user. </li>
* </ul>
*
* @param req The clints request.
* @param res The servlets response.
* @return The CmsObject
* @exception IOException Thrown if user autherization fails.
*/
private CmsObject initUser(I_CmsRequest cmsReq, I_CmsResponse cmsRes) throws IOException {
HttpSession session;
String user = null;
String group = null;
Integer project = null;
String loginParameter;
// get the original ServletRequest and response
HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
HttpServletResponse res = (HttpServletResponse)cmsRes.getOriginalResponse();
CmsObject cms = new CmsObject();
//set up the default Cms object
try {
m_opencms.initUser(cms, cmsReq, cmsRes, C_USER_GUEST, C_GROUP_GUEST, C_PROJECT_ONLINE_ID);
// check if a parameter "opencms=login" was included in the request.
// this is used to force the HTTP-Authentification to appear.
loginParameter = cmsReq.getParameter("opencms");
if(loginParameter != null) {
// do only show the authentication box if user is not already
// authenticated.
if(req.getHeader("Authorization") == null) {
if(loginParameter.equals("login")) {
requestAuthorization(req, res);
}
}
}
// check for the clearcache parameter
loginParameter = cmsReq.getParameter("_clearcache");
if(loginParameter != null) {
cms.clearcache();
}
// get the actual session
session = req.getSession(false);
// there is no session
if((session == null)) {
// was there an old session-id?
String oldSessionId = req.getRequestedSessionId();
if(oldSessionId != null) {
// yes - try to load that session
Hashtable sessionData = null;
try {
sessionData = m_opencms.restoreSession(oldSessionId);
}
catch(CmsException exc) {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[OpenCmsServlet] cannot restore session: " + com.opencms.util.Utils.getStackTrace(exc));
}
}
// can the session be restored?
if(sessionData != null) {
// create a new session first
session = req.getSession(true);
m_sessionStorage.putUser(session.getId(), sessionData);
// restore the session-data
session.setAttribute(C_SESSION_DATA, sessionData.get(C_SESSION_DATA));
}
}
}
// there was a session returned, now check if this user is already authorized
if(session != null) {
// get the username
user = m_sessionStorage.getUserName(session.getId());
//check if a user was returned, i.e. the user is authenticated
if(user != null) {
group = m_sessionStorage.getCurrentGroup(session.getId());
project = m_sessionStorage.getCurrentProject(session.getId());
m_opencms.initUser(cms, cmsReq, cmsRes, user, group, project.intValue());
}
}
else {
// there was either no session returned or this session was not
// found in the CmsCoreSession storage
String auth = req.getHeader("Authorization");
// User is authenticated, check password
if(auth != null) {
// only do basic authentification
if(auth.toUpperCase().startsWith("BASIC ")) {
// Get encoded user and password, following after "BASIC "
String userpassEncoded = auth.substring(6);
// Decode it, using any base 64 decoder
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
String userstr = new String(dec.decodeBuffer(userpassEncoded));
String username = null;
String password = null;
StringTokenizer st = new StringTokenizer(userstr, ":");
if(st.hasMoreTokens()) {
username = st.nextToken();
}
if(st.hasMoreTokens()) {
password = st.nextToken();
}
// autheification in the DB
try {
try {
// try to login as a user first ...
user = cms.loginUser(username, password);
} catch(CmsException exc) {
// login as user failed, try as webuser ...
user = cms.loginWebUser(username, password);
}
// authentification was successful create a session
session = req.getSession(true);
OpenCmsServletNotify notify = new OpenCmsServletNotify(session.getId(), m_sessionStorage);
session.setAttribute("NOTIFY", notify);
}
catch(CmsException e) {
if(e.getType() == CmsException.C_NO_ACCESS) {
// authentification failed, so display a login screen
requestAuthorization(req, res);
}
else {
throw e;
}
}
}
}
}
}
catch(CmsException e) {
errorHandling(cms, cmsReq, cmsRes, e);
}
return cms;
}
/**
* This method sends a request to the client to display a login form.
* It is needed for HTTP-Authentification.
*
* @param req The clints request.
* @param res The servlets response.
*/
private void requestAuthorization(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.setHeader("WWW-Authenticate", "BASIC realm=\"OpenCms\"");
res.setStatus(401);
}
/**
* Updated the the user data stored in the CmsCoreSession after the requested document
* is processed.<br>
*
* This is nescessary if the user data (current group or project) was changed in
* the requested document. <br>
*
* The user data is only updated if the user was authenticated to the system.
*
* @param cms The actual CmsObject.
* @param cmsReq The clints request.
* @param cmsRes The servlets response.
* @return The CmsObject
*/
private void updateUser(CmsObject cms, I_CmsRequest cmsReq, I_CmsResponse cmsRes) throws IOException {
HttpSession session = null;
// get the original ServletRequest and response
HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
//get the session if it is there
session = req.getSession(false);
// if the user was authenticated via sessions, update the information in the
// sesssion stroage
if((session != null)) {
if(!cms.getRequestContext().currentUser().getName().equals(C_USER_GUEST)) {
Hashtable sessionData = new Hashtable(4);
sessionData.put(C_SESSION_USERNAME, cms.getRequestContext().currentUser().getName());
sessionData.put(C_SESSION_CURRENTGROUP, cms.getRequestContext().currentGroup().getName());
sessionData.put(C_SESSION_PROJECT, new Integer(cms.getRequestContext().currentProject().getId()));
Hashtable oldData = (Hashtable)session.getAttribute(C_SESSION_DATA);
if(oldData == null) {
oldData = new Hashtable();
}
sessionData.put(C_SESSION_DATA, oldData);
// was there any change on current-user, current-group or current-project?
boolean dirty = false;
dirty = dirty || (!sessionData.get(C_SESSION_USERNAME).equals(m_sessionStorage.getUserName(session.getId())));
dirty = dirty || (!sessionData.get(C_SESSION_CURRENTGROUP).equals(m_sessionStorage.getCurrentGroup(session.getId())));
dirty = dirty || (!sessionData.get(C_SESSION_PROJECT).equals(m_sessionStorage.getCurrentProject(session.getId())));
// update the user-data
m_sessionStorage.putUser(session.getId(), sessionData);
// was the session changed?
if((session.getAttribute(C_SESSION_IS_DIRTY) != null) || dirty) {
// yes- store it to the database
session.removeAttribute(C_SESSION_IS_DIRTY);
try {
m_opencms.storeSession(session.getId(), sessionData);
}
catch(CmsException exc) {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[OpenCmsServlet] cannot store session: " + com.opencms.util.Utils.getStackTrace(exc));
}
}
}
// check if the session notify is set, it is nescessary to remove the
// session from the internal storage on its destruction.
OpenCmsServletNotify notify = null;
Object sessionValue = session.getAttribute("NOTIFY");
if(sessionValue instanceof OpenCmsServletNotify) {
notify = (OpenCmsServletNotify)sessionValue;
if(notify == null) {
notify = new OpenCmsServletNotify(session.getId(), m_sessionStorage);
session.setAttribute("NOTIFY", notify);
}
}
else {
notify = new OpenCmsServletNotify(session.getId(), m_sessionStorage);
session.setAttribute("NOTIFY", notify);
}
}
}
}
}
|
package com.twu.biblioteca.menuObjects;
import com.twu.biblioteca.LibraryMember;
import com.twu.biblioteca.inputOutputDevice.InputOutputManager;
import com.twu.biblioteca.menuObjects.IMenuItem;
import java.io.IOException;
public class Exit implements IMenuItem {
/**
* Executes the Exit function
*/
@Override
public int executeAction(LibraryMember libraryMember, InputOutputManager inputOutputManager) throws IOException {
return 1;
}
@Override
public String displayMenuItem() {
return "Exit";
}
}
|
package com.vmware.vim25.mo.samples;
import java.net.URL;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
import com.vmware.vim25.mo.util.*;
/**
* This sample shows how to get hold of the first VirtualMachine in an inventory and retrieve its properties.
* @author sjin
*/
public class HelloVM
{
public static void main(String[] args) throws Exception
{
CommandLineParser clp = new CommandLineParser(new OptionSpec[]{}, args);
String urlStr = clp.get_option("url");
String username = clp.get_option("username");
String password = clp.get_option("password");
ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true);
Folder rootFolder = si.getRootFolder();
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
if(mes==null || mes.length ==0)
{
return;
}
VirtualMachine vm = (VirtualMachine) mes[0];
VirtualMachineConfigInfo vminfo = vm.getConfig();
VirtualMachineCapability vmc = vm.getCapability();
vm.getResourcePool();
System.out.println("Hello " + vm.getName());
System.out.println("GuestOS: " + vminfo.getGuestFullName());
System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported());
si.getServerConnection().logout();
}
}
|
package com.timepath.swing;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JRootPane;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
*
* @author timepath
*/
@SuppressWarnings("serial")
public class ThemeSelector extends JComboBox {
public ThemeSelector() {
Vector comboBoxItems = new Vector();
final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
this.setModel(model);
String lafId = UIManager.getLookAndFeel().getClass().getName();
for(UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {
try {
Class.forName(lafInfo.getClassName());
} catch(ClassNotFoundException ex) {
continue;
}
String name = lafInfo.getName();
model.addElement(name);
if(lafInfo.getClassName().equals(lafId)) {
model.setSelectedItem(name);
}
}
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String laf = (String) ThemeSelector.this.getSelectedItem();
try {
boolean originallyDecorated = UIManager.getLookAndFeel().getSupportsWindowDecorations();
for(UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if(laf.equals(info.getName())) {
LOG.log(Level.INFO, "Setting L&F: {0}", info.getClassName());
try {
UIManager.setLookAndFeel(info.getClassName());
} catch(InstantiationException ex) {
Logger.getLogger(ThemeSelector.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalAccessException ex) {
Logger.getLogger(ThemeSelector.class.getName()).log(Level.SEVERE, null, ex);
} catch(UnsupportedLookAndFeelException ex) {
Logger.getLogger(ThemeSelector.class.getName()).log(Level.SEVERE, null, ex);
} catch(ClassNotFoundException ex) {
// Logger.getLogger(ThemeSelector.class.getName()).log(Level.SEVERE, null, ex);
LOG.warning("Unable to load user L&F");
}
}
}
boolean decorate = UIManager.getLookAndFeel().getSupportsWindowDecorations();
boolean decorateChanged = decorate != originallyDecorated;
boolean frameDecorations = false; // TODO: Frame decoration
// JFrame.setDefaultLookAndFeelDecorated(decorate);
// JDialog.setDefaultLookAndFeelDecorated(decorate);
for(Window w : Window.getWindows()) {
SwingUtilities.updateComponentTreeUI(w);
if(decorateChanged && frameDecorations) {
w.dispose();
handle(w, decorate);//w.isVisible());
w.setVisible(true);
}
}
} catch(Exception ex) {
LOG.log(Level.WARNING, "Failed loading L&F: " + laf, ex);
}
}
private void handle(Window window, boolean decorations) {
int decor = JRootPane.FRAME;
JRootPane rpc = null;
if(window instanceof RootPaneContainer) {
rpc = ((RootPaneContainer) window).getRootPane();
}
if(window instanceof JFrame) {
((JFrame) window).setUndecorated(decorations);
} else if(window instanceof JDialog) {
((JDialog) window).setUndecorated(decorations);
} else {
LOG.log(Level.WARNING, "Unhandled setUndecorated mapping: {0}", window);
}
if(rpc != null) {
rpc.setWindowDecorationStyle(decor);
}
}
});
}
private static final Logger LOG = Logger.getLogger(ThemeSelector.class.getName());
}
|
package com.xruby.compiler;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import com.xruby.compiler.codegen.CompilationResults;
import com.xruby.runtime.builtin.ObjectFactory;
import com.xruby.runtime.builtin.RubyFixnum;
import com.xruby.runtime.builtin.RubyIO;
import com.xruby.runtime.builtin.RubyString;
import com.xruby.runtime.lang.*;
import junit.framework.TestCase;
import java.io.*;
class CompilerTestCase extends TestCase {
protected void compile_run_and_compare_result(String[] program_texts, int[] results) {
assertEquals("the number of 'results' should match 'program_texts'",
program_texts.length, results.length);
for (int i = 0; i < program_texts.length; ++i) {
RubyCompiler compiler = new RubyCompiler();
try {
CompilationResults codes = compiler.compileString(program_texts[i]);
assertNotNull(codes);
RubyProgram p = codes.getRubyProgram();
RubyValue v = p.invoke();
RubyFixnum r = (RubyFixnum)v;
assertEquals(results[i], r.toInt());
} catch (RubyException e) {
assertTrue("RubyException at " + i + ": " + e.toString(), false);
} catch (RecognitionException e) {
assertTrue("RecognitionException at " + i + ": " + e.toString(), false);
} catch (TokenStreamException e) {
assertTrue("TokenStreamException at " + i + ": " + e.toString(), false);
} catch (InstantiationException e) {
assertTrue("InstantiationException at " + i + ": " + e.toString(), false);
} catch (IllegalAccessException e) {
assertTrue("IllegalAccessException at " + i + ": " + e.toString(), false);
} catch (VerifyError e) {
assertTrue("VerifyError at " + i + ": " + e.toString(), false);
} /*catch (NullPointerException e) {
assertTrue("NullPointerException at " + i + ": " + e.toString(), false);
}*/
}
}
protected void compile_run_and_compare_result(String[] program_texts, String[] results) {
assertEquals("the number of 'results' should match 'program_texts'",
program_texts.length, results.length);
for (int i = 0; i < program_texts.length; ++i) {
RubyCompiler compiler = new RubyCompiler();
try {
CompilationResults codes = compiler.compileString(program_texts[i]);
assertNotNull(codes);
RubyProgram p = codes.getRubyProgram();
RubyValue v = p.invoke();
RubyString r = (RubyString) v;
assertEquals(results[i], r.toString());
} catch (RubyException e) {
assertTrue("RubyException at " + i + ": " + e.toString(), false);
} catch (RecognitionException e) {
assertTrue("RecognitionException at " + i + ": " + e.toString(), false);
} catch (TokenStreamException e) {
assertTrue("TokenStreamException at " + i + ": " + e.toString(), false);
} catch (InstantiationException e) {
assertTrue("InstantiationException at " + i + ": " + e.toString(), false);
} catch (IllegalAccessException e) {
assertTrue("IllegalAccessException at " + i + ": " + e.toString(), false);
} catch (VerifyError e) {
assertTrue("VerifyError at " + i + ": " + e.toString(), false);
} /*catch (NullPointerException e) {
assertTrue("NullPointerException at " + i + ": " + e.toString(), false);
}*/
}
}
protected void compile_run_and_compare_result(String[] program_texts, RubyValue[] results) {
assertEquals("the number of 'results' should match 'program_texts'",
program_texts.length, results.length);
for (int i = 0; i < program_texts.length; ++i) {
RubyCompiler compiler = new RubyCompiler();
try {
CompilationResults codes = compiler.compileString(program_texts[i]);
assertNotNull(codes);
RubyProgram p = codes.getRubyProgram();
RubyValue v = p.invoke();
assertEquals(results[i], v);
} catch (RubyException e) {
assertTrue("RubyException at " + i + ": " + e.toString(), false);
} catch (RecognitionException e) {
assertTrue("RecognitionException at " + i + ": " + e.toString(), false);
} catch (TokenStreamException e) {
assertTrue("TokenStreamException at " + i + ": " + e.toString(), false);
} catch (InstantiationException e) {
assertTrue("InstantiationException at " + i + ": " + e.toString(), false);
} catch (IllegalAccessException e) {
assertTrue("IllegalAccessException at " + i + ": " + e.toString(), false);
} catch (VerifyError e) {
assertTrue("VerifyError at " + i + ": " + e.toString(), false);
} /*catch (NullPointerException e) {
assertTrue("NullPointerException at " + i + ": " + e.toString(), false);
}*/
}
}
protected void compile_run_and_catch_exception(String[] program_texts, RubyException[] exceptions) {
assertEquals("the number of 'exception' should match 'program_texts'",
program_texts.length, exceptions.length);
for (int i = 0; i < program_texts.length; ++i) {
RubyCompiler compiler = new RubyCompiler();
try {
CompilationResults codes = compiler.compileString(program_texts[i]);
assertNotNull(codes);
RubyProgram p = codes.getRubyProgram();
p.invoke();
fail("Error at " + i + ": should throw RubyException");
} catch (RubyException e) {
RubyValue v1 = RubyAPI.convertRubyException2RubyValue(exceptions[i]);
RubyValue v2 = RubyAPI.convertRubyException2RubyValue(e);
if (v1.toString() != null) {
assertEquals("Exception message mismatch at " + i, v1.toString(), v2.toString());
}
assertEquals("Exception type mismatch at " + i, v1.getRubyClass().getName(), v2.getRubyClass().getName());
continue;
} catch (RecognitionException e) {
assertTrue("RecognitionException at " + i + ": " + e.toString(), false);
} catch (TokenStreamException e) {
assertTrue("TokenStreamException at " + i + ": " + e.toString(), false);
} catch (InstantiationException e) {
assertTrue("InstantiationException at " + i + ": " + e.toString(), false);
} catch (IllegalAccessException e) {
assertTrue("IllegalAccessException at " + i + ": " + e.toString(), false);
} catch (VerifyError e) {
assertTrue("VerifyError at " + i + ": " + e.toString(), false);
} /*catch (NullPointerException e) {
assertTrue("NullPointerException at " + i + ": " + e.toString(), false);
}*/
}
}
protected void compile_run_and_compare_output(String[] program_texts, String[] outputs) {
assertEquals("the number of 'outputs' should match 'program_texts'",
program_texts.length, outputs.length);
for (int i = 0; i < program_texts.length; ++i) {
// FIXME: temp code here
RubyClass.resetCache();
RubyCompiler compiler = new RubyCompiler();
try {
CompilationResults codes = compiler.compileString(program_texts[i]);
assertNotNull(codes);
RubyProgram p = codes.getRubyProgram();
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintStream original = System.out;
RubyRuntime.setStdout(output);
p.invoke();
RubyRuntime.setStdout(original);
assertEquals("Failed at " + i, outputs[i], output.toString());
} catch (RubyException e) {
throw e;
//fail("RubyException at " + i + ": " + e.toString());
} catch (RecognitionException e) {
fail("RecognitionException at " + i + ": " + e.toString());
} catch (TokenStreamException e) {
fail("TokenStreamException at " + i + ": " + e.toString());
} catch (InstantiationException e) {
fail("InstantiationException at " + i + ": " + e.toString());
} catch (IllegalAccessException e) {
fail("IllegalAccessException at " + i + ": " + e.toString());
} catch (VerifyError e) {
fail("VerifyError at " + i + ": " + e.toString());
} catch (NoSuchFieldError e) {
fail("NoSuchFieldError at " + i + ": " + e.toString());
} /*catch (NullPointerException e) {
assertTrue("NullPointerException at " + i + ": " + e.toString(), false);
}*/
}
}
};
public class RubyCompilerTest extends CompilerTestCase {
public void setUp() {
RubyRuntime.init(new String[] {"my_arg"});
}
public void test_raise() throws RecognitionException, TokenStreamException, InstantiationException, IllegalAccessException {
String program_texts = "raise 'test'";
RubyCompiler compiler = new RubyCompiler();
CompilationResults codes = compiler.compileString(program_texts);
assertTrue(null != codes);
RubyProgram p = codes.getRubyProgram();
try {
p.invoke();
} catch (RubyException e) {
RubyValue v = RubyAPI.convertRubyException2RubyValue(e);
assertEquals(v.getRubyClass(), RubyRuntime.RuntimeErrorClass);
String s = v.toString();
assertEquals("test", s);
return;
}
assertTrue("You should not reach here!", false);
}
public void test_simple_integer() {
String[] program_texts = { "2", "0", "123456", "0b1100110", "0xFF",
"070", "+9", "-100"};
int[] results = { 2, 0, 123456, 102, 255, 56, 9, -100};
compile_run_and_compare_result(program_texts, results);
}
public void test_ascii_value() {
String[] program_texts = { "?a", "?A", "?\\n", "?\\r", "?\\C-a", "?\\M-a", "?\\M-\\C-a"};
int[] results = {97, 65, 10, 13, 1, 225, 129};
compile_run_and_compare_result(program_texts, results);
}
public void test_Fixnum_misc() {
String[] program_texts = {
"print (-7).div(4)",
"print 4.quo(2)",
"print 1.to_f",
"print 3.to_f",
//"print 1.to_f / 3"
};
String[] outputs = {
"-2",
"2.0",
"1.0",
"3.0",
//"0.333333333333333"
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Numeric_Coerce() {
String[] program_texts = {
"class A\n"
+ "def coerce other\n"
+ "if Integer === other\n"
+ "[other, 5]\n"
+ "else\n"
+ "[Float(other), 5.0]\n"
+ "end\n"
+ "end\n"
+ "end\n"
+ "\n\n"
+ "o = A.new\n"
+ "print 1 + o\n"
+ "print 1.0 + o\n"
+ "print 5 - o\n"
+ "print 5.0 - o\n"
+ "print 1 * o\n"
+ "print 1.0 * o\n"
+ "print 1 / o\n"
+ "print 1.0 / o\n"
};
String[] outputs = {
"66.000.055.000.2"
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Float_Integer() {
String[] program_texts = {
"print Integer('1')",
"print Float(2)",
"print Integer(2)",
"print Float(4.2).to_i",
};
String[] outputs = {
"1",
"2.0",
"2",
"4",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Bignum() {
String[] program_texts = {
//TODO"print 1234567890.class",
"print 0x123456789abcdef0",
"print (1 << 40)",
"print ((1 << 40) >> 30)",
"print (0x123456789abcdef0 <=> 0x123456789abcdef0)",
"print ((1 << 600) <=> ((1 << 600) + 1))",
"print (0xabcdef0123456789 * 0x123456789abcdef0)"
};
String[] outputs = {
//"Bignum",
"1311768467463790320",
"1099511627776",
"1024",
"0",
"-1",
"16239449295734013608292442272905420400"
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_BinaryOperatorExpression() {
String[] program_texts = { "2+2", "0 + 100", "0 + 0", "654321 + 9999",
"0xFF + 1", "3 - 5", "3 * 5 * 2", "100/2", "4%2", "7%3",
"1 + 2 + 3 -0 + 100", "6- 5 *2 + 100 - 6", "4.div 2", };
int[] results = { 4, 100, 0, 664320, 256, -2, 30, 50, 0, 1, 106, 90, 2};
compile_run_and_compare_result(program_texts, results);
}
public void test_BinaryOperatorExpression2() {
String[] program_texts = {
"print 2 > 1",
"print 2 == 1",
"print 1 >= 0",
"print 1 <=> 0",
"print 9 <=> 9",
"print 1 <=> 2",
"print 1 <= 2",
};
String[] outputs = {
"true",
"false",
"true",
"1",
"0",
"-1",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_simple_methodcall() {
String[] program_texts = {
"1.to_i",
"0.to_int",
"123.to_i.to_int.to_i",
"\"500\".to_i",
};
int[] results = {
1,
0,
123,
500,
};
compile_run_and_compare_result(program_texts, results);
}
public void test_double_quote_string() {
String[] program_texts = {
"print \"\\56\"",
"print \"\\x63\"",
"print \"\\142\"",
"print \"\\142\\102\"",
};
String[] outputs = {
".",
"c",
"b",
"bB",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Method_Proc_arity() {
String[] program_texts = {
"def f(a,b,c); end; method(:f).arity",
"Proc.new {||}.arity",
"Proc.new {|a|}.arity",
"Proc.new {|a,b|}.arity",
"Proc.new {|*a|}.arity",
"Proc.new {|a,*b|}.arity",
};
int[] results = {
3,
0,
1,
2,
-1,
-2,
};
compile_run_and_compare_result(program_texts, results);
}
public void test_String_index() {
String[] program_texts = {"\"hello\".index('e')"};
int[] results = {
1
};
compile_run_and_compare_result(program_texts, results);
program_texts = new String[]{"\"hello\".index('lo')"};
results = new int[]{
3
};
compile_run_and_compare_result(program_texts, results);
program_texts = new String[]{"\"hello\".index('a')"};
RubyValue[] res = {RubyConstant.QNIL};
compile_run_and_compare_result(program_texts, res);
program_texts = new String[]{"\"hello\".index(101)"};
results = new int[]{1};
compile_run_and_compare_result(program_texts, results);
program_texts = new String[]{"\"helle\".index('e', 3)"};
results = new int[]{4};
compile_run_and_compare_result(program_texts, results);
program_texts = new String[]{"\"helle\".index('e', -3)"};
results = new int[]{4};
compile_run_and_compare_result(program_texts, results);
program_texts = new String[]{"\"hello\".index(/[aeiou]/, -3)"};
res = new RubyValue[]{ObjectFactory.FIXNUM4};
compile_run_and_compare_result(program_texts, res);
program_texts = new String[]{"\"hll\".index(/[aeiou]/, -3)"};
res = new RubyValue[]{RubyConstant.QNIL};
compile_run_and_compare_result(program_texts, res);
}
public void test_String_succ() {
String[] program_texts = {
"a = 'a'; print a.succ!, a",
"a = 'a'; print a.succ, a",
"print ''.succ",
};
String[] results = {
"bb",
"ba",
"",
};
compile_run_and_compare_output(program_texts, results);
}
public void test_array() {
String[] program_texts = { "[1, 'xxx', 1.2].length", "[].length",};
int[] results = { 3, 0,};
compile_run_and_compare_result(program_texts, results);
}
public void test_array_access() {
String[] program_texts = {
"[1.8, 24, 55][-1]",
"[123][0]",
"[1.8, 24, 35][2]",
"a = [0, 9];a[1]",
"a = [1,2,3]; a.[](0)",
};
int[] results = {
55,
123,
35,
9,
1,
};
compile_run_and_compare_result(program_texts, results);
}
public void test_array_assignment() {
String[] program_texts = {
"a = [1, 2, 3]; a[0] = 9; print a[0]",
};
String[] outputs = {
"9",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_array_expand() {
String[] program_texts = {
"a = [5,6,[1, 2]]; print a, a.length",
"a = [5,6,*[1, 2]]; print a, a.length",
"a = [5,6,*1]; print a, a.length ",
"a = [5,6,*nil]; print a, a.length",
"a = [*nil]; print a, '|', a.length, a[0].class",
"a = [*[1, 2]]; print a, '|', a.length, a[0].class",
};
String[] outputs = {
"56123",
"56124",
"5613",
"563",
"|1NilClass",
"12|2Fixnum",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Array_join() {
String[] program_texts = {
"print [ 'a', 'b', 'c'].join",
"print [ 'a', 'b', 'c'].join('-')",
};
String[] outputs = {
"abc",
"a-b-c",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Array_sort() {
String[] program_texts = {
"a = [ 3, 2, 1]; print a.sort!, a",
"print [ 4, 6, 5].sort! {|x, y| x <=> y}",
"print [ 4, 6, 5].sort! {|x, y| 0}",
"a = [ 3, 2, 1]; print a.sort, a",
};
String[] outputs = {
"123123",
"456",
"465",
"123321",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Array_misc() {
String[] program_texts = {
"p [1,2,3].reject {|x| x==2}",
"a=[]; a.insert 2, 3, 4; p a",
"print [ 11, 22, 33, 44 ].fetch(1)",
"a = [1, 2, 1, 3]; a.delete_if {|x| true if x == 1}; p a",
"[1, 2, 3].reverse_each {|x| print x}",
"print %w$a b c $[1..-1]",
"p [1,2].clear",
"p Array.new(3, 0)",
"p Array.new(3)",
"print [3, 4].first, [].first, [5, 6, 7].first(2)",
"print [3, 4].last, [].last, [5, 6, 7].last(2)",
"print [1, 3].at(1)",
"a = [1, 2]; b = a.dup; b.shift; p a, b",
"print [1, 3].delete(2)",
"print [1, 2, 3].delete(2)",
"a = [1, 2, 3, 2]; a.delete(2); p a",
"p [] << 1",
"p [] << [1, 2]",
"p [].push(1, 2)",
"p [2, 3].insert(0, 1)",
"p [1, 2, 3][1..2]",
"p [1, 2, 3][1...2]",
"print [].empty?",
"a = [1,2,3]; a[1,0] = [1,2,3]; print a, a.size",
"print [ 1, 2, 3 ] * \",\"",
"print [1, 2].hash == [1, 2].hash",
"print [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]",
"print [ 1, 1, 3, 5 ] | [ 1, 2, 3 ]",
"print [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]",
"a = [4,5,6]; a[1,2] = 9; print a",
"a = [4,5,6]; a[1,0] = 9; print a",
"a = [nil, 4,5, nil, 6]; a.compact!; print a",
"a = [nil, 4, 4,6, nil, 6]; a.uniq!; print a",
"a = [4,5, 6]; a.reverse!; print a",
"a = [4,5, 6,7]; a.reverse!; print a",
};
String[] outputs = {
"[1, 3]\n",
"[nil, nil, 3, 4]\n",
"22",
"[2, 3]\n",
"321",
"bc",
"[]\n",
"[0, 0, 0]\n",
"[nil, nil, nil]\n",
"3nil56",
"4nil67",
"3",
"[1, 2]\n[2]\n",
"nil",
"2",
"[1, 3]\n",
"[1]\n",
"[[1, 2]]\n",
"[1, 2]\n",
"[1, 2, 3]\n",
"[2, 3]\n",
"[2]\n",
"true",
"1123236",
"1,2,3",
"true",
"13",
"1352",
"335",
"49",
"4956",
"456",
"46",
"654",
"7654",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Array_compare() {
String[] program_texts = {
"print [ 4, 6, 5] <=> [ 4, 6, 5]",
"print [ 4, 6, 5] <=> [ 4, 6]",
"print [ 4, 6] <=> [ 4, 6, 5]",
};
String[] outputs = {
"0",
"1",
"-1",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Array_populate() {
String[] program_texts = {
"a = Array[ 4, 6, 5];print a[1]",
"a = Array.[](4, 6, 5);print a[2]",
};
String[] outputs = {
"6",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Array_index_rindex(){
String[] program_texts = {
"a = [ \"a\", \"b\", \"c\" ];print a.index(\"b\") ",
"a = [ \"a\", \"b\", \"c\" ];print a.index(\"z\") ",
"a = [ \"a\", \"b\", \"c\" ];print a.rindex(\"a\") ",
"a = [ \"a\", \"b\", \"c\" ];print a.index(\"c\") ",
"a = [ \"a\", \"b\", \"c\" ];print a.rindex(\"z\") ",
};
String[] outputs = {
"1",
"nil",
"0",
"2",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_UNARY_PLUS_MINUS_METHOD_NAME() {
String[] program_texts = {
"print 1.-@",
"print 2.-@ {}",
"print -3.to_s",
};
String[] outputs = {
"-1",
"-2",
"-3",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_p() {
String[] program_texts = {
"p 1.234",
"p [1, [3,4], 2]",
};
String[] outputs = {
"1.234\n",
"[1, [3, 4], 2]\n",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_print() {
String[] program_texts = {
"print \"hello, world!\"",
"print 2*3*10",
"print 'x', 'y', 123",
"print",
"$_ = 'hello'; print; $_ = nil",
"$, = '|'; print 1,2,3; $, = nil",
"$\\ = '!'; print 1,2,3; $\\ = nil",
"print [5,6,7]",
"print [ nil ]",
"print [ nil ][0];",
"Kernel.print 123",
};
String[] outputs = {
"hello, world!",
"60",
"xy123",
"nil",
"hello",
"1|2|3",
"123!",
"567",
"",
"nil",
"123",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_method_compile() {
String program_texts =
"def f\n" +
" print 123\n" +
"end\n" +
"f";
RubyCompiler compiler = new RubyCompiler();
try {
CompilationResults codes = compiler.compileString(program_texts);
assertEquals(3, codes.size());
} catch (Exception e) {
assertTrue("Error : " + e.toString(), false);
}
}
public void test_duplicate_method_run() {
String[] program_texts = {
"def f\n" +
" print 123\n" +
"end\n" +
"def f\n" +
" print 456\n" +
"end\n" +
"f",
};
String[] outputs = {
"456",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_method_return() {
String[] program_texts = {
"def f\n" +
" 123\n" +
"end\n" +
"print f()",
"def f1\n" +
" 456\n" +
"end\n" +
"print f1",
"def f2\n" +
" return 'xxx'\n" +
"end\n" +
"print f2",
"def r; return; end; a = r(); print a",
"def f\n" +
" return 1, 2, 3\n" +
"end\n" +
"print f()",
"def f(a); a; end; print f('yyy')",
};
String[] outputs = {
"123",
"456",
"xxx",
"nil",
"123",
"yyy",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_asterisk_parameter() {
String[] program_texts = {
"def a *; print 'ok'; end; a 1, 2, 3",
"def my_print(*a)\n" +
" print a\n" +
"end\n" +
"my_print ':)', 5634 , 888",
"def my_print(a, *b)\n" +
" print b, a\n" +
"end\n" +
"my_print ':)', 5634 , 888",
"def my_print(*a)\n" +
" print a, a\n" +
"end\n" +
"my_print ':)', 5634 , 888",
};
String[] outputs = {
"ok",
":)5634888",
"5634888:)",
":)5634888:)5634888",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_method_run() {
String[] program_texts = {
"def (1.class).fred; print 'x'; end; Fixnum.fred ",
"def a; 6; end; print(a)",
"a = 5; def a; 6; end; print(a)",
"def my_print(a, b, c)\n" +
" print c\n" +
" print a\n" +
"end\n" +
"my_print ':)', 5634 , 888",
"def f\n" +
" print 123\n" +
"end\n" +
"f",
"def my_print(a)\n" +
" print a\n" +
"end\n" +
"my_print ':)'",
"def f(a); a = 1; end; x = 100; f(x); print x",
"def f(x); x= 5; print x; end; f(4)",
};
String[] outputs = {
"x",
"6",
"5",
"888:)",
"123",
":)",
"100",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Class_superclass() {
String[] program_texts = {
"print Class.new.superclass",
"print String.superclass",
"print Class.superclass",
"print Object.superclass",
};
String[] outputs = {
"Object",
"Object",
"Module",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_class() {
String[] program_texts = {
"1.times {class ClassInBlock; end};",
"class C\n" +
" def f\n" +
" print \"~~~~\"\n" +
" end\n" +
"end\n" +
"C.new.f",
"class C1\n" +
" def f\n" +
" print \"~~~~\"\n" +
" end\n" +
" def f\n" +
" print \"!!!\"\n" +
" end\n" +
"end\n" +
"C1.new.f",
"class C2\n" +
" def f\n" +
" print \"????\"\n" +
" end\n" +
"end\n" +
"class C2\n" +
" def f2\n" +
" print \"*****\"\n" +
" end\n" +
"end\n" +
"C2.new.f2",
"class C3\n" +
" def f1\n" +
" print \"????\"\n" +
" end\n" +
"end\n" +
"class C3\n" +
" def f2\n" +
" print \"*****\"\n" +
" end\n" +
"end\n" +
"C3.new.f1",
};
String[] outputs = {
"",
"~~~~",
"!!!",
"*****",
"????",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_inheritence() {
String[] program_texts = {
"class B\n" +
" def say\n" +
" print 7654\n" +
" end\n" +
"end\n" +
"\n" +
"class S < B\n" +
"end\n" +
"\n" +
"S.new.say",
"def B\n" +
" print 999\n" +
"end\n" +
"\n" +
"class B\n" +
" def hello\n" +
" print 7654\n" +
" end\n" +
"end\n" +
"\n" +
"class S < B\n" +
"end\n" +
"\n" +
"S.new.hello\n" +
"B()",
"def B\n" +
" print 999\n" +
"end\n" +
"\n" +
"class B\n" +
" def hello\n" +
" print 4567\n" +
" end\n" +
"end\n" +
"\n" +
"class S < B\n" +
"end\n" +
"\n" +
"S.new.hello\n" +
"B", //<-- B should resolved as class B, not method B()
};
String[] outputs = {
"7654",
"7654999",
"4567",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_class_inheritence_exception() {
String[] program_texts = {
"B = 1\n" +
"class S < B\n" +
"end\n" +
"\n" +
"S.new.hello",
"class C;end; class C < String;end",
"class D < Class;end",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.TypeErrorClass, "superclass must be a Class (Fixnum given)"),
new RubyException(RubyRuntime.TypeErrorClass, "superclass mismatch for class C"),
new RubyException(RubyRuntime.TypeErrorClass,"can't make subclass of Class"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_class_inherited(){
String[] program_texts = {
"class Top\n"+
" def Top.inherited(sub)\n"+
" print sub\n"+
" end\n"+
"end\n"+
"class Middle < Top\n"+
"end\n",
};
String[] outputs = {
"Middle",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_define_method(){
String[] program_texts = {
"class TestDefineMethod;end\n" +
"class <<TestDefineMethod\n" +
" TestDefineMethodConstant = proc do\n" +
" print self\n" +
" end\n" +
" define_method(:test_define_method, TestDefineMethodConstant)\n" +
"end\n" +
"TestDefineMethod.test_define_method",
};
String[] outputs = {
"TestDefineMethod",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_dot_class_method() {
String[] program_texts = {
"print 1.class\n",
"print 0.1.class\n",
"print 'hello'.class\n",
"print true.class\n",
"print false.class\n",
"print nil.class\n",
"print String.class",
"print 1.class.class",
"print Kernel.class",
"print Comparable.class",//Comparable is defined in builtin.rb
};
String[] outputs = {
"Fixnum",
"Float",
"String",
"TrueClass",
"FalseClass",
"NilClass",
"Class",
"Class",
"Module",
"Module",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_assign() {
String[] program_texts = {
"a = true ? 1 : 2; print a",
"a = b = 12\n" +
"print a\n",
//"a = b = 'xxx'\n" +
//"print b\n",
"a = 999\n" +
"print a\n",
"a = b = 888\n" +
"print a, b\n",
"a = 777\n" +
"a = 666\n" +
"print a\n",
"a = 555\n" +
"b = a\n" +
"print b\n",
"a=5; a+=6; print a",
"a = b = 1 + 2 + 3; print a, b ",
"a = (b = 1 + 2) + 3; print a, b ",
};
String[] outputs = {
"1",
"12",
//"xxx",
"999",
"888888",
"666",
"555",
"11",
"66",
"63",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_if() {
String[] program_texts = {
"buf=\"\"\n" +
"option = true\n" +
"if option\n" +
" if option\n" +
" 1.times{|y| buf += \"x\" }\n" +
" end\n" +
"end\n" +
"print buf",
"a=true\n" +
"if a\n" +
"elsif a\n" +
" x=2\n" +
"end\n" +
"\n" +
"print x",
"if false;print 1; else; end",
"if true\n" +
" print 1\n" +
"else\n" +
" print 2\n" +
"end",
"if false\n" +
" print 1\n" +
"else\n" +
" print 2\n" +
"end",
"if true\n" +
" print 'xxx'\n" +
"end",
"if false then" +
" print 1\n" +
"elsif true\n" +
" print 2\n" +
"else\n" +
" print 3\n" +
"end",
};
String[] outputs = {
"x",
"nil",
"",
"1",
"2",
"xxx",
"2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_ternaryIfThenElseExpression() {
String[] program_texts = {
"print true ? 1: 2",
"print false ? 1 : 2",
};
String[] outputs = {
"1",
"2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_case() {
String[] program_texts = {
"case \"xxx\"\n" +
"when \"yyy\", \"xxx\"\n" +
" print true\n" +
"else\n" +
" print false\n" +
"end ",
"case; when true; print 1; else; print 2; end",
"b = proc {print 0}; case 1; when 2; a = 3, 4; else b.call; end",
"class C; end; def C.f; [5]; end\n" +
"case 5;when *C.f; print 123; end",
"case [1, 2]; when *[[1, 2]]; print 'ok'; end",
"case 1; when 1; end",
"print case 1\n" +
" when 1\n" +
" 1234\n" +
" else\n" +
" 2345\n" +
"end",
"print case 100\n" +
" when 1\n" +
" 123\n" +
" when 2\n" +
" 234\n" +
" when 3\n" +
" 34\n" +
" else\n" +
" 2245\n" +
"end",
"print case 3\n" +
" when 1\n" +
" 123\n" +
" when 2\n" +
" 234\n" +
" when 3\n" +
" 34\n" +
" else\n" +
" 2245\n" +
"end",
};
String[] outputs = {
"true",
"1",
"0",
"123",
"ok",
"",
"1234",
"2245",
"34",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_unless() {
String[] program_texts = {
"a = 1 unless 1==2; print a",
"a =unless false\n" +
" 111\n" +
"else\n" +
" 222\n" +
"end\n" +
"\n" +
"print a",
"a =unless true then" +
" 111\n" +
"else\n" +
" 222\n" +
"end\n" +
"\n" +
"print a",
"$bad = false; unless $x == $x; $bad = true; end; print $bad"
};
String[] outputs = {
"1",
"111",
"222",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_ensure() {
String[] program_texts = {
"def f;print 1;ensure; print 2;return; end; f",
"while true\n" +
" begin\n" +
" break\n" +
" ensure\n" +
" print \"break\"\n" +
" end\n" +
"end",
"print begin; end",
"begin; print 'xxx'; ensure; print 'ensure'; end",
"begin; ensure; print 'ensure'; end",
"begin\n" +
" raise \"!!!!\"\n" +
"rescue RuntimeError\n" +
" print \"xxx\"\n" +
"ensure\n" +
" print \"yyy\"\n" +
"end",
"begin\n" +
"rescue NoMethodError\n" +
" print \"xxx\"\n" +
"else\n" +
" print \"zzz\"\n" +
"ensure\n" +
" print \"yyy\"\n" +
"end",
"begin\n" +
" 1\n" +
"rescue NoMethodError\n" +
" print \"333\"\n" +
"else\n" +
" print \"444\"\n" +
"ensure\n" +
" print \"555\"\n" +
"end",
"begin\n" +
" raise \"!!!\"\n" +
"rescue RuntimeError\n" +
" print \"333\"\n" +
"else\n" +
" print \"444\"\n" +
"ensure\n" +
" print \"555\"\n" +
"end",
"begin\n" +
" begin\n" +
" raise \"this must be handled no.5\"\n" +
" ensure\n" +
" print \"ok\"\n" +
" end\n" +
"rescue\n" +
" print \"catch\"\n" +
"end",
"begin\n" +
" begin\n" +
" raise \"this must be handled\"\n" +
" ensure\n" +
" print \"ok\"\n" +
" end\n" +
"rescue\n" +
"end",
};
String[] outputs = {
"12",
"break",
"nil",
"xxxensure",
"ensure",
"xxxyyy",
"zzzyyy",
"444555",
"333555",
"okcatch",
"ok",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_stack_depth_consistency_in_begin_end() {
String[] program_texts = {
"begin; true; rescue; false; end; begin; true; rescue; false; end",
"a = [ begin; 1; rescue; 2; end]; print a",
"print begin; true; rescue; false; end",
};
String[] outputs = {
"",
"1",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_exception() {
String[] program_texts = {
"if ((a=5) == 5 rescue false);b= a;end;print b",
"if ((a=4) == 4 rescue false);print a;end",
"if ((a=3) rescue false);print a;end",
"begin; require 'XXXXX'; rescue LoadError; end; print $!",
"begin\n" +
"eval(\"def foo; BEGIN {}; end\")\n" +
"rescue SyntaxError=>e\n" +
"print e.class\n" +
"end",
"begin; throw TypeError;rescue Exception =>e; print e; end",
"def f\n" +
" begin\n" +
" a=1\n" +
" raise '!'\n" +
" end\n" +
" rescue\n" +
" print a\n" +
"end\n" +
"f",
"begin; raise 'www'; rescue; print $!; end",
"begin; throw 'vvv'; rescue; print $!; end",
"def f(a); end; begin; f; rescue; print 55 ; end",
"begin\n" +
" raise \"!!!!\"\n" +
"rescue RuntimeError\n" +
" print \"xxx\"\n" +
"end",
"begin\n" +
" raise \"!!!!\"\n" +
"rescue\n" +
" print \"yyy\"\n" +
"end",
"begin\n" +
" raise \"!!!!\"\n" +
"rescue RuntimeError\n" +
" print \"aaa\"\n" +
"end\n" +
"print 'bbb'",
"begin\n" +
" print 'zzz'\n" +
"rescue RuntimeError\n" +
" print \"ccc\"\n" +
"end\n" +
"print 'ddd'",
"begin\n" +
" raise \"!!!!\"\n" +
"rescue RuntimeError\n" +
" print \"111\"\n" +
"rescue RuntimeError\n" +
" print \"222\"\n" +
"end",
"begin\n" +
" raise \"!!!!\"\n" +
" rescue RuntimeError => e\n" +
" print e\n" +
"end",
"begin\n" +
" raise \"test\"\n" +
"rescue => e\n" +
" print e\n" +
"end",
"begin\n" +
" begin\n" +
" raise \"this must be handled no.5\"\n" +
" end\n" +
"rescue\n" +
" print \"catch\"\n" +
"end",
"begin raise Exception.new, 'zzz'\n" +
"rescue Exception=> e; print e; end",
"begin raise Exception, 'ooo'\n" +
"rescue Exception=> e; print e; end",
};
String[] outputs = {
"5",
"4",
"3",
"nil",
"SyntaxError",
"TypeError is not a symbol",
"1",
"www",
"uncaught throw `vvv'",
"55",
"xxx",
"yyy",
"aaabbb",
"zzzddd",
"111",
"!!!!",
"test",
"catch",
"zzz",
"ooo",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_binding() {
String[] program_texts = {
"p = binding; eval 'foo11 = 1', p; print eval('foo11')",
"x = binding; eval('for i6 in 1..1; j6=3; end', x); eval('print defined?(j6)', x)",
"x = proc{}; x = binding; print x.class",
"x = binding; eval 'i = 1', x; print(eval('i', x))",
"module TestBinding\n" +
" A = 6\n" +
" $x = binding\n" +
"end\n" +
"\n" +
"print eval(\"A\", $x)",
"def getBinding(x); lambda {return binding}.call; end\n" +
"b = getBinding(666)\n" +
"print eval(\"x\", b)",
"def getBinding(param); return binding; end\n" +
"b = getBinding(\"hello\")\n" +
"print eval(\"param\", b) ",
"def getBinding(param); x = 5; return binding; end\n" +
"b = getBinding(\"hello\")\n" +
"print eval(\"x\", b) ",
};
String[] outputs = {
"1",
"local-variable",
"Binding",
"1",
"6",
"666",
"hello",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_eval() {
String[] program_texts = {
"eval('print 7', nil,'(erb)')",
//TODO remove the 'binding;' the test will fail in xruby
"binding;begin;eval '';rescue;end\n" +
"i = 5;print(eval('i'))",
"b = binding; eval('test_eval2 = 6', b); eval('print test_eval2')",
"eval('print nil'); test_eval1 = 5; eval('print test_eval1')",
"eval('print 123', nil)",
"x = proc{}; eval('test_eval = 2', x); print eval('test_eval', x);",
"TestEval = 5; print eval('TestEval')",
"a = 1; eval('print a')",
"print eval('')",
"eval('print 54321')",
};
String[] outputs = {
"7",
"5",
"6",
"nil5",
"123",
"2",
"5",
"1",
"nil",
"54321",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_not_equal() {
String[] program_texts = {
"print 'abc'!=123",
"print 'abc'!='abc'",
};
String[] outputs = {
"true",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_equal() {
String[] program_texts = {
"print 1.equal?(1)",
"print 'ab' 'cd'=='abcd'",
"print 'abc'==123",
"print 'abc'=='abc'",
"print 'abc'=='abcd'",
"a = 'xxx'; b = 'xxx'; print a==b",
"print nil==nil",
"print 1==1",
"print []==[]",
"print [1, 2, 3]==[1, 2, 3]",
"print [1, 2, 3]==[1, 2, 3, 4]",
"a = nil; print a==nil",
"$x = '0'; print $x == $x",
//"print :s == :s",
};
String[] outputs = {
"true",
"true",
"false",
"true",
"false",
"true",
"true",
"true",
"true",
"true",
"false",
"true",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_precedence() {
String[] program_texts = {
"false || b = 2;print b",
//TODO"x=1;print(x << y = 2);print y",
//TODO"x=1;print(x + y = 2);print y",
};
String[] outputs = {
"2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_and_or() {
String[] program_texts = {
"false or a = 1; print a",
"print nil and 'xxx'",
"print true && 'xxx'",
"print 1 or 'yyyy'",
"print false || 5678",
"true && (print 'xxx')",
"false && (print 'xxx')",
"false || (print 'xxx')",
"true || (print 'xxx')",
};
String[] outputs = {
"1",
"nil",
"xxx",
"1",
"5678",
"xxx",
"",
"xxx",
"",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_not() {
String[] program_texts = {
"print !!true",
"print !true",
"print !false",
"def f; false; end; print 33 if !f",
};
String[] outputs = {
"true",
"false",
"true",
"33",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_symbol() {
String[] program_texts = {
"print :self",
"print :\"
"print :[]=",
"print :\"!\"",
"print :'='",
"print :hello1.id2name",
"print :hello2.to_a",
"print :fred.inspect",
"print :next.to_a",
"print :<<",
"print :eql?",
"print :test.to_s",
"print :test.to_sym"
};
String[] outputs = {
"self",
"1",
"[]=",
"!",
"=",
"hello1",
"hello2",
":fred",
"next",
"<<",
"eql?",
"test",
"test"
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_global_variable() {
String[] program_texts = {
"$a = 1234; print $a",
"$B = 'xyz'; print $B",
"print $NO_SUCH_VARIABLE",
"print $a0 = 'xxx'",
"def f\n" +
" $G = 123\n" +
"end\n" +
"f\n" +
"print $G",
"def f\n" +
" $F0 = 123\n" +
"end\n" +
"print $F0",
"print $$.instance_of?(Fixnum)",
};
String[] outputs = {
"1234",
"xyz",
"nil",
"xxx",
"123",
"nil",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_assign_read_only_global_variable() {
String[] program_texts = {
"$$ = 1",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.NameErrorClass, "$$ is a read-only variable"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_command_output() {
String[] program_texts = {
"print `echo xxx`",
};
String[] outputs = {
"xxx\n",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_require_exception() {
String[] program_texts = {
"require 'no_such_file_xxx'",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.LoadErrorClass, "no such file to load -- no_such_file_xxx"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_require() throws FileNotFoundException {
String program_text = "print 'xxxxx'";
File file = new File("test_require.rb");
file.delete();
PrintStream fstm = new PrintStream(file);
fstm.print(program_text);
fstm.close();
assertTrue(file.exists());
try {
String[] program_texts = {
"require 'test_require'",
};
String[] outputs = {
"xxxxx",
};
compile_run_and_compare_output(program_texts, outputs);
} finally {
assertTrue(file.delete());
}
}
public void test_require_2_files() throws FileNotFoundException {
String program_text1 = "print 'xxxxx'; REQUIRE_2_FILES = 1";
File file1 = new File("test_require1.rb");
file1.delete();
PrintStream fstm1 = new PrintStream(file1);
fstm1.print(program_text1);
fstm1.close();
assertTrue(file1.exists());
String program_text2 = "print 'yyyyy', REQUIRE_2_FILES";
File file2 = new File("test_require2.rb");
file2.delete();
PrintStream fstm2 = new PrintStream(file2);
fstm2.print(program_text2);
fstm2.close();
assertTrue(file2.exists());
try {
String[] program_texts = {
"require 'test_require1'; require 'test_require2'",
};
String[] outputs = {
"xxxxxyyyyy1",
};
compile_run_and_compare_output(program_texts, outputs);
} finally {
assertTrue(file1.delete());
assertTrue(file2.delete());
}
}
public void test_require_2_files_with_global() throws FileNotFoundException {
String program_text1 = "$G010 = 'cccc'";
File file1 = new File("test_require3.rb");
file1.delete();
PrintStream fstm1 = new PrintStream(file1);
fstm1.print(program_text1);
fstm1.close();
assertTrue(file1.exists());
String program_text2 = "print $G010";
File file2 = new File("test_require4.rb");
file2.delete();
PrintStream fstm2 = new PrintStream(file2);
fstm2.print(program_text2);
fstm2.close();
assertTrue(file2.exists());
try {
String[] program_texts = {
"require 'test_require3'; require 'test_require4'",
};
String[] outputs = {
"cccc",
};
compile_run_and_compare_output(program_texts, outputs);
} finally {
assertTrue(file1.delete());
assertTrue(file2.delete());
}
}
public void test_yield() {
String[] program_texts = {
"def f; yield [], *[]; end; f {|x, | p x}",
"def f; yield [1,2,3,4] end;f {|w,x,y,z| print w,9,x,9,y,9,z}",
"def f; yield [1, 2], 3; end; f {|(x, y), z| print x, y, z}",
"def f; yield *[[]]; end; f {|a| print a.class, a.length}",
"def f; yield [[]]; end; f {|a| print a.class, a.length}",
"def f; yield [[]]; end; f {|a,b,*c| print a,'!',b,'!',c}",
"def f; yield *[[]]; end; f {|a,b,*c| print a,'|',b,'|',c}",
"def f; yield []; end; f {|a,b,*c| print a, b, c, 3}",
"def f; yield []; end; f {|a| print a, a.class}",
"def f; yield []; end; f {|*a| print a, a.class, a.length, a[0].class}",
"def f; yield; end; f {|*a| print a}",
"def f; yield; end; f {|a,b,*c| print a, b, c, 1}",
"def f; yield nil; end; f {|a,b,*c| print a, b, c, 2}",
"def f; ar = [1, 2,3,4]; yield ar; end; f {|a,b,*c| print c}",
"def f; yield 1, 2; end; f {|a| print a, a.class}",
"def f; yield 1, 2; end; f {|a, b| print a, b}",
"def f; yield *[3, 4]; end; f {|a, b| print a, b}",
"def f; yield [1]; end; f {|a| print a, a.class}",
"def f; yield [nil]; end; f {|a| print a, a.class, '|', a.length}",
"def f; yield nil; end; f {|a| print a}",
"def f; yield *nil; end; f {|a| print a, a.class}",
};
String[] outputs = {
"[]\n",
"1929394",
"123",
"Array0",
"Array1",
"!nil!",
"|nil|",
"nilnil3",
"Array",
"Array1Array",
"",
"nilnil1",
"nilnil2",
"34",
"12Array",
"12",
"34",
"1Array",
"Array|1",
"nil",
"nilNilClass",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_block() {
String[] program_texts = {
"[1].each do \n" +
" |test| print test; end",
"a= true\n" +
"1.times {|var| 1.times {|var|}} if a\n" +
"1.times {|var| 1.times {|var|}}",
"module TestPrintModuleInBlock; 1.times {print TestPrintModuleInBlock}; end",
"def a\n" +
" yield(\"haha\")\n" +
"end\n" +
"a {|x| print x}",
"3.times {print 'Ho!'}",
"5.times do |i|\n" +
" print i\n" +
"end",
"def a\n" +
" print yield(5)\n" +
"end\n" +
"a {|x| print x}",
"def a\n" +
" print yield(66)\n" +
"end\n" +
"a {|x| print x; 99}",
"3.times {|x, y| print x, y}",
};
String[] outputs = {
"1",
"",
"TestPrintModuleInBlock",
"haha",
"Ho!Ho!Ho!",
"01234",
"5nil",
"6699",
"0nil1nil2nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_yield_in_block() {
String[] program_texts = {
"def f; 2.times {yield} ; end; f {print '5'}",
"def f; 2.times { 3.times {yield}} ; end; f {print '5'}",
};
String[] outputs = {
"55",
"555555",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_No_VerifyError() {
String[] program_texts = {
" def f(sock, f)\n" +
" if chunked?\n" +
" while s = f.read(1024)\n" +
" sock\n" +
" end\n" +
" else\n" +
" while s = f.read(1024)\n" +
" sock\n" +
" end\n" +
" end\n" +
" end",
"x=1\n" +
"if x\n" +
" s = 1.times {|s| 2}\n" +
"end\n" +
"s",
"a=1\n" +
"if a\n" +
" x=1\n" +
" 1.times {x=2}\n" +
"else\n" +
" 1.times {x=3}\n" +
"end",
"arg = nil\n" +
"nonopt ||= proc {|arg| arg}\n" +
"arg = nil",
};
String[] outputs = {
"",
"",
"",
"",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_block_binding_scope() {
String[] program_texts = {
"a = 1; print self, a; 1.times {print self, a; 1.times {print self, a}}",
"a=1; 4.times {print a}",
"def f(a); 1.times {print a} end; f 101",
"a = 1; 5.times {|a| print a;}; print a",
"5.times {b = 3; print b;}",
"a=1; 4.times {a=2; print a}; print a",
"a = 1; 5.times {a = 9}; print a",
"a = 1; 5.times {|a| a = 9; print a;}; print a",
"a = 1; 5.times {|a| print a; a = 9; print a;}; print a",
"a = 1; 5.times {|a| print a; if false; a = 9; end; print a;}; print a",
"a = 1; 5.times {|*a| print a}; print a",
"a = 1; 4.times {|*a| a = 6; print a}; print a",
"def f(x); 1.times { x = 5} ; print x; end; f(1)",
"def f(&x); x.call; end; f {print 555}",
"class TestBlockBindingScope\n" +
" def initialize(num)\n" +
" @num = num\n" +
" end\n" +
" \n" +
" def each(&block)\n" +
" for i in 0 .. @num \n" +
" block.call(i) \n" +
" end \n" +
" end\n" +
" \n" +
"end\n" +
"\n" +
"te = TestBlockBindingScope.new(10)\n" +
"te.each {|item| print item}",
"class Array\n" +
" def test_self_in_block\n" +
" self.length.times do |index|\n" +
" print self[index]\n" +
" end\n" +
" end\n" +
"end\n" +
"\n" +
"foo = [4,5,6]\n" +
"foo.test_self_in_block",
};
String[] outputs = {
"main1main1main1",
"1111",
"101",
"012344",
"33333",
"22222",
"9",
"999999",
"09192939499",
"00112233444",
"012344",
"66666",
"5",
"555",
"012345678910",
"456",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_alias_global_variable() {
String[] program_texts = {
"$A = 1234; alias $B $A; print $A",
"$A = 'xyz'; alias $B $A; print $B",
"$A = 'xyz'; alias $B $A; print $C",
"$A = 'abcd'; alias $B $A; alias $C $B; print $C",
"$X = 1234; alias $Y $X; $X = 2345; print $X",
"$X = 1234; alias $Y $X; $X = 2345; print $Y",
};
String[] outputs = {
"1234",
"xyz",
"nil",
"abcd",
"2345",
"2345",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_alias_method() {
String[] program_texts = {
"1.times {alias :aliased_print :print};aliased_print 6",
"class Test_alias_method\n" +
"def a; print 34; end; alias_method :b, :a ;\n" +
"end\n" +
"Test_alias_method.new.b",
"module M; alias fail2 fail; end",
"def F_alias; print 22 ; end;alias G_alias F_alias; G_alias()",
"def f= x; print x;end; alias test_alias f=; test_alias 5",
"unless 1 == 1; alias :b :print; end",
"print(if true; alias :b :print; end)",
"def a; print 'qqq'; end; alias b a ; a",
"def c; print 'aaa'; end; alias d c ; d",
"def e; print 'bbb'; end; alias :f :e ; f",
"class TestAliasMethod\n" +
" def f\n" +
" print \"~~~~\"\n" +
" end\n" +
" alias g f\n" +
"end\n" +
"TestAliasMethod.new.f",
"class TestAliasMethod2\n" +
" def f\n" +
" print \"3333\"\n" +
" end\n" +
" alias g f\n" +
"end\n" +
"TestAliasMethod2.new.g",
"class Alias0; def foo; print \"foo\" end; end\n" +
"class Alias1<Alias0; alias bar foo; end\n" +
"Alias1.new.foo",
};
String[] outputs = {
"6",
"34",
"",
"22",
"5",
"",
"nil",
"qqq",
"aaa",
"bbb",
"~~~~",
"3333",
"foo",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_undef_should_not_remove_methods_from_super_class() {
String[] program_texts = {
"module TestUndef3; def test_undef_f; print 3;end; end\n" +
"module TestUndef4; include TestUndef3; undef :test_undef_f; end\n" +
"class TestUndef5; include TestUndef3; end\n" +
"TestUndef5.new.test_undef_f",
"class TestUndef1; def f; print 9898; end; end\n" +
"class TestUndef2 < TestUndef1; undef f; end\n" +
"TestUndef1.new.f",
};
String[] outputs = {
"3",
"9898",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_undef_method() {
String[] program_texts = {
"def a; print 'qqq'; end; undef a; a",
"def b; print 'qqq'; end; undef :b; b",
"class CTest\n" +
" def f123\n" +
" print \"~~~~\"\n" +
" end\n" +
" undef f123\n" +
"end\n" +
"CTest.new.f123",
"class CUndef\n" +
" def f12\n" +
" print \"~~~~\"\n" +
" end\n" +
" undef_method :f12\n" +
"end\n" +
"CUndef.new.f12",
"class TestUndef1; def f; print 9898; end; end\n" +
"class TestUndef2 < TestUndef1; undef f; end\n" +
"TestUndef2.new.f",
};
RubyException[] exceptions = {
//TODO exception type is not correct
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'a' for Object"),
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'b' for Object"),
new RubyException(RubyRuntime.NoMethodErrorClass, null),
new RubyException(RubyRuntime.NoMethodErrorClass, null),
new RubyException(RubyRuntime.NoMethodErrorClass, null),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_Enumerable() {
String[] program_texts = {
"a = [1, 3, 2].sort_by {|x| print x; 1};p a\n"+
"a = %w{apple pear fig }; b = a.sort_by {|word| word.length}; p a, b\n",
"p (1..10).sort {|a,b| b <=> a}\n",
"a = (1..10).detect {|i| i % 5 == 0 and i % 7 == 0 }; print a",
"a = (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }; print a",
"[1,2,3].each_with_index{|x, y| print x,y}",
"p (1..10).find_all {|i| i % 3 == 0 }",
"p [1, 2, 3, 4].find_all {|i| i % 3 == 0 }",
"p (5..10).inject {|sum, n| sum + n }\n"+
"p (5..10).inject(1) {|product, n| product * n }",
"class Two\n"+
" include Comparable\n"+
" attr :str\n"+
" def <=>(other)\n"+
" if !other.kind_of? Two\n"+
" return false\n"+
" end\n"+
" @str.size <=>other.str.size\n"+
" end\n"+
" def initialize(str)\n"+
" @str = str\n"+
" end\n"+
" def inspect\n"+
" @str\n"+
" end\n"+
" def add(other)\n"+
" Two.new(@str + other.str)\n"+
" end\n" +
"end\n"+
"class One\n"+
" include Enumerable\n"+
" def initialize\n"+
" t1 = Two.new(\"1\")\n"+
" t2 = Two.new(\"bc\")\n"+
" t3 = Two.new(\"567\")\n"+
" t4 = Two.new(\"0000\")\n"+
" @data = [t1,t2,t3,t4]\n"+
" end\n"+
" def each\n"+
" i = 0\n"+
" n = @data.size\n"+
" while i < n\n"+
" yield(@data[i])\n"+
" i += 1\n"+
" end \n"+
" #@data.each{|i|yield(i)}\n"+
" end\n"+
" def One.test\n"+
" o = One.new\n"+
" p o.member?(\"2\")\n"+
" p o.include?(Two.new(\"bc\"))\n"+
" p o.to_a\n"+
" p o.entries\n"+
" p o.inject{|sum,element|sum.add(element)}\n"+
" p o.inject(Two.new(\"begin\")){|sum,element|sum.add(element)}\n"+
" p o.max\n"+
" p o.min\n"+
" end\n"+
"end\n"+
"One.test\n",
"p [ nil, true, 99 ].any? \n"+
"p [ 2, true, 99 ].all? \n"+
"p [ nil, true, 99 ].all? \n"+
"p %w{ ant bear cat}.all? {|word| word.length >= 3}\n",
"p (1..4).collect {|i| i*i }\n"+
"p (1..4).map { \"cat\" }\n",
"p (1..6).partition {|i| (i&1).zero?}\n",
"p (1..100).grep 38..44\n"+
"c= [\"SEK_END\", \"SEEK_SET\", \"SEEK_CUR\"]\n"+
"p c.grep(/SEEK/)\n",
"a = [ 4, 5 ]\n"+
"b = [ 7, 8, 9 ]\n"+
"p (1..3).zip(a, b)\n"+
"p (1..3).zip\n",
};
String[] outputs = {
"132[1, 3, 2]\n[\"apple\", \"pear\", \"fig\"]\n[\"fig\", \"pear\", \"apple\"]\n",
"[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n",
"nil",
"35",
"102132",
"[3, 6, 9]\n",
"[3]\n",
"45\n151200\n",
"false\ntrue\n[1, bc, 567, 0000]\n[1, bc, 567, 0000]\n1bc5670000\nbegin1bc5670000\n0000\n1\n",
"true\ntrue\nfalse\ntrue\n",
"[1, 4, 9, 16]\n[\"cat\", \"cat\", \"cat\", \"cat\"]\n",
"[[2, 4, 6], [1, 3, 5]]\n",
"[38, 39, 40, 41, 42, 43, 44]\n[\"SEEK_SET\", \"SEEK_CUR\"]\n",
"[[1, 4, 7], [2, 5, 8], [3, nil, 9]]\n[[1], [2], [3]]\n",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_default() {
String[] program_texts = {
"h = Hash.new {print 4;3}; print h[2]",
"h = Hash.new(1); print h[2]",
"h = {}; def h.default(x); print 'x'; x; end; print h[1], h[2]",
"h = { 'a' => 100, 'b' => 200 }; print h.default",
"h = { 'a' => 100, 'b' => 200 };h.default = 'Go fish'; print h['a'], h['z'] ",
"h = Hash.new() {1}; h.default=5; print h[33]",
};
String[] outputs = {
"43",
"1",
"xx12",
"nil",
"100Go fish",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_misc() {
String[] program_texts = {
"p({1=>2, 4=>3, 2=>3}.delete_if {|x, y| x < y})",
"{6=>'x'}.each_key {|k| print k}",
"h={[1] => 1};print h[[1]]",
"h = {1=>2}; print h.delete(1); print h.delete(4); print h.size",
"a = {:s => 9}; print a[:s], a['s']",
"a = {1=>2}; a[1] = 3; p a",
// "p({1 => 2, 3 => 4}.merge!({3 =>7, 4=>6}))", // Different Hash Implementation
"p({1 => 2, 3 => 4})",
"print({1 =>3}.fetch(1))",
"print({1 =>4}.fetch(2, 5))",
"{1 =>4}.fetch(2) {|x| print x}",
"a = {1, 2}; b = a.dup; b.shift; print a, b",
"print {}",
"h1 = Hash.new { |hash1, key1| hash1[key1] = 'xx' }; print h1[123]",
"a = Hash.new{|h, k|k}; print a[99], a[88]",
"a = Hash.new{print 2; 1}; print a[99], a[88]",
"a = Hash.new{print 2; 1}; print a[99]",
"h4 = {'a' => 'xxxx', 'b' => 'yyyy'}; print h4.length",
"h3 = {'a' => 'xxxx', 'b' => 'yyyy'}; print h3['NO_SUCH_THING']",
"h2 = {'a' => 'xxxx', 'b' => 'yyyy'}; print h2['a']",
"h5 = {'a' => 'xxxx', 1 => 'yyyy'}; print h5[1]",
"h6 = {'a' => 'xxxx', 1 => 'yyyy'}; h6['a'] = 'zzz'; print h6['a']",
"h7 = {}; h7['c'] = 1234; print h7['c']",
"a = {1, 2}; print a[1]",
};
String[] outputs = {
"{4=>3}\n",
"6",
"1",
"2nil0",
"9nil",
"{1=>3}\n",
// "{1=>2, 3=>7, 4=>6}\n",
"{1=>2, 3=>4}\n",
"3",
"5",
"2",
"12",
"nil",
"xx",
"9988",
"2211",
"21",
"2",
"nil",
"xxxx",
"yyyy",
"zzz",
"1234",
"2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_each() {
String[] program_texts = {
"{1=>2}.each {|x, y| print x, y}",
};
String[] outputs = {
"12",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_hash_key_has_value() {
String[] program_texts = {
"a = {1=> 2}; print a.has_key?(1), a.has_key?(2)",
"a = {1=> 2}; print a.has_value?(1), a.has_value?(2)",
};
String[] outputs = {
"truefalse",
"falsetrue",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_values_at() {
String[] program_texts = {
"a = {1=> 2, 3 =>4}; print a.values_at(0)",
"a = {1=> 2, 3 =>4}; print a.values_at(1, 3)",
"a = {1=> 2, 3 =>4}; print a.values_at()",
};
String[] outputs = {
"",
"24",
"",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_equal() {
String[] program_texts = {
"print ({1=> 2, 3 =>4} == {1=> 2, 3 =>4})",
"print ({1=> 2, 3 =>4} == {1=> 2})",
"print ({1=> 2, 3 =>4} == { 3 =>4, 1=> 2})",
};
String[] outputs = {
"true",
"false",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_keys_values() {
String[] program_texts = {
"h = {'a' => 100, 'b' => 200, 'c' => 300, 'd' => 400}; print h.keys.sort",
"h = {'a' => 100, 'b' => 200, 'c' => 300, 'd' => 400}; print h.values.sort",
};
String[] outputs = {
"abcd",
"100200300400",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Hash_shift() {
String[] program_texts = {
"h = {'a' => 100}; print h.shift, h.size",
"h = {}; print h.shift, h.size",
};
String[] outputs = {
"a1000",
"nil0",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_while_until() {
String[] program_texts = {
"print 7 while false",
"begin; print 5; end while false",
"begin; print 6; end until true",
"i = 0\n" +
"while i<20; i+=1; result = i; end\n" +
"print result",
"i = 0\n" +
"while i<3; i+=1; result = i; end\n" +
"print result",
"i = 1 ;while i < 1 ; end; print i",
"while false; print 'xxx'; end",
"until true; print 'xxx'; end",
"a = 0\n" +
"while a > 1\n" +
" print 'xxx'\n" +
" a = 1\n" +
"end",
"a = 2\n" +
"while a > 1\n" +
" print 'xxx'\n" +
" a = 1\n" +
"end",
};
String[] outputs = {
"",
"5",
"6",
"20",
"3",
"1",
"",
"",
"",
"xxx",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_break_in_while() {
String[] program_texts = {
"i = 0; while i < 5; i = i + 1; print i; break if i == 3; end",
"print (while true; break 66; end)",
"print (while true; break; end)",
};
String[] outputs = {
"123",
"66",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_break_in_block() {
String[] program_texts = {
"3.times {|x| print x;while true; break;end}",
"i =0\n" +
"def f\n" +
" 1.upto(10) {|i|\n" +
" yield i\n" +
" }\n" +
"end\n" +
"f{|i| break if i == 5}\n" +
"\n" +
"print i",
};
String[] outputs = {
"012",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_redo_in_while() {
String[] program_texts = {
"i = 0; while i < 5; i = i+1; redo if i == 3; print i; end",
};
String[] outputs = {
"1245",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_redo_in_block() {
String[] program_texts = {
"done = false\n" +
"loop {\n" +
" print \"in loop\"\n" +
" break if done\n" +
" done = true\n" +
" redo\n" +
"}",
"count = 1;\n" +
"for i in 1..9\n" +
" print i\n" +
" break if count == 4\n" +
" count = count + 1\n" +
" redo\n" +
"end",
};
String[] outputs = {
"in loopin loop",
"1111",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_retry_in_begin_end() {
String[] program_texts = {
"$bad = true\n" +
"begin\n" +
" raise \"this will be handled\"\n" +
"rescue\n" +
" if $bad\n" +
" $bad = false\n" +
" retry\n" +
" print \"you should not see this\"\n" +
" end\n" +
"end",
};
String[] outputs = {
"",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_retry() {
String[] program_texts = {
" sum=0\n" +
" for i in 1..10\n" +
" sum += i\n" +
" i -= 1\n" +
" print i\n" +
" if i > 0 && sum < 5\n" +
" retry\n" +
" end\n" +
" end",
"count = 1;\n" +
"for i in 1..9\n" +
" print i\n" +
" break if count == 4\n" +
" count = count + 1\n" +
" retry\n" +
"end",
};
String[] outputs = {
"010123456789",
"1111",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_next_in_while() {
String[] program_texts = {
"i = 0; while i < 5; i = i + 1; next; print i; end",
"i = 0; while i < 5; i = i + 1; next if i == 3; print i; end",
"i = 0; while i < 5; i = i + 1; next (print 'x') if i ==3; print i; end",
};
String[] outputs = {
"",
"1245",
"12x45",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_local_variable_assigned_in_whille_condition() {
String[] program_texts = {
"$TestWhile = 0\n" +
"def f\n" +
" $TestWhile = $TestWhile + 1 \n" +
"end\n" +
"\n" +
"while i = f(); break if i > 5; print i; end ",
};
String[] outputs = {
"12345",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_self() {
String[] program_texts = {
"print 1.next",
"print 2.next.next",
"print self.class",
"class A\n" +
" print self.class\n" +
"end",
"print self",
};
String[] outputs = {
"2",
"4",
"Object",
"Class",
"main",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_printf() {
String[] program_texts = {
"printf '%d %d %s', 1, 2, 'vvv'",
"printf '
"printf '\\n'",
"printf \"\\n\"",
};
String[] outputs = {
"1 2 vvv",
"
"\\n",
"\n",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_to_a() {
String[] program_texts = {
"print 1.to_a.class",
"print 1.to_a",
"print [1, 2, 3].to_a",
"print nil.to_a.length",
};
String[] outputs = {
"Array",
"1",
"123",
"0",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_scope() {
String[] program_texts = {
"x=0;1.times {x = 1};1.times {x = 2};print x",
"b = 1; 1.times {1.times {b=6}}; print b",
"a = 5; 1.times {1.times {print a}}",
"begin \n" +
" for k,v in true\n" +
" end\n" +
"rescue\n" +
"end\n" +
" \n" +
"print k",
"if false; test_scope_1 = 1; end; print test_scope_1",
"case 4; when 1; test_scope_2 = 1; end; print test_scope_2",
"a = 5\n" +
"class A\n" +
" a=9\n" +
" print a\n" +
"end\n" +
"print a",
};
String[] outputs = {
"2",
"6",
"5",
"nil",
"nil",
"nil",
"95",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_public() {
String[] program_texts = {
"module M; public :fail; end",
"class TestPublic1\n" +
" public\n" +
" def f\n" +
" print \"1111\"\n" +
" end\n" +
"end\n" +
"TestPublic1.new.f",
"class TestPublic2\n" +
" private\n" +
" def f\n" +
" print \"2222\"\n" +
" end\n" +
" public :f\n" +
"end\n" +
"TestPublic2.new.f",
"class TestPublic3\n" +
" private\n" +
" def f\n" +
" print \"3333\"\n" +
" end\n" +
" public 'f'\n" +
"end\n" +
"TestPublic3.new.f",
};
String[] outputs = {
"",
"1111",
"2222",
"3333",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_protected() {
String[] program_texts = {
"class C\n" +
" def test_protected1; end\n" +
" protected :test_protected1 \n" +
" def test_protected2(x); defined?(x.test_protected1) ;end\n" +
"end\n" +
"\n" +
"a = C.new; print a.test_protected2(a)",
};
String[] outputs = {
"method",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_private_class_method() {
String[] program_texts = {
"class TestPCMB; def TestPCMB.f; print 1;end; end\n" +
"class TestPCMC < TestPCMB;private_class_method :f;end\n" +
"TestPCMB.f",
};
String[] outputs = {
"1",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_private_protected() {
String[] bad_program_texts = {
"class TestPrivateProtected1\n" +
" private\n" +
" def f\n" +
" print \"~~~~\"\n" +
" end\n" +
"end\n" +
"TestPrivateProtected1.new.pf",
"class TestPrivateProtected2\n" +
" protected\n" +
" def test_private_protected2\n" +
" print \"~~~~\"\n" +
" end\n" +
"end\n" +
"TestPrivateProtected2.new.test_private_protected2",
"class TestPrivateProtected3\n" +
" def tpp1\n" +
" print \"1111\"\n" +
" end\n" +
" private :tpp1\n" +
"end\n" +
"TestPrivateProtected3.new.tpp1",
"class TestPrivateProtected4\n" +
" def test_private_protected4\n" +
" print \"1111\"\n" +
" end\n" +
" private :no_such_method\n" +
"end\n",
"def test_private_protected5; end\n" +
"Object.new.test_private_protected5",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'pf' for TestPrivateProtected1"),
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'test_private_protected2' for TestPrivateProtected2"),
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'tpp1' for TestPrivateProtected3"),
new RubyException(RubyRuntime.NameErrorClass, "undefined method 'no_such_method' for TestPrivateProtected4"),
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'test_private_protected5' for Object"),
};
compile_run_and_catch_exception(bad_program_texts, exceptions);
}
public void test_defined() {
String[] program_texts = {
"print defined?(Kernel.print), defined?(Object.print)",
"test_defined_scope1 = 1; print defined?(test_defined_scope1)",
"1.times {test_defined_scope0 = 1}; print defined?(test_defined_scope0)",
"print defined?(yield)",
"def defined_test\n" +
" print defined?(yield)\n" +
"end\n" +
"\n" +
"defined_test\n" +
"defined_test {print 333}",
"print defined? yield",
"class C; def C.g; print 456; end; end\n" +
"def f; print 123; C; end\n" +
"print defined?(f().g)",
"$x=1; print defined?($x)",
"print defined?(Array)",
"print defined?(::Kernel)",
"print defined?(NO_SUCH_CONSTANT_XXX)",
"print defined?(Kernel::NO_SUCH_CONSTANT_XXX)",
"print defined?(1 == 2)",
"print defined? nil",
"print defined? 123",
"print defined? no_such_method",
"print defined? no_such_method(1, 2, 3)",
"print defined? to_s",
"def test_defined1(x); 'xxx'; end; print defined? test_defined1(1, 2)",
"def test_defined; end; undef test_defined; print defined? test_defined",
"print defined? super",
"class C; print defined? super; end",
"class TestDefined0; end\n" +
"class TestDefined2 < TestDefined0; def test_define; print defined? super end; end\n" +
"TestDefined2.new.test_define",
"class TestDefined0; def test_define; end; end\n" +
"class TestDefined2 < TestDefined0; def test_define; print defined? super end; end\n" +
"TestDefined2.new.test_define",
};
String[] outputs = {
"methodnil",
"local-variable",
"nil",
"nil",
"nilyield",
"nil",
"123method",
"global-variable",
"constant",
"constant",
"nil",
"nil",
"method",
"nil",
"expression",
"nil",
"nil",
"method",
"method",
"nil",
"nil",
"nil",
"nil",
"super",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Array_concat() {
String[] program_texts = {
"x = [ 'a', 'b' ].concat( ['c', 'd'] ); print x, x.length",
};
String[] outputs = {
"abcd4",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_instance_variable() {
String[] program_texts = {
"print @a",
"@a= 234; print @a",
"class TestInstanceVariable\n" +
" def f\n" +
" @a = 123\n" +
" end\n" +
" \n" +
" def display\n" +
" print @a\n" +
" end\n" +
"end\n" +
"\n" +
"a = TestInstanceVariable.new\n" +
"a.f\n" +
"a.display",
" class MyClass\n" +
" @one = 1\n" +
" def do_something\n" +
" @one = 2\n" +
" end\n" +
" def output\n" +
" print @one\n" +
" end\n" +
" end\n" +
" instance = MyClass.new\n" +
" instance.output\n" +
" instance.do_something\n" +
" instance.output",
};
String[] outputs = {
"nil",
"234",
"123",
"nil2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Class_name() {
String[] program_texts = {
"class Kernel::KC1 < Object;end;print Kernel::KC1",
"module TestClassName3; class TestClassName4; print name; end; end",
"class TestClassName2; attr_reader :name, :tests; print name; end",
"class TestClassName; print name; end",
};
String[] outputs = {
"Kernel::KC1",
"TestClassName3::TestClassName4",
"TestClassName2",
"TestClassName",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Object_extend() {
String[] program_texts = {
"a = 'x'; print a.frozen?; a.freeze; print a.frozen?",
"module Mod; def hello; \"Mod\"; end; end\n" +
"class Klass; def hello; \"Klass\"; end; end\n" +
"k = Klass.new; print k.hello; k.extend(Mod);print k.hello",
};
String[] outputs = {
"falsetrue",
"KlassMod",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_class_variable() {
String[] program_texts = {
"class TestClassVariableB1\n" +
" @@var__1 = 777\n" +
" def TestClassVariableB1.f\n" +
" @@var__1\n" +
" end\n" +
"end\n" +
"\n" +
"module TestClassVariableM1\n" +
" @@var__1 = 666\n" +
"end\n" +
"\n" +
"class TestClassVariableC1 < TestClassVariableB1\n" +
" include TestClassVariableM1\n" +
" \n" +
"end\n" +
"\n" +
"print TestClassVariableC1.f",
"class TestClassVariable2\n" +
" @@test_class_variable = \"xxx\"\n" +
" def test_class_variable1\n" +
" @@test_class_variable\n" +
" end\n" +
"end\n" +
"\n" +
"class TestClassVariable3 < TestClassVariable2\n" +
"end\n" +
"\n" +
"print TestClassVariable3.new.test_class_variable1",
"@@a= 567; print @@a",
"class TestClassVariable\n" +
" def f\n" +
" @@a = 123\n" +
" end\n" +
" \n" +
" def display\n" +
" print @@a\n" +
" end\n" +
"end\n" +
"\n" +
"a = TestClassVariable.new\n" +
"a.f\n" +
"a.display",
" class MyClass\n" +
" @@value = 1\n" +
" def add_one\n" +
" @@value= @@value + 1\n" +
" end\n" +
" \n" +
" def value\n" +
" @@value\n" +
" end\n" +
" end\n" +
" instanceOne = MyClass.new\n" +
" instanceTwo = MyClass.new\n" +
" print instanceOne.value\n" +
" instanceOne.add_one\n" +
" print instanceOne.value\n" +
" print instanceTwo.value",
"class TestClassVariable0\n" +
" @@test_class_variable = \"xxx\"\n" +
" def f\n" +
" @@test_class_variable\n" +
" end\n" +
"end\n" +
"\n" +
"class TestClassVariable1 < TestClassVariable0\n" +
" @@test_class_variable = \"yyy\"\n" +
"end\n" +
"\n" +
"print TestClassVariable0.new.f",
"class TestClassVariable4\n" +
" @@test_class_variable = \"000\"\n" +
" print @@test_class_variable\n" +
"end\n",
"class TestClassVariable5\n" +
" @@test_class_variable = \"zzz\"\n" +
" def TestClassVariable5.f\n" +
" @@test_class_variable\n" +
" end\n" +
"end\n" +
"\n" +
"print TestClassVariable5.f",
"class TestClassVariable6\n" +
" @@test_class_variable = \"ppp\"\n" +
" class <<self\n" +
" def f\n" +
" @@test_class_variable\n" +
" end\n" +
" end\n" +
"end\n" +
"\n" +
"print TestClassVariable6.f",
"module TestClassVariableM\n" +
" @@var = 999\n" +
"end\n" +
"\n" +
"class TestClassVariableC\n" +
" include TestClassVariableM\n" +
" def f\n" +
" @@var\n" +
" end\n" +
"end\n" +
"\n" +
"print TestClassVariableC.new.f",
"class TestClassVariableB2\n" +
" @@var = 777\n" +
" def g1\n" +
" @@var\n" +
" end\n" +
" \n" +
"end\n" +
"\n" +
"module TestClassVariableM2\n" +
" @@var = 999\n" +
" def g2\n" +
" @@var\n" +
" end\n" +
"end\n" +
"\n" +
"class TestClassVariableC2 < TestClassVariableB2\n" +
" include TestClassVariableM2\n" +
"end\n" +
"\n" +
"a = TestClassVariableC2.new\n" +
"print a.g1, a.g2 ",
};
String[] outputs = {
"777",
"xxx",
"567",
"123",
"122",
"yyy",
"000",
"zzz",
"ppp",
"999",
"777999",
};
compile_run_and_compare_output(program_texts, outputs);
String[] bad_program_texts = {
"print @@no_scuh_variable",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.NameErrorClass, "uninitialized class variable @@no_scuh_variable in Object"),
};
compile_run_and_catch_exception(bad_program_texts, exceptions);
}
public void test_multiple_assignment_non_local_variable() {
String[] program_texts = {
"@x,@y=1, 2; print @x, @y",
};
String[] outputs = {
"12",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_multiple_assignment_no_asterisk() {
String[] program_texts = {
"a = true; if a; x = (a,b=1,2); p x; end",
"a = []; a[0], a [2] = 3, 9; p a",
"w,x,y,z = [1,2,3,4];print w,9,x,9,y,9,z",
"c = (a,b=1,2); p c",
"a, = 1,2; print a",
"a, b = 3, 4; print a, b",
"a = 1; b = 2; a, b = b, a; print a, b",
"a = 1; b = 2; c = 3; a, b, c = b, a; print a, b, c",
"a = 1; b = 2; a, b = b, a, print(3); print a, b",
"a = 1, 2, 3; print a.class, a",
"a = 1, 2.5; print a",
};
String[] outputs = {
"[1, 2]\n",
"[3, nil, 9]\n",
"1929394",
"[1, 2]\n",
"1",
"34",
"21",
"21nil",
"321",
"Array123",
"12.5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_multiple_assignment_asterisk_only_on_the_left() {
String[] program_texts = {
"a, b, * = [1, 2, 3]; print a, b",
"*a = nil; print a.class, a.length, a[0]",
"a, b, *c = 1, 2, 3, 4, 5; print a, b, c.class, c",
"a,b,*c = nil; print a, b, c, c.class, c.length",
"*a = 1, 2, 3, 4, 5; print a",
"a, *b = 88, 99; print a, b, b.class",
"a,b,*c = []; print a, '|', b, '|', c",
"a,b,*c = [1, 2, 3]; print a, '|', b, '|', c",
"*a = []; print a[0].class",
};
String[] outputs = {
"12",
"Array1nil",
"12Array345",
"nilnilArray0",
"12345",
"8899Array",
"nil|nil|",
"1|2|3",
"Array",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_multiple_assignment_asterisk_only_on_the_right() {
String[] program_texts = {
"a = *nil; print a",
"a = *123; print a",
"a = 1; b = *a; print b",
"a = []; b = *a; print b, b.class",
"x = [1, 2, 3]; a, b, c = *x; print a, ',', b, ',', c",
"x = [1, 2, 3]; a, b = *x; print a, ',', b",
"x = [1, 2, 3]; a = *x; print a, a.class, a.length",
"x = [1, 2, 3]; a, b = 99, *x; print a, ',', b",
"x = [1, 2, 3]; a, b = 88, 99, *x; print a, ',', b",
"a,=*[1]; print a, a.class",
};
String[] outputs = {
"nil",
"123",
"1",
"nilNilClass",
"1,2,3",
"1,2",
"123Array3",
"99,1",
"88,99",
"1Fixnum",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_multiple_assignment_asterisk_on_both_sides() {
String[] program_texts = {
"a, *b = 1, *[2, 3]; print a, ',', b",
"a, *b = 1, *2; print a, ',', b, b.class",
"*a = *1; print a, a.class",
"*a = *nil; print a, a.class",
"*a = 1, 2, *[3, 4]; print a, '|', a.length",
"a, *b = 1, 2, *[3, 4]; print a, '|', b, '|', b.length",
"a, b, *c = 1, *[2, 3]; print a, '|', b, '|', c",
"a, b, *c = 1, *[2, 3, 4]; print a, '|', b, '|', c",
"a,b,*c = *[[]]; print a, b, c",
};
String[] outputs = {
"1,23",
"1,2Array",
"1Array",
"Array",
"1234|4",
"1|234|3",
"1|2|3",
"1|2|34",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_nested_assignment() {
String[] program_texts = {
"b, (c, d), e = 1,2,3,4; print b, c, d, e",
"b, (c, d), e = 1,[2,3,4],5; print b, c, d, e",
"b, (c,*d), e = 1,[2,3,4],5; print b, c, d, d.class, e",
};
String[] outputs = {
"12nil3",
"1235",
"1234Array5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_return() {
String[] program_texts = {
"def r; return 1; end; a = r(); print 1",
"def r; return *1; end; a = r(); print a, a.class",
"def r; return []; end; a = r(); print a, a.class",
"def r; return [*[]]; end; a = r(); print a, a.class, '*'",
"def r; return *[[]]; end; a = *r(); print a",
"def r; return *nil; end; *a = r(); print a.class, a.length, a[0]", //a == [nil]
};
String[] outputs = {
"1",
"1Fixnum",
"Array",
"Array*",
"nil",
"Array1nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_lamda_proc() {
String[] program_texts = {
"f = lambda{|x,| x}; p f.call([42])",
"def f; print 1; end; lambda(&method(:f)).call",
"a = lambda {print 'xxx'}; a.call",
"a = lambda {|x| print x}; a.call('yyy')",
"a = proc {|x, y| print x, y}; a.call(1, 2)",
"a = lambda {print self}; a.call",
};
String[] outputs = {
"[42]\n",
"1",
"xxx",
"yyy",
"12",
"main",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_loop_no_block_given() {
String[] program_texts = {
"loop",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.LocalJumpErrorClass, "in `loop': no block given"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_loop() {
String[] program_texts = {
"a = loop do break; end; print a",
"a = loop do break 123; end; print a",
};
String[] outputs = {
"nil",
"123",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_return_break_next_in_block() {
String[] program_texts = {
"def f █ 1.times {block.call}; print 'yyy'; end\n" +
"def test_return2; f {print 'xxx';return}; end\n" +
"test_return2",
"def f; [1, 2].each {|x| print x; return 4}; end; print(f)",
"def test()\n" +
" 3.times do |index|\n" +
" print index\n" +
" return\n" +
" end\n" +
"end\n" +
"\n" +
"test()",
"def test()\n" +
" 3.times do |index|\n" +
" print index\n" +
" break\n" +
" end\n" +
"end\n" +
"\n" +
"test()",
"def test()\n" +
" 3.times do |index|\n" +
" print index\n" +
" next\n" +
" end\n" +
"end\n" +
"\n" +
"test()",
"def f()\n" +
" 3.times do |index|\n" +
" return 123\n" +
" end\n" +
" print 456\n" +
"end\n" +
"\n" +
"print f()",
};
String[] outputs = {
"xxx",
"14",
"0",
"0",
"012",
"123",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_next_in_block() {
String[] program_texts = {
"def f; a= yield; print a; end; f {next 1}",
"def f; a= yield; print a, a.class; end; f {next *nil}",
"count = 1;\n" +
"for i in 1..9\n" +
" print i\n" +
" break if count == 4\n" +
" count = count + 1\n" +
" next\n" +
"end",
};
String[] outputs = {
"1",
"nilNilClass",
"1234",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_range_exception() {
String[] program_texts = {
"1 .. 'x'",
"'x' ... 3",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.ArgumentErrorClass, "bad value for range"),
new RubyException(RubyRuntime.ArgumentErrorClass, "bad value for range"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_range_equal() {
String[] program_texts = {
"print (1..2) == (1..2), (1..2) == (1...3)",
"a = 1..3; print a === 0",
"a = 1..3; print a === 1",
"a = 1..3; print a === 2",
"a = 1..3; print a === 3",
"a = 1..3; print a === 4",
"a = 1...3; print a === 3",
"a = 1...3; print a === 'x'",
"print 'abcd' === 'abcd'",
};
String[] outputs = {
"truefalse",
"false",
"true",
"true",
"true",
"false",
"false",
"false",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Range_to_a() {
String[] program_texts = {
"print((1...1).to_a)",
"print ((1..7).to_a)",
};
String[] outputs = {
"",
"1234567",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_regex_case_equal() {
String[] program_texts = {
"print /^f.*r$/ === 'foobar'",
"print /hello/ === '1234'",
};
String[] outputs = {
"true",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_regex_match() {
String[] program_texts = {
"print(/\\A\\w:\\/\\z/ =~ 'C:/')",
"print /(.)(.)(\\d+)(\\d)/.match(\"THX1138.\")",
"print /(.)(.)(\\d+)(\\d)/.match(\"THX.\")",
"print /(.)(.)(\\d)+(\\d)/ =~ \"THX1138.\"",
"print /(.)(.)(\\d+)(\\d)/ =~ \"THX.\"",
};
String[] outputs = {
"0",
"HX1138",
"nil",
"1",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_MatchData() {
String[] program_texts = {
"m = /(.)(.)(\\d+)(\\d)/.match('THX1138.'); print m[0]",
};
String[] outputs = {
"HX1138",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Regex_quote() {
String[] program_texts = {
"print Regexp.quote('ABCD')",
"print Regexp.quote('(AB)CD')",
"print Regexp.quote('[AB]CD')",
"print Regexp.quote('{AB}CD')",
"print Regexp.quote('*+?|')",
"print Regexp.quote('=!><~')",
};
String[] outputs = {
"ABCD",
"\\(AB\\)CD",
"\\[AB\\]CD",
"\\{AB\\}CD",
"\\*\\+\\?\\|",
"=!><~",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_RegexpExpressionSubstitution() {
String [] program_texts = {
"print /^f
"a = 'f.*r'; print /^
};
String[] outputs = {
"true",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test__FILE__() {
String [] program_texts = {
"print __FILE__",
};
String[] outputs = {
"-",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test__LINE__() {
String [] program_texts = {
"print __LINE__ \n print __LINE__ \n\n print __LINE__",
};
String[] outputs = {
"124",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_StringExpressionSubstitution() {
String [] program_texts = {
"print \"\\n
"print \"#{1}\" \"3\" \"#{2}\" ",
"print \"abc#{}opq#{ }xyz\"",
"$a=1;$b= 2;print \"abc#$a opq#$b xyz\"",
"a=3;b= 4;print \"abc#{a}opq#{ b }xyz\"",
"a=1;print \"abc#{a=a+1}\"; print a",
};
String[] outputs = {
"\n1\n",
"132",
"abcopqxyz",
"abc1 opq2 xyz",
"abc3opq4xyz",
"abc22",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_File() {
File file = new File("test_File.txt");
file.delete();
assert(!file.exists());
String [] program_texts = {
"f = open('test_File.txt', 'w'); print f.class; print f.close",
};
String[] outputs = {
"Filenil",
};
compile_run_and_compare_output(program_texts, outputs);
assertTrue(file.exists());
assertTrue(file.delete());
}
public void test_File_misc() {
String [] program_texts = {
"print File::SEPARATOR",
"print File.join('usr', 'mail', 'gumby')",
"print File.expand_path('sub', '
"print File.expand_path('/', 'c:/sub')",
"print File.expand_path('/dir', '//machine/share/sub')",
"print File.expand_path('../../bin', '/tmp/x')",
"print File.expand_path('/', '//machine/share/sub')",
"print File.expand_path('.', '
"print File.dirname('/')",
"print File.basename('abc.rb', '.*')",
"print File.basename('/')",
"print File.dirname('/abc/def')",
//Windows only "print File.expand_path('a', '/')",
};
String[] outputs = {
"/",
"usr/mail/gumby",
"//sub",
"c:/",
"//machine/share/dir",
"/bin",
"//machine/share",
"
"/",
"abc",
"/",
"/abc",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_wrong_number_of_arguments() {
String[] program_texts = {
"def f(a = 0) end; f 5, 6, 7",
"def f(a) end; f 1, 2",
"def f() end; f 1",
"def f(a) end; f",
"def f(a, b, c) end; f(1)",
"def f(a, b, c=2) end; f(1)",
"def f(b); b.call(1);end; f(lambda {||})",
"def f(b); b.call(1, 2);end; f(lambda {|x, y, z|})",
"def f(b); b.call(1, 2);end; f(lambda {|x, |})",
"def getblock(&b); b; end; res = getblock(&lambda{||}); res.call(1, 2)",
"def f= x; print x;end; alias test_wrong_number_of_arguments f=\n" +
"module M; def test_wrong_number_of_arguments; end;end; include M\n" +
"test_wrong_number_of_arguments",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.ArgumentErrorClass, "in `f': wrong number of arguments (3 for 1)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "in `f': wrong number of arguments (2 for 1)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "in `f': wrong number of arguments (1 for 0)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "in `f': wrong number of arguments (0 for 1)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "in `f': wrong number of arguments (1 for 3)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "in `f': wrong number of arguments (1 for 2)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments (1 for 0)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments (2 for 3)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments (2 for 1)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments (2 for 0)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "in `f=': wrong number of arguments (0 for 1)"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_default_argument() {
String [] program_texts = {
"def f(a = 5432) print a; end; f 666",
"def f(a = 5432) print a; end; f",
"def f(a = 111, b = 222) print a, b; end; f",
"def f(a = 111, b = 222) print a, b; end; f 333",
"def f(a = 111, b = 222) print a, b; end; f 333, 444",
"def x; 99; end; def f(a=x()) print a; end; f",
"def f(a=x()) print a; end; print 'hi'; def x; print 'x';99; end; f",
"def f(a=x()) print a; end; print 'hi'; def x; print 'x';99; end; f 88",
};
String[] outputs = {
"666",
"5432",
"111222",
"333222",
"333444",
"99",
"hix99",
"hi88",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_module() {
String [] program_texts = {
"module TestModule10;end\n" +
"class TestModule10::TestModule11;end\n" +
"print TestModule10::TestModule11",
"module Kernel::A;end;print Kernel::A",
"module M1;end; module M1::M2;print self;end",
"module Kernel::M2;print self;end",
"module TestModule; end; print TestModule.class",
"module TestModule; end; print TestModule",
};
String[] outputs = {
"TestModule10::TestModule11",
"Kernel::A",
"M1::M2",
"Kernel::M2",
"Module",
"TestModule",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_include_module() {
String [] program_texts = {
"module Test1; module Test2; def test_include_3; print Test2; end; end; end\n" +
"include Test1::Test2; test_include_3",
"module TEST_CONSTANT_M; TEST_CONSTANT = 5; end\n" +
"print(include(TEST_CONSTANT_M))\n" +
"print TEST_CONSTANT",
"module TestTopLevelIncludeModule\n" +
" def test_top_level_include_module\n" +
" print 77777\n" +
" end\n" +
"end\n" +
"\n" +
"include TestTopLevelIncludeModule\n" +
"test_top_level_include_module",
"module TestTopLevelIncludeModule\n" +
" @@var = 100\n" +
" \n" +
" def test_top_level_include_module\n" +
" print @@var\n" +
" end\n" +
"end\n" +
"\n" +
"include TestTopLevelIncludeModule\n" +
"test_top_level_include_module",
"module TestTopLevelIncludeModule1\n" +
" def g\n" +
" print \"B1\"\n" +
" end\n" +
"end\n" +
"\n" +
"module TestTopLevelIncludeModule2\n" +
" def g\n" +
" print \"B2\"\n" +
" end\n" +
"end\n" +
"\n" +
"include TestTopLevelIncludeModule1\n" +
"include TestTopLevelIncludeModule2\n" +
"g",
"module TestTopLevelIncludeModule3\n" +
"end\n" +
"\n" +
"include TestTopLevelIncludeModule3\n" +
"\n" +
"module TestTopLevelIncludeModule3\n" +
" def test_top_level_include_module2\n" +
" print 8765\n" +
" end\n" +
"end\n" +
"\n" +
"test_top_level_include_module2",
"module TestIncludeM; def f; print 7654; end; end\n" +
"class TestIncludeC; include TestIncludeM; end\n" +
"TestIncludeC.new.f",
"module TestIncludeM2; def f; print 1234; end; end\n" +
"class TestIncludeC2; include TestIncludeM2; alias :g :f; end\n" +
"TestIncludeC2.new.g",
};
String[] outputs = {
"Test1::Test2",
"Object5",
"77777",
"100",
"B2",
"8765",
"7654",
"1234",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_break_LocalJumpError() {
String[] program_texts = {
"a = Proc.new {break}; a.call",
"def getblock(&b); b; end\n" +
"res = getblock { break }\n" +
"res.call",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.LocalJumpErrorClass, "break from proc-closure"),
new RubyException(RubyRuntime.LocalJumpErrorClass, "break from proc-closure"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_include_wrong_type() {
String[] program_texts = {
"include 'x'",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.TypeErrorClass, "wrong argument type String (expected Module)"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_class_and_module_name_conflict() {
String[] program_texts = {
"module TestNameConflict;end; class TestNameConflict;end",
"class TestNameConflict2;end; module TestNameConflict2;end;",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.TypeErrorClass, "TestNameConflict is not a class"),
new RubyException(RubyRuntime.TypeErrorClass, "TestNameConflict2 is not a module"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_class_module_in_class_module() {
String [] program_texts = {
"module M; class Object; print 'another object'; end; end",
"module ConstantInModule\n" +
" class C\n" +
" def f\n" +
" print \"MCf\"\n" +
" end\n" +
" end\n" +
"end\n" +
"\n" +
"ConstantInModule::C.new.f",
"class ConstantInModule2\n" +
" class C\n" +
" def f\n" +
" print \"MCf2\"\n" +
" end\n" +
" end\n" +
"end\n" +
"\n" +
"ConstantInModule2::C.new.f",
"TestM0 = 0\n" +
"\n" +
"module TestM1\n" +
" module TestM2\n" +
" module TestM3\n" +
" TestM4 = 1\n" +
" print TestM0,TestM1, TestM2, TestM3, TestM4\n" +
" end\n" +
" end\n" +
"end",
"module TestConst1\n" +
" module TestConst2\n" +
" end\n" +
"end\n" +
"\n" +
"module TestConst1\n" +
" class TestConst3\n" +
" print TestConst2\n" +
" end\n" +
"end",
};
String[] outputs = {
"another object",
"MCf",
"MCf2",
"0TestM1TestM1::TestM2TestM1::TestM2::TestM31",
"TestConst1::TestConst2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_colon2_as_method_call() {
String [] program_texts = {
"module M; def M.colon2_as_method_call2 x; print x; end; end\n" +
"M::colon2_as_method_call2 345",
"def Object.test_colon2_as_method_call; print 'xxx'; end\n" +
"Object::test_colon2_as_method_call",
};
String[] outputs = {
"345",
"xxx",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_constant_in_singletonmethod() {
String [] program_texts = {
"module M; N = 4; end\n" +
"class << M\n" +
" N = 3\n" +
" print N\n" +
" def f\n" +
" print N\n" +
" end\n" +
"end\n" +
"M.f",
"module M;end\n" +
"class << M\n" +
" N = 3\n" +
" print N\n" +
"end",
"a='x';def a.f;print String;end;a.f",
};
String[] outputs = {
"33",
"3",
"String",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_constant_in_class_module() {
String [] program_texts = {
"module TestConstant20; end\n" +
"class << TestConstant20\n" +
" N =2\n" +
" def f(klass)\n" +
" class << klass\n" +
" print N\n" +
" end\n" +
" end\n" +
"end\n" +
"\n" +
"module TestConstant21;end\n" +
"TestConstant20.f TestConstant21",
"TestConstant10=3\n" +
"class TestConstant11\n" +
" TestConstant10=4\n" +
" def TestConstant11.f\n" +
" print TestConstant10\n" +
" end\n" +
"end\n" +
"TestConstant11.f",
"module ConstantInModule; C6 = 6; def ConstantInModule.f; print C6; end; end; ConstantInModule.f",
"print Object::Kernel",
"TestConstant = 1999; print ::TestConstant",
"::TestConstant0 = 9991; print ::TestConstant0",
"module ConstantInModule; ABC = 123; end; print ConstantInModule::ABC",
"C1 = 9;module TestConstant1;C1 = 10;print C1;end",
"C2 = 9;module TestConstant2;C2 = 10;print ::C2;end",
"C3 = 9;module TestConstant3;C3 = 11;print self::C3;end",
"C4 = 8;module TestConstant4;print C4;end",
"C5 = 5\n" +
"class TestConstant5\n" +
" def f\n" +
" print C5\n" +
" end\n" +
"end\n" +
"\n" +
"TestConstant5.new.f",
};
String[] outputs = {
"2",
"4",
"6",
"Kernel",
"1999",
"9991",
"123",
"10",
"9",
"11",
"8",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_constant_in_module_exception() {
String[] program_texts = {
"Object::CONSTANT_IN_MODULE_EXCEPTION_YYY",
"CONSTANT_IN_MODULE_EXCEPTION_XXX",
"module ConstantInModuleException; end; ConstantInModuleException::NO_SUCH_CONST_XXX",
"a=1; a::B",
"ConstantInModuleException2=9; ConstantInModuleException2::B",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.NameErrorClass, "uninitialized constant CONSTANT_IN_MODULE_EXCEPTION_YYY"),
new RubyException(RubyRuntime.NameErrorClass, "uninitialized constant CONSTANT_IN_MODULE_EXCEPTION_XXX"),
new RubyException(RubyRuntime.NameErrorClass, "uninitialized constant ConstantInModuleException::NO_SUCH_CONST_XXX"),
new RubyException(RubyRuntime.TypeErrorClass, "1 is not a class/module"),
new RubyException(RubyRuntime.TypeErrorClass, "9 is not a class/module"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_initialize() {
String [] program_texts = {
"class TestInitialize\n" +
" def initialize\n" +
" print \"in initialize\"\n" +
" end\n" +
"end\n" +
" \n" +
"TestInitialize.new",
"print String.new('xxx')",
"class TestInitializeString < String; end; print TestInitializeString.new('yyy')",
};
String[] outputs = {
"in initialize",
"xxx",
"yyy",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_attr() {
String [] program_texts = {
"class TestAttr; attr :size, true; end; c = TestAttr.new; c.size= 5; print c.size",
};
String[] outputs = {
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_attr_reader() {
String [] program_texts = {
"class TestAttrReader\n" +
" attr_reader :a\n" +
"\n" +
" def initialize\n" +
" @a = 5\n" +
" end\n" +
"end\n" +
"\n" +
"print TestAttrReader.new.a",
"class TestAttrReader2\n" +
" attr_reader 'b'\n" +
"\n" +
" def initialize\n" +
" @b = 6\n" +
" end\n" +
"end\n" +
"\n" +
"print TestAttrReader2.new.b",
};
String[] outputs = {
"5",
"6",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_attr_reader_exception() {
String[] program_texts = {
"module AttrReaderException; attr_reader 1; end",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.TypeErrorClass, "1 is not a symbol"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_assignment_method() {
String [] program_texts = {
"class TestAssignmetMethod\n" +
" def a=(x)\n" +
" print \"fff\"\n" +
" end\n" +
"end\n" +
"\n" +
"TestAssignmetMethod.new.a=4",
};
String[] outputs = {
"fff",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_assignment_parameter() {
String [] program_texts = {
"def f x\n" +
" while x > 0\n" +
" x -= 1\n" +
" print x\n" +
" end\n" +
"end\n" +
"\n" +
"f(5)",
};
String[] outputs = {
"43210",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_attr_writer() {
String [] program_texts = {
"class TestAttrWriter\n" +
" attr_writer :a\n" +
"\n" +
" def get_a\n" +
" @a\n" +
" end\n" +
"end\n" +
"\n" +
"x = TestAttrWriter.new; x.a = 5; print x.get_a",
};
String[] outputs = {
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_attr_accessor() {
String [] program_texts = {
" class TestSingletonAttrAccessor\n" +
" @use_pp = true\n" +
" class << self; attr_accessor :use_pp; end\n" +
"end\n" +
"print TestSingletonAttrAccessor.use_pp",
"class TestAttrAccessor\n" +
" attr_accessor :a\n" +
"end\n" +
"\n" +
"x = TestAttrAccessor.new; x.a = 5; print x.a",
};
String[] outputs = {
"true",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_kind_of() {
String [] program_texts = {
"print Kernel.kind_of?(Kernel)",
"print(1.kind_of?(Object))",
"print(1.kind_of?(Fixnum))",
"print(1.kind_of?(Numeric))",
"print(1.kind_of?(String))",
};
String[] outputs = {
"true",
"true",
"true",
"true",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_instance_of() {
String [] program_texts = {
"print(1.instance_of?(Object))",
"print(1.instance_of?(Fixnum))",
"print(1.instance_of?(Numeric))",
"print(1.instance_of?(String))",
};
String[] outputs = {
"false",
"true",
"false",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_respond_to() {
String [] program_texts = {
"print 1.respond_to?('to_s')",
"print 1.respond_to?(:to_s)",
"print 1.respond_to?('no_such_method_xxx')",
"print 1.respond_to?(:no_such_method_xxx)",
"print 1.respond_to?(:lambda, true)",
"print 1.respond_to?(:lambda)",
};
String[] outputs = {
"true",
"true",
"false",
"false",
"true",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_singleton_method() {
String [] program_texts = {
"module TestSingleton10;end\n" +
"module TestSingleton11; end\n" +
"class << TestSingleton11\n" +
" TestSingleton12=2\n" +
" def f\n" +
" class <<TestSingleton10\n" +
" print TestSingleton12\n" +
" end\n" +
" end\n" +
"end\n" +
"TestSingleton11.f",
"module M; def M::colon2_singleton; print 'ppp'; end; end\n" +
"M.colon2_singleton",
"module M; def M.f x; print x; end end; M::f(77)",
"class TestSingleton0;\n" +
" def TestSingleton0.test_singleton; 123; end\n" +
"end\n" +
"\n" +
"class TestSingleton1 < TestSingleton0; end\n" +
"\n" +
"print TestSingleton1.test_singleton",
"a = 'x'; def a.ffff; print 9521 end; a.ffff",
"class TestSingletonClass; end\n" +
"def TestSingletonClass.new_method;print 4321;end\n" +
"TestSingletonClass.new_method\n",
"class Class < Module\n" +
" def test_meta\n" +
" print \"Test meta\"\n" +
" end\n" +
"end\n" +
"\n" +
"Module.test_meta",
};
String[] outputs = {
"2",
"ppp",
"77",
"123",
"9521",
"4321",
"Test meta",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_singleton_method_exception() {
String [] program_texts = {
"class TestSingleton2; end\n" +
"class TestSingleton3 < TestSingleton2;\n" +
" def TestSingleton3.f; 123; end\n" +
"end\n" +
"\n" +
"print TestSingleton2.f",
};
RubyException[] exceptions = {
//TODO message should be "undefined method `f' for TestSingleton2:Class"
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'f' for Class"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_if_unless_modifier() {
String [] program_texts = {
"print 123 if true",
"print 123 if false",
"print 456 unless false",
"print 456 unless true",
"print 1 if true if true",
};
String[] outputs = {
"123",
"",
"456",
"",
"1",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_send() {
String [] program_texts = {
"print 'xx'.send(:length)",
"print 1.__send__('+', 2)",
};
String[] outputs = {
"2",
"3",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_method_parameter_assignment() {
String [] program_texts = {
"def f x=1; x = 4; print x;end; f",
"def f x; x = 3; print x;end; f 1",
};
String[] outputs = {
"4",
"3",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_method_and_call() {
String [] program_texts = {
"m = 'xx'.method(:length); print m.call",
"m = 1.method('+'); print m.call(2)",
"m = 1.method('+'); print m",
"1.times {def f; print self; end}; f ",
};
String[] outputs = {
"2",
"3",
"#<Method: Fixnum#+>",
"main",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Kernel_methods() {
String [] program_texts = {
"print 1.methods.include?('methods')",
"print 1.methods.include?('no_such_method_xxxx')",
};
String[] outputs = {
"true",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_implicit_hash() {
String [] program_texts = {
"def f a; print a.class, a['a'], a['b']; end\n" +
"f 'a' => 1, 'b' => 2",
};
String[] outputs = {
"Hash12",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_block_arg() {
String [] program_texts = {
"def bar(&blk); blk.call([:key, :value]);end\n" +
"bar{|k,v| print k, v}",
"def f(x, &block); if x; block = 1; end; print block; end; f true",
"def f(x); x; end; print f(33, &nil)",
"def f; yield; end\n" +
"def g1 &arg; f &arg; end\n" +
"g1 {print 321}",
"def f\n" +
" yield 222, 333\n" +
"end\n" +
"\n" +
"def g2 &arg\n" +
" f &arg\n" +
"end\n" +
"\n" +
"g2 {|x, y| print x, y}",
"def f &arg; print arg.class; end; f {}",
"def f &arg; print arg.class; end; f",
"def f(&arg); arg.call; end; f {print 123}",
"def f(&arg); arg.call(345); end; f {|x| print x}",
};
String[] outputs = {
"keyvalue",
"1",
"33",
"321",
"222333",
"Proc",
"NilClass",
"123",
"345",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_super() {
String [] program_texts = {
"class TestSuper21;def f x, y;print x + y; end;end\n" +
"class TestSuper22 < TestSuper21; def f(x, y); super x, y;end; end\n" +
"TestSuper22.new.f 3, 2",
"def f(x, y); super x;end",
"class TestSuper11;def f x;print x; end;end\n" +
"class TestSuper12 < TestSuper11; def f(); super 1;end; end\n" +
"TestSuper12.new.f",
"class TestSuper1; def f; 2 end; end\n" +
"class TestSuper2 < TestSuper1; def f; 1.times {return super} end end\n" +
"print TestSuper2.new.f",
"class TestSuper1; def f x; x end; end\n" +
"class TestSuper2 < TestSuper1; def f x; 1.times {return super} end end\n" +
"print TestSuper2.new.f(3)",
"def f *x; print x; end\n" +
"class TestSuper3;def f *x; 1.times {super} ; end;end\n" +
"TestSuper3.new.f 2, 3",
"class C; def initialize x = 1; super(); print x; end; end; C.new",
"class TestSuperSingleton; def TestSuperSingleton.f x; print x; end; end\n" +
"class TestSuperSingleton2 < TestSuperSingleton; def TestSuperSingleton2.f x; super; end; end\n" +
"TestSuperSingleton2.f 456",
"class TestSuperImplicitParameter\n" +
" def print x\n" +
" super\n" +
" end\n" +
"end\n" +
"\n" +
"TestSuperImplicitParameter.new.print 333",
"class TestSuper8\n" +
" def test_super\n" +
" print 123\n" +
" end\n" +
"end\n" +
"\n" +
"class TestSuper9 < TestSuper8\n" +
" def test_super\n" +
" super\n" +
" end\n" +
"end\n" +
"\n" +
"class TestSuper10 < TestSuper9\n" +
"end\n" +
"\n" +
"TestSuper10.new.test_super",
"class MyString < String\n" +
" def to_s\n" +
" super\n" +
" end\n" +
"end\n" +
"print MyString.new(\"xxx\").to_s",
"class TestSuper1\n" +
" def f\n" +
" yield\n" +
" end\n" +
"end\n" +
"\n" +
"class TestSuper2 < TestSuper1\n" +
" def f\n" +
" super\n" +
" end\n" +
"end\n" +
"\n" +
"TestSuper2.new.f {print \"yyy\"}",
"class TestSuper3\n" +
" def f\n" +
" yield\n" +
" end\n" +
"end\n" +
"\n" +
"class TestSuper4 < TestSuper3\n" +
" def f\n" +
" super {print \"zzz\"}\n" +
" end\n" +
"end\n" +
"\n" +
"TestSuper4.new.f",
"class TestSuper5\n" +
" def f\n" +
" print 321\n" +
" end\n" +
"end\n" +
"\n" +
"class TestSuper6 < TestSuper5\n" +
"end\n" +
"\n" +
"class TestSuper7 < TestSuper6\n" +
" def f\n" +
" super\n" +
" end\n" +
"end\n" +
"\n" +
"TestSuper7.new.f",
};
String[] outputs = {
"5",
"",
"1",
"2",
"3",
"23",
"1",
"456",
"333",
"123",
"xxx",
"yyy",
"zzz",
"321",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_heredoc_expression_substitution() {
String [] program_texts = {
"print <<EOF\n" +
"x#{456}y\n" +
"EOF\n",
"print <<EOF, 9\n" +
"x#{456}y\n" +
"EOF\n",
"print <<EOF, 9\n" +
"x#{456}y\n" +
"EOF\n" +
"print 8\n",
/*TODO
"print 1, <<EOF1, 2, <<EOF2, 3\n" +
"#{print 2}\n" +
"EOF1\n" +
"#{print 5}\n" +
"EOF2\n",
*/
};
String[] outputs = {
"x456y\n",
"x456y\n9",
"x456y\n98",
//"251\n2\n3\n",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_heredoc() {
String [] program_texts = {
"print <<EOF\n" +
"A\\
"EOF\n",
"print <<END;\n" +
"ABCD\n" +
"END\n",
"print <<EOF\n" +
"hey\n" +
"EOF\n",
"print <<EOF\n" +
" hey\n" +
"EOF\n",
"print <<-EOF\n" +
" hey\n" +
" EOF\n",
"print <<-EOF + 'xxx'\n" +
" hey\n" +
" EOF\n",
"print(<<EOF)\n" +
" eee\n" +
"EOF\n",
"print <<-EOF + \"#{'yyy'}\"\n" +
" hey\n" +
" EOF\n",
};
String[] outputs = {
"A
"ABCD\n",
"hey\n",
" hey\n",
" hey\n",
" hey\n" +
"xxx",
" eee\n",
" hey\n" +
"yyy",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_multiple_heredoc() {
String [] program_texts = {
"print <<EOF, 99, <<EOA\n" +
" hey\n" +
"EOF\n" +
" there\n" +
"EOA\n",
"print <<-EOF, 99, <<-EOA\n" +
" hello\n" +
" EOF\n" +
" there\n" +
" EOA\n",
"print <<-EOF + 'xxx' + <<-EOA\n" +
" hello\n" +
" EOF\n" +
" there\n" +
" EOA\n",
"print <<-EOF + String.new('yyy') + <<-EOA\n" +
" hello\n" +
" EOF\n" +
" there\n" +
" EOA\n",
};
String[] outputs = {
" hey\n" +
"99 there\n",
" hello\n" +
"99 there\n",
" hello\n" +
"xxx there\n",
" hello\n" +
"yyy there\n",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_class_left_shift() {
String [] program_texts = {
"a = \"\"\n" +
"class <<a\n" +
" def f\n" +
" 99\n" +
" end\n" +
"end\n" +
"\n" +
"print a.f",
"class TestClassLeftShift\n" +
" class << self\n" +
" def f\n" +
" 88\n" +
" end\n" +
" end\n" +
"end\n" +
"\n" +
"print TestClassLeftShift.f",
"class TestClassLeftShift\n" +
" class << TestClassLeftShift\n" +
" def f\n" +
" 77\n" +
" end\n" +
" end\n" +
"end\n" +
"\n" +
"print TestClassLeftShift.f",
};
String[] outputs = {
"99",
"88",
"77",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_IO_gets() {
RubyIO out = ObjectFactory.createFile("test_IO_gets.txt", "w");
out.print("line 1\n");
out.print("line 2");
out.close();
String [] program_texts = {
"f = open(\"test_IO_gets.txt\"); print f.gets(nil); f.close",
"f = open(\"test_IO_gets.txt\"); print f.gets; f.close",
"f = open(\"test_IO_gets.txt\"); print f.gets; print f.gets; print f.gets; f.close",
"f = open(\"test_IO_gets.txt\"); print f.gets; print $_; f.close",
};
String[] outputs = {
"line 1\nline 2",
"line 1\n",
"line 1\nline 2\nnil",//TODO should be "line 1\nline 2nil", IO#gets should be fixed
"line 1\nline 1\n",
};
compile_run_and_compare_output(program_texts, outputs);
File f = new File("test_IO_gets.txt");
assertTrue(f.delete());
}
public void test_IO_eof() throws IOException {
File f = new File("test_IO_eof.txt");
PrintWriter out = new PrintWriter(new FileWriter(f));
out.print("line 1\n");
out.print("line 2");
out.close();
String [] program_texts = {
"f = open(\"test_IO_eof.txt\"); f.gets(nil); print f.eof?; f.close",
"f = open(\"test_IO_eof.txt\"); print f.eof; f.close",
};
String[] outputs = {
"true",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
assertTrue(f.delete());
}
public void test_IO_misc() {
String [] program_texts = {
"$stdout << 'Hello ' << 'world!'",
};
String[] outputs = {
"Hello world!",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_string_match() {
String [] program_texts = {
"\"abcabc\" =~ /.*a/; print $&, $&.class",
"print \"\" =~ /^$/",
"print \"a\\n\\n\" =~ /^$/",
"print '123' !~ 123",
"print '123' =~ 123",
"print \"cat o' 9 tails\" =~ /\\d/",
"print \"cat o' 9 tails\" =~ /abc/",
};
String[] outputs = {
"abcaString",
"0",
"2",
"true",
"false",
"7",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_W_ARRAY() {
String [] program_texts = {
"p %w$a b c$",
"p %w{ a b c }",
};
String[] outputs = {
"[\"a\", \"b\", \"c\"]\n",
"[\"a\", \"b\", \"c\"]\n",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_String_misc() {
String [] program_texts = {
"print('a'.sub!(/#{'a'}/i, 'b'))",
"print 'Tuesday, July'.gsub!(/[^-+',.\\/:0-9@a-z\\x80-\\xff]+/i, ' ')",
"'cruel world'.scan(/\\w+/) {|w| print \"<<
"'cruel world'.scan(/(.)(.)/) {|x,y| print y, x }",
"'cruel world'.scan(/(.)(.)/) {|x,y| print $&}",
"print('%27Stop%21%27'.gsub(/((?:%[0-9a-fA-F]{2})+)/n) {'x'})",
"print '%21%27'.delete('%')",
"print 'aaBBcc'.delete!('a-z')",
"print ' abcd '.lstrip!",
"print %q{location:1 in 'l'}.sub(/\\A(.+:\\d+).*/, ' [\\\\1]')",
"print 'a.gif'.sub(/.*\\.([^\\.]+)$/, '<\\&>')",
"print 'a.gif'.sub(/.*\\.([^\\.]+)$/, 'a\\2b')",
"print 'a.gif'.sub(/.*\\.([^\\.]+)$/, '\\1')",
"print '%05d' % 123",
"print '%s:%s' % [ 'a', 'b' ]",
"print '0x0a'.hex",
"print 'xxxx'.hex",
"print 'pp'[-3..-1]",
"print 'hello world'.count('lo')",
"print 'abaca'.tr('a', 'z')",
"print \"\\na\\nb\\n\".tr(\"\\n\", ' ')",
"print 'xxx'.strip, 'xxx'.strip!, ' xxx '.strip, 'yyy '.strip!",
"a = 'a'; print a << 'b', a",
"print 'complex.rb'[-3..-1]",
"print 'complex.rb'[-3, -1]",
"print 'yyy'.inspect",
"p 'xxx'",
"print ''.empty?, 'x'.empty?",
"print 'x'[-1]",
"print 'x'[2]",
"print \"\\#\".length",
"print 'abcd'.delete('bc')",
"print 'abcc'.squeeze!('a-z')",
"print 'aaaabbcddd'.tr_s!('a-z', 'A-Z')",
"print 'abc'.tr!('a-z', 'A-Z')",
"print 'hello'.tr('a-y', 'b-z')",
"print 'stressed'.reverse",
"print 'stressed'.reverse!",
};
String[] outputs = {
"b",
"Tuesday, July",
"<<cruel>><<world>>",
"rceu lowlr",
"cruel worl",
"xStopx",
"2127",
"BB",
"abcd ",
" [location:1]",
"<a.gif>",
"ab",
"gif",
"00123",
"a:b",
"10",
"0",
"nil",
"5",
"zbzcz",
" a b ",
"xxxnilxxxyyy",
"abab",
".rb",
"nil",
"\"yyy\"",
"\"xxx\"\n",
"truefalse",
"120",
"nil",
"1",
"ad",
"abc",
"ABCD",
"ABC",
"ifmmp",
"desserts",
"desserts",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_gsub() {
String [] program_texts = {
"print 'abca'.gsub('a', 'c')",
"print 'abca'.sub('a', 'c')",
"$_ = 'quick brown fox'; gsub /[aeiou]/, '*'; print $_",
"$_ = 'quick brown fox'; print gsub /[aeiou]/, '&'",
"$_ = 'quick brown fox'; print $_.gsub /[aeiou]/, '-'",
"$_ = 'quick brown fox'; print gsub! /cat/, '*'; print $_",
"$_ = 'quick brown fox'; print($_.gsub!(/cat/, '-')); print $_",
"print 'ABCD\nABCDE'.gsub!(/((.|\n)*?)B((.|\n)*?)D/){$3}",
"'hello'.gsub(/./) {|s| print s + ','}",
"print 'hello'.gsub(/./) {|s| s + ' '}",
};
String[] outputs = {
"cbcc",
"cbca",
"q**ck br*wn f*x",
"q&&ck br&wn f&x",
"q--ck br-wn f-x",
"nilquick brown fox",
"nilquick brown fox",
"CCE",
"h,e,l,l,o,",
"h e l l o ",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_String_scan() {
String [] program_texts = {
"p 'cruel world'.scan(/\\w+/) ",
"print 'cruel world'.scan(/(..)(..)/) == [['cr', 'ue'], ['l ', 'wo']]",
"print '1a2b3c'.scan(/(\\d.)/) == [['1a'], ['2b'], ['3c']]",
};
String[] outputs = {
"[\"cruel\", \"world\"]\n",
"true",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_String_chmop() {
String [] program_texts = {
"print 'hello\n'.chomp",
"print 'hello'.chomp!('llo')",
"print 'a'.chomp!('=')",
"print 'a'.chomp('=')",
};
String[] outputs = {
"hello",
"he",
"nil",
"a",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_String_split() {
String [] program_texts = {
"a = ' a b c '.split(' '); print a, a.size",
"a = ' a b c d'.split; print a, a.size",
"a = ' the time'.split(//); print a, a.size",
"print (' the time'.split)",
"print ('abc de b,sf cde'.split(/ /).length)",
"print ('abc de b,sf cde'.split(/ /, 2).length)",
"print ('abc de b,sf cde'.split(/ ,/).length)",
"print ('abc de b,sf cde'.split(/ ,/, 2).length)",
"print ('abc de b,sf cde'.split(/[ ,]/).length)",
"print ('abc de b,sf cde'.split(/[ ,]/, 2).length)"
};
String[] outputs = {
"abc3",
"abcd4",
" the time9",
"thetime",
"4",
"2",
"1",
"1",
"5",
"2"
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_for_in() {
String [] program_texts = {
" sum=0\n" +
" for i in 1..10\n" +
" sum += i\n" +
" i -= 1\n" +
" print i\n" +
" if i > 0\n" +
" redo\n" +
" end\n" +
" end",
"for x, (y, z) in [1, [2, [3, 4]]]; print x,y,z; end",
"for i_test_for_in in 1..1; j_test_for_in=3; end; print i_test_for_in, j_test_for_in",
"for i in 1..5 do print i end",
"for i in 1..5 do print i end; print i",
"for x, y in {1=>2} do print x, y end",
};
String[] outputs = {
"0102103210432105432106543210765432108765432109876543210",
"1nilnil234",
"13",
"12345",
"123455",
"12",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Marshal() {
String [] program_texts = {
"StrClone=String.clone; print Marshal.load(Marshal.dump(StrClone.new('abc'))).class",
"StrClone=String.clone; print Marshal.dump(StrClone.new('abc')) == \"\004\\bC:\\rStrClone\\\"\\babc\"",
"print Marshal.load(Marshal.dump(:hello))",
"print Marshal.load(Marshal.dump(265252859812191058636308480000000))",
"print Marshal.load(Marshal.dump(12345678900))",
"str = Marshal.dump('thing'); print str.class",
"str = Marshal.dump('thing'); print str[0], str[1]",
"str = Marshal.dump(0); print str.length, str[3]",
"str = Marshal.dump(5); print str.length, str[3]",
"str = Marshal.dump('thing'); print str == \"\\x04\\x08\\\"\\nthing\"",
"str = Marshal.dump([1, 3]); print str == \"\\x04\\x08[\\x07i\\x06i\\x08\"",
"str = Marshal.dump({1 => 3}); print str == \"\\x04\\x08{\\x06i\\x06i\\x08\"",
"str = Marshal.dump(0x99_99_99_99_99_99); print str[2], '|', str[3], '|', str[4]",
"print Marshal.load(Marshal.dump(nil))",
"print Marshal.load(Marshal.dump(true))",
"print Marshal.load(Marshal.dump(false))",
"print Marshal.load(Marshal.dump(0))",
"print Marshal.load(Marshal.dump(1))",
"print Marshal.load(Marshal.dump('hello'))",
"print Marshal.load(Marshal.dump([0, 1, 2]))",
"print Marshal.load(Marshal.dump({4 => 5}))",
"print Marshal.load(Marshal.dump(2.5))",
};
String[] outputs = {
"StrClone",
"true",
"hello",
"265252859812191058636308480000000",
"12345678900",
"String",
"48",
"40",
"410",
"true",
"true",
"true",
"108|43|8",
"nil",
"true",
"false",
"0",
"1",
"hello",
"012",
"45",
"2.5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Math() {
String [] program_texts = {
"print Math.exp(1).class",
"print Math.exp(1.1).class",
"print Math.sqrt(4)",
"include Math; print sqrt(9)",
};
String[] outputs = {
"Float",
"Float",
"2.0",
"3.0",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_ARGV() {
String [] program_texts = {
"print ARGV[0], ARGV[1]",
};
String[] outputs = {
"my_argnil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Module_compare() {
String [] program_texts = {
"print String >= String, String >= Object, Object >= String",
"print String < Module",
"print Object < String",
"print String < Object",
//TODO"print String < Kernel",
//TODO"print Kernel < String",
"print String <=> 123",
"print String <=> String",
"print String <=> Object",
"print Object <=> String",
"print Array <=> String",
};
String[] outputs = {
"truefalsetrue",
"nil",
"false",
"true",
//"true",
//"false",
"nil",
"0",
"-1",
"1",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Module_module_eval() {
String [] program_texts = {
"class TestModuleEval; end\n" +
"TestModuleEval.module_eval(%q{def test_module_eval() 123 end})\n" +
"print TestModuleEval.new.test_module_eval",
"class TestModuleEval2; end\n" +
"TestModuleEval2.module_eval('print self')",
};
String[] outputs = {
"123",
"TestModuleEval2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Module_class_eval() {
String [] program_texts = {
"class TestClassEval; def f() 1 end end\n" +
"TestClassEval.class_eval do def f() 2 end end\n" +
"print TestClassEval.new.f",
};
String[] outputs = {
"2",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Kernel_instance_eval() {
String [] program_texts = {
"'x'.instance_eval { print self }",
};
String[] outputs = {
"x",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Module_const_set_get() {
String [] program_texts = {
"module M end\n" +
"print M.const_set(:TEST_CONSTANT1, 1)\n" +
"print M::TEST_CONSTANT1\n" +
"print M.const_get(:TEST_CONSTANT1)\n" +
"print M.const_set('TEST_CONSTANT2', 2)\n" +
"print M::TEST_CONSTANT2",
};
String[] outputs = {
"11122",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Module_misc() {
String [] program_texts = {
"class TestInstanceMethods; protected; def test_instance_methods; end; private; def x; end; end\n" +
"a = TestInstanceMethods.instance_methods(false)\n" +
"p a",
"class TestProtectedInstanceMethods; protected; def test_protected_instance_methods; end; end\n" +
"a = TestProtectedInstanceMethods.protected_instance_methods(false)\n" +
"p a",
"class TestPrivateInstanceMethods; private; def test_private_instance_methods; end; end\n" +
"a = TestPrivateInstanceMethods.private_instance_methods(false)\n" +
"p a",
"class TestPublicInstanceMethods; def test_public_instance_methods; end; end\n" +
"a = TestPublicInstanceMethods.public_instance_methods(false)\n" +
"p a",
"class TestPublicInstanceMethods2; def test_public_instance_methods2; end; end\n" +
"a = TestPublicInstanceMethods2.public_instance_methods(true)\n" +
"print a.include?('test_public_instance_methods2')",
"module TestModuleFunction\n" +
" def test_module_function; print 123; end\n" +
" module_function :test_module_function\n" +
"end\n" +
"TestModuleFunction.test_module_function",
};
String[] outputs = {
"[\"test_instance_methods\"]\n",
"[\"test_protected_instance_methods\"]\n",
"[\"test_private_instance_methods\"]\n",
"[\"test_public_instance_methods\"]\n",
"true",
"123",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Module_ancestors() {
String [] program_texts = {
"module Testancestors; end; print Testancestors.ancestors",
"module Testancestors0; end; print Testancestors0.ancestors[0].class",
"module Testancestors1; end; module Testancestors2; include Testancestors1; end; print Testancestors2.ancestors",
"module TA1; end; module TA2; include TA1; end; module TA3; include TA2; end; print TA3.ancestors",
};
String[] outputs = {
"Testancestors",
"Module",
"Testancestors2Testancestors1",
"TA3TA2TA1",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_clone_dup() {
String [] program_texts = {
"b ='b'; c= b.dup; c[0]='c'; print b, c",
"StrClone=String.clone; print StrClone.class, StrClone == String, StrClone.new('abc').class",
"a = Object.new\n" +
"def a.test_clone\n" +
" print \"clone\"\n" +
"end\n" +
"b = a.clone\n" +
"b.test_clone",
};
String[] outputs = {
"bc",
"ClassfalseStrClone",
"clone",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_clone_exception() {
String [] program_texts = {
"a = Object.new\n" +
"b = a.clone\n" +
"def b.test_clone_exception\n" +
" print \"clone\"\n" +
"end\n" +
"a.test_clone_exception",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method 'test_clone_exception' for Object"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_TRUE_FALSE_NIL() {
String [] program_texts = {
"print TRUE, FALSE, NIL",
};
String[] outputs = {
"truefalsenil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Kernel_throw() {
String [] program_texts = {
"throw\n",
"throw 123\n",
"throw :test_throw",
"print catch(:test_cacth) {throw :xxx, 5; print 2}",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.ArgumentErrorClass, "in `throw': wrong number of arguments (0 for 1)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "123 is not a symbol"),
new RubyException(RubyRuntime.NameErrorClass, "uncaught throw `test_throw'"),
new RubyException(RubyRuntime.NameErrorClass, "uncaught throw `xxx'"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_Kernel_catch() {
String [] program_texts = {
"print catch(:test_cacth) {}",
"print catch(:test_cacth) {print 2}",
"print catch(:test_cacth) {throw :test_cacth; print 2}",
"print catch(:test_cacth) {throw :test_cacth, 5; print 2}",
};
String[] outputs = {
"nil",
"2nil",
"nil",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_trace_var_exception() {
String [] program_texts = {
"untrace_var\n",
"untrace_var 123\n",
"untrace_var :test_untrace_var",
"untrace_var :$test_untrace_var",
"trace_var :$test_untrace_var",
};
RubyException[] exceptions = {
new RubyException(RubyRuntime.ArgumentErrorClass, "in `untrace_var': wrong number of arguments (0 for 1)"),
new RubyException(RubyRuntime.ArgumentErrorClass, "123 is not a symbol"),
new RubyException(RubyRuntime.NameErrorClass, "undefined global variable test_untrace_var"),
new RubyException(RubyRuntime.NameErrorClass, "undefined global variable $test_untrace_var"),
new RubyException(RubyRuntime.ArgumentErrorClass, "tried to create Proc object without a block"),
};
compile_run_and_catch_exception(program_texts, exceptions);
}
public void test_trace_var() {
String [] program_texts = {
"trace_var (:$test_trace_var1) {print $test_trace_var1;}; $test_trace_var1 = 5",
"trace_var (:$test_untrace_var2) {print $test_untrace_var2;}; trace_var (:$test_untrace_var2) {print 2;};$test_untrace_var2 = 5",
"trace_var (:$test_untrace_var3) {|x| print x}; $test_untrace_var3 = 6; untrace_var :$test_untrace_var3; $test_untrace_var3 = 7",
"trace_var(:$test_trace_var4) {$test_trace_var4 = 9}; $test_trace_var4 = 8; print $test_trace_var4",
};
String[] outputs = {
"5",
"25",
"6",
"9",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_block_given() {
String [] program_texts = {
"def f; 1.times {print block_given?}; end; f {}",
"def f; print block_given?; end; f &nil",
"def try\n" +
" if block_given?\n" +
" print true\n" +
" else\n" +
" print false\n" +
" end\n" +
"end\n" +
"try\n" +
"try { \"hello\" }\n" +
"try do \"hello\" end",
"print iterator?",
};
String[] outputs = {
"true",
"false",
"falsetruetrue",
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Method_to_proc() {
String [] program_texts = {
"method(:print).to_proc.call(\"xxx\")",
"class TestToProc; def test_to_proc; print self.class; end; end\n" +
"TestToProc.new.method(:test_to_proc).to_proc.call",
};
String[] outputs = {
"xxx",
"TestToProc",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Module_case_equal() {
String [] program_texts = {
"print NilClass === true",
"print NilClass === nil",
"print Object === true",
"print Math === nil",
};
String[] outputs = {
"false",
"true",
"true",
"false",
//"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_new() {
String [] program_texts = {
"class MyString < String; end;print MyString.new.class",
"class MyHash < Hash; end;print MyHash.new.class",
"class MyArray < Array; end;print MyArray.new.class",
};
String[] outputs = {
"MyString",
"MyHash",
"MyArray",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Struct_new() {
String [] program_texts = {
"Customer = Struct.new(:name, :address);a = Customer.new('Dave', '123 Main');print a.class,a.name",
"Struct.new('TestStructNew6', :name); a = Struct::TestStructNew6.new('ppp'); a[0] = 'ooo'; print a.name",
"Struct.new('TestStructNew5', :name); a = Struct::TestStructNew5.new('zzz'); print a.to_a, a.to_a.class",
"Struct.new('TestStructNew4', :name); a = Struct::TestStructNew4.new('yyy'); print a[0]",
"Struct.new('TestStructNew3', :name); a = Struct::TestStructNew3.new('xxx'); print a.class",
"Struct.new('TestStructNew2', :name); a = Struct::TestStructNew2.new('xxx'); print a.name",
"c= Struct.new('TestStructNew0'); print c.class",
"Struct.new('TestStructNew1'); print Struct::TestStructNew1",
};
String[] outputs = {
"CustomerDave",
"ooo",
"zzzArray",
"yyy",
"Struct::TestStructNew3",
"xxx",
"Class",
"Struct::TestStructNew1",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Proc_new() {
String [] program_texts = {
"p = proc{test_proc = 0; proc{test_proc}}.call; test_proc=7; print p.call",
"test_proc4 = 0; p = proc{test_proc4}; test_proc4=7; print p.call",
"test_proc5 = 6; p=proc{test_proc5=77}; p.call; print test_proc5",
"test_proc3 = 6; proc{test_proc3=55}.call; print test_proc3",
"p = proc{test_proc2=55}; test_proc2 = 6; p.call; print test_proc2",
"x = []; (0..9).each{|i5| x[i5] = proc{i5*2}}; print x[4].call",
"def f\n" +
" Proc.new{return 1}.call()\n" +
" print 2\n" +
"end\n" +
"\n" +
"print f",
"def f\n" +
" lambda{return 1}.call()\n" +
" print 2\n" +
"end\n" +
"\n" +
"print f",
"print Proc.new{|a,| a}.call(4,5,6)",
"class Proc\n" +
" alias :callxxx :call\n" +
"end\n" +
"\n" +
"def f\n" +
" Proc.new{return 5}.callxxx\n" +
" print 2\n" +
"end\n" +
"\n" +
"print f",
};
String[] outputs = {
"0",
"7",
"77",
"55",
"6",
"8",
"1",
"2nil",
"4",
"5",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_return_value_of_def() {
String [] program_texts = {
"a = def f; end; print a",
"print eval('def f; end')",
};
String[] outputs = {
"nil",
"nil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_pack() {
String [] program_texts = {
"print [97, 98].pack('UU')",
"print [\"abcd\"].pack('x3a4').length",
"print [-1].pack('s_')[0]",
"print [-32767].pack('s_')[1]",
"print [-123456].pack('l_')[0]",
"print [987.654321098 / 100.0].pack('i1')[0]",
"print [987].pack('d')[5]",
"print [32767].pack('s')[0]",
"print [-100].pack('c')[0]",
"print [128].pack('C')[0]",
"print ['abcdef'].pack('a6')",
"print [127,128].pack('CC') == \"\177\200\"",
};
String[] outputs = {
"ab",
"7",
"255",
"128",
"192",
"9",
"216",
"255",
"156",
"128",
"abcdef",
"true",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_unpack() {
String [] program_texts = {
"print \"\377\377\377\377\".unpack('N*')",
"print 'ab'.unpack('UU')",
"print \">a\221E\312\300\\#@\".unpack('d')",
"print \"\000\000\000abcd\".unpack('x3a4')",
"print \"90\000\000\".unpack('i')",
"print \"@\342\001\000\".unpack('l')",
"print \"\001\200\".unpack('s_')",
"print \"\300\035\376\377\".unpack('l_')",
"print \"abcdef\".unpack('a6')",
"print \"\000\000\000\000\000\".unpack('x5')",
"print \"\001\234\".unpack('c2')",
"print \"\200\".unpack('C')",
};
String[] outputs = {
"4294967295",
"9798",
"9.87654321098",
"abcd",
"12345",
"123456",
"-32767",
"-123456",
"abcdef",
"",
"1-100",
"128",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_method_missing() {
String[] program_texts = {
"alias old_method_missing method_missing\n" +
"def method_missing a, *arg; print a; end\n" +
"no_such_method_xxx\n" +
"alias method_missing old_method_missing",
"alias old_method_missing method_missing\n" +
"def method_missing a, *arg; print a.class, arg; end\n" +
"no_such_method_xxx 1, 2\n" +
"alias method_missing old_method_missing",
};
String[] outputs = {
"no_such_method_xxx",
"Symbol12",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_ENV() {
String[] program_texts = {
"print ENV, ENV.class",
"ENV['a'] = 'b';print ENV['a']\n" +
"ENV.delete 'a';print ENV['a']",
};
String[] outputs = {
"ENVObject",
"bnil",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Numeric_step() {
String[] program_texts = {
"1.step(10, 2) { |i| print i }",
"4.step(0,-1) {|x| print x}",
};
String[] outputs = {
"13579",
"43210",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Thread() {
String[] program_texts = {
"Thread.current[\"name\"] = \"A\";\n" +
"print Thread.current[\"name\"]\n" +
"print Thread.current[\"name2\"]\n" +
"print Thread.current[:name]",
"print Thread.current == Thread.current",
"a = Thread.new {print 33}; a.join",
"print Thread.current.class",
};
String[] outputs = {
"AnilA",
"true",
"33",
"Thread",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_FileTest() {
String[] program_texts = {
"print FileTest.exist?('no_such_file_xxx')",
};
String[] outputs = {
"false",
};
compile_run_and_compare_output(program_texts, outputs);
}
public void test_Time() {
String[] program_texts = {
"t = Time.gm(2000,2,1,20,15,6);print t.year, t.month, t.day",
"print Time.gm(2000, 2, 1, 20, 15, 1).zone",
"t = Time.gm(2000, 2, 1, 20, 15, 1); print t.gmt?",
"print Time.gm(2000, 1, 2, 3, 4, 5)"
};
String[] outputs = {
"200021",
"UTC",
"true",
"Sun Jan 02 03:04:05 UTC 2000"
};
compile_run_and_compare_output(program_texts, outputs);
}
/*
TODO does not work with exception
TODO wrong format, should fix the implementation
public void test_Kernel_caller() {
String[] program_texts = {
"def f; p caller(); end; def g; f; end; g",
"def f; p caller(0); end; def g; f; end; g",
"def f; p caller(2); end; def g; f; end; g",
};
String[] outputs = {
"[g]", //TODO should be: ["test.rb:1:in `g'", "test.rb:1"]
"[f, g]",
"[]",
};
compile_run_and_compare_output(program_texts, outputs);
}*/
}
|
package com.yz.service.imp;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.yz.dao.IPersonDao;
import com.yz.dao.ISocialManDao;
import com.yz.dao.IUnitDao;
import com.yz.model.Person;
import com.yz.model.SocialMan;
import com.yz.model.Unit;
import com.yz.model.UserRole;
import com.yz.service.IPersonService;
import com.yz.service.IUnitService;
import com.yz.util.GenerateSqlFromExcel;
@Component("personService")
public class PersonServiceImp implements IPersonService {
private IPersonDao personDao;
private IUnitService unitService;
private ISocialManDao socialManDao;
public IPersonDao getPersonDao() {
return personDao;
}
@Resource
public void setPersonDao(IPersonDao personDao) {
this.personDao = personDao;
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#add(com.yz.model.Person)
*/
public void add(Person person) throws Exception {
personDao.save(person);
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#delete(com.yz.model.Person)
*/
public void delete(Person person) {
personDao.delete(person);
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#deleteById(int)
*/
public void deleteById(int id) {
personDao.deleteById(id);
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#update(com.yz.model.Person)
*/
public void update(Person person) {
personDao.update(person);
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#getPersons()
*/
public List<Person> getPersons() {
return personDao.getPersons();
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#loadById(int)
*/
public Person loadById(int id) {
return personDao.loadById(id);
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#getPageCount(int,
* java.lang.String, int)
*/
public int getPageCount(int totalCount, int size) {
return totalCount % size == 0 ? totalCount / size
: (totalCount / size + 1);
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#getTotalCount(int,
* java.lang.String)
*/
public int getTotalCount(int con, String convalue, UserRole userRole,
int type, int queryState, String starttime, String endtime) {
String queryString = "select count(*) from Person mo where 1=1 ";
Object[] p = null;
if (con != 0 && convalue != null && !convalue.equals("")) {
if (con == 1) {
queryString += "and mo.name like ? ";
}
if (con == 2) {
queryString += "and mo.number like ? ";
}
if (con == 3) {
queryString += "and mo.idcard like ? ";
}
if (con == 4) {
queryString += "and mo.userRole.realname like ? ";
}
p = new Object[] { '%' + convalue + '%' };
}
if (type != 0) {
queryString += " and mo.type =" + type;
}
if (queryState != 0) {
queryString += " and mo.handleState =" + queryState;
}
if (starttime != null && !starttime.equals("")) {
queryString += " and mo.joinDate>='" + starttime + "'";
}
if (endtime != null && !endtime.equals("")) {
queryString += " and mo.joinDate<='" + endtime + "'";
}
String pids = "";
if(userRole!=null&&userRole.getUnit()!=null&&userRole.getUnit().getPids()!=null)
{
pids = userRole.getUnit().getPids().replace(" ", "");
queryString = setStringIds(queryString,pids);
}else
{
queryString += " and mo.id in (0)";
}
return personDao.getUniqueResult(queryString, p);
}
public Person getPersonByPersonname(String personname) {
String queryString = "from Person mo where mo.name=:personname";
String[] paramNames = new String[] { "personname" };
Object[] values = new Object[] { personname };
return personDao.queryByNamedParam(queryString, paramNames, values);
}
/*
* (non-Javadoc)
*
* @see com.yz.service.imp.IPersonServiceImp#queryList(int,
* java.lang.String, int, int)
*/
public List<Person> queryList(int con, String convalue, UserRole userRole,
int page, int size, int type, int queryState, String starttime,
String endtime) {
String queryString = "from Person mo where 1=1 ";
Object[] p = null;
if (con != 0 && convalue != null && !convalue.equals("")) {
if (con == 1) {
queryString += "and mo.name like ? ";
}
if (con == 2) {
queryString += "and mo.number like ? ";
}
if (con == 3) {
queryString += "and mo.idcard like ? ";
}
if (con == 4) {
queryString += "and mo.userRole.realname like ? ";
}
p = new Object[] { '%' + convalue + '%' };
}
if (type != 0) {
queryString += " and mo.type =" + type;
}
if (queryState != 0) {
queryString += " and mo.handleState =" + queryState;
}
if (starttime != null && !starttime.equals("")) {
queryString += " and mo.joinDate>='" + starttime + "'";
}
if (endtime != null && !endtime.equals("")) {
queryString += " and mo.joinDate<='" + endtime + "'";
}
String pids = "";
if(userRole!=null&&userRole.getUnit()!=null&&userRole.getUnit().getPids()!=null)
{
pids = userRole.getUnit().getPids().replace(" ", "");
queryString = setStringIds(queryString,pids);
}else
{
queryString += " and mo.id in (0)";
}
return personDao.pageList(queryString, p, page, size);
}
public Person getPersonById(Integer uppersonid) {
// TODO Auto-generated method stub
return personDao.getPersonById(uppersonid);
}
public Person queryPersonById(int id) {
String queryString = "from Person mo where mo.id=:id";
String[] paramNames = new String[] { "id" };
Object[] values = new Object[] { id };
return personDao.queryByNamedParam(queryString, paramNames, values);
}
public List<Person> getPersonsByTypeAndHandleState(int type,
int handleState, UserRole userRole) {
// TODO Auto-generated method stub
String queryString = "from Person mo where mo.type=" + type
+ " and mo.handleState=" + handleState;
String pids = "";
if(userRole!=null&&userRole.getUnit()!=null&&userRole.getUnit().getPids()!=null)
{
pids = userRole.getUnit().getPids().replace(" ", "");
queryString = setStringIds(queryString,pids);
}else
{
queryString += " and mo.id in (0)";
}
return personDao.queryList(queryString);
}
private String setStringIds(String queryString,String pids) {
// TODO Auto-generated method stub
if(pids!=""&&!pids.equals(","))
{
String lastChar = pids.substring(pids.length()-1, pids.length());
if(lastChar.equals(","))
{
pids = pids.substring(0, pids.length()-1);
}
queryString += " and mo.id in ("+pids+")";
}else
{
queryString += " and mo.id in (0)";
}
return queryString;
}
public int savereturn(Person person) {
// TODO Auto-generated method stub
return personDao.savereturn(person);
}
public void saveSocialManWithExcel(File file,
UserRole userRole) {
try {
GenerateSqlFromExcel generate = new GenerateSqlFromExcel();
ArrayList<String[]> arrayList = generate
.generateStationBugSql(file);
for (int i = 0; arrayList != null && i < arrayList.size(); i++) {
String[] data = arrayList.get(i);
Person person = new Person();
// POPO
SocialMan socialMan = new SocialMan();
person.setNumber(data[0].toString());
person.setName(data[1].toString());
person.setBirthday(data[2].toString());
person.setQq(data[3].toString());
person.setWechat(data[4].toString());
person.setIdcard(data[5].toString());
person.setRegisterAddress(data[6].toString());
person.setRegisterAddressArea(data[7].toString());
person.setType(15);
person.setSocialMan(socialMan);
socialManDao.save(socialMan);
int pid = personDao.savereturn(person);
if (userRole.getUnit() != null) {
int uid = userRole.getUnit().getId();
Unit un = unitService.queryByUid(uid);
if (un.getPids() != null && un.getPids() != "") {
un.setPids(handleIDs(un.getPids(), pid + ""));
} else {
un.setPids(pid + ",");
}
System.out.println(un.getPids());
unitService.update(un);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ids
private String handleIDs(String objIDs, String objID) {
Set<String> ids = new HashSet<String>();
String newIDs = "";
String[] arrayIDs = objIDs.split(",");
for (int i = 0; i < arrayIDs.length; i++) {
ids.add(arrayIDs[i]);
}
ids.add(objID);
for (String id : ids) {
newIDs = newIDs + id + ",";
}
System.out.println(newIDs);
return newIDs;
}
public ISocialManDao getSocialManDao() {
return socialManDao;
}
@Resource
public void setSocialManDao(ISocialManDao socialManDao) {
this.socialManDao = socialManDao;
}
public IUnitService getUnitService() {
return unitService;
}
@Resource
public void setUnitService(IUnitService unitService) {
this.unitService = unitService;
}
}
|
package memorymeasurer;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ConcurrentHashMultiset;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.LinkedHashMultiset;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import com.google.common.collect.TreeMultimap;
import com.google.common.collect.TreeMultiset;
import java.lang.reflect.Constructor;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import objectexplorer.MemoryMeasurer;
import objectexplorer.ObjectGraphMeasurer;
import objectexplorer.ObjectGraphMeasurer.Footprint;
public class ElementCostOfDataStructures {
public static void main(String[] args) throws Exception {
caption(" Basic Lists, Sets, Maps ");
analyze(new CollectionPopulator(defaultSupplierFor(ArrayList.class)));
analyze(new ImmutableListPopulator());
analyze(new CollectionPopulator(defaultSupplierFor(HashSet.class)));
analyze(new ImmutableSetPopulator());
analyze(new CollectionPopulator(defaultSupplierFor(TreeSet.class), EntryFactories.COMPARABLE));
analyze(new ImmutableSortedSetPopulator());
analyze(new MapPopulator(defaultSupplierFor(HashMap.class)));
analyze(new ImmutableMapPopulator());
analyze(new MapPopulator(defaultSupplierFor(LinkedHashMap.class)));
analyze(new MapPopulator(defaultSupplierFor(TreeMap.class), EntryFactories.COMPARABLE));
analyze(new ImmutableSortedMapPopulator());
caption("ConcurrentHashMap/MapMaker");
analyze(new MapPopulator(defaultSupplierFor(ConcurrentHashMap.class)));
analyze("MapMaker", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().makeMap(); } }));
analyze("MapMaker_Expires", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().expiration(5, TimeUnit.DAYS).makeMap(); } }));
analyze("MapMaker_Evicts", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).makeMap(); } }));
analyze("MapMaker_ExpiresEvicts", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).makeMap(); } }));
analyze("MapMaker_SoftKeys", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().softKeys().makeMap(); } }));
analyze("MapMaker_SoftValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().softValues().makeMap(); } }));
analyze("MapMaker_SoftKeysValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().softKeys().softValues().makeMap(); } }));
analyze("MapMaker_Evicts_SoftKeys", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).softKeys().makeMap(); } }));
analyze("MapMaker_Evicts_SoftValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).softValues().makeMap(); } }));
analyze("MapMaker_Evicts_SoftKeysValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).softKeys().softValues().makeMap(); } }));
analyze("MapMaker_Expires_SoftKeys", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().expiration(3, TimeUnit.DAYS).softKeys().makeMap(); } }));
analyze("MapMaker_Expires_SoftValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().expiration(3, TimeUnit.DAYS).softValues().makeMap(); } }));
analyze("MapMaker_Expires_SoftKeysValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().expiration(3, TimeUnit.DAYS).softKeys().softValues().makeMap(); } }));
analyze("MapMaker_ExpiresEvicts_SoftKeys", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softKeys().makeMap(); } }));
analyze("MapMaker_ExpiresEvicts_SoftValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softValues().makeMap(); } }));
analyze("MapMaker_ExpiresEvicts_SoftKeysValues", new MapPopulator(new Supplier<Map>() { public Map get() { return
new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softKeys().softValues().makeMap(); } }));
caption(" Multisets ");
analyze("HashMultiset_Worst", new MultisetPopulator_Worst(new Supplier<Multiset>() { public Multiset get() { return
HashMultiset.create(); } }));
analyze("LinkedHashMultiset_Worst", new MultisetPopulator_Worst(new Supplier<Multiset>() { public Multiset get() { return
LinkedHashMultiset.create(); } }));
analyze(new ImmutableSetMultimapPopulator_Worst());
analyze("TreeMultiset_Worst", new MultisetPopulator_Worst(new Supplier<Multiset>() { public Multiset get() { return
TreeMultiset.create(); } }, EntryFactories.COMPARABLE));
analyze("ConcurrentHashMultiset_Worst", new MultisetPopulator_Worst(new Supplier<Multiset>() { public Multiset get() { return
ConcurrentHashMultiset.create(); } }));
System.out.println();
analyze("HashMultiset_Best ", new MultisetPopulator_Best(new Supplier<Multiset>() { public Multiset get() { return
HashMultiset.create(); } }));
analyze("LinkedHashMultiset_Best ", new MultisetPopulator_Best(new Supplier<Multiset>() { public Multiset get() { return
LinkedHashMultiset.create(); } }));
analyze(new ImmutableSetMultimapPopulator_Best());
analyze("TreeMultiset_Best ", new MultisetPopulator_Best(new Supplier<Multiset>() { public Multiset get() { return
TreeMultiset.create(); } }, EntryFactories.COMPARABLE));
analyze("ConcurrentHashMultiset_Best", new MultisetPopulator_Best(new Supplier<Multiset>() { public Multiset get() { return
ConcurrentHashMultiset.create(); } }));
caption(" Multimaps ");
analyze("HashMultimap_Worst", new MultimapPopulator_Worst(new Supplier<Multimap>() { public Multimap get() { return
HashMultimap.create(); } }));
analyze("LinkedHashMultimap_Worst", new MultimapPopulator_Worst(new Supplier<Multimap>() { public Multimap get() { return
LinkedHashMultimap.create(); } }));
analyze("TreeMultimap_Worst", new MultimapPopulator_Worst(new Supplier<Multimap>() { public Multimap get() { return
TreeMultimap.create(); } }, EntryFactories.COMPARABLE));
analyze("ArrayListMultimap_Worst", new MultimapPopulator_Worst(new Supplier<Multimap>() { public Multimap get() { return
ArrayListMultimap.create(); } }));
analyze("LinkedListMultimap_Worst", new MultimapPopulator_Worst(new Supplier<Multimap>() { public Multimap get() { return
LinkedListMultimap.create(); } }));
analyze(new ImmutableMultimapPopulator_Worst());
analyze(new ImmutableListMultimapPopulator_Worst());
System.out.println();
analyze("HashMultimap_Best ", new MultimapPopulator_Best(new Supplier<Multimap>() { public Multimap get() { return
HashMultimap.create(); } }));
analyze("LinkedHashMultimap_Best ", new MultimapPopulator_Best(new Supplier<Multimap>() { public Multimap get() { return
LinkedHashMultimap.create(); } }));
analyze("TreeMultimap_Best ", new MultimapPopulator_Best(new Supplier<Multimap>() { public Multimap get() { return
TreeMultimap.create(); } }, EntryFactories.COMPARABLE));
analyze("ArrayListMultimap_Best ", new MultimapPopulator_Best(new Supplier<Multimap>() { public Multimap get() { return
ArrayListMultimap.create(); } }));
analyze("LinkedListMultimap_Best", new MultimapPopulator_Best(new Supplier<Multimap>() { public Multimap get() { return
LinkedListMultimap.create(); } }));
analyze(new ImmutableMultimapPopulator_Best());
analyze(new ImmutableListMultimapPopulator_Best());
caption(" Tables ");
analyze("HashBasedTable", new TablePopulator_Worst(new Supplier<Table>() { public Table get() { return
HashBasedTable.create(); } } ));
analyze("TreeBasedTable", new TablePopulator_Worst(new Supplier<Table>() { public Table get() { return
TreeBasedTable.create(); } }, EntryFactories.COMPARABLE));
caption(" BiMaps ");
analyze("HashBiMap", new MapPopulator(new Supplier<Map>() { public Map get() { return
HashBiMap.create(); } }));
analyze(new ImmutableBiMapPopulator());
caption(" Misc ");
analyze(new MapPopulator(defaultSupplierFor(WeakHashMap.class)));
analyze(new CollectionPopulator(defaultSupplierFor(LinkedList.class)));
analyze(new CollectionPopulator(defaultSupplierFor(ArrayDeque.class)));
analyze(new CollectionPopulator(defaultSupplierFor(LinkedHashSet.class)));
analyze(new CollectionPopulator(defaultSupplierFor(PriorityQueue.class), EntryFactories.COMPARABLE));
analyze(new CollectionPopulator(defaultSupplierFor(PriorityBlockingQueue.class), EntryFactories.COMPARABLE));
analyze(new CollectionPopulator(defaultSupplierFor(ConcurrentSkipListSet.class), EntryFactories.COMPARABLE));
analyze(new CollectionPopulator(defaultSupplierFor(CopyOnWriteArrayList.class)));
analyze(new CollectionPopulator(defaultSupplierFor(CopyOnWriteArraySet.class)));
analyze(new CollectionPopulator(defaultSupplierFor(DelayQueue.class), EntryFactories.DELAYED));
analyze(new CollectionPopulator(defaultSupplierFor(LinkedBlockingQueue.class)));
analyze(new CollectionPopulator(defaultSupplierFor(LinkedBlockingDeque.class)));
}
private static void caption(String caption) {
System.out.println();
System.out.println("========================================== " + caption
+ " ==========================================");
System.out.println();
}
static void analyze(Populator<?> populator) {
analyze(populator.toString(), populator);
}
static void analyze(String caption, Populator<?> populator) {
AvgEntryCost cost = averageEntryCost(populator, 16, 256 * 31);
System.out.printf("%40s :: Bytes = %6.2f, Objects = %5.2f Refs = %5.2f Primitives = %s%n",
caption, cost.bytes, cost.objects, cost.refs, cost.primitives);
}
static AvgEntryCost averageEntryCost(Populator<?> populator, int initialEntries, int entriesToAdd) {
Preconditions.checkArgument(initialEntries >= 0, "initialEntries negative");
Preconditions.checkArgument(entriesToAdd > 0, "entriesToAdd negative or zero");
Predicate<Object> predicate = Predicates.not(Predicates.instanceOf(
populator.getEntryType()));
Object collection1 = populator.construct(initialEntries);
Footprint footprint1 = ObjectGraphMeasurer.measure(collection1, predicate);
long bytes1 = MemoryMeasurer.measureBytes(collection1, predicate);
Object collection2 = populator.construct(initialEntries + entriesToAdd);
Footprint footprint2 = ObjectGraphMeasurer.measure(collection2, predicate);
long bytes2 = MemoryMeasurer.measureBytes(collection2, predicate);
double objects = (footprint2.getObjects() - footprint1.getObjects()) / (double) entriesToAdd;
double refs = (footprint2.getReferences() - footprint1.getReferences()) / (double) entriesToAdd;
double bytes = (bytes2 - bytes1) / (double)entriesToAdd;
Map<Class<?>, Double> primitives = Maps.newHashMap();
for (Class<?> primitiveType : primitiveTypes) {
int initial = footprint1.getPrimitives().count(primitiveType);
int ending = footprint2.getPrimitives().count(primitiveType);
if (initial != ending) {
primitives.put(primitiveType, (ending - initial) / (double) entriesToAdd);
}
}
return new AvgEntryCost(objects, refs, primitives, bytes);
}
private static final ImmutableSet<Class<?>> primitiveTypes = ImmutableSet.<Class<?>>of(
boolean.class, byte.class, char.class, short.class,
int.class, float.class, long.class, double.class);
private static class AvgEntryCost {
final double objects;
final double refs;
final ImmutableMap<Class<?>, Double> primitives;
final double bytes;
AvgEntryCost(double objects, double refs, Map<Class<?>, Double> primitives, double bytes) {
this.objects = objects;
this.refs = refs;
this.primitives = ImmutableMap.copyOf(primitives);
this.bytes = bytes;
}
}
private static class DefaultConstructorSupplier<C> implements Supplier<C> {
private final Constructor<C> constructor;
DefaultConstructorSupplier(Class<C> clazz) throws NoSuchMethodException {
this.constructor = clazz.getConstructor();
}
public C get() {
try {
return constructor.newInstance();
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
@Override
public String toString() {
return constructor.getDeclaringClass().getSimpleName();
}
}
static <C> DefaultConstructorSupplier<C> defaultSupplierFor(Class<C> clazz) throws NoSuchMethodException {
return new DefaultConstructorSupplier(clazz);
}
}
interface Populator<C> {
Class<?> getEntryType();
C construct(int entries);
}
abstract class AbstractPopulator<C> implements Populator<C> {
private final EntryFactory entryFactory;
AbstractPopulator() { this(EntryFactories.REGULAR); }
AbstractPopulator(EntryFactory entryFactory) {
this.entryFactory = entryFactory;
}
protected Object newEntry() {
return entryFactory.get();
}
public Class<?> getEntryType() {
return entryFactory.getEntryType();
}
}
abstract class MutablePopulator<C> extends AbstractPopulator<C> {
private final Supplier<? extends C> factory;
MutablePopulator(Supplier<? extends C> factory) {
this(factory, EntryFactories.REGULAR);
}
MutablePopulator(Supplier<? extends C> factory, EntryFactory entryFactory) {
super(entryFactory);
this.factory = factory;
}
protected abstract void addEntry(C target);
public C construct(int entries) {
C collection = factory.get();
for (int i = 0; i < entries; i++) {
addEntry(collection);
}
return collection;
}
@Override
public String toString() {
return factory.toString();
}
}
class MapPopulator extends MutablePopulator<Map> {
MapPopulator(Supplier<? extends Map> mapFactory) {
super(mapFactory);
}
MapPopulator(Supplier<? extends Map> mapFactory, EntryFactory entryFactory) {
super(mapFactory, entryFactory);
}
public void addEntry(Map map) {
map.put(newEntry(), newEntry());
}
}
class CollectionPopulator extends MutablePopulator<Collection> {
CollectionPopulator(Supplier<? extends Collection> collectionFactory) {
super(collectionFactory);
}
CollectionPopulator(Supplier<? extends Collection> collectionFactory, EntryFactory entryFactory) {
super(collectionFactory, entryFactory);
}
public void addEntry(Collection collection) {
collection.add(newEntry());
}
}
class MultimapPopulator_Worst extends MutablePopulator<Multimap> {
MultimapPopulator_Worst(Supplier<? extends Multimap> multimapFactory) {
super(multimapFactory);
}
MultimapPopulator_Worst(Supplier<? extends Multimap> multimapFactory, EntryFactory entryFactory) {
super(multimapFactory, entryFactory);
}
public void addEntry(Multimap multimap) {
multimap.put(newEntry(), newEntry());
}
}
class MultimapPopulator_Best extends MutablePopulator<Multimap> {
MultimapPopulator_Best(Supplier<? extends Multimap> multimapFactory) {
super(multimapFactory);
}
MultimapPopulator_Best(Supplier<? extends Multimap> multimapFactory, EntryFactory entryFactory) {
super(multimapFactory, entryFactory);
}
private final Object key = newEntry();
public void addEntry(Multimap multimap) {
multimap.put(key, newEntry());
}
}
class MultisetPopulator_Worst extends MutablePopulator<Multiset> {
MultisetPopulator_Worst(Supplier<? extends Multiset> multisetFactory) {
super(multisetFactory);
}
MultisetPopulator_Worst(Supplier<? extends Multiset> multisetFactory, EntryFactory entryFactory) {
super(multisetFactory, entryFactory);
}
public void addEntry(Multiset multiset) {
multiset.add(newEntry());
}
}
class MultisetPopulator_Best extends MutablePopulator<Multiset> {
MultisetPopulator_Best(Supplier<? extends Multiset> multisetFactory) {
super(multisetFactory);
}
MultisetPopulator_Best(Supplier<? extends Multiset> multisetFactory, EntryFactory entryFactory) {
super(multisetFactory, entryFactory);
}
private final Object key = newEntry();
public void addEntry(Multiset multiset) {
multiset.add(key);
}
}
class TablePopulator_Worst extends MutablePopulator<Table> {
TablePopulator_Worst(Supplier<? extends Table> tableFactory) {
super(tableFactory);
}
TablePopulator_Worst(Supplier<? extends Table> tableFactory, EntryFactory entryFactory) {
super(tableFactory, entryFactory);
}
public void addEntry(Table table) {
table.put(newEntry(), newEntry(), newEntry());
}
}
/** Immutable classes */
class ImmutableListPopulator extends AbstractPopulator<ImmutableList> {
public ImmutableList construct(int entries) {
ImmutableList.Builder builder = ImmutableList.builder();
for (int i = 0; i < entries; i++) {
builder.add(newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableList";
}
}
class ImmutableSetPopulator extends AbstractPopulator<ImmutableSet> {
public ImmutableSet construct(int entries) {
ImmutableSet.Builder builder = ImmutableSet.builder();
for (int i = 0; i < entries; i++) {
builder.add(newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableSet";
}
}
class ImmutableMapPopulator extends AbstractPopulator<ImmutableMap> {
public ImmutableMap construct(int entries) {
ImmutableMap.Builder builder = ImmutableMap.builder();
for (int i = 0; i < entries; i++) {
builder.put(newEntry(), newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableMap";
}
}
class ImmutableSortedSetPopulator extends AbstractPopulator<ImmutableSortedSet> {
ImmutableSortedSetPopulator() {
super(EntryFactories.COMPARABLE);
}
public ImmutableSortedSet construct(int entries) {
ImmutableSortedSet.Builder builder = ImmutableSortedSet.<Comparable>naturalOrder();
for (int i = 0; i < entries; i++) {
builder.add(newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableSortedSet";
}
}
class ImmutableSortedMapPopulator extends AbstractPopulator<ImmutableSortedMap> {
ImmutableSortedMapPopulator() {
super(EntryFactories.COMPARABLE);
}
public ImmutableSortedMap construct(int entries) {
ImmutableSortedMap.Builder builder = ImmutableSortedMap.<Comparable, Object>naturalOrder();
for (int i = 0; i < entries; i++) {
builder.put(newEntry(), newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableSortedMap";
}
}
class ImmutableBiMapPopulator extends AbstractPopulator<ImmutableBiMap> {
public ImmutableBiMap construct(int entries) {
ImmutableBiMap.Builder builder = ImmutableBiMap.builder();
for (int i = 0; i < entries; i++) {
builder.put(newEntry(), newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableBiMap";
}
}
class ImmutableMultimapPopulator_Worst extends AbstractPopulator<ImmutableMultimap> {
public ImmutableMultimap construct(int entries) {
ImmutableMultimap.Builder builder = ImmutableMultimap.builder();
for (int i = 0; i < entries; i++) {
builder.put(newEntry(), newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableMultimap_Worst";
}
}
class ImmutableMultimapPopulator_Best extends AbstractPopulator<ImmutableMultimap> {
public ImmutableMultimap construct(int entries) {
ImmutableMultimap.Builder builder = ImmutableMultimap.builder();
Object key = newEntry();
for (int i = 0; i < entries; i++) {
builder.put(key, newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableMultimap_Best ";
}
}
class ImmutableListMultimapPopulator_Worst extends AbstractPopulator<ImmutableListMultimap> {
public ImmutableListMultimap construct(int entries) {
ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder();
for (int i = 0; i < entries; i++) {
builder.put(newEntry(), newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableListMultimap_Worst";
}
}
class ImmutableListMultimapPopulator_Best extends AbstractPopulator<ImmutableListMultimap> {
public ImmutableListMultimap construct(int entries) {
ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder();
Object key = newEntry();
for (int i = 0; i < entries; i++) {
builder.put(key, newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableListMultimap_Best ";
}
}
class ImmutableSetMultimapPopulator_Worst extends AbstractPopulator<ImmutableSetMultimap> {
public ImmutableSetMultimap construct(int entries) {
ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder();
for (int i = 0; i < entries; i++) {
builder.put(newEntry(), newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableSetMultimap_Worst";
}
}
class ImmutableSetMultimapPopulator_Best extends AbstractPopulator<ImmutableSetMultimap> {
public ImmutableSetMultimap construct(int entries) {
ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder();
Object key = newEntry();
for (int i = 0; i < entries; i++) {
builder.put(key, newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableSetMultimap_Best ";
}
}
class ImmutableMultisetPopulator_Worst extends AbstractPopulator<ImmutableMultiset> {
public ImmutableMultiset construct(int entries) {
ImmutableMultiset.Builder builder = ImmutableMultiset.builder();
for (int i = 0; i < entries; i++) {
builder.add(newEntry());
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableMultiset_Worst";
}
}
class ImmutableMultisetPopulator_Best extends AbstractPopulator<ImmutableMultiset> {
public ImmutableMultiset construct(int entries) {
ImmutableMultiset.Builder builder = ImmutableMultiset.builder();
Object key = newEntry();
for (int i = 0; i < entries; i++) {
builder.add(key);
}
return builder.build();
}
@Override
public String toString() {
return "ImmutableMultiset_Best ";
}
}
interface EntryFactory extends Supplier {
Class<?> getEntryType();
}
enum EntryFactories implements EntryFactory {
REGULAR {
public Class<?> getEntryType() { return Element.class; }
public Object get() { return new Element(); }
},
COMPARABLE {
public Class<?> getEntryType() { return ComparableElement.class; }
public Object get() { return new ComparableElement(); }
},
DELAYED {
public Class<?> getEntryType() { return DelayedElement.class; }
public Object get() { return new DelayedElement(); }
};
}
class Element { }
class ComparableElement extends Element implements Comparable {
public int compareTo(Object o) { return 1; }
}
class DelayedElement extends Element implements Delayed {
public long getDelay(TimeUnit unit) { return 0; }
public int compareTo(Delayed o) { return 1; }
}
|
package hl.jsoncrud;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
import hl.common.JdbcDBMgr;
public class CRUDMgr {
private final static String JSONFILTER_IN = "in";
private final static String JSONFILTER_FROM = "from";
private final static String JSONFILTER_TO = "to";
private final static String JSONFILTER_STARTWITH = "startwith";
private final static String JSONFILTER_ENDWITH = "endwith";
private final static String JSONFILTER_CONTAIN = "contain";
private final static String JSONFILTER_CASE_INSENSITIVE = "ci";
private final static String JSONFILTER_NOT = "not";
private final static String SQL_IN_SEPARATOR = ",";
private final static String SQLLIKE_WILDCARD = "%";
private final static char[] SQLLIKE_RESERVED_CHARS = new char[]{'%','_'};
private final static String REGEX_JSONFILTER = "([a-zA-Z_-]+?)(?:\\.("+JSONFILTER_NOT+"))?"
+"(?:\\.("+JSONFILTER_FROM+"|"+JSONFILTER_TO+"|"+JSONFILTER_IN+"|"
+JSONFILTER_STARTWITH+"|"+JSONFILTER_ENDWITH+"|"+JSONFILTER_CONTAIN+"|"+JSONFILTER_NOT+"|"
+JSONFILTER_CASE_INSENSITIVE+"))"
+"(?:\\.("+JSONFILTER_CASE_INSENSITIVE+"|"+JSONFILTER_NOT+"))?"
+"(?:\\.("+JSONFILTER_CASE_INSENSITIVE+"|"+JSONFILTER_NOT+"))?";
private Map<String, JdbcDBMgr> mapDBMgr = null;
private Map<String, Map<String, String>> mapJson2ColName = null;
private Map<String, Map<String, String>> mapColName2Json = null;
private Map<String, Map<String, String>> mapJson2Sql = null;
private Map<String, Map<String,DBColMeta>> mapTableCols = null;
private Pattern pattSQLjsonname = null;
private Pattern pattJsonColMapping = null;
private Pattern pattJsonSQL = null;
private Pattern pattJsonNameFilter = null;
private Pattern pattInsertSQLtableFields = null;
private JsonCrudConfig jsoncrudConfig = null;
private String config_prop_filename = null;
public CRUDMgr()
{
config_prop_filename = null;
init();
}
public JSONObject getVersionInfo()
{
JSONObject jsonVer = new JSONObject();
jsonVer.put("framework", "jsoncrud");
jsonVer.put("version", "0.5.2 beta");
return jsonVer;
}
public CRUDMgr(String aPropFileName)
{
config_prop_filename = aPropFileName;
if(aPropFileName!=null && aPropFileName.trim().length()>0)
{
try {
jsoncrudConfig = new JsonCrudConfig(aPropFileName);
} catch (IOException e) {
throw new RuntimeException("Error loading "+aPropFileName, e);
}
}
init();
}
public CRUDMgr(Properties aProp)
{
try {
jsoncrudConfig = new JsonCrudConfig(aProp);
} catch (IOException e) {
throw new RuntimeException("Error loading Properties "+aProp.toString(), e);
}
init();
}
private void init()
{
mapDBMgr = new HashMap<String, JdbcDBMgr>();
mapJson2ColName = new HashMap<String, Map<String, String>>();
mapColName2Json = new HashMap<String, Map<String, String>>();
mapJson2Sql = new HashMap<String, Map<String, String>>();
mapTableCols = new HashMap<String, Map<String, DBColMeta>>();
pattJsonColMapping = Pattern.compile("jsonattr\\.([a-zA-Z_-]+?)\\.colname");
pattJsonSQL = Pattern.compile("jsonattr\\.([a-zA-Z_-]+?)\\.sql");
pattSQLjsonname = Pattern.compile("\\{(.+?)\\}");
pattInsertSQLtableFields = Pattern.compile("insert\\s+?into\\s+?([a-zA-Z_]+?)\\s+?\\((.+?)\\)");
pattJsonNameFilter = Pattern.compile(REGEX_JSONFILTER);
try {
reloadProps();
if(jsoncrudConfig.getAllConfig().size()==0)
{
throw new IOException("Fail to load properties file - "+config_prop_filename);
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
initPaginationConfig();
initValidationErrCodeConfig();
}
private void initValidationErrCodeConfig()
{
Map<String, String> mapErrCodes = jsoncrudConfig.getConfig(JsonCrudConfig._DB_VALIDATION_ERRCODE_CONFIGKEY);
if(mapErrCodes!=null && mapErrCodes.size()>0)
{
String sMetaKey = null;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_EXCEED_SIZE);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_EXCEED_SIZE = sMetaKey;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_INVALID_TYPE);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_INVALID_TYPE = sMetaKey;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_NOT_NULLABLE);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_NOT_NULLABLE = sMetaKey;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_SYSTEM_FIELD);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_SYSTEM_FIELD = sMetaKey;
}
mapErrCodes = jsoncrudConfig.getConfig(JsonCrudConfig._JSONCRUD_FRAMEWORK_ERRCODE_CONFIGKEY);
if(mapErrCodes!=null && mapErrCodes.size()>0)
{
String sMetaKey = null;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_JSONCRUDCFG);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_JSONCRUDCFG = sMetaKey;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_SQLEXCEPTION);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_SQLEXCEPTION = sMetaKey;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_PLUGINEXCEPTION);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_PLUGINEXCEPTION = sMetaKey;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_INVALID_FILTER);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_INVALID_FILTER = sMetaKey;
sMetaKey = mapErrCodes.get(JsonCrudConfig.ERRCODE_INVALID_SORTING);
if(sMetaKey!=null)
JsonCrudConfig.ERRCODE_INVALID_SORTING = sMetaKey;
}
}
private void initPaginationConfig()
{
Map<String, String> mapPagination = jsoncrudConfig.getConfig(JsonCrudConfig._PAGINATION_CONFIGKEY);
if(mapPagination!=null && mapPagination.size()>0)
{
String sMetaKey = null;
sMetaKey = mapPagination.get(JsonCrudConfig._LIST_META);
if(sMetaKey!=null)
JsonCrudConfig._LIST_META = sMetaKey;
sMetaKey = mapPagination.get(JsonCrudConfig._LIST_RESULT);
if(sMetaKey!=null)
JsonCrudConfig._LIST_RESULT = sMetaKey;
sMetaKey = mapPagination.get(JsonCrudConfig._LIST_TOTAL);
if(sMetaKey!=null)
JsonCrudConfig._LIST_TOTAL = sMetaKey;
sMetaKey = mapPagination.get(JsonCrudConfig._LIST_FETCHSIZE);
if(sMetaKey!=null)
JsonCrudConfig._LIST_FETCHSIZE = sMetaKey;
sMetaKey = mapPagination.get(JsonCrudConfig._LIST_START);
if(sMetaKey!=null)
JsonCrudConfig._LIST_START = sMetaKey;
sMetaKey = mapPagination.get(JsonCrudConfig._LIST_SORTING);
if(sMetaKey!=null)
JsonCrudConfig._LIST_SORTING = sMetaKey;
}
}
public JSONObject checkJSONmapping(String aCrudKey, JSONObject aDataJson, Map<String, String> aCrudCfgMap) throws JsonCrudException
{
boolean isExceptionOnUnknownJsonAttr = false;
String sExceptionOnUnknownAttr = aCrudCfgMap.get(JsonCrudConfig._PROP_KEY_EXCEPTION_ON_UNKNOWN_ATTR);
if(sExceptionOnUnknownAttr!=null)
{
isExceptionOnUnknownJsonAttr = sExceptionOnUnknownAttr.trim().equalsIgnoreCase("true");
}
JSONObject jsonMappedObj = new JSONObject();
Map<String, String> mapCrudJsonSql = mapJson2Sql.get(aCrudKey);
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
Map<String, DBColMeta> mapCrudDBCols = mapTableCols.get(aCrudKey);
for(String sJsonAttr : aDataJson.keySet())
{
boolean isInJsonCrudConfig = mapCrudJsonCol.get(sJsonAttr)!=null;
boolean isInDBSchema = mapCrudDBCols.get(sJsonAttr)!=null;
boolean isInJsonSQL = mapCrudJsonSql.get(sJsonAttr)!=null;
if(!isInJsonCrudConfig && !isInDBSchema && !isInJsonSQL)
{
if(isExceptionOnUnknownJsonAttr)
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Invalid input data ! - CrudKey:["+aCrudKey+"], Key:["+sJsonAttr+"]");
}
else
{
continue;
}
}
jsonMappedObj.put(sJsonAttr, aDataJson.get(sJsonAttr));
}
return jsonMappedObj;
}
public JSONObject create(String aCrudKey, JSONObject aDataJson) throws JsonCrudException
{
Map<String, String> mapCrudCfg = jsoncrudConfig.getConfig(aCrudKey);
if(mapCrudCfg==null || mapCrudCfg.size()==0)
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Invalid crud configuration key ! - "+aCrudKey);
JSONObject jsonData = checkJSONmapping(aCrudKey, aDataJson, mapCrudCfg);
jsonData = castJson2DBVal(aCrudKey, jsonData);
StringBuffer sbColName = new StringBuffer();
StringBuffer sbParams = new StringBuffer();
StringBuffer sbRollbackParentSQL = new StringBuffer();
List<Object> listValues = new ArrayList<Object>();
List<String> listUnmatchedJsonName = new ArrayList<String>();
String sTableName = mapCrudCfg.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
for(String sJsonName : jsonData.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
if(sColName!=null)
{
Object o = jsonData.get(sJsonName);
if(o!=null && o!=JSONObject.NULL)
{
listValues.add(o);
if(sbColName.length()>0)
{
sbColName.append(",");
sbParams.append(",");
}
sbColName.append(sColName);
sbParams.append("?");
sbRollbackParentSQL.append(" AND ").append(sColName).append(" = ? ");
}
}
else
{
listUnmatchedJsonName.add(sJsonName);
}
}
String sSQL = "INSERT INTO "+sTableName+"("+sbColName.toString()+") values ("+sbParams.toString()+")";
String sJdbcName = mapCrudCfg.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jArrCreated = null;
try {
jArrCreated = dbmgr.executeUpdate(sSQL, listValues);
}
catch(Throwable ex)
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, "sql:"+sSQL+", params:"+listParamsToString(listValues), ex);
}
if(jArrCreated.length()>0)
{
JSONObject jsonCreated = jArrCreated.getJSONObject(0);
jsonCreated = convertCol2Json(aCrudKey, jsonCreated);
for(String sAttrName : jsonCreated.keySet())
{
jsonData.put(sAttrName, jsonCreated.get(sAttrName));
}
//child create
if(listUnmatchedJsonName.size()>0)
{
JSONArray jsonArrReturn = retrieve(aCrudKey, jsonData);
for(int i=0 ; i<jsonArrReturn.length(); i++ )
{
JSONObject jsonReturn = jsonArrReturn.getJSONObject(i);
//merging json obj
for(String sDataJsonKey : jsonData.keySet())
{
jsonReturn.put(sDataJsonKey, jsonData.get(sDataJsonKey));
}
for(String sJsonName2 : listUnmatchedJsonName)
{
List<Object[]> listParams2 = getSubQueryParams(mapCrudCfg, jsonReturn, sJsonName2);
String sObjInsertSQL = mapCrudCfg.get("jsonattr."+sJsonName2+"."+JsonCrudConfig._PROP_KEY_CHILD_INSERTSQL);
long lupdatedRow = 0;
try {
lupdatedRow = updateChildObject(dbmgr, sObjInsertSQL, listParams2);
}
catch(Throwable ex)
{
try {
//rollback parent
sbRollbackParentSQL.insert(0, "DELETE FROM "+sTableName+" WHERE 1=1 ");
JSONArray jArrRollbackRows = dbmgr.executeUpdate(sbRollbackParentSQL.toString(), listValues);
if(jArrCreated.length() != jArrRollbackRows.length())
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, "Record fail to Rollback!");
}
}
catch(Throwable ex2)
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, "[Rollback Failed], parent:[sql:"+sbRollbackParentSQL.toString()+",params:"+listParamsToString(listValues)+"], child:[sql:"+sObjInsertSQL+",params:"+listParamsToString(listParams2)+"]", ex);
}
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, "[Rollback Success] : child : sql:"+sObjInsertSQL+", params:"+listParamsToString(listParams2), ex);
}
}
}
}
JSONArray jsonArray = retrieve(aCrudKey, jsonData);
if(jsonArray==null || jsonArray.length()==0)
return null;
else
return (JSONObject) jsonArray.get(0);
}
else
{
return null;
}
}
public JSONObject retrieveFirst(String aCrudKey, JSONObject aWhereJson) throws JsonCrudException
{
JSONArray jsonArr = retrieve(aCrudKey, aWhereJson);
if(jsonArr!=null)
{
if(jsonArr.length()>0)
return (JSONObject) jsonArr.get(0);
else
return new JSONObject(); //empty result
}
return null;
}
public JSONArray retrieve(String aCrudKey, JSONObject aWhereJson) throws JsonCrudException
{
JSONObject json = retrieve(aCrudKey, aWhereJson, 0, 0, null, null);
if(json==null)
{
return new JSONArray();
}
return (JSONArray) json.get(JsonCrudConfig._LIST_RESULT);
}
public JSONArray retrieve(String aCrudKey, JSONObject aWhereJson, String[] aSorting, String[] aReturns) throws JsonCrudException
{
JSONObject json = retrieve(aCrudKey, aWhereJson, 0, 0, aSorting, aReturns);
if(json==null)
{
return new JSONArray();
}
return (JSONArray) json.get(JsonCrudConfig._LIST_RESULT);
}
public JSONObject retrieve(String aCrudKey, String aSQL, Object[] aObjParams,
long aStartFrom, long aFetchSize) throws JsonCrudException
{
return retrieve(aCrudKey, aSQL, aObjParams, aStartFrom, aFetchSize, null);
}
private JSONObject retrieve(String aCrudKey, String aSQL, Object[] aObjParams,
long aStartFrom, long aFetchSize, String[] aReturns) throws JsonCrudException
{
JSONObject jsonReturn = null;
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
Map<String, String> mapCrudSql = mapJson2Sql.get(aCrudKey);
String sSQL = aSQL;
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
List<String> listReturnsAttrName = new ArrayList<String>();
if(aReturns!=null)
{
for(String sAttrName : aReturns)
{
listReturnsAttrName.add(sAttrName);
}
}
boolean isFilterByReturns = listReturnsAttrName.size()>0;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
if(aStartFrom<=0)
aStartFrom = 1;
JSONArray jsonArr = new JSONArray();
try{
conn = dbmgr.getConnection();
stmt = conn.prepareStatement(sSQL);
stmt = JdbcDBMgr.setParams(stmt, aObjParams);
rs = stmt.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
long lTotalResult = 0;
while(rs.next())
{
lTotalResult++;
if(lTotalResult < aStartFrom)
continue;
JSONObject jsonOnbj = new JSONObject();
for(int i=0; i<meta.getColumnCount(); i++)
{
// need to have full result so that subquery can be execute
String sColName = meta.getColumnLabel(i+1);
Object oObj = rs.getObject(sColName);
if(oObj==null)
oObj = JSONObject.NULL;
jsonOnbj.put(sColName, oObj);
}
jsonOnbj = convertCol2Json(aCrudKey, jsonOnbj);
if(mapCrudSql.size()>0)
{
for(String sJsonName : mapCrudSql.keySet())
{
if(isFilterByReturns)
{
if(!listReturnsAttrName.contains(sJsonName))
//skip
continue;
}
if(!jsonOnbj.has(sJsonName))
{
List<Object> listParams2 = new ArrayList<Object>();
String sSQL2 = mapCrudSql.get(sJsonName);
Matcher m = pattSQLjsonname.matcher(sSQL2);
while(m.find())
{
String sBracketJsonName = m.group(1);
if(jsonOnbj.has(sBracketJsonName))
{
listParams2.add(jsonOnbj.get(sBracketJsonName));
}
}
sSQL2 = sSQL2.replaceAll("\\{.+?\\}", "?");
if(sSQL2.indexOf("?")>-1)
{
if(listParams2.size()==0)
{
break;
//throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION,
// "Insufficient sql paramters - sql:"+mapCrudSql.get(sJsonName)+", params:"+listParamsToString(listParams2));
}
}
String sSQL2FetchLimit = map.get("jsonattr."+sJsonName+".sql.fetch.limit");
long lFetchLimit = 0;
if(sSQL2FetchLimit!=null)
{
try {
lFetchLimit = Integer.parseInt(sSQL2FetchLimit);
}catch(NumberFormatException ex)
{
ex.printStackTrace();
lFetchLimit = 0;
}
}
JSONArray jsonArrayChild = retrieveChild(dbmgr, sSQL2, listParams2, 1, lFetchLimit);
if(jsonArrayChild!=null)
{
String sPropKeyMapping = "jsonattr."+sJsonName+"."+JsonCrudConfig._PROP_KEY_CHILD_MAPPING;
String sChildMapping = map.get(sPropKeyMapping);
if(sChildMapping!=null)
{
sChildMapping = sChildMapping.trim();
if(sChildMapping.startsWith("\"") && sChildMapping.endsWith("\""))
{
JSONObject jsonData = jsonArrayChild.getJSONObject(0);
String sData = "";
if(jsonData!=null)
{
String sAttrkey = sChildMapping.substring(1, sChildMapping.length()-1);
if(jsonData.has(sAttrkey))
{
sData = jsonData.getString(sAttrkey);
}
}
jsonOnbj.put(sJsonName, sData);
}
else if(sChildMapping.startsWith("[") && sChildMapping.endsWith("]"))
{
JSONArray jArrMappingData = new JSONArray();
JSONArray jArrMapping = new JSONArray(sChildMapping);
for(int i=0; i<jsonArrayChild.length(); i++)
{
JSONObject jsonData = jsonArrayChild.getJSONObject(i);
for(int j=0; j<jArrMapping.length(); j++)
{
String sKey = jArrMapping.getString(j);
if(jsonData.has(sKey))
{
Object oMappingData = jsonData.get(sKey);
jArrMappingData.put(oMappingData);
}
else
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG,
"Invalid Child Mapping : "+sPropKeyMapping+"="+sChildMapping);
}
}
}
jsonOnbj.put(sJsonName, jArrMappingData);
}
else if(sChildMapping.startsWith("{") && sChildMapping.endsWith("}"))
{
JSONObject jsonMappingData = null;
JSONObject jsonChildMapping = new JSONObject(sChildMapping);
int iKeys = jsonChildMapping.keySet().size();
if(iKeys>0)
{
jsonMappingData = new JSONObject();
for(int i=0; i<jsonArrayChild.length(); i++)
{
JSONObject jsonData = jsonArrayChild.getJSONObject(i);
for(String sKey : jsonChildMapping.keySet())
{
String sMapKey = jsonData.getString(sKey);
Object oMapVal = jsonData.get(jsonChildMapping.getString(sKey));
jsonMappingData.put(sMapKey, oMapVal);
}
}
}
if(jsonMappingData!=null)
{
jsonOnbj.put(sJsonName, jsonMappingData);
}
else
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG,
"Invalid Child Mapping : "+sPropKeyMapping+"="+sChildMapping);
}
}
else
{
jsonOnbj.put(sJsonName, jsonArrayChild);
}
}
}
}
}
if(isFilterByReturns)
{
JSONObject jsonObjReturn = new JSONObject();
for(Object oAttrKey : jsonOnbj.keySet())
{
String sAttKey = oAttrKey.toString();
if(listReturnsAttrName.contains(sAttKey))
{
jsonObjReturn.put(sAttKey, jsonOnbj.get(sAttKey));
}
}
jsonOnbj = jsonObjReturn;
}
jsonArr.put(jsonOnbj);
if(aFetchSize>0 && jsonArr.length()>=aFetchSize)
{
break;
}
}
while(rs.next()){
lTotalResult++;
}
if(jsonArr!=null)
{
jsonReturn = new JSONObject();
jsonReturn.put(JsonCrudConfig._LIST_RESULT, jsonArr);
JSONObject jsonMeta = new JSONObject();
jsonMeta.put(JsonCrudConfig._LIST_TOTAL, lTotalResult);
jsonMeta.put(JsonCrudConfig._LIST_START, aStartFrom);
if(aFetchSize>0)
jsonMeta.put(JsonCrudConfig._LIST_FETCHSIZE, aFetchSize);
jsonReturn.put(JsonCrudConfig._LIST_META, jsonMeta);
}
}
catch(SQLException sqlEx)
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, "crudKey:"+aCrudKey+", sql:"+sSQL+", params:"+listParamsToString(aObjParams), sqlEx);
}
finally
{
try {
dbmgr.closeQuietly(conn, stmt, rs);
} catch (SQLException e) {
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, e);
}
}
return jsonReturn;
}
private JSONArray retrieveChild(JdbcDBMgr aJdbcMgr, String aSQL, List<Object> aObjParamList, long iFetchStart, long iFetchSize) throws SQLException
{
Connection conn2 = null;
PreparedStatement stmt2 = null;
ResultSet rs2 = null;
int iTotalCols = 0;
JSONArray jsonArr2 = null;
try{
conn2 = aJdbcMgr.getConnection();
stmt2 = conn2.prepareStatement(aSQL);
stmt2 = JdbcDBMgr.setParams(stmt2, aObjParamList);
rs2 = stmt2.executeQuery();
ResultSetMetaData meta = rs2.getMetaData();
iTotalCols = meta.getColumnCount();
if(iTotalCols>0)
jsonArr2 = new JSONArray();
long lTotalCnt = 0;
if(iFetchStart<=0)
iFetchStart = 1;
if(iFetchSize<0)
iFetchSize = 0;
while(rs2.next())
{
lTotalCnt++;
if(lTotalCnt<iFetchStart)
continue;
JSONObject json2 = new JSONObject();
for(int i=1; i<=iTotalCols; i++)
{
String sColName = meta.getColumnLabel(i);
Object o = rs2.getObject(i);
if(o==null)
o = JSONObject.NULL;
json2.put(sColName, o);
}
jsonArr2.put(json2);
if(iFetchSize>0 && lTotalCnt>=iFetchSize)
continue;
}
}catch(SQLException sqlEx)
{
throw new SQLException("sql:"+aSQL+", params:"+listParamsToString(aObjParamList), sqlEx);
}
finally{
aJdbcMgr.closeQuietly(conn2, stmt2, rs2);
}
return jsonArr2;
}
public JSONObject retrieve(String aCrudKey, JSONObject aWhereJson,
long aStartFrom, long aFetchSize, String[] aSorting, String[] aReturns) throws JsonCrudException
{
JSONObject jsonWhere = castJson2DBVal(aCrudKey, aWhereJson);
if(jsonWhere==null)
jsonWhere = new JSONObject();
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Invalid crud configuration key ! - "+aCrudKey);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
if(sTableName==null || sTableName.trim().length()==0)
{
return null;
}
// WHERE
StringBuffer sbWhere = new StringBuffer();
for(String sOrgJsonName : jsonWhere.keySet())
{
boolean isCaseInSensitive = false;
boolean isNotCondition = false;
String sOperator = " = ";
String sJsonName = sOrgJsonName;
Object oJsonValue = jsonWhere.get(sOrgJsonName);
Map<String, String> mapSQLEscape = new HashMap<String, String>();
if(sJsonName.indexOf(".")>-1)
{
Matcher m = pattJsonNameFilter.matcher(sJsonName);
if(m.find())
{
sJsonName = m.group(1);
String sJsonNOT = m.group(2);
String sJsonOperator = m.group(3);
String sJsonCIorNOT_1 = m.group(4);
String sJsonCIorNOT_2 = m.group(5);
if(JSONFILTER_CASE_INSENSITIVE.equalsIgnoreCase(sJsonCIorNOT_1) || JSONFILTER_CASE_INSENSITIVE.equalsIgnoreCase(sJsonCIorNOT_2)
|| JSONFILTER_CASE_INSENSITIVE.equals(sJsonOperator))
{
isCaseInSensitive = true;
}
if(JSONFILTER_NOT.equalsIgnoreCase(sJsonNOT)
|| JSONFILTER_NOT.equalsIgnoreCase(sJsonCIorNOT_1) || JSONFILTER_NOT.equalsIgnoreCase(sJsonCIorNOT_2)
|| JSONFILTER_NOT.equals(sJsonOperator))
{
isNotCondition = true;
}
if(JSONFILTER_FROM.equals(sJsonOperator))
{
sOperator = " >= ";
}
else if(JSONFILTER_TO.equals(sJsonOperator))
{
sOperator = " <= ";
}
else if(JSONFILTER_TO.equals(sJsonOperator))
{
sOperator = " <= ";
}
else if(JSONFILTER_IN.equals(sJsonOperator))
{
sOperator = " IN ";
}
else if(oJsonValue!=null && oJsonValue instanceof String)
{
String sJsonValue = String.valueOf(oJsonValue);
if(isRequireSQLEscape(sJsonValue))
{
String sEscapeChar = getSQLEscapeChar(sJsonValue);
mapSQLEscape.put(sOrgJsonName, " ESCAPE '"+sEscapeChar+"' ");
for(char c : SQLLIKE_RESERVED_CHARS)
{
sJsonValue = sJsonValue.replaceAll(String.valueOf(c), sEscapeChar+c);
}
}
if(JSONFILTER_STARTWITH.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = sJsonValue+SQLLIKE_WILDCARD;
}
else if (JSONFILTER_ENDWITH.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = SQLLIKE_WILDCARD+sJsonValue;
}
else if (JSONFILTER_CONTAIN.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = SQLLIKE_WILDCARD+sJsonValue+SQLLIKE_WILDCARD;
}
}
}
}
String sColName = mapCrudJsonCol.get(sJsonName);
if(sColName!=null)
{
sbWhere.append(" AND ");
if(oJsonValue==null || oJsonValue==JSONObject.NULL)
{
sbWhere.append(sColName).append(" IS NULL ");
continue;
}
if(isNotCondition)
{
sbWhere.append(" NOT (");
}
StringBuffer sbSQLparam = new StringBuffer();
sbSQLparam.append("?");
if(sOperator.trim().equalsIgnoreCase("IN"))
{
//multi-value
sbSQLparam.setLength(0);
String sStrValues = oJsonValue.toString();
StringTokenizer tk = new StringTokenizer(sStrValues, SQL_IN_SEPARATOR);
while(tk.hasMoreTokens())
{
String sVal = tk.nextToken();
oJsonValue = castJson2DBVal(aCrudKey, sJsonName, sVal.trim());
if(sbSQLparam.length()>0)
sbSQLparam.append(", ");
sbSQLparam.append("?");
listValues.add(oJsonValue);
}
}
else
{
oJsonValue = castJson2DBVal(aCrudKey, sJsonName, oJsonValue);
listValues.add(oJsonValue);
}
if(isCaseInSensitive && (oJsonValue instanceof String))
{
sbWhere.append(" UPPER(").append(sColName).append(") ").append(sOperator).append(" UPPER(").append(sbSQLparam.toString()).append(")");
}
else
{
sbWhere.append(sColName).append(sOperator).append(" (").append(sbSQLparam.toString()).append(")");
}
if(sOperator.equalsIgnoreCase(" like "))
{
String sEscapeSQL = mapSQLEscape.get(sOrgJsonName);
if(sEscapeSQL!=null)
sbWhere.append(sEscapeSQL);
}
if(isNotCondition)
{
sbWhere.append(" )");
}
}
else
{
Map<String, String> mapJsonSql = mapJson2Sql.get(aCrudKey);
if(mapJsonSql==null || mapJsonSql.get(sJsonName)==null)
throw new JsonCrudException(JsonCrudConfig.ERRCODE_INVALID_FILTER, "Invalid filter - "+aCrudKey+" : "+sJsonName);
}
}
StringBuffer sbOrderBy = new StringBuffer();
if(aSorting!=null && aSorting.length>0)
{
for(String sOrderBy : aSorting)
{
String sOrderSeqKeyword = "";
int iOrderSeq = sOrderBy.indexOf('.');
if(iOrderSeq>-1)
{
sOrderSeqKeyword = sOrderBy.substring(iOrderSeq+1);
}
else if(iOrderSeq==-1)
{
iOrderSeq = sOrderBy.length();
}
String sJsonAttr = sOrderBy.substring(0, iOrderSeq);
String sOrderColName = mapCrudJsonCol.get(sJsonAttr);
if(sOrderColName!=null)
{
if(sbOrderBy.length()>0)
{
sbOrderBy.append(",");
}
sbOrderBy.append(sOrderColName);
if(sOrderSeqKeyword.length()>0)
sbOrderBy.append(" ").append(sOrderSeqKeyword);
}
else
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_INVALID_SORTING, "Invalid sorting - "+aCrudKey+" : "+sJsonAttr);
}
}
if(sbOrderBy.length()>0)
{
sbWhere.append(" ORDER BY ").append(sbOrderBy.toString());
}
}
String sSQL = "SELECT * FROM "+sTableName+" WHERE 1=1 "+sbWhere.toString();
JSONObject jsonReturn = retrieve(
aCrudKey, sSQL,
listValues.toArray(new Object[listValues.size()]),
aStartFrom, aFetchSize, aReturns);
if(jsonReturn!=null && jsonReturn.has(JsonCrudConfig._LIST_META))
{
if(aSorting!=null)
{
JSONObject jsonMeta = jsonReturn.getJSONObject(JsonCrudConfig._LIST_META);
StringBuffer sbOrderBys = new StringBuffer();
for(String sOrderBy : aSorting)
{
if(sbOrderBys.length()>0)
sbOrderBys.append(",");
sbOrderBys.append(sOrderBy);
}
if(sbOrderBys.length()>0)
jsonMeta.put(JsonCrudConfig._LIST_SORTING, sbOrderBys.toString());
jsonReturn.put(JsonCrudConfig._LIST_META, jsonMeta);
}
}
return jsonReturn;
}
private String getSQLEscapeChar(String aSqlStrValue)
{
for(char ch : JsonCrudConfig.SQLLIKE_ESCAPE_CHARS)
{
if(aSqlStrValue.indexOf(ch)==-1)
{
return String.valueOf(ch);
}
}
return null;
}
private boolean isRequireSQLEscape(String aSqlStrValue)
{
for(char cReservedChar : SQLLIKE_RESERVED_CHARS)
{
if(aSqlStrValue.indexOf(cReservedChar)>-1)
{
return true;
}
}
return false;
}
public JSONArray update(String aCrudKey, JSONObject aDataJson, JSONObject aWhereJson) throws JsonCrudException
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map.size()==0)
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Invalid crud configuration key ! - "+aCrudKey);
JSONObject jsonData = checkJSONmapping(aCrudKey, aDataJson, map);
jsonData = castJson2DBVal(aCrudKey, jsonData);
JSONObject jsonWhere = castJson2DBVal(aCrudKey, aWhereJson);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
List<String> listUnmatchedJsonName = new ArrayList<String>();
//SET
StringBuffer sbSets = new StringBuffer();
for(String sJsonName : jsonData.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
if(sColName!=null)
{
if(sbSets.length()>0)
sbSets.append(",");
sbSets.append(sColName).append(" = ? ");
listValues.add(jsonData.get(sJsonName));
}
else
{
listUnmatchedJsonName.add(sJsonName);
}
}
// WHERE
StringBuffer sbWhere = new StringBuffer();
for(String sJsonName : jsonWhere.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
if(sColName==null)
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Missing Json to dbcol mapping ("+sJsonName+":"+jsonWhere.get(sJsonName)+") ! - "+aCrudKey);
}
sbWhere.append(" AND ").append(sColName).append(" = ? ");
listValues.add(jsonWhere.get(sJsonName));
}
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = "UPDATE "+sTableName+" SET "+sbSets.toString()+" WHERE 1=1 "+sbWhere.toString();
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jArrUpdated = new JSONArray();
long lAffectedRow2 = 0;
try{
if(sbSets.length()>0)
{
jArrUpdated = dbmgr.executeUpdate(sSQL, listValues);
}
if(jArrUpdated.length()>0 || sbSets.length()==0)
{
//child update
JSONArray jsonArrReturn = retrieve(aCrudKey, jsonWhere);
for(int i=0 ; i<jsonArrReturn.length(); i++ )
{
JSONObject jsonReturn = jsonArrReturn.getJSONObject(i);
//merging json obj
for(String sDataJsonKey : jsonData.keySet())
{
jsonReturn.put(sDataJsonKey, jsonData.get(sDataJsonKey));
}
for(String sJsonName2 : listUnmatchedJsonName)
{
List<Object[]> listParams2 = getSubQueryParams(map, jsonReturn, sJsonName2);
String sObjInsertSQL = map.get("jsonattr."+sJsonName2+"."+JsonCrudConfig._PROP_KEY_CHILD_INSERTSQL);
lAffectedRow2 += updateChildObject(dbmgr, sObjInsertSQL, listParams2);
}
}
}
}
catch(SQLException sqlEx)
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, "sql:"+sSQL+", params:"+listParamsToString(listValues), sqlEx);
}
if(jArrUpdated.length()>0 || lAffectedRow2>0)
{
JSONArray jsonArray = retrieve(aCrudKey, jsonWhere);
return jsonArray;
}
else
{
return null;
}
}
public JSONArray delete(String aCrudKey, JSONObject aWhereJson) throws JsonCrudException
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Invalid crud configuration key ! - "+aCrudKey);
JSONObject jsonWhere = castJson2DBVal(aCrudKey, aWhereJson);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
StringBuffer sbWhere = new StringBuffer();
for(String sJsonName : jsonWhere.keySet())
{
Object o = jsonWhere.get(sJsonName);
String sColName = mapCrudJsonCol.get(sJsonName);
if(o==null || o==JSONObject.NULL)
{
sbWhere.append(" AND ").append(sColName).append(" IS NULL ");
}
else
{
sbWhere.append(" AND ").append(sColName).append(" = ? ");
listValues.add(o);
}
}
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = "DELETE FROM "+sTableName+" WHERE 1=1 "+sbWhere.toString();
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jsonArray = null;
jsonArray = retrieve(aCrudKey, jsonWhere);
if(jsonArray.length()>0)
{
JSONArray jArrAffectedRow = new JSONArray();
try {
jArrAffectedRow = dbmgr.executeUpdate(sSQL, listValues);
}
catch(SQLException sqlEx)
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_SQLEXCEPTION, "sql:"+sSQL+", params:"+listParamsToString(listValues), sqlEx);
}
if(jArrAffectedRow.length()>0)
{
return jsonArray;
}
}
return null;
}
private void clearAll()
{
mapDBMgr.clear();
mapJson2ColName.clear();
mapColName2Json.clear();
mapJson2Sql.clear();
mapTableCols.clear();
}
public JsonCrudConfig getJsonCrudConfig()
{
return jsoncrudConfig;
}
public Map<String, String> getAllConfig()
{
return jsoncrudConfig.getAllConfig();
}
public Map<String, String> getCrudConfigs(String aConfigKey)
{
if(!aConfigKey.startsWith(JsonCrudConfig._PROP_KEY_CRUD))
aConfigKey = JsonCrudConfig._PROP_KEY_CRUD + "." + aConfigKey;
Map<String, String> mapCrudCfg = jsoncrudConfig.getConfig(aConfigKey);
if(mapCrudCfg!=null && mapCrudCfg.size()>0)
{
JdbcDBMgr jdbcMgr = mapDBMgr.get(aConfigKey);
if(jdbcMgr!=null)
{
Map<String , String> mapJdbcCfg = jdbcMgr.getReferenceConfig();
if(mapJdbcCfg!=null)
{
mapCrudCfg.putAll(mapJdbcCfg);
}
}
}
return mapCrudCfg;
}
private JdbcDBMgr initNRegJdbcDBMgr(String aJdbcConfigKey, Map<String, String> mapJdbcConfig) throws SQLException
{
JdbcDBMgr dbmgr = mapDBMgr.get(aJdbcConfigKey);
if(dbmgr==null)
{
String sJdbcClassName = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME);
String sJdbcUrl = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_URL);
String sJdbcUid = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_UID);
String sJdbcPwd = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_PWD);
if(sJdbcClassName!=null && sJdbcUrl!=null)
{
try {
dbmgr = new JdbcDBMgr(sJdbcClassName, sJdbcUrl, sJdbcUid, sJdbcPwd);
}catch(Exception ex)
{
throw new SQLException("Error initialize JDBC - "+aJdbcConfigKey, ex);
}
int lconnpoolsize = -1;
String sConnPoolSize = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CONNPOOL);
if(sConnPoolSize!=null)
{
try{
lconnpoolsize = Integer.parseInt(sConnPoolSize);
if(lconnpoolsize>-1)
{
dbmgr.setDBConnPoolSize(lconnpoolsize);
}
}
catch(NumberFormatException ex){}
}
}
if(dbmgr!=null)
{
dbmgr.setReferenceConfig(mapJdbcConfig);
mapDBMgr.put(aJdbcConfigKey, dbmgr);
}
}
return dbmgr;
}
public void reloadProps() throws Exception
{
clearAll();
if(jsoncrudConfig==null)
{
jsoncrudConfig = new JsonCrudConfig(config_prop_filename);
}
for(String sKey : jsoncrudConfig.getConfigCrudKeys())
{
if(!sKey.startsWith(JsonCrudConfig._PROP_KEY_CRUD+"."))
{
if(sKey.startsWith(JsonCrudConfig._PROP_KEY_JDBC))
{
Map<String, String> map = jsoncrudConfig.getConfig(sKey);
initNRegJdbcDBMgr(sKey, map);
}
//only process crud.xxx
continue;
}
JdbcDBMgr dbmgr = null;
Map<String, String> mapCrudConfig = jsoncrudConfig.getConfig(sKey);
String sDBConfigName = mapCrudConfig.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
if(sDBConfigName!=null && sDBConfigName.trim().length()>0)
{
dbmgr = mapDBMgr.get(sDBConfigName);
if(dbmgr==null)
{
Map<String, String> mapDBConfig = jsoncrudConfig.getConfig(sDBConfigName);
if(mapDBConfig==null)
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Invalid "+JsonCrudConfig._PROP_KEY_DBCONFIG+" - "+sDBConfigName);
String sJdbcClassname = mapDBConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME);
if(sJdbcClassname!=null)
{
dbmgr = initNRegJdbcDBMgr(sDBConfigName, mapDBConfig);
}
else
{
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "Invalid "+JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME+" - "+sJdbcClassname);
}
}
}
if(dbmgr!=null)
{
Map<String, String> mapCrudJson2Col = new HashMap<String, String> ();
Map<String, String> mapCrudCol2Json = new HashMap<String, String> ();
Map<String, String> mapCrudJsonSql = new HashMap<String, String> ();
for(String sCrudCfgKey : mapCrudConfig.keySet())
{
Matcher m = pattJsonColMapping.matcher(sCrudCfgKey);
if(m.find())
{
String jsonname = m.group(1);
String dbcolname = mapCrudConfig.get(sCrudCfgKey);
mapCrudJson2Col.put(jsonname, dbcolname);
mapCrudCol2Json.put(dbcolname, jsonname);
continue;
}
m = pattJsonSQL.matcher(sCrudCfgKey);
if(m.find())
{
String jsonname = m.group(1);
String sql = mapCrudConfig.get(sCrudCfgKey);
if(sql==null) sql = "";
else sql = sql.trim();
if(sql.length()>0)
{
mapCrudJsonSql.put(jsonname, sql);
}
continue;
}
}
String sTableName = mapCrudConfig.get(JsonCrudConfig._PROP_KEY_TABLENAME);
System.out.print("[init] "+sKey+" - "+sTableName+" ... ");
if(sTableName!=null && sTableName.trim().length()>0)
{
Map<String, DBColMeta> mapCols = getTableMetaData(sKey, dbmgr, sTableName);
if(mapCols!=null)
{
System.out.println(mapCols.size()+" cols meta loaded.");
mapTableCols.put(sKey, mapCols);
for(String sColName : mapCols.keySet())
{
//No DB Mapping configured
if(mapCrudCol2Json.get(sColName)==null)
{
mapCrudJson2Col.put(sColName, sColName);
mapCrudCol2Json.put(sColName, sColName);
}
}
}
}
mapJson2ColName.put(sKey, mapCrudJson2Col);
mapColName2Json.put(sKey, mapCrudCol2Json);
mapJson2Sql.put(sKey, mapCrudJsonSql);
}
}
}
public Map<String, String[]> validateDataWithSchema(String aCrudKey, JSONObject aJsonData)
{
return validateDataWithSchema(aCrudKey, aJsonData, false);
}
public Map<String, String[]> validateDataWithSchema(String aCrudKey, JSONObject aJsonData, boolean isDebugMode)
{
Map<String, String[]> mapError = new HashMap<String, String[]>();
if(aJsonData!=null)
{
Map<String, String> mapJsonToCol = mapJson2ColName.get(aCrudKey);
StringBuffer sbErrInfo = new StringBuffer();
Map<String, DBColMeta> mapCols = mapTableCols.get(aCrudKey);
if(mapCols!=null && mapCols.size()>0)
{
for(String sJsonKey : aJsonData.keySet())
{
String sJsonColName = mapJsonToCol.get(sJsonKey);
if(sJsonColName==null)
{
//skip not mapping found
continue;
}
DBColMeta col = mapCols.get(sJsonColName);
if(col!=null)
{
Object oVal = aJsonData.get(sJsonKey);
List<String> listErr = new ArrayList<String>();
////// Check if Nullable //////////
if(!col.getColnullable())
{
if(oVal==null || oVal.toString().trim().length()==0)
{
sbErrInfo.setLength(0);
sbErrInfo.append(JsonCrudConfig.ERRCODE_NOT_NULLABLE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' cannot be empty. ").append(col);
}
listErr.add(sbErrInfo.toString());
}
}
if(oVal!=null)
{
////// Check Data Type //////////
boolean isInvalidDataType = false;
if(oVal instanceof String)
{
isInvalidDataType = !col.isString();
}
else if (oVal instanceof Boolean)
{
isInvalidDataType = (!col.isBit() && !col.isBoolean());
}
else if (oVal instanceof Long
|| oVal instanceof Double
|| oVal instanceof Float
|| oVal instanceof Integer)
{
isInvalidDataType = !col.isNumeric();
}
if(isInvalidDataType)
{
sbErrInfo.setLength(0);
sbErrInfo.append(JsonCrudConfig.ERRCODE_INVALID_TYPE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' invalid type, expect:").append(col.getColtypename()).append(" actual:").append(oVal.getClass().getSimpleName()).append(". ").append(col);
}
listErr.add(sbErrInfo.toString());
}
////// Check Data Size //////////
if(oVal instanceof String && !isInvalidDataType)
{
String sVal = oVal.toString();
if(sVal.length()>col.getColsize())
{
sbErrInfo.setLength(0);
sbErrInfo.append(JsonCrudConfig.ERRCODE_EXCEED_SIZE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' exceed allowed size, expect:").append(col.getColsize()).append(" actual:").append(sVal.length()).append(". ").append(col);
}
listErr.add(sbErrInfo.toString());
}
}
///// Check if Data is autoincremental //////
if(col.getColautoincrement())
{
sbErrInfo.setLength(0);
sbErrInfo.append(JsonCrudConfig.ERRCODE_SYSTEM_FIELD);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' not allowed (auto increment field). ").append(col);
}
listErr.add(sbErrInfo.toString());
}
}
if(listErr.size()>0)
{
mapError.put(sJsonKey, listErr.toArray(new String[listErr.size()]));
}
}
}
}
}
return mapError;
}
public JSONObject castJson2DBVal(String aCrudKey, JSONObject aDataObj)
{
if(aDataObj==null)
return null;
JSONObject jsonObj = new JSONObject();
for(String sKey : aDataObj.keySet())
{
Object o = aDataObj.get(sKey);
o = castJson2DBVal(aCrudKey, sKey, o);
jsonObj.put(sKey, o);
}
return jsonObj;
}
public Object castJson2DBVal(String aCrudKey, String aJsonName, Object aVal)
{
if(aVal == null)
return JSONObject.NULL;
if(!(aVal instanceof String))
return aVal;
if(aJsonName.toLowerCase().indexOf(".in")>-1)
return aVal;
//only cast string value
aJsonName = getJsonNameNoFilter(aJsonName);
Object oVal = aVal;
DBColMeta col = getDBColMetaByJsonName(aCrudKey, aJsonName);
if(col!=null)
{
String sVal = String.valueOf(aVal);
if(col.isNumeric())
{
if(sVal.indexOf('.')>-1)
oVal = Double.parseDouble(sVal);
else
oVal = Long.parseLong(sVal);
}
else if(col.isBoolean() || col.isBit())
{
oVal = Boolean.parseBoolean(sVal);
}
}
return oVal;
}
public DBColMeta getDBColMetaByColName(String aCrudKey, String aColName)
{
Map<String,DBColMeta> cols = mapTableCols.get(aCrudKey);
for(DBColMeta col : cols.values())
{
if(col.getColname().equalsIgnoreCase(aColName))
{
return col;
}
}
return null;
}
public DBColMeta getDBColMetaByJsonName(String aCrudKey, String aJsonName)
{
aJsonName = getJsonNameNoFilter(aJsonName);
Map<String,DBColMeta> cols = mapTableCols.get(aCrudKey);
Map<String,String> mapCol2Json = mapColName2Json.get(aCrudKey);
for(DBColMeta col : cols.values())
{
String sColJsonName = mapCol2Json.get(col.getColname());
if(sColJsonName!=null && sColJsonName.equalsIgnoreCase(aJsonName))
{
return col;
}
}
return null;
}
private Map<String, DBColMeta> getTableMetaData(String aKey, JdbcDBMgr aDBMgr, String aTableName) throws SQLException
{
Map<String, DBColMeta> mapDBColJson = new HashMap<String, DBColMeta>();
String sSQL = "SELECT * FROM "+aTableName+" WHERE 1=2";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = aDBMgr.getConnection();
stmt = conn.prepareStatement(sSQL);
rs = stmt.executeQuery();
Map<String, String> mapColJsonName = mapColName2Json.get(aKey);
if(mapColJsonName==null)
mapColJsonName = new HashMap<String,String>();
ResultSetMetaData meta = rs.getMetaData();
for(int i=0; i<meta.getColumnCount(); i++)
{
int idx = i+1;
DBColMeta coljson = new DBColMeta();
coljson.setColseq(idx);
coljson.setTablename(meta.getTableName(idx));
coljson.setColname(meta.getColumnLabel(idx));
coljson.setColclassname(meta.getColumnClassName(idx));
coljson.setColtypename(meta.getColumnTypeName(idx));
coljson.setColtype(String.valueOf(meta.getColumnType(idx)));
coljson.setColsize(meta.getColumnDisplaySize(idx));
coljson.setColnullable(ResultSetMetaData.columnNullable == meta.isNullable(idx));
coljson.setColautoincrement(meta.isAutoIncrement(idx));
String sJsonName = mapColJsonName.get(coljson.getColname());
if(sJsonName!=null)
{
coljson.setJsonname(sJsonName);
}
mapDBColJson.put(coljson.getColname(), coljson);
}
}
finally
{
aDBMgr.closeQuietly(conn, stmt, rs);
}
if(mapDBColJson.size()==0)
return null;
else
{
return mapDBColJson;
}
}
public boolean isDebugMode(String aCrudConfigKey)
{
Map<String, String> mapCrudConfig = jsoncrudConfig.getConfig(aCrudConfigKey);
if(mapCrudConfig!=null)
{
return Boolean.parseBoolean(mapCrudConfig.get(JsonCrudConfig._PROP_KEY_DEBUG));
}
return false;
}
private String listParamsToString(List listParams)
{
if(listParams!=null)
return listParamsToString(listParams.toArray(new Object[listParams.size()]));
else
return null;
}
private String listParamsToString(Object[] aObjParams)
{
JSONArray jsonArr = new JSONArray();
if(aObjParams!=null && aObjParams.length>0)
{
for(int i=0; i<aObjParams.length; i++)
{
Object o = aObjParams[i];
if(o.getClass().isArray())
{
Object[] objs = (Object[]) o;
JSONArray jsonArr2 = new JSONArray();
for(int j=0; j<objs.length; j++)
{
jsonArr2.put(objs[j].toString());
}
jsonArr.put(jsonArr2);
}
else
{
jsonArr.put(o);
}
}
}
return jsonArr.toString();
}
private long updateChildObject(JdbcDBMgr aDBMgr, String aObjInsertSQL, List<Object[]> aListParams) throws JsonCrudException
{
long lAffectedRow = 0;
String sChildTableName = null;
String sChildTableFields = null;
Matcher m = pattInsertSQLtableFields.matcher(aObjInsertSQL.toLowerCase());
if(m.find())
{
sChildTableName = m.group(1);
sChildTableFields = m.group(2);
}
StringBuffer sbWhere = new StringBuffer();
StringTokenizer tk = new StringTokenizer(sChildTableFields,",");
while(tk.hasMoreTokens())
{
if(sbWhere.length()>0)
{
sbWhere.append(" AND ");
}
else
{
sbWhere.append("(");
}
String sField = tk.nextToken();
sbWhere.append(sField).append(" = ? ");
}
sbWhere.append(")");
if(aListParams!=null && aListParams.size()>0)
{
List<Object> listFlattenParam = new ArrayList<Object>();
StringBuffer sbObjSQL2 = new StringBuffer();
sbObjSQL2.append("SELECT * FROM ").append(sChildTableName).append(" WHERE 1=1 ");
sbObjSQL2.append(" AND ").append(sbWhere);
List<Object[]> listParams_new = new ArrayList<Object[]>();
for(Object[] obj2 : aListParams)
{
for(Object o : obj2)
{
if((o instanceof String) && o.toString().equals(""))
{
o = null;
}
listFlattenParam.add(o);
}
try {
if(aDBMgr.getQueryCount(sbObjSQL2.toString(), obj2)==0)
{
listParams_new.add(obj2);
}
} catch (SQLException e) {
throw new JsonCrudException(
JsonCrudConfig.ERRCODE_SQLEXCEPTION, "sql:"+sbObjSQL2.toString()+", params:"+listParamsToString(obj2), e);
}
}
aListParams.clear();
aListParams.addAll(listParams_new);
listParams_new.clear();
aObjInsertSQL = aObjInsertSQL.replaceAll("\\{.+?\\}", "?");
try{
lAffectedRow += aDBMgr.executeBatchUpdate(aObjInsertSQL, aListParams);
}
catch(SQLException sqlEx)
{
throw new JsonCrudException(
JsonCrudConfig.ERRCODE_SQLEXCEPTION, "sql:"+aObjInsertSQL+", params:"+listParamsToString(aListParams), sqlEx);
}
}
return lAffectedRow;
}
private List<Object[]> getSubQueryParams(Map<String, String> aCrudCfgMap, JSONObject aJsonParentData, String aJsonName) throws JsonCrudException
{
String sPrefix = "jsonattr."+aJsonName+".";
String sObjSQL = aCrudCfgMap.get(sPrefix+JsonCrudConfig._PROP_KEY_CHILD_INSERTSQL);
String sObjMapping = aCrudCfgMap.get(sPrefix+JsonCrudConfig._PROP_KEY_CHILD_MAPPING);
String sObjKeyName = null;
String sObjValName = null;
List<Object[]> listAllParams = new ArrayList<Object[]>();
List<Object> listParamObj = new ArrayList<Object>();
if(sObjSQL!=null && sObjMapping!=null)
{
Object obj = aJsonParentData.get(aJsonName);
Iterator iter = null;
boolean isKeyValPair = (obj instanceof JSONObject);
JSONObject jsonKeyVal = null;
if(isKeyValPair)
{
//Key-Value pair
JSONObject jsonObjMapping = new JSONObject(sObjMapping);
sObjKeyName = jsonObjMapping.keySet().iterator().next();
sObjValName = (String) jsonObjMapping.get(sObjKeyName);
jsonKeyVal = (JSONObject) obj;
iter = jsonKeyVal.keySet().iterator();
}
else if(obj instanceof JSONArray)
{
//Single level Array
JSONArray jsonObjMapping = new JSONArray(sObjMapping);
sObjKeyName = (String) jsonObjMapping.iterator().next();
JSONArray jsonArr = (JSONArray) obj;
iter = jsonArr.iterator();
}
while(iter.hasNext())
{
String sKey = (String) iter.next();
listParamObj.clear();
Matcher m = pattSQLjsonname.matcher(sObjSQL);
while(m.find())
{
String sBracketJsonName = m.group(1);
if(aJsonParentData.has(sBracketJsonName))
{
listParamObj.add(aJsonParentData.get(sBracketJsonName));
}
else if(sBracketJsonName.equals(sObjKeyName))
{
listParamObj.add(sKey);
}
else if(jsonKeyVal!=null && sBracketJsonName.equals(sObjValName))
{
listParamObj.add(jsonKeyVal.get(sKey));
}
}
listAllParams.add(listParamObj.toArray(new Object[listParamObj.size()]));
}
}
if(sObjKeyName==null)
throw new JsonCrudException(JsonCrudConfig.ERRCODE_JSONCRUDCFG, "No object mapping found ! - "+aJsonName);
return listAllParams;
}
private boolean isEmptyJson(String aJsonString)
{
if(aJsonString==null || aJsonString.trim().length()==0)
return true;
aJsonString = aJsonString.replaceAll("\\s", "");
while(aJsonString.startsWith("{") || aJsonString.startsWith("["))
{
if(aJsonString.length()==2)
return true;
if("{\"\":\"\"}".equalsIgnoreCase(aJsonString))
{
return true;
}
aJsonString = aJsonString.substring(1, aJsonString.length()-1);
}
return false;
}
private String getJsonNameNoFilter(String aJsonName)
{
int iPos = aJsonName.indexOf(".");
if(iPos >-1)
{
aJsonName = aJsonName.substring(0,iPos);
}
return aJsonName;
}
public JSONObject convertCol2Json(String aCrudKey, JSONObject aJSONObject)
{
if(!aCrudKey.startsWith(JsonCrudConfig._PROP_KEY_CRUD+"."))
{
aCrudKey = JsonCrudConfig._PROP_KEY_CRUD+"."+aCrudKey;
}
Map<String, String> mapCrudCol2Json = mapColName2Json.get(aCrudKey);
if(aJSONObject==null || mapCrudCol2Json==null || mapCrudCol2Json.size()==0)
{
return aJSONObject;
}
JSONObject jsonConverted = new JSONObject();
for(String sColName : aJSONObject.keySet())
{
String sMappedKey = mapCrudCol2Json.get(sColName);
if(sMappedKey==null)
sMappedKey = sColName;
Object obj = aJSONObject.get(sColName);
if(obj instanceof JSONObject)
{
obj = convertCol2Json(aCrudKey, (JSONObject) obj);
}
else if(obj instanceof JSONArray)
{
JSONArray jArrNew = new JSONArray();
JSONArray jArr = (JSONArray) obj;
for(int i=0; i<jArr.length(); i++)
{
Object obj2 = jArr.get(i);
if(obj2 instanceof JSONObject)
{
obj2 = convertCol2Json(aCrudKey, (JSONObject) obj2);
}
jArrNew.put(obj2);
}
obj = jArrNew;
}
jsonConverted.put(sMappedKey, obj);
}
return jsonConverted;
}
public JdbcDBMgr getJdbcMgr(String aJdbcConfigName)
{
return mapDBMgr.get(aJdbcConfigName);
}
}
|
package org.voltdb.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import org.voltdb.VoltDB;
import org.voltdb.benchmark.tpcc.TPCCProjectBuilder;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.Systemsettings;
import org.voltdb.catalog.Table;
import org.voltdb.catalog.User;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.types.ConstraintType;
import com.google.common.base.Joiner;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class TestCatalogUtil extends TestCase {
protected Catalog catalog;
protected Database catalog_db;
@Override
protected void setUp() throws Exception {
catalog = TPCCProjectBuilder.getTPCCSchemaCatalog();
assertNotNull(catalog);
catalog_db = catalog.getClusters().get("cluster").getDatabases().get("database");
assertNotNull(catalog_db);
}
public void testGetSortedCatalogItems() {
for (Table catalog_tbl : catalog_db.getTables()) {
int last_idx = -1;
List<Column> columns = CatalogUtil.getSortedCatalogItems(catalog_tbl.getColumns(), "index");
assertFalse(columns.isEmpty());
assertEquals(catalog_tbl.getColumns().size(), columns.size());
for (Column catalog_col : columns) {
assertTrue(catalog_col.getIndex() > last_idx);
last_idx = catalog_col.getIndex();
}
}
}
public void testToSchema() {
String search_str = "";
// Simple check to make sure things look ok...
for (Table catalog_tbl : catalog_db.getTables()) {
String sql = CatalogUtil.toSchema(catalog_tbl);
assertTrue(sql.startsWith("CREATE TABLE " + catalog_tbl.getTypeName()));
// Columns
for (Column catalog_col : catalog_tbl.getColumns()) {
assertTrue(sql.indexOf(catalog_col.getTypeName()) != -1);
}
// Constraints
for (Constraint catalog_const : catalog_tbl.getConstraints()) {
ConstraintType const_type = ConstraintType.get(catalog_const.getType());
Index catalog_idx = catalog_const.getIndex();
List<ColumnRef> columns = CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(), "index");
if (!columns.isEmpty()) {
search_str = "";
String add = "";
for (ColumnRef catalog_colref : columns) {
search_str += add + catalog_colref.getColumn().getTypeName();
add = ", ";
}
assertTrue(sql.indexOf(search_str) != -1);
}
switch (const_type) {
case PRIMARY_KEY:
assertTrue(sql.indexOf("PRIMARY KEY") != -1);
break;
case FOREIGN_KEY:
search_str = "REFERENCES " + catalog_const.getForeignkeytable().getTypeName();
assertTrue(sql.indexOf(search_str) != -1);
break;
}
}
}
}
public void testDeploymentCRCs() {
final String dep1 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"</deployment>";
// differs in a meaningful way from dep1
final String dep2 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<cluster hostcount='4' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"</deployment>";
// differs in whitespace and attribute order from dep1
final String dep3 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2' />" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <httpd port='0' >" +
" <jsonapi enabled='true'/>" +
" </httpd>" +
"</deployment>";
// admin-mode section actually impacts CRC, dupe above and add it
final String dep4 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <admin-mode port='32323' adminstartup='true'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <httpd port='0' >" +
" <jsonapi enabled='true'/>" +
" </httpd>" +
"</deployment>";
// hearbeat-config section actually impacts CRC, dupe above and add it
final String dep5 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <admin-mode port='32323' adminstartup='true'/>" +
" <heartbeat timeout='30'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <httpd port='0' >" +
" <jsonapi enabled='true'/>" +
" </httpd>" +
"</deployment>";
// security section actually impacts CRC, dupe above and add it
final String dep6 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<security enabled=\"true\"/>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"</deployment>";
// users section actually impacts CRC, dupe above and add it
final String dep7 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<security enabled=\"true\"/>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"<users> " +
"<user name=\"joe\" password=\"aaa\" groups=\"louno,lodue\" roles=\"lotre\"/>" +
"<user name=\"jone\" password=\"bbb\" groups=\"latre,launo\" roles=\"ladue\"/>" +
"</users>" +
"</deployment>";
// users section actually impacts CRC, dupe above
final String dep8 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<security enabled=\"true\"/>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"<users> " +
"<user name=\"joe\" password=\"aaa\" roles=\"lotre,lodue,louno\"/>" +
"<user name=\"jone\" password=\"bbb\" roles=\"launo,ladue,latre\"/>" +
"</users>" +
"</deployment>";
// users section actually impacts CRC, change above
final String dep9 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<security enabled=\"true\"/>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"<users> " +
"<user name=\"joe\" password=\"aaa\" roles=\"lotre,lodue\"/>" +
"<user name=\"jone\" password=\"bbb\" roles=\"launo,ladue,latre,laquattro\"/>" +
"</users>" +
"</deployment>";
final String dep10 = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<security enabled=\"true\"/>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"<export enabled='true' >" +
"<onserver exportto='custom' exportconnectorclass=\"com.foo.export.ExportClient\" >" +
"<configuration>" +
"<property name=\"foo\">false</property>" +
"<property name=\"type\">CSV</property>" +
"<property name=\"with-schema\">false</property>" +
"</configuration>" +
"</onserver>" +
"</export>" +
"<users> " +
"<user name=\"joe\" password=\"aaa\" roles=\"lotre,lodue\"/>" +
"<user name=\"jone\" password=\"bbb\" roles=\"launo,ladue,latre,laquattro\"/>" +
"</users>" +
"</deployment>";
final File tmpDep1 = VoltProjectBuilder.writeStringToTempFile(dep1);
final File tmpDep2 = VoltProjectBuilder.writeStringToTempFile(dep2);
final File tmpDep3 = VoltProjectBuilder.writeStringToTempFile(dep3);
final File tmpDep4 = VoltProjectBuilder.writeStringToTempFile(dep4);
final File tmpDep5 = VoltProjectBuilder.writeStringToTempFile(dep5);
final File tmpDep6 = VoltProjectBuilder.writeStringToTempFile(dep6);
final File tmpDep7 = VoltProjectBuilder.writeStringToTempFile(dep7);
final File tmpDep8 = VoltProjectBuilder.writeStringToTempFile(dep8);
final File tmpDep9 = VoltProjectBuilder.writeStringToTempFile(dep9);
final File tmpDep10 = VoltProjectBuilder.writeStringToTempFile(dep10);
final long crcDep1 = CatalogUtil.getDeploymentCRC(tmpDep1.getPath());
final long crcDep2 = CatalogUtil.getDeploymentCRC(tmpDep2.getPath());
final long crcDep3 = CatalogUtil.getDeploymentCRC(tmpDep3.getPath());
final long crcDep4 = CatalogUtil.getDeploymentCRC(tmpDep4.getPath());
final long crcDep5 = CatalogUtil.getDeploymentCRC(tmpDep5.getPath());
final long crcDep6 = CatalogUtil.getDeploymentCRC(tmpDep6.getPath());
final long crcDep7 = CatalogUtil.getDeploymentCRC(tmpDep7.getPath());
final long crcDep8 = CatalogUtil.getDeploymentCRC(tmpDep8.getPath());
final long crcDep9 = CatalogUtil.getDeploymentCRC(tmpDep9.getPath());
final long crcDep10 = CatalogUtil.getDeploymentCRC(tmpDep10.getPath());
assertTrue(crcDep1 > 0);
assertTrue(crcDep2 > 0);
assertTrue(crcDep3 > 0);
assertTrue(crcDep4 > 0);
assertTrue(crcDep5 > 0);
assertTrue(crcDep6 > 0);
assertTrue(crcDep7 > 0);
assertTrue(crcDep8 > 0);
assertTrue(crcDep9 > 0);
assertTrue(crcDep10 > 0);
assertTrue(crcDep1 != crcDep2);
assertTrue(crcDep1 == crcDep3);
assertTrue(crcDep3 != crcDep4);
assertTrue(crcDep4 != crcDep5);
assertTrue(crcDep1 != crcDep6);
assertTrue(crcDep6 != crcDep7);
assertTrue(crcDep7 == crcDep8);
assertTrue(crcDep8 != crcDep9);
}
public void testDeploymentHeartbeatConfig()
{
final String dep =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <admin-mode port='32323' adminstartup='true'/>" +
" <heartbeat timeout='30'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <httpd port='0' >" +
" <jsonapi enabled='true'/>" +
" </httpd>" +
"</deployment>";
// make sure someone can't give us 0 for timeout value
final String boom =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <admin-mode port='32323' adminstartup='true'/>" +
" <heartbeat timeout='0'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <httpd port='0' >" +
" <jsonapi enabled='true'/>" +
" </httpd>" +
"</deployment>";
final File tmpDep = VoltProjectBuilder.writeStringToTempFile(dep);
final File tmpBoom = VoltProjectBuilder.writeStringToTempFile(boom);
long crcDep = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpDep.getPath(), true);
assertEquals(30, catalog.getClusters().get("cluster").getHeartbeattimeout());
// This returns -1 on schema violation
crcDep = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpBoom.getPath(), true);
assertEquals(-1, crcDep);
}
public void testAutoSnapshotEnabledFlag() throws Exception
{
final String depOff =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <snapshot frequency=\"5s\" retain=\"10\" prefix=\"pref2\" enabled=\"false\"/>" +
"</deployment>";
final String depOn =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <snapshot frequency=\"5s\" retain=\"10\" prefix=\"pref2\" enabled=\"true\"/>" +
"</deployment>";
final File tmpDepOff = VoltProjectBuilder.writeStringToTempFile(depOff);
CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpDepOff.getPath(), true);
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
assertFalse(db.getSnapshotschedule().get("default").getEnabled());
setUp();
final File tmpDepOn = VoltProjectBuilder.writeStringToTempFile(depOn);
CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpDepOn.getPath(), true);
db = catalog.getClusters().get("cluster").getDatabases().get("database");
assertFalse(db.getSnapshotschedule().isEmpty());
assertTrue(db.getSnapshotschedule().get("default").getEnabled());
assertEquals(10, db.getSnapshotschedule().get("default").getRetain());
}
public void testSecurityEnabledFlag() throws Exception
{
final String secOff =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <security enabled=\"false\"/>" +
"</deployment>";
final String secOn =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <security enabled=\"true\"/>" +
"</deployment>";
final File tmpSecOff = VoltProjectBuilder.writeStringToTempFile(secOff);
CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpSecOff.getPath(), true);
Cluster cluster = catalog.getClusters().get("cluster");
assertFalse(cluster.getSecurityenabled());
setUp();
final File tmpSecOn = VoltProjectBuilder.writeStringToTempFile(secOn);
CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpSecOn.getPath(), true);
cluster = catalog.getClusters().get("cluster");
assertTrue(cluster.getSecurityenabled());
}
public void testUserRoles() throws Exception {
final String depRole = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<security enabled=\"true\"/>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"<users> " +
"<user name=\"joe\" password=\"aaa\" roles=\"lotre,lodue,louno\"/>" +
"<user name=\"jane\" password=\"bbb\" roles=\"launo,ladue,latre\"/>" +
"</users>" +
"</deployment>";
catalog_db.getGroups().add("louno");
catalog_db.getGroups().add("lodue");
catalog_db.getGroups().add("lotre");
catalog_db.getGroups().add("launo");
catalog_db.getGroups().add("ladue");
catalog_db.getGroups().add("latre");
final File tmpRole = VoltProjectBuilder.writeStringToTempFile(depRole);
CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpRole.getPath(), true);
Database db = catalog.getClusters().get("cluster")
.getDatabases().get("database");
User joe = db.getUsers().get("joe");
assertNotNull(joe);
assertNotNull(joe.getGroups().get("louno"));
assertNotNull(joe.getGroups().get("lodue"));
assertNotNull(joe.getGroups().get("lotre"));
assertNull(joe.getGroups().get("latre"));
User jane = db.getUsers().get("jane");
assertNotNull(jane);
assertNotNull(jane.getGroups().get("launo"));
assertNotNull(jane.getGroups().get("ladue"));
assertNotNull(jane.getGroups().get("latre"));
assertNull(jane.getGroups().get("lotre"));
}
public void testScrambledPasswords() throws Exception {
final String depRole = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
"<security enabled=\"true\"/>" +
"<cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"<paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
"<httpd port='0'>" +
"<jsonapi enabled='true'/>" +
"</httpd>" +
"<users> " +
"<user name=\"joe\" password=\"1E4E888AC66F8DD41E00C5A7AC36A32A9950D271\" plaintext=\"false\" roles=\"louno\"/>" +
"<user name=\"jane\" password=\"AAF4C61DDCC5E8A2DABEDE0F3B482CD9AEA9434D\" plaintext=\"false\" roles=\"launo\"/>" +
"</users>" +
"</deployment>";
catalog_db.getGroups().add("louno");
catalog_db.getGroups().add("launo");
final File tmpRole = VoltProjectBuilder.writeStringToTempFile(depRole);
CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpRole.getPath(), true);
Database db = catalog.getClusters().get("cluster")
.getDatabases().get("database");
User joe = db.getUsers().get("joe");
assertNotNull(joe);
assertNotNull(joe.getGroups().get("louno"));
assertNotNull(joe.getShadowpassword());
User jane = db.getUsers().get("jane");
assertNotNull(jane);
assertNotNull(jane.getGroups().get("launo"));
assertNotNull(joe.getShadowpassword());
}
public void testSystemSettingsMaxTempTableSize() throws Exception
{
final String depOff =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <snapshot frequency=\"5s\" retain=\"10\" prefix=\"pref2\" enabled=\"false\"/>" +
"</deployment>";
final String depOn =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <paths><voltdbroot path=\"/tmp/" + System.getProperty("user.name") + "\" /></paths>" +
" <snapshot frequency=\"5s\" retain=\"10\" prefix=\"pref2\" enabled=\"true\"/>" +
" <systemsettings>" +
" <temptables maxsize=\"200\"/>" +
" </systemsettings>" +
"</deployment>";
final File tmpDepOff = VoltProjectBuilder.writeStringToTempFile(depOff);
long crcDepOff = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpDepOff.getPath(), true);
Systemsettings sysset = catalog.getClusters().get("cluster").getDeployment().get("deployment").getSystemsettings().get("systemsettings");
assertEquals(100, sysset.getMaxtemptablesize());
setUp();
final File tmpDepOn = VoltProjectBuilder.writeStringToTempFile(depOn);
long crcDepOn = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpDepOn.getPath(), true);
sysset = catalog.getClusters().get("cluster").getDeployment().get("deployment").getSystemsettings().get("systemsettings");
assertEquals(200, sysset.getMaxtemptablesize());
assertTrue(crcDepOff != crcDepOn);
}
// XXX Need to add command log paths here when command logging
// gets tweaked to create directories if they don't exist
public void testRelativePathsToVoltDBRoot() throws Exception
{
final String voltdbroot = "/tmp/" + System.getProperty("user.name");
final String snappath = "test_snapshots";
final String exportpath = "test_export_overflow";
final String commandlogpath = "test_command_log";
final String commandlogsnapshotpath = "test_command_log_snapshot";
File voltroot = new File(voltdbroot);
for (File f : voltroot.listFiles())
{
f.delete();
}
final String deploy =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <paths>" +
" <voltdbroot path=\"" + voltdbroot + "\" />" +
" <snapshots path=\"" + snappath + "\"/>" +
" <exportoverflow path=\"" + exportpath + "\"/>" +
" <commandlog path=\"" + commandlogpath + "\"/>" +
" <commandlogsnapshot path=\"" + commandlogsnapshotpath + "\"/>" +
" </paths>" +
"</deployment>";
final File tmpDeploy = VoltProjectBuilder.writeStringToTempFile(deploy);
CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpDeploy.getPath(), true);
File snapdir = new File(voltdbroot, snappath);
assertTrue("snapshot directory: " + snapdir.getAbsolutePath() + " does not exist",
snapdir.exists());
assertTrue("snapshot directory: " + snapdir.getAbsolutePath() + " is not a directory",
snapdir.isDirectory());
File exportdir = new File(voltdbroot, exportpath);
assertTrue("export overflow directory: " + exportdir.getAbsolutePath() + " does not exist",
exportdir.exists());
assertTrue("export overflow directory: " + exportdir.getAbsolutePath() + " is not a directory",
exportdir.isDirectory());
if (VoltDB.instance().getConfig().m_isEnterprise)
{
File commandlogdir = new File(voltdbroot, commandlogpath);
assertTrue("command log directory: " + commandlogdir.getAbsolutePath() + " does not exist",
commandlogdir.exists());
assertTrue("command log directory: " + commandlogdir.getAbsolutePath() + " is not a directory",
commandlogdir.isDirectory());
File commandlogsnapshotdir = new File(voltdbroot, commandlogsnapshotpath);
assertTrue("command log snapshot directory: " +
commandlogsnapshotdir.getAbsolutePath() + " does not exist",
commandlogsnapshotdir.exists());
assertTrue("command log snapshot directory: " +
commandlogsnapshotdir.getAbsolutePath() + " is not a directory",
commandlogsnapshotdir.isDirectory());
}
}
public void testCompileDeploymentAgainstEmptyCatalog() {
Catalog catalog = new Catalog();
Cluster cluster = catalog.getClusters().add("cluster");
cluster.getDatabases().add("database");
String deploymentContent =
"<?xml version=\"1.0\"?>\n" +
"<deployment>\n" +
" <cluster hostcount='1' sitesperhost='1' kfactor='0' />\n" +
" <httpd enabled='true'>\n" +
" <jsonapi enabled='true' />\n" +
" </httpd>\n" +
" <export enabled='false'/>\n" +
"</deployment>\n";
final File schemaFile = VoltProjectBuilder.writeStringToTempFile(deploymentContent);
final String depPath = schemaFile.getPath();
CatalogUtil.compileDeploymentAndGetCRC(catalog, depPath, false);
String commands = catalog.serialize();
System.out.println(commands);
}
public void testCatalogVersionCheck() {
// really old version shouldn't work
assertFalse(CatalogUtil.isCatalogCompatible("0.3"));
// one minor version older than the min supported
int[] minCompatibleVersion = Arrays.copyOf(CatalogUtil.minCompatibleVersion,
CatalogUtil.minCompatibleVersion.length);
for (int i = minCompatibleVersion.length - 1; i >= 0; i
if (minCompatibleVersion[i] != 0) {
minCompatibleVersion[i]
break;
}
}
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int part : minCompatibleVersion) {
arrayList.add(part);
}
String version = Joiner.on('.').join(arrayList);
assertNotNull(version);
assertFalse(CatalogUtil.isCatalogCompatible(version));
// one minor version newer than the current version
final String currentVersion = VoltDB.instance().getVersionString();
int[] parseCurrentVersion = MiscUtils.parseVersionString(currentVersion);
parseCurrentVersion[parseCurrentVersion.length - 1]++;
arrayList = new ArrayList<Integer>();
for (int part : parseCurrentVersion) {
arrayList.add(part);
}
String futureVersion = Joiner.on('.').join(arrayList);
assertFalse(CatalogUtil.isCatalogCompatible(futureVersion));
// longer version string
String longerVersion = currentVersion + ".2";
assertFalse(CatalogUtil.isCatalogCompatible(longerVersion));
// shorter version string
int[] longVersion = MiscUtils.parseVersionString("2.3.1");
int[] shortVersion = MiscUtils.parseVersionString("2.3");
assertEquals(-1, MiscUtils.compareVersions(shortVersion, longVersion));
// current version should work
assertTrue(CatalogUtil.isCatalogCompatible(VoltDB.instance().getVersionString()));
}
// I'm not testing the legacy behavior here, just IV2
public void testIv2PartitionDetectionSettings() throws Exception
{
if (!VoltDB.checkTestEnvForIv2()) {
return;
}
final String noElement =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
"</deployment>";
final String ppdEnabledDefaultPrefix =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <partition-detection enabled='true'>" +
" </partition-detection>" +
"</deployment>";
final String ppdEnabledWithPrefix =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <partition-detection enabled='true'>" +
" <snapshot prefix='testPrefix'/>" +
" </partition-detection>" +
"</deployment>";
final String ppdDisabledNoPrefix =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
"<deployment>" +
" <cluster hostcount='3' kfactor='1' sitesperhost='2'/>" +
" <partition-detection enabled='false'>" +
" </partition-detection>" +
"</deployment>";
final File tmpNoElement = VoltProjectBuilder.writeStringToTempFile(noElement);
long crc = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpNoElement.getPath(), true);
assertTrue("Deployment file failed to parse", crc != -1);
Cluster cluster = catalog.getClusters().get("cluster");
assertTrue(cluster.getNetworkpartition());
assertEquals("partition_detection", cluster.getFaultsnapshots().get("CLUSTER_PARTITION").getPrefix());
setUp();
final File tmpEnabledDefault = VoltProjectBuilder.writeStringToTempFile(ppdEnabledDefaultPrefix);
crc = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpEnabledDefault.getPath(), true);
assertTrue("Deployment file failed to parse", crc != -1);
cluster = catalog.getClusters().get("cluster");
assertTrue(cluster.getNetworkpartition());
assertEquals("partition_detection", cluster.getFaultsnapshots().get("CLUSTER_PARTITION").getPrefix());
setUp();
final File tmpEnabledPrefix = VoltProjectBuilder.writeStringToTempFile(ppdEnabledWithPrefix);
crc = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpEnabledPrefix.getPath(), true);
assertTrue("Deployment file failed to parse", crc != -1);
cluster = catalog.getClusters().get("cluster");
assertTrue(cluster.getNetworkpartition());
assertEquals("testPrefix", cluster.getFaultsnapshots().get("CLUSTER_PARTITION").getPrefix());
setUp();
final File tmpDisabled = VoltProjectBuilder.writeStringToTempFile(ppdDisabledNoPrefix);
crc = CatalogUtil.compileDeploymentAndGetCRC(catalog, tmpDisabled.getPath(), true);
assertTrue("Deployment file failed to parse", crc != -1);
cluster = catalog.getClusters().get("cluster");
assertFalse(cluster.getNetworkpartition());
}
}
|
package structures;
import game.DataHandler;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RadialGradientPaint;
import java.awt.geom.Point2D;
import java.util.ArrayList;
/**
* A Body is the default class for an object that is representing a Planet.
* @author Sean Lewis
*/
public class Body extends CircularShape {
protected int mass;
private ArrayList<Moon> moons;
private boolean reflector = false;
protected int extraRadius;
protected Color[] colors;
protected float[] dist;
/**
* Initializes a new empty Body.
*/
public Body() {
}
/**
* Initializes a Body based on an already-defined CircularShape.
* @param shape a parameter
*/
public Body(CircularShape shape) {
this((int) shape.center.x, (int) shape.center.y, shape.radius,
shape.color);
}
/**
* Initializes a new Body at a center point and radius with a color. Since
* no mass is specified, the radius is used as the mass.
* @param centerX the center x coordinate
* @param centerY the center y coordinate
* @param radius the radius
* @param color the color
*/
public Body(int centerX, int centerY, int radius, Color color) {
this(centerX, centerY, radius, color, radius);
// if no mass specified, the mass is set to the radius
}
/**
* Initializes a new Body at a center point and radius with a color.
* @param centerX the center x coordinate
* @param centerY the center y coordinate
* @param radius the radius
* @param color the color
* @param mass the mass
*/
public Body(int centerX, int centerY, int radius, Color color, int mass) {
setCenter(new Point2d(centerX, centerY));
setRadius(radius);
setColor(color);
this.mass = mass;
moons = new ArrayList<Moon>();
computeColoring();
}
/**
* Computes the color ratios for the Body (dist and extraRadius).
*/
protected void computeColoring() {
dist = new float[] { 0.94f, 0.96f, 1.0f };
if (radius < 30) {
dist[0] = 0.80f;
dist[1] = 0.90f;
} else if (radius < 45) {
dist[0] = 0.84f;
dist[1] = 0.92f;
} else if (radius < 60) {
dist[0] = 0.88f;
dist[1] = 0.95f;
}
extraRadius = (int) ((dist[2] - dist[1]) * (radius / 2.0));
colors = new Color[3];
colors[0] = color;
colors[1] = Color.WHITE;
colors[2] = Color.BLACK;
}
public void draw(double dx, double dy, Graphics g) {
Graphics2D g2 = (Graphics2D) g;
if (radius < 10) {
g.setColor(color);
g.fillOval((int) Math.round(center.x - radius + dx),
(int) Math.round(center.y - radius + dy), diameter,
diameter);
} else {
g2.setPaint(new RadialGradientPaint(new Point2D.Double(center.x
+ dx, center.y + dy), radius + extraRadius, dist, colors));
g2.fillOval((int) Math.round(center.x - radius + dx - extraRadius),
(int) Math.round(center.y - radius + dy - extraRadius),
diameter + 2 * extraRadius, diameter + 2 * extraRadius);
}
}
/**
* Adds a moon to orbit this Body.
* @param m a parameter
*/
public void addMoon(Moon m) {
moons.add(m);
}
/**
* Sets the reflector property for this Body.
* @param isReflector a parameter
*/
public void setReflector(boolean isReflector) {
reflector = isReflector;
}
/**
* Return if this Body has the reflector property.
* @return if this Body has the reflector property
*/
public boolean isReflector() {
return reflector;
}
/**
* Returns the mass of the Body.
* @return the mass
*/
public int getMass() {
return mass;
}
/**
* Returns the List of Moons attached to this Body.
* @return the List of Moons
*/
public ArrayList<Moon> getMoons() {
return moons;
}
/**
* Returns the description of the Body and its attached moons.
*/
@Override
public String toString() {
String str = "body(";
str += Math.round(center.x) + ", " + Math.round(center.y) + ", "
+ radius + ", " + DataHandler.getColorDisplay(color) + ", "
+ mass + ")";
for (Moon m : moons) {
str += "\n" + m.toString();
}
return str;
}
}
|
package taskDo;
import Parser.ParsedResult;
import commandFactory.CommandAction;
import commandFactory.CommandFactory;
import commandFactory.CommandType;
import commonClasses.Constants;
import commonClasses.StorageList;
import commonClasses.SummaryReport;
public class Executor {
public Executor() {
StorageList.getInstance().loadFile();
}
public void execute(ParsedResult parsedResult) {
CommandFactory commandFactory = new CommandFactory();
CommandType commandType = parsedResult.getCommandType();
if (commandType.equals(CommandType.UNDO)) {
executeUndo(parsedResult);
}else if(commandType.equals(CommandType.REDO)){
executeRedo(parsedResult);
}else{
executeCommand(parsedResult, commandFactory, commandType);
}
CategoryList.updateCategoryList(StorageList.getInstance().getTaskList());
StorageList.getInstance().saveToFile();
}
private void executeUndo(ParsedResult parsedResult) {
if(!History.getUndoActionHistory().empty()){
CommandAction commandAction = History.getUndoActionHistory().pop();
Task lastTask = History.getUndoTaskHistory().pop();
History.getRedoActionHistory().push(commandAction);
parsedResult.setTask(lastTask);
commandAction.undo(parsedResult);
}else{
History.getUndoTaskHistory().clear();
SummaryReport.setFeedBackMsg(Constants.MESSAGE_FAIL_UNDO);
}
}
private void executeRedo(ParsedResult parsedResult) {
if(!History.getRedoActionHistory().empty()){
CommandAction commandAction = History.getRedoActionHistory().pop();
Task lastTask = History.getRedoTaskHistory().pop();
parsedResult.setTask(lastTask);
commandAction.execute(parsedResult);
}else{
History.getRedoTaskHistory().clear();
SummaryReport.setFeedBackMsg(Constants.MESSAGE_FAIL_REDO);
}
}
private void executeCommand(ParsedResult parsedResult,
CommandFactory commandFactory, CommandType commandType) {
CommandAction commandAction = commandFactory.getCommandAction(commandType);
commandAction.execute(parsedResult);
if(!commandType.equals(CommandType.DISPLAY)&&!commandType.equals(CommandType.SEARCH)){
History.getUndoActionHistory().push(commandAction);
}
}
}
|
import java.util.*;
public class TicTacToeInteraction {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
TicTacToe game = new TicTacToe();
Iterator<ArrayList<BoardState>> bestMoveDictionaryKeyIterator = game.getBestMoveDictionary().getKeyIterator();
while (bestMoveDictionaryKeyIterator.hasNext()) {
ArrayList<BoardState> key = bestMoveDictionaryKeyIterator.next();
displayBoard(key);
System.out.println(game.getBestMoveDictionary().getValue(key) + 1);
System.out.println();
}
List<BoardState> boardState;
int userInput;
displayBoard(game.getCurrentBoardState());
while (true) {
do {
System.out.print("Where would you like to place an X? ");
userInput = keyboard.nextInt();
} while (!(0 < userInput && userInput <= 9));
try {
game.placeX(userInput);
if (game.getWinner() != null) {
break;
}
game.makeOpponentMove();
if (game.getWinner() != null) {
break;
}
} catch (IllegalArgumentException error) {
System.out.println(String.format("There is already a mark at position %d", userInput));
}
boardState = game.getCurrentBoardState();
displayBoard(boardState);
}
boardState = game.getCurrentBoardState();
displayBoard(boardState);
System.out.println(String.format("%s is the winner", game.getWinner()));
}
private static void displayBoard(List board) {
for (int i = 0; i < board.size(); i++) {
if (board.get(i) == null) {
System.out.print("_ ");
} else {
System.out.print(board.get(i) + " ");
}
if (i % 3 == 2) {
System.out.println();
}
}
}
}
|
package sqlancer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.JCommander.Builder;
import sqlancer.clickhouse.ClickhouseProvider;
import sqlancer.cockroachdb.CockroachDBProvider;
import sqlancer.duckdb.DuckDBProvider;
import sqlancer.mariadb.MariaDBProvider;
import sqlancer.mysql.MySQLProvider;
import sqlancer.postgres.PostgresProvider;
import sqlancer.sqlite3.SQLite3Provider;
import sqlancer.tidb.TiDBProvider;
public final class Main {
private static final int THREADS_SHUTDOWN_EXIT_CODE = -1;
public static final File LOG_DIRECTORY = new File("logs");
public static volatile AtomicLong nrQueries = new AtomicLong();
public static volatile AtomicLong nrDatabases = new AtomicLong();
public static volatile AtomicLong nrSuccessfulActions = new AtomicLong();
public static volatile AtomicLong nrUnsuccessfulActions = new AtomicLong();
static int threadsShutdown;
static {
if (!LOG_DIRECTORY.exists()) {
LOG_DIRECTORY.mkdir();
}
}
private Main() {
}
public static final class StateLogger {
private final File loggerFile;
private File curFile;
private FileWriter logFileWriter;
public FileWriter currentFileWriter;
private static final List<String> INITIALIZED_PROVIDER_NAMES = new ArrayList<>();
private boolean logEachSelect = true;
private DatabaseProvider<?, ?> provider;
private static final class AlsoWriteToConsoleFileWriter extends FileWriter {
AlsoWriteToConsoleFileWriter(File file) throws IOException {
super(file);
}
@Override
public Writer append(CharSequence arg0) throws IOException {
System.err.println(arg0);
return super.append(arg0);
}
@Override
public void write(String str) throws IOException {
System.err.println(str);
super.write(str);
}
}
public StateLogger(String databaseName, DatabaseProvider<?, ?> provider, MainOptions options) {
this.provider = provider;
File dir = new File(LOG_DIRECTORY, provider.getDBMSName());
if (dir.exists() && !dir.isDirectory()) {
throw new AssertionError(dir);
}
ensureExistsAndIsEmpty(dir, provider);
loggerFile = new File(dir, databaseName + ".log");
logEachSelect = options.logEachSelect();
if (logEachSelect) {
curFile = new File(dir, databaseName + "-cur.log");
}
}
private synchronized void ensureExistsAndIsEmpty(File dir, DatabaseProvider<?, ?> provider) {
if (INITIALIZED_PROVIDER_NAMES.contains(provider.getDBMSName())) {
return;
}
if (!dir.exists()) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException e) {
throw new AssertionError(e);
}
}
File[] listFiles = dir.listFiles();
assert listFiles != null : "directory was just created, so it should exist";
for (File file : listFiles) {
if (!file.isDirectory()) {
file.delete();
}
}
INITIALIZED_PROVIDER_NAMES.add(provider.getDBMSName());
}
private FileWriter getLogFileWriter() {
if (logFileWriter == null) {
try {
logFileWriter = new AlsoWriteToConsoleFileWriter(loggerFile);
} catch (IOException e) {
throw new AssertionError(e);
}
}
return logFileWriter;
}
public FileWriter getCurrentFileWriter() {
if (!logEachSelect) {
throw new UnsupportedOperationException();
}
if (currentFileWriter == null) {
try {
currentFileWriter = new FileWriter(curFile, false);
} catch (IOException e) {
throw new AssertionError(e);
}
}
return currentFileWriter;
}
public void writeCurrent(StateToReproduce state) {
if (!logEachSelect) {
throw new UnsupportedOperationException();
}
printState(getCurrentFileWriter(), state);
try {
currentFileWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeCurrent(String queryString) {
if (!logEachSelect) {
throw new UnsupportedOperationException();
}
try {
getCurrentFileWriter().write(queryString + ";\n");
currentFileWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void logRowNotFound(StateToReproduce state) {
printState(getLogFileWriter(), state);
try {
getLogFileWriter().flush();
} catch (IOException e) {
throw new AssertionError(e);
}
}
public void logException(Throwable reduce, StateToReproduce state) {
String stackTrace = getStackTrace(reduce);
FileWriter logFileWriter2 = getLogFileWriter();
try {
logFileWriter2.write(stackTrace);
printState(logFileWriter2, state);
} catch (IOException e) {
throw new AssertionError(e);
} finally {
try {
logFileWriter2.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String getStackTrace(Throwable e1) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e1.printStackTrace(pw);
return "--" + sw.toString().replace("\n", "\n--");
}
private void printState(FileWriter writer, StateToReproduce state) {
StringBuilder sb = new StringBuilder();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
sb.append("-- Time: " + dateFormat.format(date) + "\n");
sb.append("-- Database: " + state.getDatabaseName() + "\n");
sb.append("
for (Query s : state.getStatements()) {
if (s.getQueryString().endsWith(";")) {
sb.append(s.getQueryString());
} else {
sb.append(s.getQueryString() + ";");
}
sb.append('\n');
}
if (state.getQueryString() != null) {
sb.append(state.getQueryString() + ";\n");
}
try {
writer.write(sb.toString());
} catch (IOException e) {
throw new AssertionError(e);
}
provider.printDatabaseSpecificState(writer, state);
}
}
public static class QueryManager {
private final Connection con;
private final StateToReproduce stateToRepro;
QueryManager(Connection con, StateToReproduce state) {
if (con == null || state == null) {
throw new IllegalArgumentException();
}
this.con = con;
this.stateToRepro = state;
}
public boolean execute(Query q) throws SQLException {
stateToRepro.statements.add(q);
boolean success = q.execute(con);
Main.nrSuccessfulActions.addAndGet(1);
return success;
}
public void incrementSelectQueryCount() {
Main.nrQueries.addAndGet(1);
}
public void incrementCreateDatabase() {
Main.nrDatabases.addAndGet(1);
}
}
public static void printArray(Object[] arr) {
for (Object o : arr) {
System.out.println(o);
}
}
public static void main(String[] args) {
System.exit(executeMain(args));
}
public static int executeMain(String[] args) throws AssertionError {
List<DatabaseProvider<?, ?>> providers = new ArrayList<>();
providers.add(new SQLite3Provider());
providers.add(new CockroachDBProvider());
providers.add(new MySQLProvider());
providers.add(new MariaDBProvider());
providers.add(new TiDBProvider());
providers.add(new PostgresProvider());
providers.add(new ClickhouseProvider());
providers.add(new DuckDBProvider());
Map<String, DatabaseProvider<?, ?>> nameToProvider = new HashMap<>();
Map<String, Object> nameToOptions = new HashMap<>();
MainOptions options = new MainOptions();
Builder commandBuilder = JCommander.newBuilder().addObject(options);
for (DatabaseProvider<?, ?> provider : providers) {
String name = provider.getDBMSName();
if (!name.toLowerCase().equals(name)) {
throw new AssertionError(name + " should be in lowercase!");
}
Object command = provider.getCommand();
if (command == null) {
throw new IllegalStateException();
}
nameToProvider.put(name, provider);
nameToOptions.put(name, command);
commandBuilder = commandBuilder.addCommand(name, command);
}
JCommander jc = commandBuilder.programName("SQLancer").build();
jc.parse(args);
if (jc.getParsedCommand() == null) {
jc.usage();
return THREADS_SHUTDOWN_EXIT_CODE;
}
if (options.printProgressInformation()) {
startProgressMonitor();
}
ExecutorService executor = Executors.newFixedThreadPool(options.getNumberConcurrentThreads());
for (int i = 0; i < options.getTotalNumberTries(); i++) {
final String databaseName = "database" + i;
executor.execute(new Runnable() {
StateToReproduce stateToRepro;
StateLogger logger;
DatabaseProvider<?, ?> provider;
@Override
public void run() {
runThread(databaseName);
}
private void runThread(final String databaseName) {
Thread.currentThread().setName(databaseName);
while (true) {
// create a new instance of the provider in case it has a global state
try {
provider = nameToProvider.get(jc.getParsedCommand()).getClass().getDeclaredConstructor()
.newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
GlobalState<?> state = provider.generateGlobalState();
stateToRepro = provider.getStateToReproduce(databaseName);
state.setState(stateToRepro);
logger = new StateLogger(databaseName, provider, options);
Randomly r = new Randomly();
state.setRandomly(r);
state.setDatabaseName(databaseName);
state.setMainOptions(options);
Object dmbsSpecificOptions = nameToOptions.get(jc.getParsedCommand());
state.setDmbsSpecificOptions(dmbsSpecificOptions);
try (Connection con = provider.createDatabase(state)) {
QueryManager manager = new QueryManager(con, stateToRepro);
try {
java.sql.DatabaseMetaData meta = con.getMetaData();
stateToRepro.databaseVersion = meta.getDatabaseProductVersion();
} catch (SQLFeatureNotSupportedException e) {
// ignore
}
state.setConnection(con);
state.setStateLogger(logger);
state.setManager(manager);
Method method = provider.getClass().getMethod("generateAndTestDatabase", state.getClass());
method.setAccessible(true);
method.invoke(provider, state);
} catch (IgnoreMeException e) {
continue;
} catch (InvocationTargetException e) {
if (e.getCause() instanceof IgnoreMeException) {
continue;
} else {
e.getCause().printStackTrace();
stateToRepro.exception = e.getCause().getMessage();
logger.logFileWriter = null;
logger.logException(e.getCause(), stateToRepro);
threadsShutdown++;
break;
}
} catch (Throwable reduce) {
reduce.printStackTrace();
stateToRepro.exception = reduce.getMessage();
logger.logFileWriter = null;
logger.logException(reduce, stateToRepro);
threadsShutdown++;
break;
} finally {
try {
if (options.logEachSelect()) {
if (logger.currentFileWriter != null) {
logger.currentFileWriter.close();
}
logger.currentFileWriter = null;
}
} catch (IOException e) {
e.printStackTrace();
}
if (threadsShutdown == options.getTotalNumberTries()) {
executor.shutdown();
}
}
}
}
});
}
if (options.getTimeoutSeconds() != -1) {
try {
executor.awaitTermination(options.getTimeoutSeconds(), TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return threadsShutdown == 0 ? 0 : THREADS_SHUTDOWN_EXIT_CODE;
}
private static void startProgressMonitor() {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new Runnable() {
private long timeMillis = System.currentTimeMillis();
private long lastNrQueries = 0;
private long lastNrDbs;
{
timeMillis = System.currentTimeMillis();
}
@Override
public void run() {
long elapsedTimeMillis = System.currentTimeMillis() - timeMillis;
long currentNrQueries = nrQueries.get();
long nrCurrentQueries = currentNrQueries - lastNrQueries;
double throughput = nrCurrentQueries / (elapsedTimeMillis / 1000d);
long currentNrDbs = nrDatabases.get();
long nrCurrentDbs = currentNrDbs - lastNrDbs;
double throughputDbs = nrCurrentDbs / (elapsedTimeMillis / 1000d);
long successfulStatementsRatio = (long) (100.0 * nrSuccessfulActions.get()
/ (nrSuccessfulActions.get() + nrUnsuccessfulActions.get()));
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(String.format(
"[%s] Executed %d queries (%d queries/s; %.2f/s dbs, successful statements: %2d%%). Threads shut down: %d.",
dateFormat.format(date), currentNrQueries, (int) throughput, throughputDbs,
successfulStatementsRatio, threadsShutdown));
timeMillis = System.currentTimeMillis();
lastNrQueries = currentNrQueries;
lastNrDbs = currentNrDbs;
}
}, 5, 5, TimeUnit.SECONDS);
}
}
|
package group4;
import group3.MovingBlob;
import group4.IMovingBlobReduction;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class BlobFilter implements IMovingBlobReduction
{
/**
* Constant thresholds which do all the magic
* All inclusive thresholds
*/
//the maximum ratio of w/h the blob can be to be considered valid
private static final double WIDTH_HEIGHT_RATIO_MAX = 1;
//minimum dimensions size for the blob
private static final int DIMENSION_MIN = 10;
//the minimum age (in frames) the blob must be to be considered valid
private static final short AGE_MIN = 10;
//the minimum velocity for an object in the center
private static final float CENTER_X_VELOCITY_MIN = (int)(1.0f / 15.0f * 32.0f);
//and the width and height of the box to check that velocity
private static final int CENTER_CHECK_WIDTH = 200;
private static final int CENTER_CHECK_HEIGHT = 100;
//the maximum X velocity the blob can have to be considered valid (6 m/s converted to px/frame)
private static final short X_VELOCITY_MAX = (int)(6.0f / 15.0f * 32.0f);
//the minimum distance from the top, left, or right border the predicted position of the blob must be in order to be considered (in px)
private static final short PREDICTED_BORDER_DISTANCE_MIN = 20;
/**
* Checks the list of potential pedestrian blobs to distinguish pedestrians from non-pedestrians.
* Non-pedestrians are removed from the list of blobs.
*
* @param blobs the list of potential pedestrian blobs
* @return the list of blobs determined to be pedestrians
*/
public List<MovingBlob> reduce(List<MovingBlob> blobs)
{
return blobs.parallelStream().filter(p -> isPedestrian(p)).collect(Collectors.toList());
}
/**
* Checks an individual blob to determine if it is a pedestrian or non-pedestrian. Determination
* is made based on blob width vs. height, blob 'age' on screen, and blob xVelocity.
*
* @param blob the blob being checked
* @return if the blob is a pedestrian
*/
private boolean isPedestrian(MovingBlob blob)
{
//lol formatting wut
return blob.width >= DIMENSION_MIN && blob.height >= DIMENSION_MIN
&& blob.width / blob.height <= WIDTH_HEIGHT_RATIO_MAX
&& (blob.age >= AGE_MIN || (blob.x + blob.width/2 >= CENTER_CHECK_WIDTH / 2
&& blob.x + blob.width/2 <= 640 - CENTER_CHECK_WIDTH / 2
&& blob.y + blob.height/2 >= CENTER_CHECK_HEIGHT / 2
&& blob.y + blob.height/2 <= 480 - CENTER_CHECK_HEIGHT / 2
&& blob.velocityX >= CENTER_X_VELOCITY_MIN))
&& Math.abs(blob.velocityX) <= X_VELOCITY_MAX
&& blob.predictedX >= PREDICTED_BORDER_DISTANCE_MIN && blob.predictedX <= (640 - PREDICTED_BORDER_DISTANCE_MIN)
&& blob.predictedY >= PREDICTED_BORDER_DISTANCE_MIN && blob.predictedY <= (480 - PREDICTED_BORDER_DISTANCE_MIN);
}
}
|
package jade.core;
import jade.util.leap.List;
import jade.util.leap.LinkedList;
import jade.util.leap.Iterator;
import jade.util.leap.Serializable;
import jade.core.behaviours.Behaviour;
/**
@author Giovanni Rimassa - Universita` di Parma
@version $Date$ $Revision$
*/
class Scheduler implements Serializable {
/**
@serial
*/
protected List readyBehaviours = new LinkedList();
/**
@serial
*/
protected List blockedBehaviours = new LinkedList();
/**
@serial
*/
private Agent owner;
/**
@serial
*/
private int currentIndex;
public Scheduler(Agent a) {
owner = a;
currentIndex = 0;
}
// Add a behaviour at the end of the behaviours queue.
// This can never change the index of the current behaviour.
// If the behaviours queue was empty notifies the embedded thread of
// the owner agent that a behaviour is now available.
public synchronized void add(Behaviour b) {
readyBehaviours.add(b);
notify();
//__CLDC_UNSUPPORTED__BEGIN
owner.notifyAddBehaviour(b);
//__CLDC_UNSUPPORTED__END
}
// Moves a behaviour from the ready queue to the sleeping queue.
public synchronized void block(Behaviour b) {
if (removeFromReady(b)) {
blockedBehaviours.add(b);
}
//__CLDC_UNSUPPORTED__BEGIN
owner.notifyChangeBehaviourState(b, Behaviour.STATE_READY, Behaviour.STATE_BLOCKED);
//__CLDC_UNSUPPORTED__END
}
// Moves a behaviour from the sleeping queue to the ready queue.
public synchronized void restart(Behaviour b) {
if (removeFromBlocked(b)) {
readyBehaviours.add(b);
notify();
}
//__CLDC_UNSUPPORTED__BEGIN
owner.notifyChangeBehaviourState(b, Behaviour.STATE_BLOCKED, Behaviour.STATE_READY);
//__CLDC_UNSUPPORTED__END
}
// Restarts all behaviours. This method simply calls
// Behaviour.restart() on every behaviour. The
// Behaviour.restart() method then notifies the agent (with the
// Agent.notifyRestarted() method), causing Scheduler.restart() to
// be called (this also moves behaviours from the blocked queue to
// the ready queue --> we must copy all behaviours into a temporary
// buffer to avoid concurrent modification exceptions).
// Why not restarting only blocked behaviours?
// Some ready behaviour can be a NDBehaviour with some of its
// children blocked. These children must be restarted too.
public synchronized void restartAll() {
//Object[] dummy = readyBehaviours.toArray();
Behaviour[] behaviours = new Behaviour[readyBehaviours.size()];
int counter = 0;
for(Iterator it = readyBehaviours.iterator(); it.hasNext();)
behaviours[counter++] = (Behaviour)it.next();
for(int i = 0; i < behaviours.length; i++) {
Behaviour b = behaviours[i];
b.restart();
}
behaviours = new Behaviour[blockedBehaviours.size()];
counter = 0;
for(Iterator it = blockedBehaviours.iterator(); it.hasNext();)
behaviours[counter++] = (Behaviour)it.next();
for(int i = 0; i < behaviours.length; i++) {
Behaviour b = behaviours[i];
b.restart();
}
}
// Removes a specified behaviour from the scheduler
public synchronized void remove(Behaviour b) {
boolean found = removeFromBlocked(b);
if(!found) {
removeFromReady(b);
}
//__CLDC_UNSUPPORTED__BEGIN
owner.notifyRemoveBehaviour(b);
//__CLDC_UNSUPPORTED__END
}
// Selects the appropriate behaviour for execution, with a trivial
// round-robin algorithm.
public synchronized Behaviour schedule() throws InterruptedException {
while(readyBehaviours.isEmpty()) {
owner.doIdle();
//DEBUG
Runtime.instance().debug("Start waiting on the scheduler");
wait();
Runtime.instance().debug("Exit waiting on the scheduler");
}
Behaviour b = (Behaviour)readyBehaviours.get(currentIndex);
currentIndex = (currentIndex + 1) % readyBehaviours.size();
return b;
}
// Removes a specified behaviour from the blocked queue.
private boolean removeFromBlocked(Behaviour b) {
return blockedBehaviours.remove(b);
}
// Removes a specified behaviour from the ready queue.
// This can change the index of the current behaviour, so a check is
// made: if the just removed behaviour has an index lesser than the
// current one, then the current index must be decremented.
private boolean removeFromReady(Behaviour b) {
int index = readyBehaviours.indexOf(b);
if(index != -1) {
readyBehaviours.remove(b);
if(index < currentIndex)
--currentIndex;
//if(currentIndex < 0)
// currentIndex = 0;
else if (index == currentIndex && currentIndex == readyBehaviours.size())
currentIndex = 0;
}
return index != -1;
}
}
|
package algorithms.misc;
import algorithms.imageProcessing.GreyscaleImage;
import algorithms.util.PairInt;
import algorithms.util.PairIntArray;
import algorithms.util.ResourceFinder;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.set.TIntSet;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* miscellaneous boiler plate code
*
* @author nichole
*/
public class Misc {
public static final int[] dx8 = new int[]{-1, -1, 0, 1, 1, 1, 0, -1};
public static final int[] dy8 = new int[]{ 0, -1, -1, -1, 0, 1, 1, 1};
public static final int[] dx4 = new int[]{-1, 0, 1, 0};
public static final int[] dy4 = new int[]{ 0, -1, 0, 1};
public static PairIntArray convertWithoutOrder(Collection<PairInt> points) {
PairIntArray out = new PairIntArray(points.size());
for (PairInt p : points) {
out.add(p.getX(), p.getY());
}
return out;
}
public static Set<PairInt> convert(PairIntArray points) {
if (points == null) {
throw new IllegalArgumentException("points cannot be null");
}
Set<PairInt> out = new HashSet<PairInt>();
for (int i = 0; i < points.getN(); ++i) {
out.add(new PairInt(points.getX(i), points.getY(i)));
}
return out;
}
public static Map<PairInt, Integer> makePointIndexMap(PairIntArray edge) {
if (edge == null) {
throw new IllegalArgumentException("edge cannot be null");
}
Map<PairInt, Integer> map = new HashMap<PairInt, Integer>();
for (int i = 0; i < edge.getN(); ++i) {
map.put(new PairInt(edge.getX(i), edge.getY(i)), Integer.valueOf(i));
}
return map;
}
public static String persistToFile(String fileName, Set<PairInt> points)
throws IOException {
if (points == null) {
throw new IllegalArgumentException("points cannot be null");
}
String outFilePath = ResourceFinder.findDirectory("bin") + "/" +
fileName;
FileOutputStream fs = null;
ObjectOutputStream os = null;
try {
File file = new File(outFilePath);
file.delete();
file.createNewFile();
fs = new FileOutputStream(file);
os = new ObjectOutputStream(fs);
int count = 0;
for (PairInt point : points) {
os.writeInt(point.getX());
os.writeInt(point.getY());
if ((count % 10) == 0) {
os.flush();
}
count++;
}
os.flush();
} finally {
if (os != null) {
os.close();
}
if (fs != null) {
fs.close();
}
}
return outFilePath;
}
public static PairIntArray deserializePairIntArray(String filePath) throws IOException {
FileInputStream fs = null;
ObjectInputStream os = null;
PairIntArray out = new PairIntArray();
try {
File file = new File(filePath);
fs = new FileInputStream(file);
os = new ObjectInputStream(fs);
while (true) {
int x = os.readInt();
int y = os.readInt();
out.add(x, y);
}
} catch (EOFException e) {
// expected
} finally {
if (os != null) {
os.close();
}
if (fs != null) {
fs.close();
}
}
return out;
}
public static Set<PairInt> deserializeSetPairInt(String filePath) throws IOException {
FileInputStream fs = null;
ObjectInputStream os = null;
Set<PairInt> set = new HashSet<PairInt>();
try {
File file = new File(filePath);
fs = new FileInputStream(file);
os = new ObjectInputStream(fs);
while (true) {
int x = os.readInt();
int y = os.readInt();
PairInt p = new PairInt(x, y);
set.add(p);
}
} catch (EOFException e) {
// expected
} finally {
if (os != null) {
os.close();
}
if (fs != null) {
fs.close();
}
}
return set;
}
public static Map<Integer, Double> getCosineThetaMapForTwoPI() {
Map<Integer, Double> map = new HashMap<Integer, Double>();
double d = 1. * Math.PI/180;
double t = 0;
for (int i = 0; i < 360; ++i) {
double c = Math.cos(t);
map.put(Integer.valueOf(i), Double.valueOf(c));
t += d;
}
return map;
}
public static Map<Integer, Double> getSineThetaMapForTwoPI() {
Map<Integer, Double> map = new HashMap<Integer, Double>();
double d = 1. * Math.PI/180;
double t = 0;
for (int i = 0; i < 360; ++i) {
double c = Math.sin(t);
map.put(Integer.valueOf(i), Double.valueOf(c));
t += d;
}
return map;
}
public static <T extends Object> void reverse(List<T> list) {
int n = list.size();
if (n < 2) {
return;
}
int end = n >> 1;
// 0 1 2 3 4
for (int i = 0; i < end; i++) {
int idx2 = n - i - 1;
T swap = list.get(i);
list.set(i, list.get(idx2));
list.set(idx2, swap);
}
}
public static TObjectIntMap<PairInt> createPointIndexMap(
PairIntArray p) {
TObjectIntMap<PairInt> map =
new TObjectIntHashMap<PairInt>();
for (int i = 0; i < p.getN(); ++i) {
PairInt pt = new PairInt(p.getX(i),
p.getY(i));
map.put(pt, i);
}
return map;
}
/**
* get an instance of SecureRandom, trying first
* the algorithm SHA1PRNG, else the
* default constructor.
* @return
*/
public static SecureRandom getSecureRandom() {
SecureRandom sr = null;
try {
sr = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Misc.class.getName()).log(Level.SEVERE, null, ex);
sr = new SecureRandom();
}
return sr;
}
public static Set<PairInt> convertToCoords(GreyscaleImage img,
TIntSet pixIdxs) {
Set<PairInt> set = new HashSet<PairInt>();
TIntIterator iter = pixIdxs.iterator();
while (iter.hasNext()) {
int pixIdx = iter.next();
int col = img.getCol(pixIdx);
int row = img.getRow(pixIdx);
set.add(new PairInt(col, row));
}
return set;
}
public static void reverse(float[] a) {
int n = a.length;
if (n < 2) {
return;
}
int end = n >> 1;
// 0 1 2 3 4
for (int i = 0; i < end; i++) {
int idx2 = n - i - 1;
float swap = a[i];
a[i] = a[idx2];
a[idx2] = swap;
}
}
/**
* assuming that the coefficients are ordered from highest order to
* lowest, e.g. coeff[0] * x^2 + coeff[1] * x coeff[2],
* apply them to x and resturn the model.
* @param coeffs
* @param x
* @return
*/
public static float[] generate(float[] coeffs, float[] x) {
float[] y = new float[x.length];
int n0 = coeffs.length;
int n = n0 - 1;
float[] xsub = Arrays.copyOf(x, x.length);
for (int i = 0; i < n; ++i) {
float c = coeffs[n - i - 1];
for (int j = 0; j < x.length; ++j) {
float t = c * xsub[j];
y[j] += t;
xsub[j] *= x[j];
}
}
for (int j = 0; j < x.length; ++j) {
y[j] += coeffs[n];
}
return y;
}
/**
* assuming that the coefficients are ordered from highest order to
* lowest, e.g. coeff[0] * x^2 + coeff[1] * x coeff[2],
* apply them to x and resturn the model.
* @param coeffs
* @param x
* @return
*/
public static double[] generate(double[] coeffs, double[] x) {
double[] y = new double[x.length];
int n0 = coeffs.length;
int n = n0 - 1;
double[] xsub = Arrays.copyOf(x, x.length);
for (int i = 0; i < n; ++i) {
double c = coeffs[n - i - 1];
for (int j = 0; j < x.length; ++j) {
double t = c * xsub[j];
y[j] += t;
xsub[j] *= x[j];
}
}
for (int j = 0; j < x.length; ++j) {
y[j] += coeffs[n];
}
return y;
}
}
|
package de.lmu.ifi.dbs.linearalgebra;
import de.lmu.ifi.dbs.data.RationalNumber;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Vector;
@SuppressWarnings("serial")
public class Matrix implements Cloneable, java.io.Serializable
{
/**
* Array for internal storage of elements.
*
* @serial internal array storage.
*/
private double[][] A;
/**
* Row dimension.
*/
private int m;
/**
* Column dimension.
*/
private int n;
/**
* Construct an m-by-n matrix of zeros.
*
* @param m
* Number of rows.
* @param n
* Number of colums.
*/
public Matrix(int m, int n)
{
this.m = m;
this.n = n;
A = new double[m][n];
}
/**
* Construct an m-by-n constant matrix.
*
* @param m
* Number of rows.
* @param n
* Number of colums.
* @param s
* Fill the matrix with this scalar value.
*/
public Matrix(int m, int n, double s)
{
this.m = m;
this.n = n;
A = new double[m][n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = s;
}
}
}
public Matrix(double[][] A)
{
m = A.length;
n = A[0].length;
for(int i = 0; i < m; i++)
{
if(A[i].length != n)
{
throw new IllegalArgumentException("All rows must have the same length.");
}
}
this.A = A;
}
/**
* Constructs a Matrix for a given
* matrix of RationalNumber.
*
*
* @param q an array of arrays of RationalNumbers.
* q is not checked for consistency (i.e. whether all rows
* are of equal length)
*/
public Matrix(RationalNumber[][] q)
{
m = q.length;
n = q[0].length;
A = new double[m][n];
for(int row = 0; row < q.length; row++)
{
for(int col = 0; col < q[row].length; col++)
{
A[row][col] = q[row][col].doubleValue();
}
}
}
/**
* Construct a matrix quickly without checking arguments.
*
* @param A
* Two-dimensional array of doubles.
* @param m
* Number of rows.
* @param n
* Number of colums.
*/
public Matrix(double[][] A, int m, int n)
{
this.A = A;
this.m = m;
this.n = n;
}
public Matrix(double vals[], int m)
{
this.m = m;
n = (m != 0 ? vals.length / m : 0);
if(m * n != vals.length)
{
throw new IllegalArgumentException("Array length must be a multiple of m.");
}
A = new double[m][n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = vals[i + j * m];
}
}
}
public static Matrix constructWithCopy(double[][] A)
{
int m = A.length;
int n = A[0].length;
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
if(A[i].length != n)
{
throw new IllegalArgumentException("All rows must have the same length.");
}
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j];
}
}
return X;
}
/**
* Make a deep copy of a matrix
*/
public Matrix copy()
{
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
System.arraycopy(A[i], 0, C[i], 0, n);
}
return X;
}
/**
* Clone the Matrix object.
*/
public Object clone()
{
return this.copy();
}
/**
* Access the internal two-dimensional array.
*
* @return Pointer to the two-dimensional array of matrix elements.
*/
public double[][] getArray()
{
return A;
}
/**
* Copy the internal two-dimensional array.
*
* @return Two-dimensional array copy of matrix elements.
*/
public double[][] getArrayCopy()
{
double[][] C = new double[m][n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j];
}
}
return C;
}
/**
* Make a one-dimensional column packed copy of the internal array.
*
* @return Matrix elements packed in a one-dimensional array by columns.
*/
public double[] getColumnPackedCopy()
{
double[] vals = new double[m * n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
vals[i + j * m] = A[i][j];
}
}
return vals;
}
/**
* Make a one-dimensional row packed copy of the internal array.
*
* @return Matrix elements packed in a one-dimensional array by rows.
*/
public double[] getRowPackedCopy()
{
double[] vals = new double[m * n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
vals[i * n + j] = A[i][j];
}
}
return vals;
}
/**
* Get row dimension.
*
* @return m, the number of rows.
*/
public int getRowDimension()
{
return m;
}
/**
* Get column dimension.
*
* @return n, the number of columns.
*/
public int getColumnDimension()
{
return n;
}
/**
* Get a single element.
*
* @param i
* Row index.
* @param j
* Column index.
* @return A(i,j)
* @throws ArrayIndexOutOfBoundsException
*/
public double get(int i, int j)
{
return A[i][j];
}
/**
* Get a submatrix.
*
* @param i0
* Initial row index
* @param i1
* Final row index
* @param j0
* Initial column index
* @param j1
* Final column index
* @return A(i0:i1,j0:j1)
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public Matrix getMatrix(int i0, int i1, int j0, int j1)
{
Matrix X = new Matrix(i1 - i0 + 1, j1 - j0 + 1);
double[][] B = X.getArray();
try
{
for(int i = i0; i <= i1; i++)
{
for(int j = j0; j <= j1; j++)
{
B[i - i0][j - j0] = A[i][j];
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Get a submatrix.
*
* @param r
* Array of row indices.
* @param c
* Array of column indices.
* @return A(r(:),c(:))
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public Matrix getMatrix(int[] r, int[] c)
{
Matrix X = new Matrix(r.length, c.length);
double[][] B = X.getArray();
try
{
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < c.length; j++)
{
B[i][j] = A[r[i]][c[j]];
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Get a submatrix.
*
* @param i0
* Initial row index
* @param i1
* Final row index
* @param c
* Array of column indices.
* @return A(i0:i1,c(:))
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public Matrix getMatrix(int i0, int i1, int[] c)
{
Matrix X = new Matrix(i1 - i0 + 1, c.length);
double[][] B = X.getArray();
try
{
for(int i = i0; i <= i1; i++)
{
for(int j = 0; j < c.length; j++)
{
B[i - i0][j] = A[i][c[j]];
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Get a submatrix.
*
* @param r
* Array of row indices.
* @param j0
* Initial column index
* @param j1
* Final column index
* @return A(r(:),j0:j1)
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public Matrix getMatrix(int[] r, int j0, int j1)
{
Matrix X = new Matrix(r.length, j1 - j0 + 1);
double[][] B = X.getArray();
try
{
for(int i = 0; i < r.length; i++)
{
for(int j = j0; j <= j1; j++)
{
B[i][j - j0] = A[r[i]][j];
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Set a single element.
*
* @param i
* Row index.
* @param j
* Column index.
* @param s
* A(i,j).
* @throws ArrayIndexOutOfBoundsException
*/
public void set(int i, int j, double s)
{
A[i][j] = s;
}
/**
* Set a submatrix.
*
* @param i0
* Initial row index
* @param i1
* Final row index
* @param j0
* Initial column index
* @param j1
* Final column index
* @param X
* A(i0:i1,j0:j1)
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public void setMatrix(int i0, int i1, int j0, int j1, Matrix X)
{
try
{
for(int i = i0; i <= i1; i++)
{
for(int j = j0; j <= j1; j++)
{
A[i][j] = X.get(i - i0, j - j0);
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices: " + e);
}
}
/**
* Set a submatrix.
*
* @param r
* Array of row indices.
* @param c
* Array of column indices.
* @param X
* A(r(:),c(:))
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public void setMatrix(int[] r, int[] c, Matrix X)
{
try
{
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < c.length; j++)
{
A[r[i]][c[j]] = X.get(i, j);
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
}
/**
* Set a submatrix.
*
* @param r
* Array of row indices.
* @param j0
* Initial column index
* @param j1
* Final column index
* @param X
* A(r(:),j0:j1)
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public void setMatrix(int[] r, int j0, int j1, Matrix X)
{
try
{
for(int i = 0; i < r.length; i++)
{
for(int j = j0; j <= j1; j++)
{
A[r[i]][j] = X.get(i, j - j0);
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
}
/**
* Set a submatrix.
*
* @param i0
* Initial row index
* @param i1
* Final row index
* @param c
* Array of column indices.
* @param X
* A(i0:i1,c(:))
* @throws ArrayIndexOutOfBoundsException
* Submatrix indices
*/
public void setMatrix(int i0, int i1, int[] c, Matrix X)
{
try
{
for(int i = i0; i <= i1; i++)
{
for(int j = 0; j < c.length; j++)
{
A[i][c[j]] = X.get(i - i0, j);
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
}
/**
* Returns the <code>j</code>th column of this matrix.
*
* @param j the index of the column to be returned
* @return the <code>j</code>th column of this matrix
*/
public Matrix getColumn(int j)
{
return getMatrix(0, getRowDimension() - 1, j, j);
// double[][] col = new double[m][1];
// for (int i = 0; i < m; i++) {
// col[i][0] = A[i][j];
// return new Matrix(col);
}
/**
* Sets the <code>j</code>th column of this matrix to the specified column.
*
* @param j the index of the column to be set
* @param column the value of the column to be set
*/
public void setColumn(int j, Matrix column)
{
if(column.getColumnDimension() != 1)
throw new IllegalArgumentException("Matrix must consist of one column!");
if(column.getRowDimension() != getRowDimension())
throw new IllegalArgumentException("Matrix must consist of the same no of rows!");
setMatrix(0, getRowDimension() - 1, j, j, column);
}
/**
* Matrix transpose.
*
* @return A'
*/
public Matrix transpose()
{
Matrix X = new Matrix(n, m);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[j][i] = A[i][j];
}
}
return X;
}
/**
* One norm
*
* @return maximum column sum.
*/
public double norm1()
{
double f = 0;
for(int j = 0; j < n; j++)
{
double s = 0;
for(int i = 0; i < m; i++)
{
s += Math.abs(A[i][j]);
}
f = Math.max(f, s);
}
return f;
}
/**
* Two norm
*
* @return maximum singular value.
*/
public double norm2()
{
return (new SingularValueDecomposition(this).norm2());
}
/**
* Infinity norm
*
* @return maximum row sum.
*/
public double normInf()
{
double f = 0;
for(int i = 0; i < m; i++)
{
double s = 0;
for(int j = 0; j < n; j++)
{
s += Math.abs(A[i][j]);
}
f = Math.max(f, s);
}
return f;
}
/**
* Frobenius norm
*
* @return sqrt of sum of squares of all elements.
*/
public double normF()
{
double f = 0;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
f = Utils.hypot(f, A[i][j]);
}
}
return f;
}
/**
* Unary minus
*
* @return -A
*/
public Matrix uminus()
{
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = -A[i][j];
}
}
return X;
}
/**
* C = A + B
*
* @param B
* another matrix
* @return A + B
*/
public Matrix plus(Matrix B)
{
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j] + B.A[i][j];
}
}
return X;
}
/**
* A = A + B
*
* @param B
* another matrix
* @return A + B
*/
public Matrix plusEquals(Matrix B)
{
checkMatrixDimensions(B);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = A[i][j] + B.A[i][j];
}
}
return this;
}
/**
* C = A - B
*
* @param B
* another matrix
* @return A - B
*/
public Matrix minus(Matrix B)
{
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j] - B.A[i][j];
}
}
return X;
}
/**
* A = A - B
*
* @param B
* another matrix
* @return A - B
*/
public Matrix minusEquals(Matrix B)
{
checkMatrixDimensions(B);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = A[i][j] - B.A[i][j];
}
}
return this;
}
/**
* Element-by-element multiplication, C = A.*B
*
* @param B
* another matrix
* @return A.*B
*/
public Matrix arrayTimes(Matrix B)
{
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j] * B.A[i][j];
}
}
return X;
}
/**
* Element-by-element multiplication in place, A = A.*B
*
* @param B
* another matrix
* @return A.*B
*/
public Matrix arrayTimesEquals(Matrix B)
{
checkMatrixDimensions(B);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = A[i][j] * B.A[i][j];
}
}
return this;
}
/**
* Element-by-element right division, C = A./B
*
* @param B
* another matrix
* @return A./B
*/
public Matrix arrayRightDivide(Matrix B)
{
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j] / B.A[i][j];
}
}
return X;
}
/**
* Element-by-element right division in place, A = A./B
*
* @param B
* another matrix
* @return A./B
*/
public Matrix arrayRightDivideEquals(Matrix B)
{
checkMatrixDimensions(B);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = A[i][j] / B.A[i][j];
}
}
return this;
}
/**
* Element-by-element left division, C = A.\B
*
* @param B
* another matrix
* @return A.\B
*/
public Matrix arrayLeftDivide(Matrix B)
{
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = B.A[i][j] / A[i][j];
}
}
return X;
}
/**
* Element-by-element left division in place, A = A.\B
*
* @param B
* another matrix
* @return A.\B
*/
public Matrix arrayLeftDivideEquals(Matrix B)
{
checkMatrixDimensions(B);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = B.A[i][j] / A[i][j];
}
}
return this;
}
/**
* Multiply a matrix by a scalar, C = s*A
*
* @param s
* scalar
* @return s*A
*/
public Matrix times(double s)
{
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
C[i][j] = s * A[i][j];
}
}
return X;
}
/**
* Multiply a matrix by a scalar in place, A = s*A
*
* @param s
* scalar
* @return replace A by s*A
*/
public Matrix timesEquals(double s)
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = s * A[i][j];
}
}
return this;
}
public Matrix times(Matrix B)
{
if(B.m != n)
{
throw new IllegalArgumentException("Matrix inner dimensions must agree.");
}
Matrix X = new Matrix(m, B.n);
double[][] C = X.getArray();
double[] Bcolj = new double[n];
for(int j = 0; j < B.n; j++)
{
for(int k = 0; k < n; k++)
{
Bcolj[k] = B.A[k][j];
}
for(int i = 0; i < m; i++)
{
double[] Arowi = A[i];
double s = 0;
for(int k = 0; k < n; k++)
{
s += Arowi[k] * Bcolj[k];
}
C[i][j] = s;
}
}
return X;
}
/**
* LU Decomposition
*
* @return LUDecomposition
* @see LUDecomposition
*/
public LUDecomposition lu()
{
return new LUDecomposition(this);
}
/**
* QR Decomposition
*
* @return QRDecomposition
* @see QRDecomposition
*/
public QRDecomposition qr()
{
return new QRDecomposition(this);
}
/**
* Cholesky Decomposition
*
* @return CholeskyDecomposition
* @see CholeskyDecomposition
*/
public CholeskyDecomposition chol()
{
return new CholeskyDecomposition(this);
}
/**
* Singular Value Decomposition
*
* @return SingularValueDecomposition
* @see SingularValueDecomposition
*/
public SingularValueDecomposition svd()
{
return new SingularValueDecomposition(this);
}
/**
* Eigenvalue Decomposition
*
* @return EigenvalueDecomposition
* @see EigenvalueDecomposition
*/
public EigenvalueDecomposition eig()
{
return new EigenvalueDecomposition(this);
}
/**
* Solve A*X = B
*
* @param B
* right hand side
* @return solution if A is square, least squares solution otherwise
*/
public Matrix solve(Matrix B)
{
return (m == n ? (new LUDecomposition(this)).solve(B) : (new QRDecomposition(this)).solve(B));
}
/**
* Solve X*A = B, which is also A'*X' = B'
*
* @param B
* right hand side
* @return solution if A is square, least squares solution otherwise.
*/
public Matrix solveTranspose(Matrix B)
{
return transpose().solve(B.transpose());
}
/**
* Matrix inverse or pseudoinverse
*
* @return inverse(A) if A is square, pseudoinverse otherwise.
*/
public Matrix inverse()
{
return solve(identity(m, m));
}
/**
* Matrix determinant
*
* @return determinant
*/
public double det()
{
return new LUDecomposition(this).det();
}
/**
* Matrix rank
*
* @return effective numerical rank, obtained from SVD.
*/
public int rank()
{
return new SingularValueDecomposition(this).rank();
}
/**
* Matrix condition (2 norm)
*
* @return ratio of largest to smallest singular value.
*/
public double cond()
{
return new SingularValueDecomposition(this).cond();
}
/**
* Matrix trace.
*
* @return sum of the diagonal elements.
*/
public double trace()
{
double t = 0;
for(int i = 0; i < Math.min(m, n); i++)
{
t += A[i][i];
}
return t;
}
/**
* Generate matrix with random elements
*
* @param m
* Number of rows.
* @param n
* Number of colums.
* @return An m-by-n matrix with uniformly distributed random elements.
*/
public static Matrix random(int m, int n)
{
Matrix A = new Matrix(m, n);
double[][] X = A.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
X[i][j] = Math.random();
}
}
return A;
}
/**
* Generate identity matrix
*
* @param m
* Number of rows.
* @param n
* Number of colums.
* @return An m-by-n matrix with ones on the diagonal and zeros elsewhere.
*/
public static Matrix identity(int m, int n)
{
Matrix A = new Matrix(m, n);
double[][] X = A.getArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
X[i][j] = (i == j ? 1.0 : 0.0);
}
}
return A;
}
/**
* Print the matrix to stdout. Line the elements up in columns with a
* Fortran-like 'Fw.d' style format.
*
* @param w
* Column width.
* @param d
* Number of digits after the decimal.
*/
public void print(int w, int d)
{
print(new PrintWriter(System.out, true), w, d);
}
/**
* Print the matrix to the output stream. Line the elements up in columns
* with a Fortran-like 'Fw.d' style format.
*
* @param output
* Output stream.
* @param w
* Column width.
* @param d
* Number of digits after the decimal.
*/
public void print(PrintWriter output, int w, int d)
{
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
print(output, format, w + 2);
}
/**
* Print the matrix to stdout. Line the elements up in columns. Use the
* format object, and right justify within columns of width characters. Note
* that is the matrix is to be read back in, you probably will want to use a
* NumberFormat that is set to US Locale.
*
* @param format
* A Formatting object for individual elements.
* @param width
* Field width for each column.
* @see java.text.DecimalFormat#setDecimalFormatSymbols
*/
public void print(NumberFormat format, int width)
{
print(new PrintWriter(System.out, true), format, width);
}
// DecimalFormat is a little disappointing coming from Fortran or C's
// printf.
// Since it doesn't pad on the left, the elements will come out different
// widths. Consequently, we'll pass the desired column width in as an
// argument and do the extra padding ourselves.
/**
* Print the matrix to the output stream. Line the elements up in columns.
* Use the format object, and right justify within columns of width
* characters. Note that is the matrix is to be read back in, you probably
* will want to use a NumberFormat that is set to US Locale.
*
* @param output
* the output stream.
* @param format
* A formatting object to format the matrix elements
* @param width
* Column width.
* @see java.text.DecimalFormat#setDecimalFormatSymbols
*/
public void print(PrintWriter output, NumberFormat format, int width)
{
output.println(); // start on new line.
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
String s = format.format(A[i][j]); // format the number
int padding = Math.max(1, width - s.length()); // At _least_ 1
// space
for(int k = 0; k < padding; k++)
output.print(' ');
output.print(s);
}
output.println();
}
output.println(); // end with blank line.
}
/**
* Read a matrix from a stream. The format is the same the print method, so
* printed matrices can be read back in (provided they were printed using US
* Locale). Elements are separated by whitespace, all the elements for each
* row appear on a single line, the last row is followed by a blank line.
*
* @param input
* the input stream.
*/
public static Matrix read(BufferedReader input) throws java.io.IOException
{
StreamTokenizer tokenizer = new StreamTokenizer(input);
// Although StreamTokenizer will parse numbers, it doesn't recognize
// scientific notation (E or D); however, Double.valueOf does.
// The strategy here is to disable StreamTokenizer's number parsing.
// We'll only get whitespace delimited words, EOL's and EOF's.
// These words should all be numbers, for Double.valueOf to parse.
tokenizer.resetSyntax();
tokenizer.wordChars(0, 255);
tokenizer.whitespaceChars(0, ' ');
tokenizer.eolIsSignificant(true);
java.util.Vector<Double> v = new java.util.Vector<Double>();
// Ignore initial empty lines
while(tokenizer.nextToken() == StreamTokenizer.TT_EOL)
;
if(tokenizer.ttype == StreamTokenizer.TT_EOF)
throw new java.io.IOException("Unexpected EOF on matrix read.");
do
{
v.addElement(Double.valueOf(tokenizer.sval)); // Read & store 1st
// row.
}
while(tokenizer.nextToken() == StreamTokenizer.TT_WORD);
int n = v.size(); // Now we've got the number of columns!
double row[] = new double[n];
for(int j = 0; j < n; j++)
// extract the elements of the 1st row.
row[j] = v.elementAt(j);
// v.removeAllElements();
Vector<double[]> rowV = new Vector<double[]>();
rowV.addElement(row); // Start storing rows instead of columns.
while(tokenizer.nextToken() == StreamTokenizer.TT_WORD)
{
// While non-empty lines
rowV.addElement(row = new double[n]);
int j = 0;
do
{
if(j >= n)
throw new java.io.IOException("Row " + v.size() + " is too long.");
row[j++] = (Double.valueOf(tokenizer.sval));
}
while(tokenizer.nextToken() == StreamTokenizer.TT_WORD);
if(j < n)
throw new java.io.IOException("Row " + v.size() + " is too short.");
}
int m = rowV.size(); // Now we've got the number of rows.
double[][] A = new double[m][];
rowV.copyInto(A); // copy the rows out of the vector
return new Matrix(A);
}
/**
* Check if size(A) == size(B) *
*/
private void checkMatrixDimensions(Matrix B)
{
if(B.m != m || B.n != n)
{
throw new IllegalArgumentException("Matrix dimensions must agree.");
}
}
/**
* toString returns String-representation of Matrix.
*/
public String toString()
{
StringBuffer output = new StringBuffer();
output.append("[\n");
for(int i = 0; i < m; i++)
{
output.append(" [");
for(int j = 0; j < n; j++)
{
output.append(" ").append(A[i][j]);
if(j < n - 1)
{
output.append(",");
}
}
output.append(" ]\n");
}
output.append("]\n");
return (output.toString());
}
/**
* Returns a string representation of this matrix. In each line the
* specified String <code>pre<\code> is prefixed.
* @param pre the prefix of each line
* @return a string representation of this matrix
*/
private String toString(String pre)
{
StringBuffer output = new StringBuffer();
output.append(pre).append("[\n").append(pre);
for(int i = 0; i < m; i++)
{
output.append(" [");
for(int j = 0; j < n; j++)
{
output.append(" ").append(A[i][j]);
if(j < n - 1)
{
output.append(",");
}
}
output.append(" ]\n").append(pre);
}
output.append("]\n").append(pre);
return (output.toString());
}
/**
* toString returns String-representation of Matrix.
*/
public String toString(NumberFormat nf)
{
int[] colMax = new int[this.getColumnDimension()];
String[][] entries = new String[m][n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
entries[i][j] = nf.format(A[i][j]);
if(entries[i][j].length() > colMax[j])
{
colMax[j] = entries[i][j].length();
}
}
}
StringBuffer output = new StringBuffer();
output.append("[\n");
for(int i = 0; i < m; i++)
{
output.append(" [");
for(int j = 0; j < n; j++)
{
output.append(" ");
int space = colMax[j] - entries[i][j].length();
for(int s = 0; s < space; s++)
{
output.append(" ");
}
output.append(entries[i][j]);
if(j < n - 1)
{
output.append(",");
}
}
output.append(" ]\n");
}
output.append("]\n");
return (output.toString());
}
/**
* Returns a string representation of this matrix. In each line the
* specified String <code>pre<\code> is prefixed.
*
* @param nf number format for output accuracy
* @param pre the prefix of each line
*
* @return a string representation of this matrix
*/
public String toString(String pre, NumberFormat nf)
{
if(nf == null)
return toString(pre);
int[] colMax = new int[this.getColumnDimension()];
String[][] entries = new String[m][n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
entries[i][j] = nf.format(A[i][j]);
if(entries[i][j].length() > colMax[j])
{
colMax[j] = entries[i][j].length();
}
}
}
StringBuffer output = new StringBuffer();
output.append(pre).append("[\n").append(pre);
for(int i = 0; i < m; i++)
{
output.append(" [");
for(int j = 0; j < n; j++)
{
output.append(" ");
int space = colMax[j] - entries[i][j].length();
for(int s = 0; s < space; s++)
{
output.append(" ");
}
output.append(entries[i][j]);
if(j < n - 1)
{
output.append(",");
}
}
output.append(" ]\n").append(pre);
}
output.append("]\n").append(pre);
return (output.toString());
}
/**
* getDiagonal returns array of diagonal-elements.
*
* @return double[] the values on the diagonaly of the Matrix
*/
public double[] getDiagonal()
{
double[] diagonal = new double[m];
for(int i = 0; i < m; i++)
{
diagonal[i] = A[i][i];
}
return diagonal;
}
/**
* normalizeCols scales columns up to normFactor of norm.
*
* @param normFactor
* factor to scale each column (take 1.0 for normalizing each
* column to length of 1.0)
*/
public void normalizeCols(double normFactor)
{
for(int col = 0; col < n; col++)
{
scaleCol(col, normFactor);
}
}
/**
* normalizeCols normalizes columns to length of 1,0.
*/
public void normalizeCols()
{
for(int col = 0; col < n; col++)
{
double norm = 0.0;
for(int row = 0; row < m; row++)
{
norm = norm + (A[row][col] * A[row][col]);
}
norm = Math.sqrt(norm);
for(int row = 0; row < m; row++)
{
A[row][col] = (A[row][col] / norm);
}
}
}
/**
* scaleCol scales given column up to normFactor.
*
* @param col
* column to be scaled
* @param normFactor
* factor to scale column
*/
public void scaleCol(int col, double normFactor)
{
for(int row = 0; row < m; row++)
{
A[row][col] = (A[row][col] * normFactor);
}
}
/**
* distanceCov returns distance of two Matrices A and B, i.e. the root of
* the sum of the squared distances A<sub>ij</sub>-B<sub>ij</sub>.
*
* @param B
* Matrix to compute distance from this (A)
* @return distance of Matrices
*/
public double distanceCov(Matrix B)
{
double distance = 0.0;
double[][] arrayB = B.getArray();
for(int col = 0; col < n; col++)
{
for(int row = 0; row < m; row++)
{
double distIJ = A[row][col] - arrayB[row][col];
distance += (distIJ * distIJ);
}
}
distance = Math.sqrt(distance);
return distance;
}
/**
* Returns the angle of the colA col of this and the colB col of B.
*
* @param colA
* the column of A to compute angle for
* @param B
* second Matrix
* @param colB
* the column of B to compute angle for
* @return double angle of the first cols of this and B
*/
public double angle(int colA, Matrix B, int colB)
{
return Math.acos(this.scalarProduct(colA, B, colB) / (this.euclideanNorm(colA) * B.euclideanNorm(colB)));
}
/**
* Returns the scalar product of the colA cols of this and the colB col of
* B.
*
* @param colA
* The column of A to compute scalar product for
* @param B
* second Matrix
* @param colB
* The column of B to compute scalar product for
* @return double The scalar product of the first cols of this and B
*/
public double scalarProduct(int colA, Matrix B, int colB)
{
double scalarProduct = 0.0;
double[][] arrayB = B.getArray();
for(int row = 0; row < m; row++)
{
double prod = A[row][colA] * arrayB[row][colB];
scalarProduct += prod;
}
return scalarProduct;
}
/**
* Returns the euclidean norm of the col column.
*
* @param col
* The column to compute euclidean norm of
* @return double
*/
public double euclideanNorm(int col)
{
return Math.sqrt(this.scalarProduct(col, this, col));
}
/**
* Returns a quadratic Matrix consisting of zeros and of the given values on
* the diagonal.
*
* @param diagonal
* @return Matrix
*/
public static Matrix diagonal(double[] diagonal)
{
Matrix result = Matrix.identity(diagonal.length, diagonal.length);
for(int i = 0; i < diagonal.length; i++)
{
result.set(i, i, diagonal[i]);
}
return result;
}
/**
* Returns a matrix derived by Gauss-Jordan-elimination
* using RationalNumbers for the transformations.
*
*
* @return a matrix derived by Gauss-Jordan-elimination
* using RationalNumbers for the transformations
*/
public Matrix exactGaussJordanElimination()
{
RationalNumber[][] gauss = exactGaussElimination();
// reduced form
for(int row = gauss.length - 1; row > 0; row
{
int firstCol = -1;
for(int col = 0; col < gauss[row].length && firstCol == -1; col++)
{
// if(gauss.get(row, col) != 0.0) // i.e. == 1
if(gauss[row][col].equals(RationalNumber.ONE))
{
firstCol = col;
}
}
if(firstCol > -1)
{
for(int currentRow = row - 1; currentRow >= 0; currentRow
{
RationalNumber multiplier = gauss[currentRow][firstCol].copy();
for(int col = firstCol; col < gauss[currentRow].length; col++)
{
RationalNumber subtrahent = gauss[row][col].times(multiplier);
gauss[currentRow][col] = gauss[currentRow][col].minus(subtrahent);
}
}
}
}
return new Matrix(gauss);
}
/**
* Returns a matrix derived by Gauss-Jordan-elimination.
*
* @return a new Matrix that is the result of Gauss-Jordan-elimination
*/
public Matrix gaussJordanElimination()
{
Matrix gauss = this.gaussElimination();
// reduced form
for(int row = gauss.getRowDimension() - 1; row > 0; row
{
int firstCol = -1;
for(int col = 0; col < gauss.getColumnDimension() && firstCol == -1; col++)
{
// if(gauss.get(row, col) != 0.0) // i.e. == 1
if(gauss.get(row, col) < DELTA * -1 || gauss.get(row, col) > DELTA)
{
firstCol = col;
}
}
if(firstCol > -1)
{
for(int currentRow = row - 1; currentRow >= 0; currentRow
{
double multiplier = gauss.get(currentRow, firstCol);
for(int col = firstCol; col < gauss.getColumnDimension(); col++)
{
gauss.set(currentRow, col, gauss.get(currentRow, col) - gauss.get(row, col) * multiplier);
}
}
}
}
return gauss;
}
/**
* Performes an exact Gauss-elimination
* of this Matrix using
* RationalNumbers to yield highest possible
* accuracy.
*
*
* @return an array of arrays of RationalNumbers
* representing the Gauss-eliminated form
* of this Matrix
*/
public RationalNumber[][] exactGaussElimination()
{
RationalNumber[][] gauss = new RationalNumber[this.getRowDimension()][this.getColumnDimension()];
for(int row = 0; row < this.getRowDimension(); row++)
{
for(int col = 0; col < this.getColumnDimension(); col++)
{
gauss[row][col] = new RationalNumber(this.get(row, col));
}
}
return exactGaussElimination(gauss);
}
/**
* Performes recursivly Gauss-elimination
* on the given matrix of RationalNumbers.
*
*
* @param gauss an array of arrays of RationalNumber
* @return recursivly derived Gauss-elimination-form
* of the given matrix of RationalNumbers
*/
public static RationalNumber[][] exactGaussElimination(RationalNumber[][] gauss)
{
int firstCol = -1;
int firstRow = -1;
// 1. find first column unequal to zero
for(int col = 0; col < gauss[0].length && firstCol == -1; col++)
{
for(int row = 0; row < gauss.length && firstCol == -1; row++)
{
// if(gauss.get(row, col) != 0.0)
if(!gauss[row][col].equals(RationalNumber.ZERO))
{
firstCol = col;
firstRow = row;
}
}
}
// 2. set row as first row
if(firstCol != -1)
{
if(firstRow != 0)
{
RationalNumber[] row = new RationalNumber[gauss[firstRow].length];
System.arraycopy(gauss[firstRow],0,row,0,gauss[firstRow].length);
System.arraycopy(gauss[0],0,gauss[firstRow],0,gauss[firstRow].length);
System.arraycopy(row,0,gauss[0],0,row.length);
}
// 3. create leading 1
if(!gauss[0][firstCol].equals(RationalNumber.ONE))
{
RationalNumber inverse = gauss[0][firstCol].multiplicativeInverse();
for(int col = 0; col < gauss[0].length; col++)
{
gauss[0][col] = gauss[0][col].times(inverse);
}
}
// 4. eliminate values unequal to zero below leading 1
for(int row = 1; row < gauss.length; row++)
{
RationalNumber multiplier = gauss[row][firstCol].copy();
// if(multiplier != 0.0)
if(!multiplier.equals(RationalNumber.ZERO))
{
for(int col = firstCol; col < gauss[row].length; col++)
{
RationalNumber subtrahent = gauss[0][col].times(multiplier);
gauss[row][col] = gauss[row][col].minus(subtrahent);
}
}
}
// 5. recursion
if(gauss.length > 1)
{
RationalNumber[][] subMatrix = new RationalNumber[gauss.length-1][gauss[1].length];
System.arraycopy(gauss,1,subMatrix,0,gauss.length-1);
RationalNumber[][] eliminatedSubMatrix = exactGaussElimination(subMatrix);
System.arraycopy(eliminatedSubMatrix,0,gauss,1,eliminatedSubMatrix.length);
}
}
return gauss;
}
/**
* Recursive gauss-elimination (non-reduced form).
*
* @return a new Matrix that is the result of Gauss-elimination
*/
public Matrix gaussElimination()
{
Matrix gauss = this.copy();
int firstCol = -1;
int firstRow = -1;
// 1. find first column unequal to zero
for(int col = 0; col < gauss.getColumnDimension() && firstCol == -1; col++)
{
for(int row = 0; row < gauss.getRowDimension() && firstCol == -1; row++)
{
// if(gauss.get(row, col) != 0.0)
if(gauss.get(row, col) < DELTA * -1 || gauss.get(row, col) > DELTA)
{
firstCol = col;
firstRow = row;
}
}
}
// 2. set row as first row
if(firstCol != -1)
{
if(firstRow != 0)
{
Matrix row = gauss.getMatrix(firstRow, firstRow, 0, gauss.getColumnDimension() - 1);
gauss.setMatrix(firstRow, firstRow, 0, gauss.getColumnDimension() - 1, gauss.getMatrix(0, 0, 0, gauss.getColumnDimension() - 1));
gauss.setMatrix(0, 0, 0, gauss.getColumnDimension() - 1, row);
}
// 3. create leading 1
double a = gauss.get(0, firstCol);
if(a != 1)
{
for(int col = 0; col < gauss.getColumnDimension(); col++)
{
gauss.set(0, col, gauss.get(0, col) / a);
}
}
// 4. eliminate values unequal to zero below leading 1
for(int row = 1; row < gauss.getRowDimension(); row++)
{
double multiplier = gauss.get(row, firstCol);
// if(multiplier != 0.0)
if(multiplier < DELTA * -1 || multiplier > DELTA)
{
for(int col = firstCol; col < gauss.getColumnDimension(); col++)
{
gauss.set(row, col, gauss.get(row, col) - gauss.get(0, col) * multiplier);
}
}
}
// 5. recursion
if(gauss.getRowDimension() > 1)
{
Matrix subMatrix = gauss.getMatrix(1, gauss.getRowDimension() - 1, 0, gauss.getColumnDimension() - 1);
gauss.setMatrix(1, gauss.getRowDimension() - 1, 0, gauss.getColumnDimension() - 1, subMatrix.gaussElimination());
}
}
return gauss;
}
/**
* A small number to handle numbers near 0 as 0.
*/
public static final double DELTA = 1E-8;
/**
* Tests Gauss Jordan elimination.
*
*
* @param args
*/
public static void main(String[] args)
{
double[][] m = {
{0,0,-2,0,7,12},
{2,4,-10,6,12,28},
{2,4,-5,6,-5,-1}
};
Matrix matrix = new Matrix(m);
System.out.println(matrix);
long start1 = System.nanoTime();
Matrix doubleComputation = matrix.copy().gaussJordanElimination();
long end1 = System.nanoTime();
long time1 = end1-start1;
long start2 = System.nanoTime();
Matrix exactComputation = matrix.exactGaussJordanElimination();
long end2 = System.nanoTime();
long time2 = end2-start2;
NumberFormat timeformat = NumberFormat.getInstance(Locale.US);
timeformat.setGroupingUsed(false);
timeformat.setMinimumIntegerDigits(time1<time2 ? Long.toString(time2).length() : Long.toString(time1).length());
System.out.println("Nano seconds required for double computation: "+timeformat.format(time1));
System.out.println("Nano seconds required for exact computation: "+timeformat.format(time2));
System.out.println("double result:");
System.out.println(doubleComputation);
System.out.println("exact result:");
System.out.println(exactComputation);
}
}
|
package de.wolfi.minopoly.components;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.metadata.FixedMetadataValue;
import de.wolfi.minopoly.Main;
import de.wolfi.minopoly.components.fields.Field;
import de.wolfi.minopoly.events.MoneyEvent;
import de.wolfi.minopoly.utils.Dangerous;
import de.wolfi.minopoly.utils.DisguiseManager;
import de.wolfi.minopoly.utils.FigureType;
import de.wolfi.minopoly.utils.MapFactory;
import de.wolfi.minopoly.utils.Messages;
import de.wolfi.minopoly.utils.TeleportCause;
import de.wolfi.utils.TimedEntity;
public class Player {
protected final @Dangerous Minopoly game;
private final org.bukkit.entity.Player hook;
private Field location;
private final Bank money;
private TimedEntity tmp;
private FigureType type;
public Player(org.bukkit.entity.Player hook, FigureType t, Minopoly game, Bank bank) {
this.hook = hook;
this.type = t;
this.game = game;
this.money = bank;
}
public void addMoney(int amount) {
this.addMoney(amount, "Grundlos");
}
public void addMoney(int amount, String reason) {
this.money.addMoney(this, amount);
Bukkit.getPluginManager().callEvent(new MoneyEvent(this, this.getMoney(), reason));
Messages.MONEY_GAIN.send(this.hook, String.valueOf(amount), reason);
}
public int getMoney(){
return this.money.getMoney(this);
}
@Override
public int hashCode() {
return this.getFigure().hashCode();
}
@Override
public boolean equals(Object compare) {
if (!(compare instanceof Player))
return false;
return this.getFigure() == ((Player) compare).getFigure();
}
public String getDisplay() {
return this.getName() + "(" + this.getFigure().getDisplay() + ")";
}
public FigureType getFigure() {
return this.type;
}
@Dangerous(y = "Internal use ONLY!")
public org.bukkit.entity.Player getHook() {
return this.hook;
}
public String getName() {
return this.hook.getName();
}
public void move(int amount) {
Messages.MOVE_STARTED.broadcast(this.getDisplay(), Integer.toString(amount));
Bukkit.getScheduler().runTaskAsynchronously(Main.getMain(), () -> {
for (int i = 0; i < amount; i++) {
final int currentNumber = i;
Bukkit.getScheduler().runTask(Main.getMain(), () -> {
Player.this.location = Player.this.game.getFieldManager().getNextField(Player.this.location);
if (currentNumber < amount - 1)
Player.this.location.byPass(Player.this);
Player.this.spawnFigure();
});
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
Messages.MOVE_FINISHED.broadcast(Player.this.getDisplay());
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
Player.this.location.playerStand(Player.this);
});
}
public void removeMoney(int amount, String reason) {
this.money.removeMoney(this, amount);
Bukkit.getPluginManager().callEvent(new MoneyEvent(this, this.getMoney(), reason));
Messages.MONEY_PAYD.send(this.hook, String.valueOf(amount), reason);
}
public void setInventory() {
this.hook.getInventory().clear();
this.hook.sendMap(MapFactory.getMap(this.game, this.hook));
}
private void spawnFigure() {
if (this.tmp != null)
this.tmp.remove();
// final Entity e = this.location.getWorld().spawnEntity(this.location.getTeleportLocation(), this.type.getEntityType());
// e.setCustomName(this.hook.getName());
// e.setCustomNameVisible(true);
// e.setMetadata("PlayerNPC", new FixedMetadataValue(Main.getMain(), this));
TimedEntity t = new TimedEntity(this.type.getEntityType(), this.location.getTeleportLocation(), 0)
.name(this.hook.getName())
.nbt("NoAI", 1)
.metadata("PlayerNPC", new FixedMetadataValue(Main.getMain(), this));
// if (e instanceof LivingEntity)
// ((LivingEntity) e).addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 60 * 60, 20));
this.tmp = t;
}
public Field getLocation() {
return location;
}
public void teleport(Field to){
this.location = to;
this.spawnFigure();
}
public void teleport(Location to, TeleportCause cause) {
this.hook.teleport(to);
if (cause == TeleportCause.MINIGAME_STARTED) {
DisguiseManager.disguise(this.hook, this.type);
if (this.tmp != null)
this.tmp.remove();
} else if (cause == TeleportCause.MINIGAME_END) {
this.setInventory();
DisguiseManager.vanish(this.hook);
this.spawnFigure();
} else if (cause == TeleportCause.MINIGAME_ACTION)
Messages.TELEPORT.send(this.hook);
}
private void transferMoneyFrom(Player player, int amount, String reason) {
player.addMoney( amount,reason);
Messages.MONEY_TRANSFER_GAIN.send(this.hook, String.valueOf(amount), player.getDisplay(), reason);
}
public void transferMoneyTo(Player player, int amount, String reason) {
this.removeMoney(amount,reason);
Messages.MONEY_TRANSFER_SENT.send(this.hook, String.valueOf(amount), player.getDisplay(), reason);
player.transferMoneyFrom(this, amount, reason);
}
public boolean isDummy() {
return this instanceof DummyPlayer;
}
protected void update(SerializeablePlayer s){
this.type = s.getF();
this.location = s.getLoc();
this.money.checkOut(this);
this.money.checkIn(this, s.getBankCard());
}
protected SerializeablePlayer serialize() {
return new SerializeablePlayer(this.game, this.location, this.type, this.money.getConsumerID(this));
}
}
|
package dr.app.beauti.treespanel;
import dr.app.beauti.components.SequenceErrorModelComponentOptions;
import dr.app.beauti.*;
import dr.app.beauti.options.*;
import dr.app.tools.TemporalRooting;
import dr.evolution.alignment.Patterns;
import dr.evolution.datatype.DataType;
import dr.evolution.distance.DistanceMatrix;
import dr.evolution.distance.F84DistanceMatrix;
import dr.evolution.tree.NeighborJoiningTree;
import dr.evolution.tree.Tree;
import dr.evolution.tree.UPGMATree;
import org.virion.jam.framework.Exportable;
import org.virion.jam.panels.ActionPanel;
import org.virion.jam.table.HeaderRenderer;
import org.virion.jam.table.TableEditorStopper;
import org.virion.jam.table.TableRenderer;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.*;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author Andrew Rambaut
* @author Walter Xie
* @version $Id:$
*/
public class TreesPanel extends BeautiPanel implements Exportable {
public final static boolean DEBUG = false;
private static final long serialVersionUID = 2778103564318492601L;
// private JComboBox userTreeCombo = new JComboBox();
// private JButton button;
// private CreateTreeAction createTreeAction = new CreateTreeAction();
private TreeDisplayPanel treeDisplayPanel;
private BeautiFrame frame = null;
private BeautiOptions options = null;
private JScrollPane scrollPane = new JScrollPane();
private JTable treesTable = null;
private TreesTableModel treesTableModel = null;
private GenerateTreeDialog generateTreeDialog = null;
private boolean settingOptions = false;
// boolean hasAlignment = false;
public JCheckBox shareSameTreePriorCheck = new JCheckBox("Share the same tree prior");
JPanel treeModelPanelParent;
// private OptionsPanel currentTreeModel = new OptionsPanel();
PartitionTreeModel currentTreeModel = null;
TitledBorder treeModelBorder;
Map<PartitionTreeModel, PartitionTreeModelPanel> treeModelPanels = new HashMap<PartitionTreeModel, PartitionTreeModelPanel>();
// private OptionsPanel treePriorPanel = new OptionsPanel();
JPanel treePriorPanelParent;
PartitionTreePrior currentTreePrior = null;
TitledBorder treePriorBorder;
Map<PartitionTreePrior, PartitionTreePriorPanel> treePriorPanels = new HashMap<PartitionTreePrior, PartitionTreePriorPanel>();
// Overall model parameters ////////////////////////////////////////////////////////////////////////
private boolean isCheckedTipDate = false;
SequenceErrorModelComponentOptions comp;
public TreesPanel(BeautiFrame parent, Action removeTreeAction) {
super();
this.frame = parent;
treesTableModel = new TreesTableModel();
treesTable = new JTable(treesTableModel);
treesTable.getTableHeader().setReorderingAllowed(false);
treesTable.getTableHeader().setResizingAllowed(false);
treesTable.getTableHeader().setDefaultRenderer(
new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
final TableColumnModel model = treesTable.getColumnModel();
final TableColumn tableColumn0 = model.getColumn(0);
tableColumn0.setCellRenderer(new ModelsTableCellRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(treesTable);
treesTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
treesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
selectionChanged();
}
});
scrollPane = new JScrollPane(treesTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setOpaque(false);
// ActionPanel actionPanel1 = new ActionPanel(false);
// actionPanel1.setAddAction(addTreeAction);
// actionPanel1.setRemoveAction(removeTreeAction);
JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
controlPanel1.setOpaque(false);
// controlPanel1.add(actionPanel1);
setCurrentModelAndPrior(null);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
panel1.add(scrollPane, BorderLayout.CENTER);
panel1.add(controlPanel1, BorderLayout.SOUTH);
JPanel panel2 = new JPanel(new BorderLayout(0, 0));
panel2.setOpaque(false);
treeModelPanelParent = new JPanel(new FlowLayout(FlowLayout.LEFT));
treeModelPanelParent.setOpaque(false);
treeModelBorder = new TitledBorder("Tree Model");
treeModelPanelParent.setBorder(treeModelBorder);
// currentTreeModel.setBorder(null);
panel2.add(treeModelPanelParent, BorderLayout.NORTH);
treeDisplayPanel = new TreeDisplayPanel(parent);
panel2.add(treeDisplayPanel, BorderLayout.CENTER);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
splitPane.setDividerLocation(180);
splitPane.setContinuousLayout(true);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setOpaque(false);
treePriorPanelParent = new JPanel(new FlowLayout(FlowLayout.LEFT));
treePriorPanelParent.setOpaque(false);
treePriorBorder = new TitledBorder("Tree Prior");
treePriorPanelParent.setBorder(treePriorBorder);
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel3.setOpaque(false);
shareSameTreePriorCheck.setEnabled(true);
shareSameTreePriorCheck.setSelected(true);
shareSameTreePriorCheck.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
updateShareSameTreePriorChanged ();
}
});
panel3.add(shareSameTreePriorCheck);
setOpaque(false);
setLayout(new BorderLayout(0, 0));
setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
add(splitPane, BorderLayout.NORTH);
add(treePriorPanelParent, BorderLayout.CENTER);
add(panel3, BorderLayout.SOUTH);
comp = new SequenceErrorModelComponentOptions ();
}
public void updateShareSameTreePriorChanged () {
options.shareSameTreePrior = shareSameTreePriorCheck.isSelected();
fireShareSameTreePriorChanged ();
}
private void fireShareSameTreePriorChanged () {
shareSameTreePriorCheck.setSelected(options.shareSameTreePrior);
if (options.shareSameTreePrior) {
options.activedSameTreePrior = currentTreePrior;
// keep previous prior for reuse
} else {
// reuse previous prior
setCurrentModelAndPrior(currentTreeModel);
}
updateTreePriorBorder();
}
private void updateTreePriorBorder() {
if (options.shareSameTreePrior) {
treePriorBorder.setTitle("Tree prior shared by all tree models");
} else {
treePriorBorder.setTitle("Tree Prior - " + currentTreePrior.getName());
}
repaint();
}
private void fireTreePriorsChanged() {
options.updatePartitionClockTreeLinks();
frame.setDirty();
}
// public void removeSelection() {
// int selRow = treesTable.getSelectedRow();
// if (!isUsed(selRow)) {
// PartitionTreeModel model = options.getPartitionTreeModels().get(selRow);
// options.getPartitionTreeModels().remove(model);
// treesTableModel.fireTableDataChanged();
// int n = options.getPartitionTreeModels().size();
// if (selRow >= n) {
// selRow--;
// treesTable.getSelectionModel().setSelectionInterval(selRow, selRow);
// if (n == 0) {
// setCurrentModelAndPrior(null);
// fireTreePriorsChanged();
private void selectionChanged() {
int selRow = treesTable.getSelectedRow();
if (selRow >= 0) {
PartitionTreeModel ptm = options.getPartitionTreeModels().get(selRow);
setCurrentModelAndPrior(ptm);
//TODO treeDisplayPanel.setTree(options.userTrees.get(selRow));
frame.modelSelectionChanged(!isUsed(selRow));
} else {
setCurrentModelAndPrior(null);
treeDisplayPanel.setTree(null);
}
}
// private void createTree() {
// if (generateTreeDialog == null) {
// generateTreeDialog = new GenerateTreeDialog(frame);
// int result = generateTreeDialog.showDialog(options);
// if (result != JOptionPane.CANCEL_OPTION) {
// GenerateTreeDialog.MethodTypes methodType = generateTreeDialog.getMethodType();
// PartitionData partition = generateTreeDialog.getDataPartition();
// Patterns patterns = new Patterns(partition.getAlignment());
// DistanceMatrix distances = new F84DistanceMatrix(patterns);
// Tree tree;
// TemporalRooting temporalRooting;
// switch (methodType) {
// case NJ:
// tree = new NeighborJoiningTree(distances);
// temporalRooting = new TemporalRooting(tree);
// tree = temporalRooting.findRoot(tree);
// break;
// case UPGMA:
// tree = new UPGMATree(distances);
// temporalRooting = new TemporalRooting(tree);
// break;
// default:
// tree.setId(generateTreeDialog.getName());
// options.userTrees.add(tree);
// treesTableModel.fireTableDataChanged();
// int row = options.userTrees.size() - 1;
// treesTable.getSelectionModel().setSelectionInterval(row, row);
// fireTreePriorsChanged();
/**
* Sets the current model that this model panel is displaying
*
* @param model the new model to display
*/
private void setCurrentModelAndPrior(PartitionTreeModel model) {
if (model != null) {
if (currentTreeModel != null) treeModelPanelParent.removeAll();
PartitionTreeModelPanel panel = treeModelPanels.get(model);
if (panel == null) {
panel = new PartitionTreeModelPanel(model, options);
treeModelPanels.put(model, panel);
}
currentTreeModel = model;
treeModelBorder.setTitle("Tree Model - " + model.getName());
treeModelPanelParent.add(panel);
PartitionTreePrior prior;
if (currentTreePrior != null) treePriorPanelParent.removeAll();
if (options.shareSameTreePrior) {
prior = options.activedSameTreePrior;
} else {
prior = model.getPartitionTreePrior();
}
PartitionTreePriorPanel panel1 = treePriorPanels.get(prior);
if (panel1 == null) {
panel1 = new PartitionTreePriorPanel(prior, this);
treePriorPanels.put(prior, panel1);
}
currentTreePrior = prior;
updateTreePriorBorder();
treePriorPanelParent.add(panel1);
repaint();
} else {
//TODO
}
}
// private void setCurrentPrior(PartitionTreePrior prior) {
// if (prior != null) {
// if (currentTreePrior != null) treePriorPanelParent.removeAll();
// PartitionTreePriorPanel panel = treePriorPanels.get(prior);
// if (panel == null) {
// panel = new PartitionTreePriorPanel(prior);
// treePriorPanels.put(prior, panel);
// currentTreePrior = prior;
// treePriorBorder.setTitle("Tree Prior - " + prior.getName());
// treePriorPanelParent.add(panel);
// repaint();
public void setCheckedTipDate(boolean isCheckedTipDate) {
this.isCheckedTipDate = isCheckedTipDate;
}
public BeautiOptions getOptions() {
return options;
}
public void setOptions(BeautiOptions options) {
this.options = options;
settingOptions = true;
// PartitionTreeModelPanel tmp = treeModelPanels.get(currentTreeModel);
// if (tmp != null) {
// tmp.setOptions();
// PartitionTreePriorPanel tpp = treePriorPanels.get(currentTreePrior);
// if (tpp != null) {
// tpp.setOptions();
// if (isCheckedTipDate) {
// tpp.removeCertainPriorFromTreePriorCombo();
// } else {
// tpp.recoveryTreePriorCombo();
Set<PartitionTreeModel> models = treeModelPanels.keySet();
for (PartitionTreeModel model : models) {
if (model != null) {
treeModelPanels.get(model).setOptions();
}
}
if (options.shareSameTreePrior) {
PartitionTreePriorPanel ptpp = treePriorPanels.get(options.activedSameTreePrior);
if (ptpp != null) {
ptpp.setOptions();
if (isCheckedTipDate) {
ptpp.removeCertainPriorFromTreePriorCombo();
} else {
ptpp.recoveryTreePriorCombo();
}
}
} else {
for (PartitionTreeModel model : models) {
PartitionTreePriorPanel ptpp = treePriorPanels.get(model.getPartitionTreePrior());
if (ptpp != null) {
ptpp.setOptions();
if (isCheckedTipDate) {
ptpp.removeCertainPriorFromTreePriorCombo();
} else {
ptpp.recoveryTreePriorCombo();
}
}
}
}
settingOptions = false;
int selRow = treesTable.getSelectedRow();
treesTableModel.fireTableDataChanged();
if (options.getPartitionTreeModels().size() > 0) {
if (selRow < 0) {
selRow = 0;
}
treesTable.getSelectionModel().setSelectionInterval(selRow, selRow);
}
if (currentTreeModel == null && options.getPartitionTreeModels().size() > 0) {
treesTable.getSelectionModel().setSelectionInterval(0, 0);
}
fireShareSameTreePriorChanged();
validate();
repaint();
}
public void getOptions(BeautiOptions options) {
if (settingOptions) return;
Set<PartitionTreeModel> models = treeModelPanels.keySet();
for (PartitionTreeModel model : models) {
treeModelPanels.get(model).getOptions(options);
}
if (options.shareSameTreePrior) {
PartitionTreePriorPanel ptpp = treePriorPanels.get(options.activedSameTreePrior);
if (ptpp != null) {
ptpp.getOptions();
}
} else {
for (PartitionTreeModel model : models) {
PartitionTreePriorPanel ptpp = treePriorPanels.get(model.getPartitionTreePrior());
if (ptpp != null) {
ptpp.getOptions();
}
}
}
}
public JComponent getExportableComponent() {
return treeDisplayPanel;
}
private boolean isUsed(int row) {
PartitionTreeModel model = options.getPartitionTreeModels().get(row);
for (PartitionData partition : options.dataPartitions) {
if (partition.getPartitionTreeModel() == model) {
return true;
}
}
return false;
}
class TreesTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Tree(s)"};
public TreesTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
return options.getPartitionTreeModels().size();
}
public Object getValueAt(int row, int col) {
PartitionTreeModel model = options.getPartitionTreeModels().get(row);
switch (col) {
case 0:
return model.getName();
default:
throw new IllegalArgumentException("unknown column, " + col);
}
}
public void setValueAt(Object aValue, int row, int col) {
// Tree tree = options.userTrees.get(row);
switch (col) {
case 0:
String name = ((String) aValue).trim();
if (name.length() > 0) {
PartitionTreeModel model = options.getPartitionTreeModels().get(row);
model.setName(name);
// keep tree prior name same as tree model name
PartitionTreePrior prior = model.getPartitionTreePrior();
prior.setName(name);
fireTreePriorsChanged();
}
break;
default:
throw new IllegalArgumentException("unknown column, " + col);
}
}
public boolean isCellEditable(int row, int col) {
boolean editable;
switch (col) {
case 0:// name
editable = true;
break;
default:
editable = false;
}
return editable;
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
if (getRowCount() == 0) {
return Object.class;
}
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
class ModelsTableCellRenderer extends TableRenderer {
public ModelsTableCellRenderer(int alignment, Insets insets) {
super(alignment, insets);
}
public Component getTableCellRendererComponent(JTable aTable,
Object value,
boolean aIsSelected,
boolean aHasFocus,
int aRow, int aColumn) {
if (value == null) return this;
Component renderer = super.getTableCellRendererComponent(aTable,
value,
aIsSelected,
aHasFocus,
aRow, aColumn);
if (!isUsed(aRow))
renderer.setForeground(Color.gray);
else
renderer.setForeground(Color.black);
return this;
}
}
// Action addTreeAction = new AbstractAction("+") {
// public void actionPerformed(ActionEvent ae) {
// createTree();
// public class CreateTreeAction extends AbstractAction {
// public CreateTreeAction() {
// super("Create Tree");
// setToolTipText("Create a NJ or UPGMA tree using a data partition");
// public void actionPerformed(ActionEvent ae) {
// createTree();
}
|
package edu.iu.grid.oim.servlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.lib.AuthorizationException;
import edu.iu.grid.oim.lib.StaticConfig;
import edu.iu.grid.oim.lib.StringArray;
import edu.iu.grid.oim.model.CertificateRequestStatus;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.db.CertificateRequestModelBase;
import edu.iu.grid.oim.model.db.CertificateRequestUserModel;
import edu.iu.grid.oim.model.db.ConfigModel;
import edu.iu.grid.oim.model.db.CertificateRequestHostModel;
import edu.iu.grid.oim.model.db.ContactModel;
import edu.iu.grid.oim.model.db.GridAdminModel;
import edu.iu.grid.oim.model.db.SmallTableModelBase;
import edu.iu.grid.oim.model.db.VOModel;
import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord;
import edu.iu.grid.oim.model.db.record.CertificateRequestUserRecord;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.GridAdminRecord;
import edu.iu.grid.oim.model.db.record.VORecord;
import edu.iu.grid.oim.model.exceptions.CertificateRequestException;
import edu.iu.grid.oim.view.divrep.form.validator.PKIPassStrengthValidator;
public class RestServlet extends ServletBase {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(RestServlet.class);
static String GOC_TICKET_MESSAGE = " -- GOC alert will be sent to GOC infrastructure team about this issue. Meanwhile, feel free to open a GOC ticket at https://ticket.grid.iu.edu";
static enum Status {OK, FAILED, PENDING};
class Reply {
Status status = Status.OK;
String detail = "Nothing to report";
JSONObject params = new JSONObject();
void out(HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
params.put("status", status.toString());
params.put("detail", detail);
out.write(params.toString());
}
}
@SuppressWarnings("serial")
class RestException extends Exception {
public RestException(String message) {
super(message);
}
public RestException(String message, Exception e) {
super(message, e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Reply reply = new Reply();
try {
String action = request.getParameter("action");
//host certificate api
if(action.equals("host_certs_request")) {
doHostCertsRequest(request, reply);
//} else if(action.equals("host_certs_renew")) {
// doHostCertsRenew(request, reply); //Tony says we don't need host cert renew
} else if(action.equals("host_certs_retrieve")) {
doHostCertsRetrieve(request, reply);
} else if(action.equals("host_certs_approve")) {
doHostCertsApprove(request, reply);
} else if(action.equals("host_certs_reject")) {
doHostCertsReject(request, reply);
} else if(action.equals("host_certs_cancel")) {
doHostCertsCancel(request, reply);
} else if(action.equals("host_certs_revoke")) {
doHostCertsRevoke(request, reply);
} else if(action.equals("host_certs_issue")) {
doHostCertsIssue(request, reply);
}
//user certificate api
else if(action.equals("user_cert_request")) {
doUserCertRequest(request, reply);
} else if(action.equals("user_cert_renew")) {
doUserCertRenew(request, reply);
} else if(action.equals("user_cert_retrieve")) {
doUserCertRetrieve(request, reply);
} else if(action.equals("user_cert_approve")) {
doUserCertApprove(request, reply);
} else if(action.equals("user_cert_reject")) {
doUserCertReject(request, reply);
} else if(action.equals("user_cert_cancel")) {
doUserCertCancel(request, reply);
} else if(action.equals("user_cert_revoke")) {
doUserCertRevoke(request, reply);
} else if(action.equals("user_cert_issue")) {
doUserCertIssue(request, reply);
}
//misc
else if(action.equals("reset_daily_quota")) {
doResetDailyQuota(request, reply);
} else if(action.equals("reset_yearly_quota")) {
doResetYearlyQuota(request, reply);
} else if(action.equals("find_expired_cert_request")) {
doFindExpiredCertificateRequests(request, reply);
} else if(action.equals("notify_expiring_cert_request")) {
doNotifyExpiringCertificateRequest(request, reply);
} else {
reply.status = Status.FAILED;
reply.detail = "No such action";
}
} catch (RestException e) {
reply.status = Status.FAILED;
reply.detail = e.getMessage();
if(e.getCause() != null) {
reply.detail += " -- " + e.getCause().getMessage() + GOC_TICKET_MESSAGE;
}
} catch(AuthorizationException e) {
//nothing unclear about auth error.
reply.status = Status.FAILED;
reply.detail = e.toString();
} catch(Exception e) {
reply.status = Status.FAILED;
reply.detail = e.toString();
if(e.getCause() != null) {
reply.detail += " -- " + e.getCause().getMessage() + GOC_TICKET_MESSAGE;
}
}
reply.out(response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Reply reply = new Reply();
try {
String action = request.getParameter("action");
if(action.equals("quota_info")) {
doQuotaInfo(request, reply);
} else if(action.equals("user_info")) {
doUserInfo(request, reply);
} else if(action.equals("hcvoid")) {
doHCVOID(request, reply);
} else {
reply.status = Status.FAILED;
reply.detail = "No such action";
}
} catch(AuthorizationException e) {
reply.status = Status.FAILED;
reply.detail = e.toString();
} catch(Exception e) {
reply.status = Status.FAILED;
reply.detail = e.toString();
if(e.getMessage() != null) reply.detail += " -- " + e.getMessage() + GOC_TICKET_MESSAGE;
}
reply.out(response);
}
private void doHostCertsRequest(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
String[] dirty_csrs = request.getParameterValues("csrs");
if(dirty_csrs == null) {
throw new RestException("csrs parameter is not set.");
}
String name, email, phone;
if(auth.isUser()) {
ContactRecord user = auth.getContact();
name = user.name;
email = user.primary_email;
phone = user.primary_phone;
context.setComment("OIM authenticated user; " + name + " submitted host certificatates request.");
} else if(auth.isUnregistered()) {
throw new RestException("Accessed via https using unregistered user certificate :" + auth.getUserDN());
} else if(auth.isDisabled()) {
throw new RestException("Accessed via https using disabled user certificate: "+ auth.getUserDN());
} else if(auth.isSecure()) {
throw new RestException("Accessed via https without a user certificate (please use http for guest access)");
} else {
//must be a guest then.. we need name/address info.
name = request.getParameter("name");
email = request.getParameter("email");
phone = request.getParameter("phone");
//TODO - validate
if(name == null || email == null || phone == null) {
throw new RestException("Please provide name, email, phone in order to create GOC ticket.");
}
context.setComment("Guest user; " + name + " submitted host certificatates request.");
}
//user may provide vo context
Integer approver_vo_id = null;
String voname = request.getParameter("vo");
try {
if(voname != null) {
VOModel vmodel = new VOModel(context);
VORecord vo = vmodel.getByName(voname);
if(vo == null) {
log.info("Failed to find user specified VO : " + voname + " .. ignoring for now - will throw later if VO context is needed");
} else {
approver_vo_id = vo.id;
}
}
} catch (SQLException e) {
throw new RestException("Failed to lookup voname: " + voname, e);
}
CertificateRequestHostModel certmodel = new CertificateRequestHostModel(context);
//lookup gridadmins for specified csr (in specified vo context)
try {
CertificateRequestHostRecord temp_rec = new CertificateRequestHostRecord();
StringArray dirty_csrs_ar = new StringArray(dirty_csrs);
temp_rec.csrs = dirty_csrs_ar.toXML();
temp_rec.approver_vo_id = approver_vo_id;
ArrayList<ContactRecord> gas = certmodel.findGridAdmin(temp_rec);
if(gas.isEmpty()) {
throw new RestException("No GridAdmins for specified CSRs/VO");
}
//reset it back to our vo_id now that we called findGridAdmin
approver_vo_id = temp_rec.approver_vo_id;
} catch (CertificateRequestException e) {
throw new RestException("Failed to find GridAdmins for specified CSRs/VO", e);
}
ArrayList<String> csrs = new ArrayList<String>();
for(String csr : dirty_csrs) {
csrs.add(csr);//no longer dirty at this point
}
//optional parameters
String request_comment = request.getParameter("request_comment");
String[] request_ccs = request.getParameterValues("request_ccs");
CertificateRequestHostRecord rec;
try {
if(auth.isUser()) {
rec = certmodel.requestAsUser(csrs, auth.getContact(), request_comment, request_ccs, approver_vo_id);
} else {
rec = certmodel.requestAsGuest(csrs, name, email, phone, request_comment, request_ccs, approver_vo_id);
}
if(rec == null) {
throw new RestException("Failed to make request");
}
log.debug("success");
reply.params.put("gocticket_url", StaticConfig.conf.getProperty("url.gocticket")+"/"+rec.goc_ticket_id);
reply.params.put("host_request_id", rec.id.toString());
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doHostCertsRetrieve(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
//Authorization auth = context.getAuthorization();
String dirty_host_request_id = request.getParameter("host_request_id");
Integer host_request_id = Integer.parseInt(dirty_host_request_id);
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
try {
CertificateRequestHostRecord rec = model.get(host_request_id);
if(rec == null) {
throw new RestException("No such host certificate request ID");
}
if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
//pass pkcs7s
JSONArray ja = new JSONArray();
StringArray pkcs7s = new StringArray(rec.cert_pkcs7);
for(int i = 0;i < pkcs7s.length(); ++i) {
ja.put(i, pkcs7s.get(i));
}
reply.params.put("pkcs7s", ja);
//per conversation with Von on 2/1/2012 about 1.1 freeze, I am removing certificates and intermediates out until
//CLI will do key-based access to the output parameter (not index)
/*
//pass certificates (pem?)
JSONArray certs_ja = new JSONArray();
StringArray certs = new StringArray(rec.cert_certificate);
for(int i = 0;i < certs.length(); ++i) {
certs_ja.put(i, certs.get(i));
}
reply.params.put("certificates", certs_ja);
//pass intermediates (pem?)
JSONArray ints_ja = new JSONArray();
StringArray intermediates = new StringArray(rec.cert_intermediate);
for(int i = 0;i < intermediates.length(); ++i) {
ints_ja.put(i, intermediates.get(i));
}
reply.params.put("intermediates", ints_ja);
*/
} else if(rec.status.equals(CertificateRequestStatus.ISSUING)) {
//TODO - issue thread should somehow report issue status instead.
//TODO - this algorithm probably won't work if the certs are renewed - since we currently don't clear certificate before re-issuing
//count number of certificate issued so far
StringArray pkcs7s = new StringArray(rec.cert_pkcs7);
int issued = 0;
JSONArray certstatus = new JSONArray();
for(int i = 0;i < pkcs7s.length(); ++i) {
String pkcs7 = pkcs7s.get(i);
if(pkcs7 != null) {
issued++;
certstatus.put(i, "ISSUED");
} else {
certstatus.put(i, "ISSUING");
}
}
reply.params.put("cert_status", certstatus);
reply.status = Status.PENDING;
reply.detail = issued + " of " + pkcs7s.length() + " certificates has been issued";
} else {
reply.status = Status.FAILED;
reply.detail = "Can't retrieve certificates on request that are not in ISSUED or ISSUING status. Current request status is " + rec.status + ".";
if(rec.status_note != null) {
reply.detail += " Last note: " + rec.status_note;
}
reply.params.put("request_status", rec.status.toString());
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
}
}
private void doHostCertsApprove(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_host_request_id = request.getParameter("host_request_id");
Integer host_request_id = Integer.parseInt(dirty_host_request_id);
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
//set comment
String request_comment = request.getParameter("request_comment");
if(request_comment == null) {
request_comment = "Approved via command line";
}
context.setComment(request_comment);
try {
CertificateRequestHostRecord rec = model.get(host_request_id);
if(rec == null) {
throw new RestException("No such host certificate request ID");
}
if(model.canApprove(rec)) {
model.approve(rec);
} else {
throw new AuthorizationException("Your request has been received and must be approved. Please watch your email for a GOC ticket notification with further instructions.");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doHostCertsReject(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_host_request_id = request.getParameter("host_request_id");
Integer host_request_id = Integer.parseInt(dirty_host_request_id);
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
try {
CertificateRequestHostRecord rec = model.get(host_request_id);
if(rec == null) {
throw new RestException("No such host certificate request ID");
}
if(model.canReject(rec)) {
model.reject(rec);
} else {
throw new AuthorizationException("You can't reject this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doHostCertsCancel(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_host_request_id = request.getParameter("host_request_id");
Integer host_request_id = Integer.parseInt(dirty_host_request_id);
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
try {
CertificateRequestHostRecord rec = model.get(host_request_id);
if(rec == null) {
throw new RestException("No such host certificate request ID");
}
if(model.canCancel(rec)) {
model.cancel(rec);
} else {
throw new AuthorizationException("You can't cancel this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doHostCertsRevoke(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_host_request_id = request.getParameter("host_request_id");
Integer host_request_id = Integer.parseInt(dirty_host_request_id);
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
//set comment
String request_comment = request.getParameter("request_comment");
if(request_comment == null) {
request_comment = "Revocation requested via command line";
}
context.setComment(request_comment);
try {
CertificateRequestHostRecord rec = model.get(host_request_id);
if(rec == null) {
throw new RestException("No such host certificate request ID");
}
if(model.canRevoke(rec)) {
model.revoke(rec);
} else {
throw new AuthorizationException("You can't revoke this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
//start issuing cert.. will not block
private void doHostCertsIssue(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_host_request_id = request.getParameter("host_request_id");
Integer host_request_id = Integer.parseInt(dirty_host_request_id);
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
try {
CertificateRequestHostRecord rec = model.get(host_request_id);
if(rec == null) {
throw new RestException("No such host certificate request ID");
}
if(model.canIssue(rec)) {
model.startissue(rec);
} else {
throw new AuthorizationException("You can't issue this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doUserCertRequest(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
//TODO - user cert request with CSR is yet to be implemented
}
private void doUserCertRenew(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
CertificateRequestUserModel model = new CertificateRequestUserModel(context);
String dirty_user_request_id = request.getParameter("user_request_id");
Integer user_request_id = null;
if(dirty_user_request_id != null) {
user_request_id = Integer.parseInt(dirty_user_request_id);
}
String dirty_serial_id = request.getParameter("serial_id");
String serial_id = null;
if(dirty_serial_id != null) {
serial_id = dirty_serial_id.replaceAll("/[^A-Z0-9 ]/", "");
}
String dirty_password = request.getParameter("password");
String password = null;
if(dirty_password != null) {
password = dirty_password.replaceAll("[^\\x00-\\x7F]", "");//replace all non-ascii
PKIPassStrengthValidator validator = new PKIPassStrengthValidator();
if(!validator.isValid(password)) {
throw new RestException("Password is too weak.");
}
} else {
throw new RestException("Password parameter is missing.");
}
//set comment
String request_comment = request.getParameter("request_comment");
if(request_comment == null) {
request_comment = "Renewal Request via command line";
}
context.setComment(request_comment);
try {
//lookup request record either by request_id or serial_id
CertificateRequestUserRecord rec = null;
if(user_request_id != null) {
rec = model.get(user_request_id);
} else if(serial_id != null) {
rec = model.getBySerialID(serial_id);
}
if(rec == null) {
throw new RestException("No such user certificate request ID or serial ID");
}
//load log
ArrayList<CertificateRequestModelBase<CertificateRequestUserRecord>.LogDetail> logs = model.getLogs(CertificateRequestUserModel.class, rec.id);
if(model.canRenew(rec, logs)) {
model.renew(rec, password);
reply.params.put("request_id", rec.id);
} else {
throw new AuthorizationException("You are not authorized to renew this certificate, or condition of the user certificate currently does not allow you to renew this certificate.");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doUserCertRetrieve(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_user_request_id = request.getParameter("user_request_id");
Integer user_request_id = Integer.parseInt(dirty_user_request_id);
CertificateRequestUserModel model = new CertificateRequestUserModel(context);
try {
CertificateRequestUserRecord rec = model.get(user_request_id);
if(rec == null) {
throw new RestException("No such user certificate request ID");
}
if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
//convert string array to jsonarray and send to user
reply.params.put("pkcs7", rec.cert_pkcs7);
reply.params.put("certificate", rec.cert_certificate);
reply.params.put("intermediate", rec.cert_intermediate);
if(model.getPrivateKey(rec.id) != null) {
KeyStore p12 = model.getPkcs12(rec);
if(p12 == null) {
throw new RestException("Failed to create pkcs12 for download");
} else {
try {
String password = model.getPassword(rec.id);
ByteArrayOutputStream os = new ByteArrayOutputStream();
p12.store(os, password.toCharArray());
//base64 encode and set it to pkcs12 param
byte[] encoded = Base64.encodeBase64(os.toByteArray());
reply.params.put("pkcs12", new String(encoded));
} catch (KeyStoreException e) {
throw new RestException("KeyStoreException while outputing pkcs12", e);
} catch (NoSuchAlgorithmException e) {
throw new RestException("NoSuchAlgorithmException while outputing pkcs12", e);
} catch (CertificateException e) {
throw new RestException("CertificateException while outputing pkcs12", e);
} catch (IOException e) {
throw new RestException("IOException while outputing pkcs12", e);
}
}
}
} else if(rec.status.equals(CertificateRequestStatus.ISSUING)) {
reply.status = Status.PENDING;
} else {
reply.status = Status.FAILED;
reply.detail = "Can't retrieve certificate on request that are not in ISSUED or ISSUING status. Current request status is " + rec.status + ".";
reply.params.put("request_status", rec.status.toString());
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
}
}
private void doUserCertApprove(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_user_request_id = request.getParameter("user_request_id");
Integer user_request_id = Integer.parseInt(dirty_user_request_id);
CertificateRequestUserModel model = new CertificateRequestUserModel(context);
//set comment
String request_comment = request.getParameter("request_comment");
if(request_comment == null) {
request_comment = "Approved via command line";
}
context.setComment(request_comment);
try {
CertificateRequestUserRecord rec = model.get(user_request_id);
if(rec == null) {
throw new RestException("No such user certificate request ID");
}
if(model.canApprove(rec)) {
model.approve(rec);
} else {
throw new AuthorizationException("You are not authorized to approve this certificate, or condition of the user certificate currently does not allow you to approve this certificate.");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doUserCertReject(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_user_request_id = request.getParameter("user_request_id");
Integer user_request_id = Integer.parseInt(dirty_user_request_id);
CertificateRequestUserModel model = new CertificateRequestUserModel(context);
try {
CertificateRequestUserRecord rec = model.get(user_request_id);
if(rec == null) {
throw new RestException("No such user certificate request ID");
}
if(model.canReject(rec)) {
model.reject(rec);
} else {
throw new AuthorizationException("You can't reject this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doUserCertCancel(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_user_request_id = request.getParameter("user_request_id");
Integer user_request_id = Integer.parseInt(dirty_user_request_id);
CertificateRequestUserModel model = new CertificateRequestUserModel(context);
try {
CertificateRequestUserRecord rec = model.get(user_request_id);
if(rec == null) {
throw new RestException("No such user certificate request ID");
}
if(model.canCancel(rec)) {
model.cancel(rec);
} else {
throw new AuthorizationException("You can't cancel this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doUserCertRevoke(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
CertificateRequestUserModel model = new CertificateRequestUserModel(context);
String dirty_user_request_id = request.getParameter("user_request_id");
Integer user_request_id = null;
if(dirty_user_request_id != null) {
user_request_id = Integer.parseInt(dirty_user_request_id);
}
String dirty_serial_id = request.getParameter("serial_id");
String serial_id = null;
if(dirty_serial_id != null) {
serial_id = dirty_serial_id.replaceAll("/[^A-Z0-9 ]/", "");
}
//set comment
String request_comment = request.getParameter("request_comment");
if(request_comment == null) {
request_comment = "Revocation requested via command line";
}
context.setComment(request_comment);
try {
//lookup request record either by request_id or serial_id
CertificateRequestUserRecord rec = null;
if(user_request_id != null) {
rec = model.get(user_request_id);
} else if(serial_id != null) {
rec = model.getBySerialID(serial_id);
}
if(rec == null) {
throw new RestException("No such user certificate request ID or serial ID");
}
if(model.canRevoke(rec)) {
model.revoke(rec);
} else {
throw new AuthorizationException("You can't revoke this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doUserCertIssue(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
String dirty_user_request_id = request.getParameter("user_request_id");
Integer user_request_id = Integer.parseInt(dirty_user_request_id);
CertificateRequestUserModel model = new CertificateRequestUserModel(context);
try {
CertificateRequestUserRecord rec = model.get(user_request_id);
if(rec == null) {
throw new RestException("No such user certificate request ID");
}
if(model.canIssue(rec)) {
model.startissue(rec, null);//command line doesn't provide any password
} else {
throw new AuthorizationException("You can't issue this request");
}
} catch (SQLException e) {
throw new RestException("SQLException while making request", e);
} catch (CertificateRequestException e) {
throw new RestException("CertificateRequestException while making request", e);
}
}
private void doQuotaInfo(HttpServletRequest request, Reply reply) throws AuthorizationException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
if(!auth.isLocal()) {
throw new AuthorizationException("You can't access this interface from there");
}
ConfigModel config = new ConfigModel(context);
reply.params.put("global_usercert_year_count", config.QuotaGlobalUserCertYearCount.getInteger());
reply.params.put("global_usercert_year_max", config.QuotaGlobalUserCertYearMax.getInteger());
reply.params.put("global_hostcert_year_count", config.QuotaGlobalHostCertYearCount.getInteger());
reply.params.put("global_hostcert_year_max", config.QuotaGlobalHostCertYearMax.getInteger());
reply.params.put("quota_hostcert_year_max", config.QuotaUserHostYearMax.getInteger());
reply.params.put("quota_hostcert_day_max", config.QuotaUserHostDayMax.getInteger());
reply.params.put("quota_usercert_year_max", config.QuotaUserCertYearMax.getInteger());
}
private void doUserInfo(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
if(!auth.isUser()) {
throw new AuthorizationException("This API is only for registered users.");
}
ConfigModel config = new ConfigModel(context);
reply.params.put("global_usercert_year_count", config.QuotaGlobalUserCertYearCount.getInteger());
reply.params.put("global_usercert_year_max", config.QuotaGlobalUserCertYearMax.getInteger());
reply.params.put("global_hostcert_year_count", config.QuotaGlobalHostCertYearCount.getInteger());
reply.params.put("global_hostcert_year_max", config.QuotaGlobalHostCertYearMax.getInteger());
reply.params.put("quota_hostcert_year_max", config.QuotaUserHostYearMax.getInteger());
reply.params.put("quota_hostcert_day_max", config.QuotaUserHostDayMax.getInteger());
reply.params.put("quota_usercert_year_max", config.QuotaUserCertYearMax.getInteger());
ContactRecord user = auth.getContact();
reply.params.put("count_hostcert_day", user.count_hostcert_day);
reply.params.put("count_hostcert_year", user.count_hostcert_year);
reply.params.put("count_usercert_year", user.count_usercert_year);
reply.detail = "User quota details for "+ auth.getUserDN();
//load domains that user can approve certificates for
try {
GridAdminModel gmodel = new GridAdminModel(context);
ArrayList<GridAdminRecord> recs = gmodel.getGridAdminsByContactID(user.id);
JSONArray domains = new JSONArray();
for(GridAdminRecord rec : recs) {
domains.put(rec.domain);
}
reply.params.put("gridadmin_domains", domains);
} catch (SQLException e) {
throw new RestException("Failed to load gridadmin list", e);
}
}
private void doResetDailyQuota(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
if(!auth.isLocal()) {
throw new AuthorizationException("You can't access this interface from there");
}
//reset user counter
ContactModel model = new ContactModel(context);
try {
model.resetCertsDailyCount();
SmallTableModelBase.emptyAllCache();
} catch (SQLException e) {
throw new RestException("SQLException while resetting user daily count", e);
}
}
//should call once an year
private void doResetYearlyQuota(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
if(!auth.isLocal()) {
throw new AuthorizationException("You can't access this interface from there");
}
//reset user counter
ContactModel model = new ContactModel(context);
try {
model.resetCertsYearlyCount();
SmallTableModelBase.emptyAllCache();
} catch (SQLException e) {
throw new RestException("SQLException while resetting user yearly count", e);
}
//reset global counter
ConfigModel config = new ConfigModel(context);
try {
config.QuotaGlobalHostCertYearCount.set("0");
config.QuotaGlobalUserCertYearCount.set("0");
} catch (SQLException e) {
throw new RestException("SQLException while resetting global yearly count", e);
}
}
//should call every day
private void doFindExpiredCertificateRequests(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
if(!auth.isLocal()) {
throw new AuthorizationException("You can't access this interface from there");
}
CertificateRequestUserModel umodel = new CertificateRequestUserModel(context);
try {
umodel.processCertificateExpired();
umodel.processStatusExpired();
} catch (SQLException e) {
throw new RestException("SQLException while processing expired user certificates", e);
}
CertificateRequestHostModel hmodel = new CertificateRequestHostModel(context);
try {
hmodel.processCertificateExpired();
hmodel.processStatusExpired();
} catch (SQLException e) {
throw new RestException("SQLException while processing expired host certificates", e);
}
}
//should call once a week
private void doNotifyExpiringCertificateRequest(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
if(!auth.isLocal()) {
throw new AuthorizationException("You can't access this interface from there");
}
CertificateRequestUserModel umodel = new CertificateRequestUserModel(context);
try {
umodel.notifyExpiringIn(30);
} catch (SQLException e) {
throw new RestException("SQLException while processing expired user certificates", e);
}
CertificateRequestHostModel hmodel = new CertificateRequestHostModel(context);
try {
hmodel.notifyExpiringIn(30);
} catch (SQLException e) {
throw new RestException("SQLException while processing expired user certificates", e);
}
}
//this is used just once to populate missing VO ID on host certificate requests
private void doHCVOID(HttpServletRequest request, Reply reply) throws AuthorizationException, RestException {
UserContext context = new UserContext(request);
Authorization auth = context.getAuthorization();
/*
if(!auth.isLocal()) {
throw new AuthorizationException("You can't access this interface from there");
}
*/
//pull all records that has no expiration dates set
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
try {
StringBuffer queries = new StringBuffer();
for(CertificateRequestHostRecord rec : model.findNullVO()) {
//String[] cns = rec.getCNs();
try {
System.out.println("processing " + rec.id);
model.findGridAdmin(rec);
if(rec.approver_vo_id == null) {
System.out.println("\tCouldn't figure out approver_vo_id");
} else {
//CertificateRequestModelBase base = model;
//base.update(model.get(rec.id), rec);
queries.append("UPDATE certificate_request_host SET approver_vo_id = "+ rec.approver_vo_id + " WHERE id = " + rec.id + " and approver_vo_id is NULL limit 1\n");
}
} catch(CertificateRequestException e) {
System.out.println("\tFailed to reset approver_vo_id");
System.out.println("\t"+e.toString());
}
/*
String[] pkc7s = rec.getPKCS7s();
java.security.cert.Certificate[] chain;
try {
chain = CertificateManager.parsePKCS7(pkc7s[0]);//grab first one
X509Certificate c0 = (X509Certificate)chain[0];
Date notafter = c0.getNotAfter();
Date notbefore = c0.getNotBefore();
java.text.SimpleDateFormat mysqlformat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sql = "UPDATE certificate_request_host SET cert_notafter = '"+mysqlformat.format(notafter)+"', cert_notbefore = '"+mysqlformat.format(notbefore)+"' WHERE id = "+rec.id+" LIMIT 1;";
reply.params.put(rec.id.toString(), sql);
} catch(CertificateException e) {
throw new RestException("SQLException while parsing pkcs7", e);
} catch (CMSException e) {
throw new RestException("SQLException while running pkcs7", e);
} catch (IOException e) {
throw new RestException("SQLException while running pkcs7", e);
}
*/
}
reply.detail = queries.toString();
} catch (SQLException e) {
throw new RestException("SQLException while running doHostCertExSQL", e);
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package recipease.gui;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import javax.swing.JOptionPane;
import recipease.objects.RecipeData;
/**
*
* @author Laura
*/
public class SuggestRecipe extends javax.swing.JFrame {
Connection con;
ConnectionManager cm;
/**
* Creates new form SuggestRecipe
*/
public SuggestRecipe() {
initComponents();
cm = new ConnectionManager();
con = cm.CreateConnection();
}
public SuggestRecipe(Connection c, ConnectionManager c1) {
con = c;
cm = c1;
initComponents();
}
private void suggestion(){
String criteria;
RecipeData recData = new RecipeData();
if(!"".equals(cuisineField.getText())){
criteria = cuisineField.getText();
String qry = "SELECT * FROM recipe WHERE Cuisine = '" + criteria +"'";
System.out.println(qry);
try{
Statement sta = con.prepareStatement(qry);
ResultSet rs = sta.executeQuery(qry);
//Gets the number of results
rs.last();
int len = rs.getRow();
if(len > 0){
//Generates a random number
Random rand = new Random();
int x = rand.nextInt(len) + 1;
System.out.println("Length of result set: " + len);
System.out.println("Random number: " + x);
//Picks a random entry from the result set
rs.beforeFirst();
//System.out.println(rs.getString(2));
while(rs.next()){
System.out.println(rs.getString(3));
if(rs.getRow() == x){
//set name
recData.setName(rs.getString(2));
//set ingredients
recData.setIngredients(rs.getString(3));
//set method
recData.setMethod(rs.getString(4));
//set cuisine
recData.setCuisine(rs.getString(5));
//set meal
recData.setMeal(rs.getString(6));
//set servings
recData.setServes(rs.getString(7));
//set Time
recData.setTime(rs.getString(8));
//break;
}
}
Recipe rec = new Recipe(recData, "suggestion");
rec.setVisible(true);
this.dispose();
}else{
//if there are no results for the search term, the user is shown a message dialog
JOptionPane.showMessageDialog(null, "Sorry! No results for that. Try again.");
cuisineField.setText("");
}
}catch(Exception e){
System.out.println("Cannot connect to database");
}
}else{
System.out.println("null");
}
}
private void suggestionMeal(){
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
cuisineField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Can't decide what to eat? Let me suggest something for you!");
cuisineField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
cuisineFieldKeyReleased(evt);
}
});
jLabel3.setText("Enter a cuisine:");
jLabel4.setText("OR");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Dinner", "Breakfast", "Lunch", "Snack", "Dessert", "Appetiser", "Salad"}));
jLabel5.setText("Choose a meal type:");
jButton1.setText("Let's Go!");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(168, 168, 168)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(127, 127, 127)
.addComponent(jLabel5))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(135, 135, 135)
.addComponent(jButton1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(49, 49, 49)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(cuisineField, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(155, 155, 155)
.addComponent(jLabel3)))
.addContainerGap(49, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jLabel1)
.addGap(24, 24, 24)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cuisineField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jButton1)
.addContainerGap(29, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
suggestion();
}//GEN-LAST:event_jButton1ActionPerformed
private void cuisineFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cuisineFieldKeyReleased
if (evt.getKeyCode() == KeyEvent.VK_ENTER){
//allows the user to just hit enter to search
suggestion();
}
}//GEN-LAST:event_cuisineFieldKeyReleased
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SuggestRecipe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SuggestRecipe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SuggestRecipe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SuggestRecipe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SuggestRecipe().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField cuisineField;
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
|
package org.voltdb.iv2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.messaging.TransactionInfoBaseMessage;
import org.voltcore.messaging.VoltMessage;
import org.voltcore.utils.CoreUtils;
import org.voltdb.client.ClientResponse;
import org.voltdb.ClientResponseImpl;
import org.voltdb.CommandLog;
import org.voltdb.CommandLog.DurabilityListener;
import org.voltdb.messaging.DumpMessage;
import org.voltdb.messaging.MultiPartitionParticipantMessage;
import org.voltdb.PartitionDRGateway;
import org.voltdb.SnapshotCompletionInterest;
import org.voltdb.SnapshotCompletionMonitor;
import org.voltdb.SystemProcedureCatalog;
import org.voltdb.VoltDB;
import org.voltdb.dtxn.TransactionState;
import org.voltdb.messaging.BorrowTaskMessage;
import org.voltdb.messaging.CompleteTransactionMessage;
import org.voltdb.messaging.FragmentResponseMessage;
import org.voltdb.messaging.FragmentTaskMessage;
import org.voltdb.messaging.InitiateResponseMessage;
import org.voltdb.messaging.Iv2InitiateTaskMessage;
import org.voltdb.messaging.Iv2LogFaultMessage;
import org.voltdb.VoltTable;
import com.google.common.primitives.Longs;
public class SpScheduler extends Scheduler implements SnapshotCompletionInterest
{
static class DuplicateCounterKey implements Comparable<DuplicateCounterKey>
{
private final long m_txnId;
private final long m_spHandle;
transient final int m_hash;
DuplicateCounterKey(long txnId, long spHandle)
{
m_txnId = txnId;
m_spHandle = spHandle;
m_hash = (37 * (int)(m_txnId ^ (m_txnId >>> 32))) +
((int)(m_spHandle ^ (m_spHandle >>> 32)));
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || !(getClass().isInstance(o))) {
return false;
}
DuplicateCounterKey other = (DuplicateCounterKey)o;
return (m_txnId == other.m_txnId && m_spHandle == other.m_spHandle);
}
// Only care about comparing TXN ID part for sorting in updateReplicas
@Override
public int compareTo(DuplicateCounterKey o)
{
if (m_txnId < o.m_txnId) {
return -1;
} else if (m_txnId > o.m_txnId) {
return 1;
} else {
if (m_spHandle < o.m_spHandle) {
return -1;
}
else if (m_spHandle > o.m_spHandle) {
return 1;
}
else {
return 0;
}
}
}
@Override
public int hashCode()
{
return m_hash;
}
@Override
public String toString()
{
return "<" + m_txnId + ", " + m_spHandle + ">";
}
};
List<Long> m_replicaHSIds = new ArrayList<Long>();
long m_sendToHSIds[] = new long[0];
private final Map<Long, TransactionState> m_outstandingTxns =
new HashMap<Long, TransactionState>();
private final Map<DuplicateCounterKey, DuplicateCounter> m_duplicateCounters =
new HashMap<DuplicateCounterKey, DuplicateCounter>();
private CommandLog m_cl;
private PartitionDRGateway m_drGateway = new PartitionDRGateway(true);
private final SnapshotCompletionMonitor m_snapMonitor;
// Need to track when command log replay is complete (even if not performed) so that
// we know when we can start writing viable replay sets to the fault log.
boolean m_replayComplete = false;
private final DurabilityListener m_durabilityListener;
//Generator of pre-IV2ish timestamp based unique IDs
private final UniqueIdGenerator m_uniqueIdGenerator;
// the current not-needed-any-more point of the repair log.
long m_repairLogTruncationHandle = Long.MIN_VALUE;
SpScheduler(int partitionId, SiteTaskerQueue taskQueue, SnapshotCompletionMonitor snapMonitor)
{
super(partitionId, taskQueue);
m_snapMonitor = snapMonitor;
m_durabilityListener = new DurabilityListener() {
@Override
public void onDurability(ArrayList<Object> durableThings) {
synchronized (m_lock) {
for (Object o : durableThings) {
m_pendingTasks.offer((TransactionTask)o);
}
}
}
};
m_uniqueIdGenerator = new UniqueIdGenerator(partitionId, 0);
}
@Override
public void setLeaderState(boolean isLeader)
{
super.setLeaderState(isLeader);
m_snapMonitor.addInterest(this);
}
@Override
public void setMaxSeenTxnId(long maxSeenTxnId)
{
super.setMaxSeenTxnId(maxSeenTxnId);
writeIv2ViableReplayEntry();
}
public void setDRGateway(PartitionDRGateway gateway)
{
m_drGateway = gateway;
if (m_drGateway != null) {
// Schedules to be fired every 5ms
VoltDB.instance().schedulePriorityWork(new Runnable() {
@Override
public void run() {
// Send a DR task to the site
m_tasks.offer(new DRTask(m_drGateway));
}
}, 0, 5, TimeUnit.MILLISECONDS);
}
}
@Override
public void shutdown()
{
m_tasks.offer(m_nullTask);
}
// This is going to run in the BabySitter's thread. This and deliver are synchronized by
// virtue of both being called on InitiatorMailbox and not directly called.
// (That is, InitiatorMailbox's API, used by BabySitter, is synchronized on the same
// lock deliver() is synchronized on.)
@Override
public void updateReplicas(List<Long> replicas)
{
// First - correct the official replica set.
m_replicaHSIds = replicas;
// Update the list of remote replicas that we'll need to send to
List<Long> sendToHSIds = new ArrayList<Long>(m_replicaHSIds);
sendToHSIds.remove(m_mailbox.getHSId());
m_sendToHSIds = Longs.toArray(sendToHSIds);
// Cleanup duplicate counters and collect DONE counters
// in this list for further processing.
List<DuplicateCounterKey> doneCounters = new LinkedList<DuplicateCounterKey>();
for (Entry<DuplicateCounterKey, DuplicateCounter> entry : m_duplicateCounters.entrySet()) {
DuplicateCounter counter = entry.getValue();
int result = counter.updateReplicas(m_replicaHSIds);
if (result == DuplicateCounter.DONE) {
doneCounters.add(entry.getKey());
}
}
// Maintain the CI invariant that responses arrive in txnid order.
Collections.sort(doneCounters);
for (DuplicateCounterKey key : doneCounters) {
DuplicateCounter counter = m_duplicateCounters.remove(key);
VoltMessage resp = counter.getLastResponse();
if (resp != null) {
// MPI is tracking deps per partition HSID. We need to make
// sure we write ours into the message getting sent to the MPI
if (resp instanceof FragmentResponseMessage) {
FragmentResponseMessage fresp = (FragmentResponseMessage)resp;
fresp.setExecutorSiteId(m_mailbox.getHSId());
}
m_mailbox.send(counter.m_destinationId, resp);
}
else {
hostLog.warn("TXN " + counter.getTxnId() + " lost all replicas and " +
"had no responses. This should be impossible?");
}
}
writeIv2ViableReplayEntry();
}
/**
* Poll the replay sequencer and process the messages until it returns null
*/
private void deliverReadyTxns() {
// First, pull all the sequenced messages, if any.
VoltMessage m = m_replaySequencer.poll();
while(m != null) {
deliver(m);
m = m_replaySequencer.poll();
}
// Then, try to pull all the drainable messages, if any.
m = m_replaySequencer.drain();
while (m != null) {
if (m instanceof Iv2InitiateTaskMessage) {
// Send IGNORED response for all SPs
Iv2InitiateTaskMessage task = (Iv2InitiateTaskMessage) m;
final InitiateResponseMessage response = new InitiateResponseMessage(task);
response.setResults(new ClientResponseImpl(ClientResponse.UNEXPECTED_FAILURE,
new VoltTable[0],
ClientResponseImpl.IGNORED_TRANSACTION));
m_mailbox.send(response.getInitiatorHSId(), response);
}
m = m_replaySequencer.drain();
}
}
/**
* Sequence the message for replay if it's for CL or DR.
*
* @param message
* @return true if the message can be delivered directly to the scheduler,
* false if the message is queued
*/
public boolean sequenceForReplay(VoltMessage message)
{
boolean canDeliver = false;
long sequenceWithTxnId = Long.MIN_VALUE;
boolean commandLog = (message instanceof TransactionInfoBaseMessage &&
(((TransactionInfoBaseMessage)message).isForReplay()));
boolean dr = ((message instanceof TransactionInfoBaseMessage &&
((TransactionInfoBaseMessage)message).isForDR()));
boolean sentinel = message instanceof MultiPartitionParticipantMessage;
boolean replay = commandLog || sentinel || dr;
boolean sequenceForReplay = m_isLeader && replay;
assert(!(commandLog && dr));
if (commandLog || sentinel) {
sequenceWithTxnId = ((TransactionInfoBaseMessage)message).getTxnId();
}
else if (dr) {
sequenceWithTxnId = ((TransactionInfoBaseMessage)message).getOriginalTxnId();
}
if (sequenceForReplay) {
InitiateResponseMessage dupe = m_replaySequencer.dedupe(sequenceWithTxnId,
(TransactionInfoBaseMessage) message);
if (dupe != null) {
// Duplicate initiate task message, send response
m_mailbox.send(dupe.getInitiatorHSId(), dupe);
}
else if (!m_replaySequencer.offer(sequenceWithTxnId, (TransactionInfoBaseMessage) message)) {
canDeliver = true;
}
else {
deliverReadyTxns();
}
// If it's a DR sentinel, send an acknowledgement
if (sentinel && !commandLog) {
MultiPartitionParticipantMessage mppm = (MultiPartitionParticipantMessage) message;
final InitiateResponseMessage response = new InitiateResponseMessage(mppm);
ClientResponseImpl clientResponse =
new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
new VoltTable[0], ClientResponseImpl.IGNORED_TRANSACTION);
response.setResults(clientResponse);
m_mailbox.send(response.getInitiatorHSId(), response);
}
}
else {
if (replay) {
// Update last seen and last polled txnId for replicas
m_replaySequencer.updateLastSeenTxnId(sequenceWithTxnId,
(TransactionInfoBaseMessage) message);
m_replaySequencer.updateLastPolledTxnId(sequenceWithTxnId,
(TransactionInfoBaseMessage) message);
}
canDeliver = true;
}
return canDeliver;
}
// SpInitiators will see every message type. The Responses currently come
// from local work, but will come from replicas when replication is
// implemented
@Override
public void deliver(VoltMessage message)
{
if (message instanceof Iv2InitiateTaskMessage) {
handleIv2InitiateTaskMessage((Iv2InitiateTaskMessage)message);
}
else if (message instanceof InitiateResponseMessage) {
handleInitiateResponseMessage((InitiateResponseMessage)message);
}
else if (message instanceof FragmentTaskMessage) {
handleFragmentTaskMessage((FragmentTaskMessage)message);
}
else if (message instanceof FragmentResponseMessage) {
handleFragmentResponseMessage((FragmentResponseMessage)message);
}
else if (message instanceof CompleteTransactionMessage) {
handleCompleteTransactionMessage((CompleteTransactionMessage)message);
}
else if (message instanceof BorrowTaskMessage) {
handleBorrowTaskMessage((BorrowTaskMessage)message);
}
else if (message instanceof Iv2LogFaultMessage) {
handleIv2LogFaultMessage((Iv2LogFaultMessage)message);
}
else if (message instanceof DumpMessage) {
handleDumpMessage();
}
else {
throw new RuntimeException("UNKNOWN MESSAGE TYPE, BOOM!");
}
}
// SpScheduler expects to see InitiateTaskMessages corresponding to single-partition
// procedures only.
public void handleIv2InitiateTaskMessage(Iv2InitiateTaskMessage message)
{
if (!message.isSinglePartition()) {
throw new RuntimeException("SpScheduler.handleIv2InitiateTaskMessage " +
"should never receive multi-partition initiations.");
}
final String procedureName = message.getStoredProcedureName();
long newSpHandle;
long uniqueId = Long.MIN_VALUE;
Iv2InitiateTaskMessage msg = message;
if (m_isLeader || message.isReadOnly()) {
/*
* A short circuit read is a read where the client interface is local to
* this node. The CI will let a replica perform a read in this case and
* it does looser tracking of client handles since it can't be
* partitioned from the local replica.
*/
if (!m_isLeader &&
CoreUtils.getHostIdFromHSId(msg.getInitiatorHSId()) !=
CoreUtils.getHostIdFromHSId(m_mailbox.getHSId())) {
VoltDB.crashLocalVoltDB("Only allowed to do short circuit reads locally", true, null);
}
/*
* If this is for CL replay or DR, update the unique ID generator
*/
if (message.isForReplay()) {
uniqueId = message.getUniqueId();
m_uniqueIdGenerator.updateMostRecentlyGeneratedUniqueId(uniqueId);
} else if (message.isForDR()) {
uniqueId = message.getStoredProcedureInvocation().getOriginalUniqueId();
// @LoadSinglepartitionTable does not have a valid uid
if (UniqueIdGenerator.getPartitionIdFromUniqueId(uniqueId) == m_partitionId) {
m_uniqueIdGenerator.updateMostRecentlyGeneratedUniqueId(uniqueId);
}
}
/*
* If this is CL replay use the txnid from the CL and also
* update the txnid to match the one from the CL
*/
if (message.isForReplay()) {
newSpHandle = message.getTxnId();
setMaxSeenTxnId(newSpHandle);
} else if (m_isLeader) {
TxnEgo ego = advanceTxnEgo();
newSpHandle = ego.getTxnId();
uniqueId = m_uniqueIdGenerator.getNextUniqueId();
} else {
/*
* The short circuit read case. Since we are not a master
* we can't create new transaction IDs, so reuse the last seen
* txnid. For a timestamp, might as well give a reasonable one
* for a read heavy workload so time isn't bursty.
*/
uniqueId = UniqueIdGenerator.makeIdFromComponents(
Math.max(System.currentTimeMillis(), m_uniqueIdGenerator.lastUsedTime),
0,
m_uniqueIdGenerator.partitionId);
//Don't think it wise to make a new one for a short circuit read
newSpHandle = getCurrentTxnId();
}
// Need to set the SP handle on the received message
// Need to copy this or the other local sites handling
// the same initiate task message will overwrite each
// other's memory -- the message isn't copied on delivery
// to other local mailboxes.
msg = new Iv2InitiateTaskMessage(
message.getInitiatorHSId(),
message.getCoordinatorHSId(),
m_repairLogTruncationHandle,
message.getTxnId(),
message.getUniqueId(),
message.isReadOnly(),
message.isSinglePartition(),
message.getStoredProcedureInvocation(),
message.getClientInterfaceHandle(),
message.getConnectionId(),
message.isForReplay());
msg.setSpHandle(newSpHandle);
// Also, if this is a vanilla single-part procedure, make the TXNID
// be the SpHandle (for now)
// Only system procedures are every-site, so we'll check through the SystemProcedureCatalog
if (SystemProcedureCatalog.listing.get(procedureName) == null ||
!SystemProcedureCatalog.listing.get(procedureName).getEverysite()) {
msg.setTxnId(newSpHandle);
msg.setUniqueId(uniqueId);
}
//Don't replicate reads, this really assumes that DML validation
//is going to be integrated soonish
if (m_isLeader && !msg.isReadOnly() && m_sendToHSIds.length > 0) {
Iv2InitiateTaskMessage replmsg =
new Iv2InitiateTaskMessage(m_mailbox.getHSId(),
m_mailbox.getHSId(),
m_repairLogTruncationHandle,
msg.getTxnId(),
msg.getUniqueId(),
msg.isReadOnly(),
msg.isSinglePartition(),
msg.getStoredProcedureInvocation(),
msg.getClientInterfaceHandle(),
msg.getConnectionId(),
msg.isForReplay());
// Update the handle in the copy since the constructor doesn't set it
replmsg.setSpHandle(newSpHandle);
for (long hsId : m_sendToHSIds) {
m_mailbox.send(hsId,
replmsg);
}
DuplicateCounter counter = new DuplicateCounter(
msg.getInitiatorHSId(),
msg.getTxnId(), m_replicaHSIds);
m_duplicateCounters.put(new DuplicateCounterKey(msg.getTxnId(), newSpHandle), counter);
}
}
else {
setMaxSeenTxnId(msg.getSpHandle());
newSpHandle = msg.getSpHandle();
uniqueId = msg.getUniqueId();
}
Iv2Trace.logIv2InitiateTaskMessage(message, m_mailbox.getHSId(), msg.getTxnId(), newSpHandle);
doLocalInitiateOffer(msg);
return;
}
/**
* Do the work necessary to turn the Iv2InitiateTaskMessage into a
* TransactionTask which can be queued to the TransactionTaskQueue.
* This is reused by both the normal message handling path and the repair
* path, and assumes that the caller has dealt with or ensured that the
* necessary ID, SpHandles, and replication issues are resolved.
*/
private void doLocalInitiateOffer(Iv2InitiateTaskMessage msg)
{
final String procedureName = msg.getStoredProcedureName();
final SpProcedureTask task =
new SpProcedureTask(m_mailbox, procedureName, m_pendingTasks, msg, m_drGateway);
if (!msg.isReadOnly()) {
if (!m_cl.log(msg, msg.getSpHandle(), m_durabilityListener, task)) {
m_pendingTasks.offer(task);
}
} else {
m_pendingTasks.offer(task);
}
}
@Override
public void handleMessageRepair(List<Long> needsRepair, VoltMessage message)
{
if (message instanceof Iv2InitiateTaskMessage) {
handleIv2InitiateTaskMessageRepair(needsRepair, (Iv2InitiateTaskMessage)message);
}
else if (message instanceof FragmentTaskMessage) {
handleFragmentTaskMessageRepair(needsRepair, (FragmentTaskMessage)message);
}
else if (message instanceof CompleteTransactionMessage) {
// It should be safe to just send CompleteTransactionMessages to everyone.
handleCompleteTransactionMessage((CompleteTransactionMessage)message);
}
else {
throw new RuntimeException("SpScheduler.handleMessageRepair received unexpected message type: " +
message);
}
}
private void handleIv2InitiateTaskMessageRepair(List<Long> needsRepair, Iv2InitiateTaskMessage message)
{
if (!message.isSinglePartition()) {
throw new RuntimeException("SpScheduler.handleIv2InitiateTaskMessageRepair " +
"should never receive multi-partition initiations.");
}
// set up duplicate counter. expect exactly the responses corresponding
// to needsRepair. These may, or may not, include the local site.
// We currently send the final response into the ether, since we don't
// have the original ClientInterface HSID stored. It would be more
// useful to have the original ClienInterface HSId somewhere handy.
List<Long> expectedHSIds = new ArrayList<Long>(needsRepair);
DuplicateCounter counter = new DuplicateCounter(
HostMessenger.VALHALLA,
message.getTxnId(), expectedHSIds);
m_duplicateCounters.put(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()), counter);
m_uniqueIdGenerator.updateMostRecentlyGeneratedUniqueId(message.getUniqueId());
// is local repair necessary?
if (needsRepair.contains(m_mailbox.getHSId())) {
needsRepair.remove(m_mailbox.getHSId());
// make a copy because handleIv2 non-repair case does?
Iv2InitiateTaskMessage localWork =
new Iv2InitiateTaskMessage(message.getInitiatorHSId(),
message.getCoordinatorHSId(), message);
doLocalInitiateOffer(localWork);
}
// is remote repair necessary?
if (!needsRepair.isEmpty()) {
Iv2InitiateTaskMessage replmsg =
new Iv2InitiateTaskMessage(m_mailbox.getHSId(), m_mailbox.getHSId(), message);
m_mailbox.send(com.google.common.primitives.Longs.toArray(needsRepair), replmsg);
}
}
private void handleFragmentTaskMessageRepair(List<Long> needsRepair, FragmentTaskMessage message)
{
// set up duplicate counter. expect exactly the responses corresponding
// to needsRepair. These may, or may not, include the local site.
List<Long> expectedHSIds = new ArrayList<Long>(needsRepair);
DuplicateCounter counter = new DuplicateCounter(
message.getCoordinatorHSId(), // Assume that the MPI's HSID hasn't changed
message.getTxnId(), expectedHSIds);
m_duplicateCounters.put(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()), counter);
// is local repair necessary?
if (needsRepair.contains(m_mailbox.getHSId())) {
// Sanity check that we really need repair.
if (m_outstandingTxns.get(message.getTxnId()) != null) {
hostLog.warn("SPI repair attempted to repair a fragment which it has already seen. " +
"This shouldn't be possible.");
// Not sure what to do in this event. Crash for now
throw new RuntimeException("Attempted to repair with a fragment we've already seen.");
}
needsRepair.remove(m_mailbox.getHSId());
// make a copy because handleIv2 non-repair case does?
FragmentTaskMessage localWork =
new FragmentTaskMessage(message.getInitiatorHSId(),
message.getCoordinatorHSId(), message);
doLocalFragmentOffer(localWork);
}
// is remote repair necessary?
if (!needsRepair.isEmpty()) {
FragmentTaskMessage replmsg =
new FragmentTaskMessage(m_mailbox.getHSId(), m_mailbox.getHSId(), message);
m_mailbox.send(com.google.common.primitives.Longs.toArray(needsRepair), replmsg);
}
}
// Pass a response through the duplicate counters.
public void handleInitiateResponseMessage(InitiateResponseMessage message)
{
// All single-partition reads are short-circuit reads and will have no duplicate counter.
// SpScheduler will only see InitiateResponseMessages for SP transactions, so if it's
// read-only here, it's short-circuited. Avoid all the lookup below. Also, don't update
// the truncation handle, since it won't have meaning for anyone.
if (message.isReadOnly()) {
// the initiatorHSId is the ClientInterface mailbox. Yeah. I know.
m_mailbox.send(message.getInitiatorHSId(), message);
return;
}
final long spHandle = message.getSpHandle();
final DuplicateCounterKey dcKey = new DuplicateCounterKey(message.getTxnId(), spHandle);
DuplicateCounter counter = m_duplicateCounters.get(dcKey);
if (counter != null) {
int result = counter.offer(message);
if (result == DuplicateCounter.DONE) {
m_duplicateCounters.remove(dcKey);
m_repairLogTruncationHandle = spHandle;
m_mailbox.send(counter.m_destinationId, counter.getLastResponse());
}
else if (result == DuplicateCounter.MISMATCH) {
VoltDB.crashLocalVoltDB("HASH MISMATCH: replicas produced different results.", true, null);
}
}
else {
// the initiatorHSId is the ClientInterface mailbox. Yeah. I know.
m_repairLogTruncationHandle = spHandle;
m_mailbox.send(message.getInitiatorHSId(), message);
}
}
// BorrowTaskMessages encapsulate a FragmentTaskMessage along with
// input dependency tables. The MPI issues borrows to a local site
// to perform replicated reads or aggregation fragment work.
private void handleBorrowTaskMessage(BorrowTaskMessage message) {
// borrows do not advance the sp handle. The handle would
// move backwards anyway once the next message is received
// from the SP leader.
long newSpHandle = getCurrentTxnId();
Iv2Trace.logFragmentTaskMessage(message.getFragmentTaskMessage(),
m_mailbox.getHSId(), newSpHandle, true);
TransactionState txn = m_outstandingTxns.get(message.getTxnId());
if (txn == null) {
// If the borrow is the first fragment for a transaction, run it as
// a single partition fragment; Must not engage/pause this
// site on a MP transaction before the SP instructs to do so.
// Do not track the borrow task as outstanding - it completes
// immediately and is not a valid transaction state for
// full MP participation (it claims everything can run as SP).
txn = new BorrowTransactionState(newSpHandle, message);
}
if (message.getFragmentTaskMessage().isSysProcTask()) {
final SysprocFragmentTask task =
new SysprocFragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, message.getFragmentTaskMessage(),
message.getInputDepMap());
m_pendingTasks.offer(task);
}
else {
final FragmentTask task =
new FragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, message.getFragmentTaskMessage(),
message.getInputDepMap());
m_pendingTasks.offer(task);
}
}
// SpSchedulers will see FragmentTaskMessage for:
// - The scatter fragment(s) of a multi-part transaction (normal or sysproc)
// - Borrow tasks to do the local fragment work if this partition is the
// buddy of the MPI. Borrow tasks may include input dependency tables for
// aggregation fragments, or not, if it's a replicated table read.
// For multi-batch MP transactions, we'll need to look up the transaction state
// that gets created when the first batch arrives.
// During command log replay a new SP handle is going to be generated, but it really
// doesn't matter, it isn't going to be used for anything.
void handleFragmentTaskMessage(FragmentTaskMessage message)
{
FragmentTaskMessage msg = message;
long newSpHandle;
if (m_isLeader) {
// Quick hack to make progress...we need to copy the FragmentTaskMessage
// before we start mucking with its state (SPHANDLE). We need to revisit
// all the messaging mess at some point.
msg = new FragmentTaskMessage(message.getInitiatorHSId(),
message.getCoordinatorHSId(), message);
//Not going to use the timestamp from the new Ego because the multi-part timestamp is what should be used
TxnEgo ego = advanceTxnEgo();
newSpHandle = ego.getTxnId();
msg.setSpHandle(newSpHandle);
if (msg.getInitiateTask() != null) {
msg.getInitiateTask().setSpHandle(newSpHandle);//set the handle
msg.setInitiateTask(msg.getInitiateTask());//Trigger reserialization so the new handle is used
}
/*
* If there a replicas to send it to, forward it!
* Unless... it's read only AND not a sysproc. Read only sysprocs may expect to be sent
* everywhere.
* In that case don't propagate it to avoid a determinism check and extra messaging overhead
*/
if (m_sendToHSIds.length > 0 && (!msg.isReadOnly() || msg.isSysProcTask())) {
FragmentTaskMessage replmsg =
new FragmentTaskMessage(m_mailbox.getHSId(),
m_mailbox.getHSId(), msg);
m_mailbox.send(m_sendToHSIds,
replmsg);
DuplicateCounter counter;
if (message.getFragmentTaskType() != FragmentTaskMessage.SYS_PROC_PER_SITE) {
counter = new DuplicateCounter(
msg.getCoordinatorHSId(),
msg.getTxnId(), m_replicaHSIds);
}
else {
counter = new SysProcDuplicateCounter(
msg.getCoordinatorHSId(),
msg.getTxnId(), m_replicaHSIds);
}
m_duplicateCounters.put(new DuplicateCounterKey(msg.getTxnId(), newSpHandle), counter);
}
}
else {
newSpHandle = msg.getSpHandle();
setMaxSeenTxnId(newSpHandle);
}
Iv2Trace.logFragmentTaskMessage(message, m_mailbox.getHSId(), newSpHandle, false);
doLocalFragmentOffer(msg);
}
/**
* Do the work necessary to turn the FragmentTaskMessage into a
* TransactionTask which can be queued to the TransactionTaskQueue.
* This is reused by both the normal message handling path and the repair
* path, and assumes that the caller has dealt with or ensured that the
* necessary ID, SpHandles, and replication issues are resolved.
*/
private void doLocalFragmentOffer(FragmentTaskMessage msg)
{
TransactionState txn = m_outstandingTxns.get(msg.getTxnId());
boolean logThis = false;
// bit of a hack...we will probably not want to create and
// offer FragmentTasks for txn ids that don't match if we have
// something in progress already
if (txn == null) {
txn = new ParticipantTransactionState(msg.getSpHandle(), msg);
m_outstandingTxns.put(msg.getTxnId(), txn);
// Only want to send things to the command log if it satisfies this predicate
// AND we've never seen anything for this transaction before. We can't
// actually log until we create a TransactionTask, though, so just keep track
// of whether it needs to be done.
logThis = (msg.getInitiateTask() != null && !msg.getInitiateTask().isReadOnly());
}
// Check to see if this is the final task for this txn, and if so, if we can close it out early
// Right now, this just means read-only.
// NOTE: this overlaps slightly with CompleteTransactionMessage handling completion. It's so tiny
// that for now, meh, but if this scope grows then it should get refactored out
if (msg.isFinalTask() && txn.isReadOnly()) {
m_outstandingTxns.remove(msg.getTxnId());
}
TransactionTask task;
if (msg.isSysProcTask()) {
task =
new SysprocFragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, msg, null);
}
else {
task =
new FragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, msg, null);
}
if (logThis) {
if (!m_cl.log(msg.getInitiateTask(), msg.getSpHandle(), m_durabilityListener, task)) {
m_pendingTasks.offer(task);
}
} else {
m_pendingTasks.offer(task);
}
}
// Eventually, the master for a partition set will need to be able to dedupe
// FragmentResponses from its replicas.
public void handleFragmentResponseMessage(FragmentResponseMessage message)
{
// Send the message to the duplicate counter, if any
DuplicateCounter counter =
m_duplicateCounters.get(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()));
if (counter != null) {
int result = counter.offer(message);
if (result == DuplicateCounter.DONE) {
m_duplicateCounters.remove(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()));
m_repairLogTruncationHandle = message.getSpHandle();
FragmentResponseMessage resp = (FragmentResponseMessage)counter.getLastResponse();
// MPI is tracking deps per partition HSID. We need to make
// sure we write ours into the message getting sent to the MPI
resp.setExecutorSiteId(m_mailbox.getHSId());
m_mailbox.send(counter.m_destinationId, resp);
}
else if (result == DuplicateCounter.MISMATCH) {
VoltDB.crashLocalVoltDB("HASH MISMATCH running multi-part procedure.", true, null);
}
// doing duplicate suppresion: all done.
return;
}
m_mailbox.send(message.getDestinationSiteId(), message);
}
public void handleCompleteTransactionMessage(CompleteTransactionMessage message)
{
if (m_isLeader) {
CompleteTransactionMessage replmsg = new CompleteTransactionMessage(message);
// Set the spHandle so that on repair the new master will set the max seen spHandle
// correctly
replmsg.setSpHandle(getCurrentTxnId());
if (m_sendToHSIds.length > 0) {
m_mailbox.send(m_sendToHSIds, replmsg);
}
} else {
setMaxSeenTxnId(message.getSpHandle());
}
TransactionState txn = m_outstandingTxns.get(message.getTxnId());
// We can currently receive CompleteTransactionMessages for multipart procedures
// which only use the buddy site (replicated table read). Ignore them for
// now, fix that later.
if (txn != null)
{
Iv2Trace.logCompleteTransactionMessage(message, m_mailbox.getHSId());
final CompleteTransactionTask task =
new CompleteTransactionTask(txn, m_pendingTasks, message, m_drGateway);
m_pendingTasks.offer(task);
// If this is a restart, then we need to leave the transaction state around
if (!message.isRestart()) {
m_outstandingTxns.remove(message.getTxnId());
}
}
}
public void handleIv2LogFaultMessage(Iv2LogFaultMessage message)
{
// Should only receive these messages at replicas, call the internal log write with
// the provided SP handle
writeIv2ViableReplayEntryInternal(message.getSpHandle());
setMaxSeenTxnId(message.getSpHandle());
}
public void handleDumpMessage()
{
String who = CoreUtils.hsIdToString(m_mailbox.getHSId());
hostLog.warn("State dump for site: " + who);
hostLog.warn("" + who + ": partition: " + m_partitionId + ", isLeader: " + m_isLeader);
if (m_isLeader) {
hostLog.warn("" + who + ": replicas: " + CoreUtils.hsIdCollectionToString(m_replicaHSIds));
if (m_sendToHSIds.length > 0) {
m_mailbox.send(m_sendToHSIds, new DumpMessage());
}
}
hostLog.warn("" + who + ": most recent SP handle: " + getCurrentTxnId() + " " +
TxnEgo.txnIdToString(getCurrentTxnId()));
hostLog.warn("" + who + ": outstanding txns: " + m_outstandingTxns.keySet() + " " +
TxnEgo.txnIdCollectionToString(m_outstandingTxns.keySet()));
hostLog.warn("" + who + ": TransactionTaskQueue: " + m_pendingTasks.toString());
if (m_duplicateCounters.size() > 0) {
hostLog.warn("" + who + ": duplicate counters: ");
for (Entry<DuplicateCounterKey, DuplicateCounter> e : m_duplicateCounters.entrySet()) {
hostLog.warn("\t" + who + ": " + e.getKey().toString() + ": " + e.getValue().toString());
}
}
}
@Override
public void setCommandLog(CommandLog cl) {
m_cl = cl;
}
@Override
public void enableWritingIv2FaultLog()
{
m_replayComplete = true;
writeIv2ViableReplayEntry();
}
/**
* If appropriate, cause the initiator to write the viable replay set to the command log
* Use when it's unclear whether the caller is the leader or a replica; the right thing will happen.
*/
void writeIv2ViableReplayEntry()
{
if (m_replayComplete) {
if (m_isLeader) {
// write the viable set locally
long faultSpHandle = advanceTxnEgo().getTxnId();
writeIv2ViableReplayEntryInternal(faultSpHandle);
// Generate Iv2LogFault message and send it to replicas
Iv2LogFaultMessage faultMsg = new Iv2LogFaultMessage(faultSpHandle);
m_mailbox.send(m_sendToHSIds,
faultMsg);
}
}
}
/**
* Write the viable replay set to the command log with the provided SP Handle
*/
void writeIv2ViableReplayEntryInternal(long spHandle)
{
if (m_replayComplete) {
m_cl.logIv2Fault(m_mailbox.getHSId(), new HashSet<Long>(m_replicaHSIds), m_partitionId,
spHandle);
}
}
@Override
public CountDownLatch snapshotCompleted(SnapshotCompletionEvent event)
{
if (event.truncationSnapshot) {
synchronized(m_lock) {
writeIv2ViableReplayEntry();
}
}
return new CountDownLatch(0);
}
}
|
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.Time;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import org.voltcore.messaging.HostMessenger.Config;
import org.voltdb.CLIConfig;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import au.com.bytecode.opencsv_voltpatches.CSVReader;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a table
* (or pass it to any stored proc, but ignoring any result other than the success code.).
*
* TODO:
* - Nulls are not handled (or at least I didn't test them).
* - Assumes localhost
* - Assumes no username/password
* - Usage help is ugly and cryptic: options are listed but not described.
* - No associated test suite.
* - Forces JVM into UTC. All input date TZs assumed to be GMT+0
* - Requires canonical JDBC SQL timestamp format
*/
class CSVLoader {
public synchronized static void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
}
private static final AtomicLong inCount = new AtomicLong(0);
private static final AtomicLong outCount = new AtomicLong(0);
private static int reportEveryNRows = 10000;
private static int waitSeconds = 10;
final CSVConfig config;
public static final String invaliderowsfile = "invalidrows.csv";
public static final String reportfile = "CSVLoaderReport.log";
public static final String logfile = "CSVLoaderLog.log";
private static String insertProcedure = "";
private static Map <Long,String> errorLines = new TreeMap<Long,String>();
private static final class MyCallback implements ProcedureCallback {
private final long m_lineNum;
private final CSVConfig mycfg;
MyCallback(long lineNumber, CSVConfig cfg)
{
m_lineNum = lineNumber;
mycfg = cfg;
}
@Override
public void clientCallback(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
System.err.println(response.getStatusString());
System.err.println("<xin>Stop at line " + m_lineNum);
synchronized (errorLines) {
if (!errorLines.containsKey(m_lineNum)) {
errorLines.put(m_lineNum, response.getStatusString());
}
if (errorLines.size() >= mycfg.abortfailurecount) {
System.err.println("The number of Failure row data exceeds " + mycfg.abortfailurecount);
System.exit(1);
}
}
return;
}
long currentCount = inCount.incrementAndGet();
System.out.println("Put line " + inCount.get() + " to databse");
if (currentCount % reportEveryNRows == 0) {
System.out.println("Inserted " + currentCount + " rows");
}
}
}
private static class CSVConfig extends CLIConfig {
@Option(desc = "directory path to produce report files.")
String inputfile = "";
@Option(desc = "procedure name to insert the data into the database.")
String procedurename = "";
@Option(desc = "insert the data into database by TABLENAME.INSERT procedure by default.")
String tablename = "";
@Option(desc = "Skip empty records in the csv file if this parameter is set.")
boolean skipEmptyRecords = false;
@Option(desc = "Trim whitespace in each line of the csv file if this parameter is set.")
boolean trimWhiteSpace = false;
@Option(desc = "Maximum rows to be read of the csv file.")
int limitrows = Integer.MAX_VALUE;
@Option(desc = "directory path to produce report files.")
String reportdir ="./";
@Option(desc = "")
int abortfailurecount = 100;
@Override
public void validate() {
if (abortfailurecount <= 0) exitWithMessageAndUsage("");
// add more checking
if (procedurename.equals("") && tablename.equals("") )
exitWithMessageAndUsage("procedure name or a table name required");
if (!procedurename.equals("") && !tablename.equals("") )
exitWithMessageAndUsage("Only a procedure name or a table name required, pass only one please");
}
}
public CSVLoader (CSVConfig cfg) {
this.config = cfg;
if(!config.tablename.equals("")) {
insertProcedure = config.tablename + ".insert";
} else {
insertProcedure = config.procedurename;
}
}
public void run() {
int waits = 0;
int shortWaits = 0;
try {
final CSVReader reader = new CSVReader(new FileReader(config.inputfile));
ProcedureCallback cb = null;
final Client client = ClientFactory.createClient();
client.createConnection("localhost");
boolean lastOK = true;
String line[] = null;
while ((config.limitrows-- > 0) && (line = reader.readNext()) != null) {
outCount.incrementAndGet();
boolean queued = false;
while (queued == false) {
String[] correctedLine = line;
cb = new MyCallback(outCount.get(), config);
// This message will be removed later
// print out the parameters right now
// String msg = "<xin>params: ";
// for (int i=0; i < correctedLine.length; i++) {
// msg += correctedLine[i] + ",";
// System.out.println(msg);
String lineCheckResult;
if( (lineCheckResult = checkLineFormat(correctedLine, client))!= null){
System.err.println("Stop at line " + (outCount.get()));
synchronized (errorLines) {
if (!errorLines.containsKey(outCount.get())) {
errorLines.put(outCount.get(),lineCheckResult);
}
if (errorLines.size() >= config.abortfailurecount) {
System.err.println("The number of Failure row data exceeds " + config.abortfailurecount);
System.exit(1);
}
}
break;
}
queued = client.callProcedure(cb, insertProcedure, (Object[])correctedLine);
if (queued == false) {
++waits;
if (lastOK == false) {
++shortWaits;
}
Thread.sleep(waitSeconds);
}
lastOK = queued;
}
}
reader.close();
client.drain();
client.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Inserted " + outCount.get() + " and acknowledged " + inCount.get() + " rows (final)");
if (waits > 0) {
System.out.println("Waited " + waits + " times");
if (shortWaits > 0) {
System.out.println("Waited too briefly? " + shortWaits + " times");
}
}
//return inCount.get();
}
/**
* TODO(xin): add line number data into the callback and add the invalid line number
* into a list that will help us to produce a separate file to record the invalid line
* data in the csv file.
*
* Asynchronously invoking procedures to response the actual wrong line number and
* start from last wrong line in the csv file is not easy. You can not ensure the
* FIFO order of the callback.
* @param args
* @return long number of the actual rows acknowledged by the database server
*/
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("csv filename required");
System.exit(1);
}
long start = System.currentTimeMillis();
CSVConfig cfg = new CSVConfig();
cfg.parse(CSVLoader.class.getName(), args);
// TODO: talk about this feature with John later
if(cfg.inputfile.equals("")) {
cfg.inputfile = args[0];
}
CSVLoader loader = new CSVLoader(cfg);
loader.run();
loader.produceInvalidRowsFile();
long elapsedTimeMillis = System.currentTimeMillis()-start;
// Get elapsed time in seconds
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println("CSVLoader elaspsed: " + elapsedTimeSec + " seconds");
}
/**
* Check for each line
* TODO(zheng):
* Use the client handler to get the schema of the table, and then check the number of
* parameters it expects with the input line fragements.
* Check the following:
* 1.blank line
* 2.# of attributes in the insertion procedure
* And does other pre-checks...(figure out it later)
* @param linefragement
*/
private String checkLineFormat(Object[] linefragement, Client client ) {
String msg = "";
int columnCnt = 0;
VoltTable procInfo = null;
try {
procInfo = client.callProcedure("@SystemCatalog",
"PROCEDURECOLUMNS").getResults()[0];
while( procInfo.advanceRow() )
{
if( insertProcedure.matches( (String) procInfo.get("PROCEDURE_NAME", VoltType.STRING) ) )
{
columnCnt++;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if( linefragement.length == 0 )
{
if( config.skipEmptyRecords )
{
msg = "checkLineFormat Error: blank line";
return msg;
}
else
{
for( int i = 0; i < columnCnt; i++)
linefragement[ i ] = "";
return null;
}
}
if( linefragement.length != columnCnt )//# attributes not match
{
msg = "checkLineFormat Error: # of attributes do not match, # of attributes needed: "+columnCnt;
return msg;
}
else if( config.trimWhiteSpace )
{//trim white space in this line.
for(int i=0; i<linefragement.length;i++)
{
linefragement[i] = ((String)linefragement[i]).replaceAll( "\\s+", "" );
}
}
return null;
}
/**
* TODO(xin): produce the invalid row file from
* Bulk the flush later...
* @param inputFile
*/
private void produceInvalidRowsFile() {
System.out.println("All the invalid row numbers are:" + errorLines.keySet());
String line = "";
// TODO: add the inputFileName to the outputFileName
String path_invaliderowsfile = config.reportdir + CSVLoader.invaliderowsfile;
String path_logfile = config.reportdir + CSVLoader.logfile;
String path_reportfile = config.reportdir + CSVLoader.reportfile;
int bulkflush = 100; // by default right now
try {
BufferedReader csvfile = new BufferedReader(new FileReader(config.inputfile));
BufferedWriter out_invaliderowfile = new BufferedWriter(new FileWriter(path_invaliderowsfile));
BufferedWriter out_logfile = new BufferedWriter(new FileWriter(path_logfile));
BufferedWriter out_reportfile = new BufferedWriter(new FileWriter(path_reportfile));
long linect = 0;
for (Long irow : errorLines.keySet()) {
while ((line = csvfile.readLine()) != null) {
if (++linect == irow) {
String message = "invalid line " + irow + ": " + line + "\n";
System.err.print(message);
out_invaliderowfile.write(line + "\n");
out_logfile.write(message + errorLines.get(irow).toString() + "\n");
break;
}
}
if (linect % bulkflush == 0) {
out_invaliderowfile.flush();
out_logfile.flush();
}
}
out_reportfile.write("Number of failed tuples:" + errorLines.size() + "\n");
out_reportfile.write("Number of acknowledged tuples:" + inCount.get() + "\n");
out_reportfile.write("Number of loaded tuples:" + (outCount.get() - errorLines.size()) + "\n");
// TODO(xin): Add more report message
out_invaliderowfile.flush();
out_logfile.flush();
out_reportfile.flush();
out_invaliderowfile.close();
out_logfile.close();
out_reportfile.close();
} catch (FileNotFoundException e) {
System.err.println("CSV file '" + config.inputfile
+ "' could not be found.");
} catch (Exception x) {
System.err.println(x.getMessage());
}
}
}
|
package org.voltdb.utils;
import java.io.*;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.voltdb.client.*;
import au.com.bytecode.opencsv_voltpatches.CSVReader;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a table
* (or pass it to any stored proc, but ignoring any result other than the success code.).
*
* TODO:
* - Nulls are not handled (or at least I didn't test them).
* - Assumes localhost
* - Assumes no username/password
* - Usage help is ugly and cryptic: options are listed but not described.
* - No associated test suite.
* - Forces JVM into UTC. All input date TZs assumed to be GMT+0
* - Requires canonical JDBC SQL timestamp format
*/
class CSVLoader {
public synchronized static void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
}
private static final AtomicLong inCount = new AtomicLong(0);
private static final AtomicLong outCount = new AtomicLong(0);
private static int reportEveryNRows = 10000;
private static int limitRows = Integer.MAX_VALUE;
private static int skipRows = 0;
private static int auditRows = 0;
private static int waitSeconds = 10;
private static boolean stripQuotes = false;
private static int[] colProjection = null;
private static final class MyCallback implements ProcedureCallback {
private final long m_sentCount;
MyCallback(long sent)
{
m_sentCount = sent;
}
@Override
public void clientCallback(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
if (m_sentCount == 0) {
System.err.print("Line ~" + inCount.get() + "-" + outCount.get() + ":");
} else {
System.err.print("Line " + m_sentCount + ":");
}
System.err.println(response.getStatusString());
System.exit(1);
}
long currentCount = inCount.incrementAndGet();
if (currentCount % reportEveryNRows == 0) {
System.out.println("Inserted " + currentCount + " rows");
}
}
}
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Two arguments, csv filename and insert procedure name, required");
System.exit(1);
}
final String filename = args[0];
final String insertProcedure = args[1];
int argsUsed = 2;
processCommandLineOptions(argsUsed, args);
int waits = 0;
int shortWaits = 0;
try {
final CSVReader reader = new CSVReader(new FileReader(filename));
final ProcedureCallback oneCallbackFitsAll = new MyCallback(0);
ProcedureCallback cb = oneCallbackFitsAll;
final Client client = ClientFactory.createClient();
client.createConnection("localhost");
boolean lastOK = true;
String line[] = null;
for (int i = 0; i < skipRows; ++i) {
reader.readNext();
// Keep these sync'ed with line numbers.
outCount.incrementAndGet();
inCount.incrementAndGet();
}
while ((limitRows-- > 0) && (line = reader.readNext()) != null) {
long counter = outCount.incrementAndGet();
boolean queued = false;
while (queued == false) {
String[] correctedLine = line;
if (colProjection != null) {
correctedLine = projectColumns(colProjection, correctedLine);
}
if (stripQuotes) {
correctedLine = stripMatchingColumnQuotes(correctedLine);
}
if (auditRows > 0) {
--auditRows;
System.err.println(joinIntoString(", ", line));
System.err.println(joinIntoString(", ", correctedLine));
System.err.println("
cb = new MyCallback(counter);
} else {
cb = oneCallbackFitsAll;
}
queued = client.callProcedure(cb, insertProcedure, (Object[])correctedLine);
if (queued == false) {
++waits;
if (lastOK == false) {
++shortWaits;
}
Thread.sleep(waitSeconds);
}
lastOK = queued;
}
}
reader.close();
client.drain();
client.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Inserted " + (outCount.get() - skipRows) + " and acknowledged " + (inCount.get() - skipRows) + " rows (final)");
if (waits > 0) {
System.out.println("Waited " + waits + " times");
if (shortWaits > 0) {
System.out.println("Waited too briefly? " + shortWaits + " times");
}
}
}
private static void processCommandLineOptions(int argsUsed, String args[]) {
final String columnsMatch = "--columns";
final String stripMatch = "--stripquotes";
final String waitMatch = "--wait";
final String auditMatch = "--audit";
final String limitMatch = "--limit";
final String skipMatch = "--skip";
final String reportMatch = "--report";
final String columnsStyle = "comma-separated-zero-based-column-numbers";
while (argsUsed < args.length) {
final String optionPrefix = args[argsUsed++];
if (optionPrefix.equalsIgnoreCase(columnsMatch)) {
if (argsUsed < args.length) {
final String colsListed = args[argsUsed++];
final String[] cols = colsListed.split(",");
if (cols != null && cols.length > 0) {
colProjection = new int[cols.length];
for (int i = 0; i < cols.length; i++) {
try {
colProjection[i] = Integer.parseInt(cols[i]);
continue;
} catch (NumberFormatException e) {
}
}
if (colProjection.length == cols.length) {
continue;
}
}
}
} else if (optionPrefix.equalsIgnoreCase(waitMatch)) {
if (argsUsed < args.length) {
try {
waitSeconds = Integer.parseInt(args[argsUsed++]);
if (waitSeconds >= 0) {
continue;
}
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(auditMatch)) {
if (argsUsed < args.length) {
try {
auditRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(limitMatch)) {
if (argsUsed < args.length) {
try {
limitRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(skipMatch)) {
if (argsUsed < args.length) {
try {
skipRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(reportMatch)) {
if (argsUsed < args.length) {
try {
reportEveryNRows = Integer.parseInt(args[argsUsed++]);
if (reportEveryNRows > 0) {
continue;
}
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(stripMatch)) {
stripQuotes = true;
continue;
}
// Fall through means an error.
System.err.println("Option arguments are invalid, expected csv filename and insert procedure name (required) and optionally" +
" '" + columnsMatch + " " + columnsStyle + "'," +
" '" + waitMatch + " s (default=10 seconds)'," +
" '" + auditMatch + " n (default=0 rows)'," +
" '" + limitMatch + " n (default=all rows)'," +
" '" + skipMatch + " n (default=0 rows)'," +
" '" + reportMatch + " n (default=10000)'," +
" and/or '" + stripMatch + " (disabled by default)'");
System.exit(2);
}
}
private static String[] stripMatchingColumnQuotes(String[] line) {
final String[] strippedLine = new String[line.length];
Pattern pattern = Pattern.compile("^([\"'])(.*)\\1$");
for (int i = 0; i < line.length; i++) {
Matcher matcher = pattern.matcher(line[i]);
if (matcher.find()) {
strippedLine[i] = matcher.group(2);
} else {
strippedLine[i] = line[i];
}
}
return strippedLine;
}
private static String[] projectColumns(int[] colSelection, String[] line) {
final String[] projectedLine = new String[colSelection.length];
for (int i = 0; i < projectedLine.length; i++) {
projectedLine[i] = line[colSelection[i]];
}
return projectedLine;
}
// This function borrowed/mutated from http:/stackoverflow.com/questions/1515437
static String joinIntoString(String glue, Object... elements)
{
int k = elements.length;
if (k == 0) {
return null;
}
StringBuilder out = new StringBuilder();
out.append(elements[0].toString());
for (int i = 1; i < k; ++i) {
out.append(glue).append(elements[i]);
}
return out.toString();
}
// This function borrowed/mutated from http:/stackoverflow.com/questions/1515437
static String joinIntoString(String glue, String... elements)
{
int k = elements.length;
if (k == 0) {
return null;
}
StringBuilder out = new StringBuilder();
out.append(elements[0]);
for (int i = 1; i < k; ++i) {
out.append(glue).append(elements[i]);
}
return out.toString();
}
}
|
package infn.bed.util;
import infn.bed.geometry.GeometricConstants;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* Parses a calibration file.
*
* @author Angelo Licastro
*/
public class CalibrationFileParser {
/**
* An instance of the File object.
*/
private final File file;
/**
* The item (scintillator bar or veto).
*/
private final String item;
/**
* The item (scintillator bar or veto) identification number.
*/
private final int id;
/**
* An ArrayList of item (scintillator bar or veto) tags.
*/
private final ArrayList<String> validationArrayList = new ArrayList<>();
/**
* The comment initializer.
*/
private final String comment = Character.toString((char)35);
/**
* The token delimiter.
*/
private final String delimiter = Character.toString((char)32);
/**
* The effective velocity.
*/
private double v_eff;
/**
* The left ADC (analog-to-digital converter) conversion factor.
*/
private double a_left;
/**
* The right ADC (analog-to-digital converter) conversion factor.
*/
private double a_right;
/**
* The attenuation length.
*/
private double lambda;
/**
* The left shift.
*/
private double delta_L;
/**
* The right shift.
*/
private double delta_R;
/**
* The left TDC (time-to-digital converter) conversion factor.
*/
private double t_left;
/**
* The right TDC (time-to-digital converter) conversion factor.
*/
private double t_right;
/**
* The item (scintillator bar or veto) length.
*/
private double l;
/**
* The constructor.
*
* <p>
* NOTE: The constructor must call _parseConfigurationFile(). Additionally, validation is not intrinsic to _parseConfigurationFile().
* </p>
*
* @param file The file to parse.
* @param item The item name (b for scintillator bar or v for veto).
* @param id The identification number of the item.
* @throws InvalidCalibrationFileException If _isValidCalibrationFile() returns false, an unchecked exception is thrown.
*/
public CalibrationFileParser(File file, String item, int id) {
this.file = file;
this.item = item;
this.id = id;
_populateValidationArray();
if (_isValidCalibrationFile()) {
_parseCalibrationFile();
} else {
throw new InvalidCalibrationFileException();
}
}
/**
* Populates validationArrayList for use in _isValidCalibrationFile().
*/
private void _populateValidationArray() {
for (int i = 1; i < GeometricConstants.BARS + 1; i++) {
validationArrayList.add("b" + i);
}
for (int i = 1; i < GeometricConstants.CRYSTALS + 1; i++) {
validationArrayList.add("v" + i);
}
for (int i = 1 + GeometricConstants.CRYSTALS; i < GeometricConstants.VETOES + 1; i++) {
validationArrayList.add("v" + i);
}
}
/**
* Formats a string by trimming excessive whitespace.
*
* @param s The string to be formatted.
* @return The formatted string.
*/
private String _format(String s) {
return s.replaceAll("\\s+", Character.toString((char)32)).trim();
}
/**
* Validates the calibration file.
*
* @return true if the calibration file is valid, false otherwise.
*/
private boolean _isValidCalibrationFile() {
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int i = 0;
while (i < validationArrayList.size()) {
String s = bufferedReader.readLine();
if (!s.startsWith(comment) && s.length() > 0) {
String tag = _format(s).split(delimiter)[0];
if (!(validationArrayList.get(i).equals(tag))) {
return false;
}
i++;
}
}
bufferedReader.close();
} catch (NullPointerException e) {
throw new InvalidCalibrationFileException();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* Parses the calibration file.
*/
private void _parseCalibrationFile() {
if (file == null || !file.exists()) {
// Oops. Something went wrong.
} else {
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String tag = item + id;
boolean found = false;
while (!found) {
String s = bufferedReader.readLine();
if (s == null) {
break;
} else {
if (!s.startsWith(comment) && s.length() > 0) {
String[] tokens = _format(s).split(delimiter);
if (tokens[0].equals(tag)) {
found = true;
v_eff = Double.parseDouble(tokens[1]);
a_left = Double.parseDouble(tokens[2]);
a_right = Double.parseDouble(tokens[3]);
lambda = Double.parseDouble(tokens[4]);
delta_L = Double.parseDouble(tokens[5]);
delta_R = Double.parseDouble(tokens[6]);
t_left = Double.parseDouble(tokens[7]);
t_right = Double.parseDouble(tokens[8]);
l = Double.parseDouble(tokens[9]);
bufferedReader.close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Returns the effective velocity.
*
* @return v_eff The effective velocity;
*/
public double getEffectiveVelocity() {
return v_eff;
}
/**
* Returns the left ADC (analog-to-digital converter) conversion factor.
*
* @return a_left The left ADC (analog-to-digital converter) conversion factor.
*/
public double getLeftADCConversionFactor() {
return a_left;
}
/**
* Returns the right ADC (analog-to-digital converter) conversion factor.
*
* @return a_right The right ADC (analog-to-digital converter) conversion factor.
*/
public double getRightADCConversionFactor() {
return a_right;
}
/**
* Returns the attenuation length.
*
* @return lambda The attenuation length.
*/
public double getAttenuationLength() {
return lambda;
}
/**
* Returns the left shift.
*
* @return delta_L The left shift.
*/
public double getLeftShift() {
return delta_L;
}
/**
* Returns the right shift.
*
* @return delta_R The right shift.
*/
public double getRightShift() {
return delta_R;
}
/**
* Returns the left TDC (time-to-digital converter) conversion factor.
*
* @return t_left The left TDC (time-to-digital converter) conversion factor.
*/
public double getLeftTDCConversionFactor() {
return t_left;
}
/**
* Returns the right TDC (time-to-digital converter) conversion factor.
*
* @return t_right The right TDC (time-to-digital converter) conversion factor.
*/
public double getRightTDCConversionFactor() {
return t_right;
}
/**
* Returns the item (scintillator bar or veto) length.
*
* @return l The item (scintillator bar or veto) length.
*/
public double getItemLength() {
return l;
}
}
|
package io.flutter.run;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.concurrency.JobScheduler;
import com.intellij.ide.actions.SaveAllAction;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.LightweightHint;
import com.intellij.util.ui.UIUtil;
import com.jetbrains.lang.dart.ide.errorTreeView.DartProblemsView;
import com.jetbrains.lang.dart.psi.DartFile;
import icons.FlutterIcons;
import io.flutter.FlutterConstants;
import io.flutter.FlutterUtils;
import io.flutter.actions.FlutterAppAction;
import io.flutter.actions.ProjectActions;
import io.flutter.actions.ReloadFlutterApp;
import io.flutter.run.common.RunMode;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.settings.FlutterSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* Handle the mechanics of performing a hot reload on file save.
*/
public class FlutterReloadManager {
private static final Logger LOG = Logger.getInstance(FlutterReloadManager.class);
private static final Map<String, NotificationGroup> toolWindowNotificationGroups = new HashMap<>();
private static NotificationGroup getNotificationGroup(String toolWindowId) {
if (!toolWindowNotificationGroups.containsKey(toolWindowId)) {
final NotificationGroup notificationGroup = NotificationGroup.toolWindowGroup("Flutter " + toolWindowId, toolWindowId, false);
toolWindowNotificationGroups.put(toolWindowId, notificationGroup);
}
return toolWindowNotificationGroups.get(toolWindowId);
}
private final @NotNull Project myProject;
private final FlutterSettings mySettings;
private Notification lastNotification;
/**
* Initialize the reload manager for the given project.
*/
public static void init(@NotNull Project project) {
// Call getInstance() will init FlutterReloadManager for the given project.
getInstance(project);
}
public static FlutterReloadManager getInstance(@NotNull Project project) {
return ServiceManager.getService(project, FlutterReloadManager.class);
}
private FlutterReloadManager(@NotNull Project project) {
this.myProject = project;
this.mySettings = FlutterSettings.getInstance();
ActionManagerEx.getInstanceEx().addAnActionListener(new AnActionListener.Adapter() {
private @Nullable Project eventProject;
private @Nullable Editor eventEditor;
public void beforeActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) {
if (!(action instanceof SaveAllAction)) {
return;
}
// Save the current project value here. If we access later (in afterActionPerformed), we can get
// exceptions if another event occurs before afterActionPerformed is called.
try {
eventProject = event.getProject();
eventEditor = CommonDataKeys.EDITOR.getData(event.getDataContext());
}
catch (Throwable t) {
// A catch-all, so any exceptions don't bubble through to the users.
LOG.warn("Exception from FlutterReloadManager", t);
}
}
@Override
public void afterActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) {
if (!(action instanceof SaveAllAction)) {
return;
}
// If this save all action is not for the current project, return.
if (myProject != eventProject) {
return;
}
try {
handleSaveAllNotification(eventEditor);
}
catch (Throwable t) {
FlutterUtils.warn(LOG, "Exception from hot reload on save", t);
}
}
}, project);
}
private void handleSaveAllNotification(@Nullable Editor editor) {
if (!mySettings.isReloadOnSave() || editor == null) {
return;
}
final AnAction reloadAction = ProjectActions.getAction(myProject, ReloadFlutterApp.ID);
final FlutterApp app = getApp(reloadAction);
if (app == null) {
return;
}
if (!app.getLaunchMode().supportsReload() || !app.appSupportsHotReload()) {
return;
}
if (!app.isStarted() || app.isReloading()) {
return;
}
// Transition the app to an about-to-reload state.
final FlutterApp.State previousAppState = app.transitionStartingHotReload();
JobScheduler.getScheduler().schedule(() -> {
clearLastNotification();
if (!app.isConnected()) {
return;
}
// Don't reload if we find structural errors with the current file.
if (hasErrorsInFile(editor.getDocument())) {
app.cancelHotReloadState(previousAppState);
showAnalysisNotification("Reload not performed", "Analysis issues found", true);
return;
}
final Notification notification = showRunNotification(app, null, "Reloading…", false);
final long startTime = System.currentTimeMillis();
app.performHotReload(true, FlutterConstants.RELOAD_REASON_SAVE).thenAccept(result -> {
if (!result.ok()) {
notification.expire();
showRunNotification(app, "Hot Reload Error", result.getMessage(), true);
}
else {
// Make sure the reloading message is displayed for at least 2 seconds (so it doesn't just flash by).
final long delay = Math.max(0, 2000 - (System.currentTimeMillis() - startTime));
JobScheduler.getScheduler().schedule(() -> UIUtil.invokeLaterIfNeeded(() -> {
notification.expire();
if (isLastNotification(notification)) {
removeRunNotifications(app);
}
}), delay, TimeUnit.MILLISECONDS);
}
});
}, 0, TimeUnit.MILLISECONDS);
}
private void reloadApp(@NotNull FlutterApp app, @NotNull String reason) {
if (app.isStarted()) {
app.performHotReload(true, reason).thenAccept(result -> {
if (!result.ok()) {
showRunNotification(app, "Hot Reload Error", result.getMessage(), true);
}
}).exceptionally(throwable -> {
showRunNotification(app, "Hot Reload Error", throwable.getMessage(), true);
return null;
});
}
}
public void saveAllAndReload(@NotNull FlutterApp app, @NotNull String reason) {
FileDocumentManager.getInstance().saveAllDocuments();
clearLastNotification();
reloadApp(app, reason);
}
public void saveAllAndReloadAll(@NotNull List<FlutterApp> appsToReload, @NotNull String reason) {
FileDocumentManager.getInstance().saveAllDocuments();
clearLastNotification();
for (FlutterApp app : appsToReload) {
reloadApp(app, reason);
}
}
private void restartApp(@NotNull FlutterApp app, @NotNull String reason) {
if (app.isStarted()) {
app.performRestartApp(reason).thenAccept(result -> {
if (!result.ok()) {
showRunNotification(app, "Hot Restart Error", result.getMessage(), true);
}
}).exceptionally(throwable -> {
showRunNotification(app, "Hot Restart Error", throwable.getMessage(), true);
return null;
});
final FlutterDevice device = app.device();
if (device != null) {
device.bringToFront();
}
}
}
public void saveAllAndRestart(@NotNull FlutterApp app, @NotNull String reason) {
FileDocumentManager.getInstance().saveAllDocuments();
clearLastNotification();
restartApp(app, reason);
}
public void saveAllAndRestartAll(@NotNull List<FlutterApp> appsToRestart, @NotNull String reason) {
FileDocumentManager.getInstance().saveAllDocuments();
clearLastNotification();
for (FlutterApp app : appsToRestart) {
restartApp(app, reason);
}
}
@Nullable
private FlutterApp getApp(AnAction reloadAction) {
if (reloadAction instanceof FlutterAppAction) {
return ((FlutterAppAction)reloadAction).getApp();
}
else {
return null;
}
}
private void showAnalysisNotification(@NotNull String title, @NotNull String content, boolean isError) {
if (!ToolWindowManager.getInstance(myProject).getToolWindow(DartProblemsView.TOOLWINDOW_ID).isVisible()) {
content += " (<a href='open.analysis.view'>view issues</a>)";
}
final NotificationGroup notificationGroup = getNotificationGroup(DartProblemsView.TOOLWINDOW_ID);
final Notification notification =
notificationGroup.createNotification(
title, content, isError ? NotificationType.ERROR : NotificationType.INFORMATION,
new NotificationListener.Adapter() {
@Override
protected void hyperlinkActivated(@NotNull final Notification notification, @NotNull final HyperlinkEvent e) {
notification.expire();
ToolWindowManager.getInstance(myProject).getToolWindow(DartProblemsView.TOOLWINDOW_ID).activate(null);
}
});
notification.setIcon(FlutterIcons.Flutter);
notification.notify(myProject);
lastNotification = notification;
}
private Notification showRunNotification(@NotNull FlutterApp app, @Nullable String title, @NotNull String content, boolean isError) {
final String toolWindowId = app.getMode() == RunMode.DEBUG ? ToolWindowId.DEBUG : ToolWindowId.RUN;
final NotificationGroup notificationGroup = getNotificationGroup(toolWindowId);
final Notification notification;
if (title == null) {
notification = notificationGroup.createNotification(content, isError ? NotificationType.ERROR : NotificationType.INFORMATION);
}
else {
notification =
notificationGroup.createNotification(title, content, isError ? NotificationType.ERROR : NotificationType.INFORMATION, null);
}
notification.setIcon(FlutterIcons.Flutter);
notification.notify(myProject);
lastNotification = notification;
return notification;
}
private boolean isLastNotification(final Notification notification) {
return notification == lastNotification;
}
private void clearLastNotification() {
lastNotification = null;
}
private void removeRunNotifications(FlutterApp app) {
final String toolWindowId = app.getMode() == RunMode.DEBUG ? ToolWindowId.DEBUG : ToolWindowId.RUN;
final Balloon balloon = ToolWindowManager.getInstance(myProject).getToolWindowBalloon(toolWindowId);
if (balloon != null) {
balloon.hide();
}
}
private boolean hasErrorsInFile(@NotNull Document document) {
// We use the IntelliJ parser and look for syntax errors in the current document.
// We block reload if we find issues in the immediate file. We don't block reload if there
// are analysis issues in other files; the compilation errors from the flutter tool
// will indicate to the user where the problems are.
final PsiErrorElement firstError = ApplicationManager.getApplication().runReadAction((Computable<PsiErrorElement>)() -> {
final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
if (psiFile instanceof DartFile) {
return PsiTreeUtil.findChildOfType(psiFile, PsiErrorElement.class, false);
}
else {
return null;
}
});
return firstError != null;
}
private LightweightHint showEditorHint(@NotNull Editor editor, String message, boolean isError) {
final AtomicReference<LightweightHint> ref = new AtomicReference<>();
ApplicationManager.getApplication().invokeAndWait(() -> {
final JComponent component = isError
? HintUtil.createErrorLabel(message)
: HintUtil.createInformationLabel(message);
final LightweightHint hint = new LightweightHint(component);
ref.set(hint);
HintManagerImpl.getInstanceImpl().showEditorHint(
hint, editor, HintManager.UNDER,
HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING | HintManager.HIDE_BY_OTHER_HINT,
isError ? 0 : 3000, false);
});
return ref.get();
}
}
|
package it.csttech.dbloader.test;
import java.lang.reflect.Method;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import it.csttech.dbloader.orm.BeanInfo;
import it.csttech.dbloader.entities.Record;
/**
* Preliminary version!
* (WIP)
*
*/
public class MockRecord {
private final BeanInfo beanInfo;
private Random random = new Random();
// Map wich associate to each setters its nextrandom method (
private final Map<Method, RandomOperation> setterRandomMap;
// l'estensione all' extract di file dovrebbe fare per ogni colonna un
// parse.
// sembra un'associazione funzionale colonna <-> metodo per queste cose devo
// fare lo pseudo paradigma funzionale con lambda o classi con unico metodo
// (vedi tutorial)
// non voglio testare ogni volta il tipo da settare!
public MockRecord(BeanInfo beanInfo) throws Exception{
this.beanInfo = beanInfo;
setterRandomMap = generateMapping();
}
/**
* voglio generare un mapping da metodi a metodi. ad ogni setter voglio
* associare un metodo di random che genera il giusto argument in modo
* random
* //TODO: specify exception
* @return
*/
private Map<Method, RandomOperation> generateMapping() throws Exception {
List<Method> setterList = new ArrayList<Method>(beanInfo.getSetters().values());
Map<Method, RandomOperation> mapping = new HashMap<Method, RandomOperation>();
for (Method m : setterList) {
Class<?> argType = m.getParameterTypes()[0];
mapping.put(m, objRelation(argType));
}
return mapping;
}
public Object next() {
Object record = null ;
try{
record = beanInfo.getInstance();
for (Method m : setterRandomMap.keySet())
m.invoke(record, setterRandomMap.get(m).next());
} catch (Exception ex){
ex.printStackTrace();
}
return record;
}
/**
* Discarded stupid non functional method
* //TODO: specify exception
* @param clazz
* @return
*/
private Object RandomObject(Class<?> clazz) throws Exception{
if (clazz.equals(boolean.class)) {
return random.nextBoolean();
} else if (clazz.equals(int.class)) {
return random.nextInt();
} else if (clazz.equals(long.class)) {
return random.nextLong();
} else if (clazz.equals(float.class)) {
return random.nextFloat();
} else if (clazz.equals(double.class)) {
return random.nextDouble();
} else if (clazz.equals(Date.class)) {
return new Date(random.nextLong());
} else
throw new Exception();
}
private RandomOperation objRelation(Class<?> clazz) throws Exception {
System.out.println(clazz);
if ( clazz.equals(boolean.class)){
return () -> random.nextBoolean();
}
else if ( clazz.equals(int.class)){
return () -> random.nextInt();
}
else if ( clazz.equals(long.class)){
return () -> random.nextLong();
}
else if (clazz.equals(float.class)){
return () -> random.nextFloat();
}
else if (clazz.equals(double.class)){
return () -> random.nextDouble();
}
else if(clazz.equals(Date.class)){
return () -> new Date(random.nextLong());
}
else if(clazz.equals(String.class)){
return () -> {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
};
}
else throw new Exception(); //TODO: specify exception
}
public static void main(String[] args) {
try {
BeanInfo beanInfo = new BeanInfo(Record.class);
MockRecord mockRecord = new MockRecord(beanInfo);
System.out.println(mockRecord.next());
} catch ( Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Ugly Naive functional part
interface RandomOperation {
public Object next();
}
}
|
package org.jaxen;
/** Implemented by classes that know how to resolve XPath function names and
* namespaces to implementations of these functions.
*
* <p>
* By using a custom <code>FunctionContext</code>, new or different
* functions may be installed and available to XPath expression writers.
* </p>
*
* @see XPathFunctionContext
*
* @author <a href="mailto:bob@werken.com">bob mcwhirter</a>
*/
public interface FunctionContext
{
/** An implementation should return a <code>Function</code> implementation object
* based on the namespace URI and local name of the function-call
* expression.
*
* <p>
* It must not use the prefix parameter to select an implementation,
* because a prefix could be bound to any namespace; the prefix parameter
* could be used in debugging output or other generated information.
* The prefix may otherwise be completely ignored.
* </p>
*
* @param namespaceURI the namespace URI to which the prefix parameter
* is bound in the XPath expression. If the function
* call expression had no prefix, the namespace URI
* is <code>null</code>.
* @param prefix the prefix that was used in the function call
* expression
* @param localName the local name of the function-call expression.
* If there is no prefix, then this is the whole
* name of the function.
*
* @return a Function implementation object.
* @throws UnresolvableException when the function cannot be resolved
*/
Function getFunction( String namespaceURI,
String prefix,
String localName ) throws UnresolvableException;
}
|
package org.apache.velocity.util;
import java.io.*;
import java.text.*;
import java.util.*;
public class Trace
{
/** Set via the trace property. */
public static final boolean ON = active();
/** The logging interface. */
private static final PrintWriter LOG = getLog();
/** Whether to log in detail. */
private static final boolean SHOW_DETAIL = showDetail();
/** String contained by the names of methods to be traced. */
private static final String PATTERN = getPattern();
/** Text which can be printed when entering a method. */
private static final String ENTER = "enter ";
/** Text which can be printed when leaving a method. */
private static final String LEAVE = "leave ";
/** Text to use for padding. */
private static final String PAD = " ";
/** The numerical format to use when printing floating point numbers. */
private static NumberFormat format = getFormat();
/** Entry per thread. */
private static Hashtable levels = new Hashtable();
/** Entry per method+thread. */
private static Hashtable timers = new Hashtable();
/** Entry per method. */
private static Hashtable totals = new Hashtable();
/** Sorts and formats totals in a manner suitable for printing. */
public static final synchronized String getFormattedTotals()
{
// Sort the data from high to low time used.
int i = 0;
TraceData data[] = new TraceData[totals.size()];
Enumeration e = totals.keys();
while (e.hasMoreElements())
{
String method = (String)e.nextElement();
TraceTotal t = (TraceTotal)totals.get(method);
data[i++] = new TraceData(method, t);
}
Arrays.sort(data);
StringBuffer buf = new StringBuffer(512);
buf.append("Trace Totals\n");
buf.append("
for (i = 0; i < data.length; i++)
{
buf.append(
pad(data[i].method, 32, false) + " " +
pad(Integer.toString(data[i].total.getCount()), 4, true) + " calls " +
pad(format.format(data[i].total.getTotal()), 8, true) + "s total " +
pad(format.format(data[i].total.getAverage()), 8, true) + "s avg.\n");
}
return buf.toString();
}
/** Pads/truncates a string. */
private static final String pad(String s, int len, boolean rightJustify)
{
if (s.length() > len)
s = s.substring(0, len-1) + '
int padding = len - s.length();
String pad = "";
for (int i = 0; i < padding; i++)
pad += " ";
if (rightJustify)
s = pad + s;
else
s = s + pad;
return s;
}
/** Resets the trace totals data. */
public static void reset()
{
totals.clear();
}
/** Begins trace of method. */
public static final void start(String method)
{
if (!doTrace(method))
return;
TraceKey key = new TraceKey(method);
Timer t = (Timer)timers.get(key);
if (t == null)
{
t = new Timer();
timers.put(key, t);
}
TraceLevel l = (TraceLevel)levels.get(key.threadName);
if (l == null)
{
l = new TraceLevel();
levels.put(key.threadName, l);
}
if (SHOW_DETAIL)
{
String pad = new String();
for (int i = 0; i < l.level; i++)
pad += PAD;
LOG.println(pad + ENTER + key);
}
l.level++;
t.start();
}
/** Ends trace of method. */
public static final void stop(String method)
{
if (!doTrace(method))
return;
TraceKey key = new TraceKey(method);
Timer t = (Timer)timers.get(key);
if (t == null)
{
System.err.println(
"Trace.stop: No trace started for " + key);
return;
}
t.stop();
TraceLevel l = (TraceLevel)levels.get(key.threadName);
if (l == null)
{
System.err.println(
"Trace.stop: Internal error; no level for thread "
+ key.threadName);
return;
}
l.level
if (SHOW_DETAIL)
{
String pad = new String();
for (int i = 0; i < l.level; i++)
pad += PAD;
LOG.println(pad + LEAVE + key + " " + t.getSeconds() + "s");
}
updateTotals(key.method, t.getSeconds());
}
/** Prints performance summary. */
public static final synchronized void printTotals()
{
printTotals(LOG);
}
/** Prints performance summary. */
public static final synchronized void printTotals(PrintStream ps)
{
printTotals(new PrintWriter(ps, true));
}
/** Prints performance summary. */
public static final synchronized void printTotals(PrintWriter writer)
{
writer.println("\n" + getFormattedTotals());
}
static final boolean active()
{
String property = System.getProperty("trace");
if (property != null)
return Boolean.valueOf(property).booleanValue();
else
return false;
}
static final boolean doTrace(String method)
{
return (PATTERN == null || method.indexOf(PATTERN) != -1);
}
static final NumberFormat getFormat()
{
NumberFormat format = NumberFormat.getInstance();
format.setMinimumFractionDigits(3);
format.setMaximumFractionDigits(3);
return format;
}
static final PrintWriter getLog()
{
String fileName = "";
try
{
fileName = System.getProperty("trace.log");
if (fileName != null && fileName.trim().length() > 0)
{
return new PrintWriter(new FileWriter(fileName, true), true);
}
}
catch (Exception e)
{
System.err.println("Can't open trace log: " +
new File(fileName).getAbsolutePath() + " : " + e);
}
return new PrintWriter(System.out, true);
}
static final String getPattern()
{
return System.getProperty("trace.pattern");
}
static final boolean showDetail()
{
String property = System.getProperty("trace.detail");
if (property != null)
return Boolean.valueOf(property).booleanValue();
else
return true;
}
static final synchronized void updateTotals(String method, double seconds)
{
TraceTotal t = (TraceTotal)totals.get(method);
if (t == null)
{
t = new TraceTotal();
totals.put(method, t);
}
t.add(seconds);
}
}
class TraceKey
{
String method;
String threadName;
TraceKey(String method)
{
this.method = method;
this.threadName = Thread.currentThread().getName();
}
public boolean equals(Object o)
{
return (this.getClass() == o.getClass()
&& this.method.equals(((TraceKey)o).method)
&& this.threadName.equals(((TraceKey)o).threadName));
}
public int hashCode()
{
return toString().hashCode();
}
public String toString()
{
return new String(method + "-" + threadName);
}
}
class TraceLevel
{
int level = 0;
}
class TraceData implements Comparable
{
String method;
TraceTotal total;
TraceData(String method, TraceTotal total)
{
this.method = method;
this.total = total;
}
public int compareTo(Object comp)
{
// Reverse order sort.
if (this.total.seconds < ((TraceData)comp).total.seconds)
return 1;
else if (this.total.seconds > ((TraceData)comp).total.seconds)
return -1;
else
return 0;
}
}
class TraceTotal
{
double seconds;
int count;
TraceTotal()
{
this.seconds = 0.0;
count = 0;
}
void add(double seconds)
{
this.seconds += seconds;
count++;
}
double getAverage()
{
return seconds / count;
}
int getCount()
{
return count;
}
double getTotal()
{
return seconds;
}
}
|
package view;
import java.util.ResourceBundle;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import model.LineData;
import model.TurtleData;
public class TurtleView {
private static final ResourceBundle myValues = ResourceBundle
.getBundle("resources/values/turtleview");
private Canvas myCanvas;
private GraphicsContext myGC;
private StackPane myLayers;
private Group myTurtles = new Group();
private Rectangle myBackground;
private Image turtleImage = new Image("images/plain-turtle-small.png");
private static final int WIDTH = Integer.parseInt(myValues
.getString("Width"));
private static final int HEIGHT = Integer.parseInt(myValues
.getString("Height"));
private static final int TURTLE_WIDTH = Integer.parseInt(myValues
.getString("TurtleWidth"));
private static final int TURTLE_HEIGHT = Integer.parseInt(myValues
.getString("TurtleHeight"));
// private static final int TURTLE_START_X = WIDTH / 2;
// private static final int TURTLE_START_Y = HEIGHT / 2;
private static final Color BACKGROUND_COLOR = Color.PURPLE;
private static final Color PEN_COLOR = Color.BLACK;
public TurtleView() {
myCanvas = new Canvas(WIDTH, HEIGHT);
myGC = myCanvas.getGraphicsContext2D();
myBackground = new Rectangle(WIDTH, HEIGHT);
setBackgroundColor(BACKGROUND_COLOR);
myLayers = new StackPane();
myLayers.getChildren().addAll(myBackground, myCanvas);//,myTurtles);
}
public void setPenColor(Color color) {
myGC.setFill(PEN_COLOR);
}
public void setBackgroundColor(Color color) {
myBackground.setFill(color);
}
// protected void addTurtle(int x, int y) {
// TurtleImage turtle = new TurtleImage(x, y, turtleImage);
// myTurtles.getChildren().add(turtle);
public Node getView() {
return myLayers;
}
public void setTurtleImage(Image img) {
turtleImage = img;
}
public void drawLines(LineData current) {
myGC.strokeLine(current.getStart().getX(), current.getStart().getY(),
current.getFinish().getX(), current.getFinish().getY());
}
public void drawTurtles(TurtleData current) {
// Image toDraw = new Image(turtleImage);
// TurtleImage toAdd = new TurtleImage(current.getX(), current.getY(),current.getHeading(), turtleImage);
// myTurtles.getChildren().add(toAdd);
myGC.drawImage(turtleImage, current.getX(), current.getY(),
TURTLE_WIDTH, TURTLE_HEIGHT);
}
}
|
package net.runelite.client.plugins.lowmemory;
import com.google.common.eventbus.Subscribe;
import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.events.GameStateChanged;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
@PluginDescriptor(
name = "Low Detail",
enabledByDefault = false
)
public class LowMemoryPlugin extends Plugin
{
@Inject
private Client client;
@Override
protected void startUp() throws Exception
{
if (client.getGameState() == GameState.LOGGED_IN)
{
client.changeMemoryMode(true);
}
}
@Override
protected void shutDown() throws Exception
{
client.changeMemoryMode(false);
}
@Subscribe
private void onGameStateChanged(GameStateChanged event)
{
if (event.getGameState() == GameState.LOGIN_SCREEN)
{
client.changeMemoryMode(true);
}
}
}
|
package net.runelite.client.ui.overlay.infobox;
import com.google.common.base.Strings;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import net.runelite.api.Client;
import net.runelite.client.config.RuneLiteConfig;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.InfoBoxComponent;
import net.runelite.client.ui.overlay.components.LayoutableRenderableEntity;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.tooltip.Tooltip;
import net.runelite.client.ui.overlay.tooltip.TooltipManager;
@Singleton
public class InfoBoxOverlay extends Overlay
{
private final PanelComponent panelComponent = new PanelComponent();
private final InfoBoxManager infoboxManager;
private final TooltipManager tooltipManager;
private final Provider<Client> clientProvider;
private final RuneLiteConfig config;
@Inject
private InfoBoxOverlay(
InfoBoxManager infoboxManager,
TooltipManager tooltipManager,
Provider<Client> clientProvider,
RuneLiteConfig config)
{
this.tooltipManager = tooltipManager;
this.infoboxManager = infoboxManager;
this.clientProvider = clientProvider;
this.config = config;
setPosition(OverlayPosition.TOP_LEFT);
panelComponent.setBackgroundColor(null);
panelComponent.setBorder(new Rectangle());
panelComponent.setGap(new Point(1, 1));
}
@Override
public Dimension render(Graphics2D graphics)
{
final List<InfoBox> infoBoxes = infoboxManager.getInfoBoxes();
if (infoBoxes.isEmpty())
{
return null;
}
panelComponent.getChildren().clear();
panelComponent.setWrapping(config.infoBoxWrap());
panelComponent.setOrientation(config.infoBoxVertical()
? PanelComponent.Orientation.VERTICAL
: PanelComponent.Orientation.HORIZONTAL);
panelComponent.setPreferredSize(new Dimension(config.infoBoxSize(), config.infoBoxSize()));
infoBoxes.forEach(box ->
{
final InfoBoxComponent infoBoxComponent = new InfoBoxComponent();
infoBoxComponent.setColor(box.getTextColor());
infoBoxComponent.setImage(box.getScaledImage());
infoBoxComponent.setText(box.getText());
infoBoxComponent.setTooltip(box.getTooltip());
panelComponent.getChildren().add(infoBoxComponent);
});
final Dimension dimension = panelComponent.render(graphics);
final Client client = clientProvider.get();
// Handle tooltips
if (client != null)
{
final Point mouse = new Point(client.getMouseCanvasPosition().getX(), client.getMouseCanvasPosition().getY());
for (final LayoutableRenderableEntity child : panelComponent.getChildren())
{
if (child instanceof InfoBoxComponent)
{
final InfoBoxComponent component = (InfoBoxComponent) child;
if (!Strings.isNullOrEmpty(component.getTooltip()))
{
final Rectangle intersectionRectangle = new Rectangle(component.getPreferredLocation(), component.getPreferredSize());
// Move the intersection based on overlay position
intersectionRectangle.translate(getBounds().x, getBounds().y);
// Move the intersection based on overlay "orientation"
final Point transformed = OverlayUtil.transformPosition(getPosition(), intersectionRectangle.getSize());
intersectionRectangle.translate(transformed.x, transformed.y);
if (intersectionRectangle.contains(mouse))
{
tooltipManager.add(new Tooltip(component.getTooltip()));
}
}
}
}
}
return dimension;
}
}
|
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Polygon;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Tabox2D {
public static boolean debug = false;
private static HashMap<String, Float> polyInfo;
private static Tabox2D instance;
private Box2DDebugRenderer renderer;
private OrthographicCamera camera;
private World world;
private SpriteBatch spriteBath;
private List<Tabody> tabodies;
private int width;
private int height;
private float meterSize;
public ShapeRenderer sr = new ShapeRenderer();
private Tabox2D(Vector2 gravity) {
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
meterSize = 100;// 1 metter = 100px, default.
pl("width: " + width + ", height: " + height);
polyInfo = new HashMap<String, Float>();
// Sides by polygon:
polyInfo.put("triangle", 3f);
polyInfo.put("square", 4f);
polyInfo.put("pentagon", 5f);
polyInfo.put("hexagon", 6f);
polyInfo.put("heptagon", 7f);
polyInfo.put("octagon", 8f);
// Angle of the sides:
polyInfo.put("triangle_angle", 120f);
polyInfo.put("square_angle", 90f);
polyInfo.put("pentagon_angle", 72f);
polyInfo.put("hexagon_angle", 60f);
polyInfo.put("heptagon_angle", 51.428f);
polyInfo.put("octagon_angle", 45f);
renderer = new Box2DDebugRenderer();
spriteBath = new SpriteBatch();
adjustCamera();
tabodies = new ArrayList<Tabody>();
world = new World(new Vector2(gravity.x, gravity.y), true);
sr = new ShapeRenderer();
}
private void adjustCamera() {
float cameraW = width / meterSize;
float cameraH = height / meterSize;
pl("cameraW: " + cameraW + ", cameraH: " + cameraH);
camera = new OrthographicCamera(cameraW, cameraH);
// Set at 0, 0, 0 in space:
float camX = camera.viewportWidth / 2;
float camY = camera.viewportHeight / 2;
camera.position.set(camX, camY, 0f);
camera.update();
}
public static Tabox2D getInstance() {
return getInstance(new Vector2(0, -9.8f));
}
public List<Tabody> getTabodies() {
return tabodies;
}
public static Tabox2D getInstance(Vector2 gravity) {
if(instance == null) {
instance = new Tabox2D(gravity);
}
return instance;
}
public void setMeterSize(float meterSize) {
if(meterSize > 500) {
perr("Max meterSize allowed: 500, " +
"using default = 100");
return;
}
this.meterSize = meterSize;
adjustCamera();
}
// Ball creator:
public Tabody newBall(String type, float x, float y, float r) {
// Scale proportions:
x = x / meterSize;
y = y / meterSize;
r = r / meterSize;
CircleShape circleShape;
BodyDef defBall = new BodyDef();
setType(defBall, type);
defBall.position.set(x, y);
Tabody ball = new Tabody();
ball.body = world.createBody(defBall);
circleShape = new CircleShape();
circleShape.setRadius(r);
FixtureDef fixtureBall = new FixtureDef();
fixtureBall.shape = circleShape;
fixtureBall.density = 1;
fixtureBall.friction = 1;
fixtureBall.restitution = 0.5f;//0.2f;
ball.w = r * 2 * meterSize;
ball.h = r * 2 * meterSize;
ball.fixture = fixtureBall;
ball.bodyType = "ball";
ball.body.createFixture(fixtureBall);
circleShape.dispose();
tabodies.add(ball);
return ball;
}
// Box creator:
public Tabody newBox(String type, float x, float y, float w, float h) {
// Scale proportions:
x = x / meterSize;
y = y / meterSize;
w = w / meterSize;
h = h / meterSize;
PolygonShape polygonShape;
BodyDef defBox = new BodyDef();
setType(defBox, type);
defBox.position.set(x + w / 2, y + h / 2);
Tabody box = new Tabody();
box.body = world.createBody(defBox);
polygonShape = new PolygonShape();
polygonShape.setAsBox(w / 2, h / 2);
FixtureDef fixtureBox = new FixtureDef();
fixtureBox.shape = polygonShape;
fixtureBox.density = 1;
fixtureBox.friction = 1;
fixtureBox.restitution = 0.2f;
box.w = w * meterSize;
box.h = h * meterSize;
box.fixture = fixtureBox;
box.bodyType = "box";
box.body.createFixture(fixtureBox);
polygonShape.dispose();
tabodies.add(box);
return box;
}
// Polygons creators:
public Tabody newTriangle(String type, Vector2 center, float radius) {
return generateRegularPoly("triangle", type, center, radius);
}
public Tabody newSquare(String type, Vector2 center, float radius) {
return generateRegularPoly("square", type, center, radius);
}
public Tabody newPentagon(String type, Vector2 center, float radius) {
return generateRegularPoly("pentagon", type, center, radius);
}
public Tabody newHexagon(String type, Vector2 center, float radius) {
return generateRegularPoly("hexagon", type, center, radius);
}
public Tabody newHeptagon(String type, Vector2 center, float radius) {
return generateRegularPoly("heptagon", type, center, radius);
}
public Tabody newOctagon(String type, Vector2 center, float radius) {
return generateRegularPoly("octagon", type, center, radius);
}
private Tabody generateRegularPoly(String polyName, String type, Vector2 center, float rad) {
// Scale proportions:
center.set(center.x / meterSize, center.y / meterSize);
rad /= meterSize;
PolygonShape polygonShape;
BodyDef defPoly = new BodyDef();
setType(defPoly, type);
defPoly.position.set(0, 0);
//defPoly.position.set(center.x, center.y);
Tabody regularPoly = new Tabody();
regularPoly.body = world.createBody(defPoly);
//regularPoly.body.setFixedRotation(true);
polygonShape = new PolygonShape();
// Generate points:
List<Vector2> pts = new ArrayList<Vector2>();
Vector2 p0 = new Vector2(center.x, center.y + rad);
float conv = MathUtils.degreesToRadians;
float angleInDeg = polyInfo.get(polyName + "_angle");
float cos = MathUtils.cos(conv * angleInDeg);
float sin = MathUtils.sin(conv * angleInDeg);
for(int i = 0; i < polyInfo.get(polyName); i++) {
pts.add(new Vector2(p0.x, p0.y));
p0.set(p0.x - center.x, p0.y - center.y);
float newX = p0.x * cos - p0.y * sin;
float newY = p0.x * sin + p0.y * cos;
p0.x = newX + center.x;
p0.y = newY + center.y;
}
// Get bounding box:
float[] rawPoints = new float[pts.size() * 2];
int pointIndex = 0;
for(int i = 0; i < rawPoints.length - 1; i += 2) {
rawPoints[i] = pts.get(pointIndex).x;
rawPoints[i + 1] = pts.get(pointIndex).y;
pointIndex++;
}
Polygon polyForBox = new Polygon();
polyForBox.setVertices(rawPoints);
Rectangle boundingRect = polyForBox.getBoundingRectangle();
float widthOfBox = boundingRect.getWidth();
float heightOfBox = boundingRect.getHeight();
//polygonShape.setAsBox(w / 2, h / 2);
polygonShape.set(rawPoints);
FixtureDef fixtureBox = new FixtureDef();
fixtureBox.shape = polygonShape;
fixtureBox.density = 1;
fixtureBox.friction = 1;
fixtureBox.restitution = 0.1f;
regularPoly.w = widthOfBox * meterSize;//radius * 2 * meterSize;
regularPoly.h = heightOfBox * meterSize;//radius * 2 * meterSize;
regularPoly.fixture = fixtureBox;
regularPoly.bodyType = "poly";
regularPoly.body.createFixture(fixtureBox);
polygonShape.dispose();
tabodies.add(regularPoly);
return regularPoly;
}
// Other stuff:
public void update() {
this.update(Gdx.graphics.getDeltaTime());
}
public void update(float delta) {
world.step(delta, 6, 2);
// Move sprites:
for(Tabody t : tabodies) {
if(t.sprite != null) {
float xb = t.body.getPosition().x * meterSize;
float yb = t.body.getPosition().y * meterSize;
xb -= t.sprite.getWidth() / 2;
yb -= t.sprite.getHeight() / 2;
t.sprite.setPosition(xb, yb);
t.sprite.setRotation(t.body.getAngle() * MathUtils.radiansToDegrees);
}
}
}
public void dispose() {
world.dispose();
renderer.dispose();
}
public void draw() {
// Draw sprites:
for(Tabody t : tabodies) {
if(t.sprite != null) {
spriteBath.begin();
t.sprite.draw(spriteBath);
spriteBath.end();
}
if(this.debug) {
renderer.render(world, camera.combined);
sr.begin(ShapeRenderer.ShapeType.Filled);
sr.setAutoShapeType(true);
//sr.setColor(Color.DARK_GRAY);
if(t.bodyType.equals("poly")) {
/*
sr.setColor(Color.MAROON);
PolygonShape ps = (PolygonShape)t.body.getFixtureList().get(0).getShape();
int vc = ps.getVertexCount();
Polygon polyAux = new Polygon();
Vector2 tmp = new Vector2();
int vertIndex = 0;
float[] vertices = new float[vc * 2];
for(int i = 0; i < vertices.length - 1; i+= 2) {
ps.getVertex(vertIndex, tmp);
vertices[i] = tmp.x * meterSize;
vertices[i + 1] = tmp.y * meterSize;
vertIndex++;
}
//pl(vertices.length);
polyAux.setVertices(vertices);
Rectangle boxAux = polyAux.getBoundingRectangle();
polyAux.setOrigin(boxAux.x + boxAux.width / 2, boxAux.y + boxAux.height / 2);
polyAux.setRotation(t.body.getAngle() * MathUtils.radiansToDegrees);
polyAux.setPosition(
t.body.getPosition().x * meterSize,
t.body.getPosition().y * meterSize);
float[] trans = polyAux.getTransformedVertices();
sr.polygon(trans);
*/
}
sr.setColor(Color.RED);
// Center of mass:
sr.circle(
t.body.getWorldCenter().x * meterSize,
t.body.getWorldCenter().y * meterSize, 3);
// Geometric center:
sr.setColor(Color.CYAN);
sr.set(ShapeRenderer.ShapeType.Line);
sr.circle(
t.body.getPosition().x * meterSize,
t.body.getPosition().y * meterSize, 3);
sr.end();
}
}
}
private void setType(BodyDef def, String type) {
type = type.toLowerCase();
if(type.equals("d")) {
def.type = BodyDef.BodyType.DynamicBody;
} else if(type.equals("s")) {
def.type = BodyDef.BodyType.StaticBody;
} else if(type.equals("k")) {
def.type = BodyDef.BodyType.KinematicBody;
} else {
perr("'d', 's' or 'k' expected");
}
}
public class Tabody {
Body body;
String bodyType;// "circle", "rectangle" or "polygon".
Sprite sprite;
FixtureDef fixture;
Vector2 geomCenter;
float w, h;
float[] vertices;
public Tabody setTexture(Texture texture) {
this.sprite = new Sprite(texture);
float scaleX = this.w / this.sprite.getWidth();
float scaleY = this.h / this.sprite.getHeight();
float posX = this.body.getPosition().x * meterSize;
float posY = this.body.getPosition().y * meterSize;
sprite.setOrigin(texture.getWidth() / 2, texture.getHeight() / 2);
sprite.setPosition(posX, posY);
sprite.setScale(scaleX, scaleY);
return this;
}
}
@Override
public Object clone() {
return this;
}
private static void pl(Object o){
System.out.println(o);
}
private static void perr(Object o){
System.err.println(o);
}
private static String nl() {
return System.getProperty("line.separator");
}
}
|
package net.kencochrane.raven.sentrystub;
import net.kencochrane.raven.sentrystub.auth.AuthValidator;
import net.kencochrane.raven.sentrystub.auth.InvalidAuthException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
@WebListener
public class SentryUdpContextListener implements ServletContextListener {
private static final Logger logger = Logger.getLogger(SentryUdpContextListener.class.getCanonicalName());
private static final int DEFAULT_SENTRY_UDP_PORT = 9001;
private static final String SENTRY_UDP_PORT_PARAMETER = "sentryUdpPort";
private ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private DatagramSocket udpSocket;
private AuthValidator authValidator;
@Override
public void contextInitialized(ServletContextEvent sce) {
String sentryUdpPortParameter = sce.getServletContext().getInitParameter(SENTRY_UDP_PORT_PARAMETER);
startUdpSocket(sentryUdpPortParameter != null
? Integer.parseInt(sentryUdpPortParameter)
: DEFAULT_SENTRY_UDP_PORT);
authValidator = new AuthValidator();
authValidator.loadSentryUsers("/sentry.properties");
}
private void startUdpSocket(int port) {
try {
udpSocket = new DatagramSocket(port);
new UdpListenerThread().start();
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
executorService.shutdownNow();
udpSocket.close();
}
private static class UdpRequestHandler implements Runnable {
private final DatagramPacket datagramPacket;
private UdpRequestHandler(DatagramPacket datagramPacket) {
this.datagramPacket = datagramPacket;
}
@Override
public void run() {
InputStream bais = new ByteArrayInputStream(datagramPacket.getData(),
datagramPacket.getOffset(),
datagramPacket.getLength());
validateAuthHeader(bais);
}
/**
* Extracts the Auth Header from a binary stream and leave the stream as is once the header is parsed.
*
* @param inputStream
*/
private void validateAuthHeader(InputStream inputStream) {
try {
Map<String, String> authHeader = parseAuthHeader(inputStream);
authValidator.validateSentryAuth(authHeader);
} catch (IOException e) {
throw new InvalidAuthException("Impossible to extract the auth header from an UDP packet", e);
}
}
private Map<String, String> parseAuthHeader(InputStream inputStream) throws IOException {
Map<String, String> authHeader = new HashMap<String, String>();
int i;
StringBuilder sb = new StringBuilder();
String key = null;
while ((i = inputStream.read()) >= 0) {
if (i == '\n') {
authHeader.put(key, sb.toString().trim());
//Assume it's the double \n, parse the next once
inputStream.read();
break;
} else if (i == '=' && key == null) {
key = sb.toString().trim();
sb = new StringBuilder();
} else if (i == ',' && key != null) {
authHeader.put(key, sb.toString().trim());
sb = new StringBuilder();
key = null;
} else {
sb.append((char) i);
}
}
return authHeader;
}
}
private class UdpListenerThread extends Thread {
@Override
public void run() {
// We'll assume that no-one sends a > 65KB datagram (max size allowed on IPV4).
final int datagramPacketSize = 65536;
while (!udpSocket.isClosed()) {
try {
byte[] buffer = new byte[datagramPacketSize];
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
udpSocket.receive(datagramPacket);
executorService.execute(new UdpRequestHandler(datagramPacket));
} catch (Exception e) {
logger.log(Level.WARNING, "An exception occurred during the reception of a UDP packet.", e);
}
}
}
}
}
|
package bizcal.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import bizcal.common.DayViewConfig;
import bizcal.common.Event;
import bizcal.swing.util.FrameArea;
import bizcal.util.BizcalException;
import bizcal.util.DateInterval;
import bizcal.util.DateUtil;
import bizcal.util.Interval;
import bizcal.util.TimeOfDay;
import bizcal.util.Tuple;
public class DayView extends CalendarView {
public static int PIXELS_PER_HOUR = 80;
private static final int CAPTION_ROW_HEIGHT0 = 20;
public static final int PREFERRED_DAY_WIDTH = 10;
public static final Integer GRID_LEVEL = new Integer(1);
private List<List<FrameArea>> frameAreaCols = new ArrayList<List<FrameArea>>();
private List<List<Event>> eventColList = new ArrayList<List<Event>>();
private List<Date> _dateList = new ArrayList<Date>();
private Map<Tuple, JLabel> timeLines = new HashMap<Tuple, JLabel>();
private Map hourLabels = new HashMap();
private Map minuteLabels = new HashMap();
private List<JLabel> vLines = new ArrayList<JLabel>();
private List<JPanel> calBackgrounds = new ArrayList<JPanel>();
private ColumnHeaderPanel columnHeader;
private TimeLabelPanel rowHeader;
private int dayCount;
private JScrollPane scrollPane;
private JLayeredPane calPanel;
private boolean firstRefresh = true;
private DayViewConfig config;
private List<JLabel> dateFooters = new ArrayList<JLabel>();
/**
* @param desc
* @throws Exception
*/
public DayView(DayViewConfig desc) throws Exception {
this(desc, null);
}
/**
* @param desc
* @param upperLeftCornerComponent component that is displayed in the upper left corner of the scrollpaine
* @throws Exception
*/
public DayView(DayViewConfig desc, Component upperLeftCornerComponent) throws Exception {
super(desc);
this.config = desc;
calPanel = new JLayeredPane();
calPanel.setLayout(new Layout());
ThisMouseListener mouseListener = new ThisMouseListener();
ThisKeyListener keyListener = new ThisKeyListener();
calPanel.addMouseListener(mouseListener);
calPanel.addMouseMotionListener(mouseListener);
calPanel.addKeyListener(keyListener);
// calPanel.setPreferredSize(new
// Dimension(calPanel.getPreferredSize().width,
// calPanel.getPreferredSize().height+200));
scrollPane = new JScrollPane(calPanel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setCursor(Cursor.getDefaultCursor());
scrollPane.getVerticalScrollBar().setUnitIncrement(15);
if (upperLeftCornerComponent == null) {
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, createCorner(true,
true));
} else {
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, upperLeftCornerComponent);
}
scrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER, createCorner(true,
false));
scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, createCorner(
false, true));
columnHeader = new ColumnHeaderPanel(desc);
columnHeader.setShowExtraDateHeaders(desc.isShowExtraDateHeaders());
scrollPane.setColumnHeaderView(columnHeader.getComponent());
// set the time label at the left side
rowHeader = new TimeLabelPanel(desc, new TimeOfDay(this.config.getDayStartHour(), 0),
new TimeOfDay(this.config.getDayEndHour(), 0));
rowHeader.setFooterHeight(getFooterHeight());
scrollPane.setRowHeaderView(rowHeader.getComponent());
// scrollPane.setPreferredSize(new Dimension(scrollPane.getWidth(),
// scrollPane.getHeight()+400));
// calPanel.addComponentListener(new ComponentAdapter() {
// @Override
// public void componentResized(ComponentEvent e) {
//
// try {
// // DayView.this.refresh();
// // DayView.this.refresh0();
// } catch (Exception e1) {
// e1.printStackTrace();
//
}
public void refresh0() throws Exception {
if (calPanel == null || this.getModel() == null)
return;
dayCount = (int) (getModel().getInterval().getDuration() / (24 * 3600 * 1000));
calPanel.removeAll();
calPanel.setBackground(Color.WHITE);
rowHeader.setStartEnd(new TimeOfDay(this.config.getDayStartHour(), 0),
new TimeOfDay(this.config.getDayEndHour(), 0));
rowHeader.setFooterHeight(getFooterHeight());
rowHeader.getComponent().revalidate();
frameAreaCols.clear();
eventColList.clear();
timeLines.clear();
hourLabels.clear();
minuteLabels.clear();
calBackgrounds.clear();
vLines.clear();
dateFooters.clear();
addDraggingComponents(calPanel);
Font hourFont = getDesc().getFont().deriveFont((float) 12);
hourFont = hourFont.deriveFont(Font.BOLD);
// Steps through the time axis and adds hour labels, minute labels
// and timelines in different maps.
// key: date, value: label
long pos = getFirstInterval().getStartDate().getTime();
while (pos < getFirstInterval().getEndDate().getTime()) {
Date date = new Date(pos);
int timeSlots = this.config.getNumberOfTimeSlots();
// do not print more than 6 minute time slots (every 10'')
if (PIXELS_PER_HOUR > 120)
timeSlots = 6;
if (timeSlots > 10)
timeSlots = 10;
// create a horizontal line for each time slot
Color color = getDesc().getLineColor();
Color hlineColor = new Color(color.getRed(), color.getGreen(), color.getBlue(),getDesc().getGridAlpha());
for (int i = 1; i <= timeSlots; i++) {
JLabel line = new JLabel();
line.setOpaque(true);
line.setBackground(hlineColor);
calPanel.add(line, GRID_LEVEL);
timeLines.put(new Tuple(date, ""+(60/timeSlots)*i), line);
addHorizontalLine(line);
}
// // Hour line
// JLabel line = new JLabel();
// line.setBackground(getDesc().getLineColor());
// line.setOpaque(true);
// calPanel.add(line, GRID_LEVEL);
// timeLines.put(new Tuple(date, "00"), line);
// addHorizontalLine(line);
//
//// // Quarter hour line
//// // ev lgga denna loop efter att vi placerat ut aktiviteterna
//// // d kommer den hamna lngst bak men nd synas
//// line = new JLabel();
//// line.setBackground(getDesc().getLineColor());
//// line.setOpaque(true);
//// calPanel.add(line, GRID_LEVEL);
//// timeLines.put(new Tuple(date, "15"), line);
//// addHorizontalLine(line);
//
// // Half hour line
// // ev lgga denna loop efter att vi placerat ut aktiviteterna
// // d kommer den hamna lngst bak men nd synas
// line = new JLabel();
// line.setBackground(getDesc().getLineColor());
// line.setOpaque(true);
// calPanel.add(line, GRID_LEVEL);
// timeLines.put(new Tuple(date, "30"), line);
// addHorizontalLine(line);
// // 3*Quarter hour line
// // ev lgga denna loop efter att vi placerat ut aktiviteterna
// // d kommer den hamna lngst bak men nd synas
// line = new JLabel();
// line.setBackground(getDesc().getLineColor());
// line.setOpaque(true);
// calPanel.add(line, GRID_LEVEL);
// timeLines.put(new Tuple(date, "45"), line);
// addHorizontalLine(line);
pos += 3600 * 1000;
}
if (config.isShowDateFooter()) {
JLabel line = new JLabel();
line.setBackground(getDesc().getLineColor());
line.setOpaque(true);
calPanel.add(line, GRID_LEVEL);
timeLines.put(new Tuple(new Date(pos), "00"), line);
}
createColumns();
Iterator i = getSelectedCalendars().iterator();
while (i.hasNext()) {
bizcal.common.Calendar cal = (bizcal.common.Calendar) i.next();
JPanel calBackground = new JPanel();
calBackground.setBackground(cal.getColor());
calBackgrounds.add(calBackground);
calPanel.add(calBackground);
}
columnHeader.setModel(getModel());
columnHeader.setPopupMenuCallback(popupMenuCallback);
columnHeader.refresh();
if (firstRefresh)
initScroll();
firstRefresh = false;
calPanel.validate();
calPanel.repaint();
// scrollPane.setPreferredSize(new DiSmension(calPanel.getPreferredSize().width, rowHeader.getComponent().getPreferredSize().height));
// put the timelines in the background
for (JLabel l : timeLines.values()) {
calPanel.setComponentZOrder(l, calPanel.getComponents().length-2);
}
scrollPane.validate();
scrollPane.repaint();
rowHeader.getComponent().updateUI();
// Hack to make to init scroll work
// JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
// scrollBar.setValue(scrollBar.getValue()-1);
}
private int getColCount() throws Exception {
return dayCount * getSelectedCalendars().size();
}
/**
* Returns the first interval to show. Start day plus one.
*
* @return
* @throws Exception
*/
private DateInterval getFirstInterval() throws Exception {
Date start = getInterval().getStartDate();
// Date end = DateUtil.getDiffDay(start, +1);
return new DateInterval(
DateUtil.round2Hour(start, this.config.getDayStartHour()),
DateUtil.round2Hour(start, this.config.getDayEndHour()));
}
/**
* @throws Exception
*/
@SuppressWarnings("unchecked")
private void createColumns() throws Exception {
DateInterval interval = getFirstInterval();
int cols = getColCount();
frameAreaHash.clear();
List events = null;
DateInterval interval2 = null;
// iterate over all columns
for (int it = 0; it < cols; it++) {
int iCal = it / dayCount;
bizcal.common.Calendar cal = (bizcal.common.Calendar) getSelectedCalendars()
.get(iCal);
Object calId = cal.getId();
// obtain all events for the calendar
events = broker.getEvents(calId);
Collections.sort(events);
if (it % dayCount == 0)
interval2 = new DateInterval(interval);
_dateList.add(interval2.getStartDate());
Calendar startdate = DateUtil.newCalendar();
startdate.setTime(interval2.getStartDate());
// create vertical lines
Color vlColor = getDesc().getLineColor();
int vlAlpha = getDesc().getGridAlpha()+50;
if (vlAlpha > 255)
vlAlpha = 255;
Color vlAlphaColor = new Color(vlColor.getRed(), vlColor.getGreen(), vlColor.getBlue(), vlAlpha);
if (it > 0) {
JLabel verticalLine = new JLabel();
verticalLine.setOpaque(true);
verticalLine.setBackground(vlAlphaColor);
// verticalLine.setBackground(getDesc().getLineColor());
if (startdate.get(Calendar.DAY_OF_WEEK) == startdate
.getFirstDayOfWeek())
verticalLine.setBackground(getDescriptor().getLineColor2());
if (getSelectedCalendars().size() > 1 && it % dayCount == 0)
verticalLine.setBackground(getDescriptor().getLineColor3());
calPanel.add(verticalLine, GRID_LEVEL);
vLines.add(verticalLine);
}
List<FrameArea> frameAreas = new ArrayList<FrameArea>();
// lgger till en framearea-lista fr varje dag
frameAreaCols.add(frameAreas);
// fr alla event fr personen inom intervallet
if (calId == null)
continue;
Interval currDayInterval = getInterval(it % dayCount);
List<Event> colEvents = new ArrayList<Event>();
eventColList.add(colEvents);
int iEvent = 0;
if (events == null)
events = new ArrayList();
Iterator j = events.iterator();
while (j.hasNext()) {
Event event = (Event) j.next();
DateInterval eventInterv = new DateInterval(event.getStart(),
event.getEnd());
if (!currDayInterval.overlap(eventInterv))
continue;
// if there are overlapping events
FrameArea area = createFrameArea(calId, event);
area.setBackground(config.getPrimaryColor());
frameAreas.add(area);
colEvents.add(event);
calPanel.add(area, new Integer(event.getLevel()));
iEvent++;
if (!frameAreaHash.containsKey(event))
frameAreaHash.put(event, area);
else {
frameAreaHash.get(event).addChild(area);
}
}
if (config.isShowDateFooter()) {
JLabel footer = new JLabel(broker.getDateFooter(cal.getId(),
interval2.getStartDate(), colEvents));
footer.setHorizontalAlignment(JLabel.CENTER);
dateFooters.add(footer);
calPanel.add(footer);
}
if (dayCount > 1)
interval2 = incDay(interval2);
}
}
// Fr in ett events start- eller slutdatum, hjden p fnstret samt
// intervallet som positionen ska berknas utifrn
private int getYPos(Date aDate, int dayNo) throws Exception {
long time = aDate.getTime();
return getYPos(time, dayNo);
}
private int getYPos(long time, int dayNo) throws Exception {
DateInterval interval = getInterval(dayNo);
time -= interval.getStartDate().getTime();
double viewPortHeight = getHeight() - getCaptionRowHeight()
- getFooterHeight();
// double timeSpan = (double) getTimeSpan();
// double timeSpan = 24 * 3600 * 1000;
double timeSpan = this.config.getHours() * 3600 * 1000;
double dblTime = time;
int ypos = (int) (dblTime / timeSpan * viewPortHeight);
ypos += getCaptionRowHeight();
return ypos;
}
/*
* private long getTimeSpan() throws Exception { return
* getDesc().getViewEndTime().getValue() -
* getDesc().getViewStartTime().getValue(); }
*/
/*
* (non-Javadoc)
*
* @see bizcal.swing.CalendarView#getDate(int, int)
*/
protected Date getDate(int xPos, int yPos) throws Exception {
int colNo = getColumn(xPos);
int dayNo = 0;
if (dayCount != 0)
dayNo = colNo % dayCount;
DateInterval interval = getInterval(dayNo);
yPos -= getCaptionRowHeight();
double ratio = ((double) yPos) / ((double) getTimeHeight());
long time = (long) (interval.getDuration() * ratio);
time += interval.getStartDate().getTime();
return new Date(time);
}
private DateInterval getInterval(int dayNo) throws Exception {
DateInterval interval = getFirstInterval();
for (int i = 0; i < dayNo; i++)
interval = incDay(interval);
return interval;
}
private int getColumn(int xPos) throws Exception {
xPos -= getXOffset();
int width = getWidth() - getXOffset();
double ratio = ((double) xPos) / ((double) width);
return (int) (ratio * getColCount());
}
private Object getCalendarId(int colNo) throws Exception {
int pos = 0;
// dayCount = 1;
if (dayCount != 0)
pos = colNo / dayCount;
bizcal.common.Calendar cal = (bizcal.common.Calendar) getSelectedCalendars()
.get(pos);
return cal.getId();
}
protected int getXOffset() {
// return LABEL_COL_WIDTH;
return 0;
}
private int getXPos(int colno) throws Exception {
double x = getWidth();
x = x - getXOffset();
double ratio = ((double) colno) / ((double) getColCount());
return ((int) (x * ratio)) + getXOffset();
/*
* BigDecimal xPos = new BigDecimal((x * ratio) + getXOffset()); return
* xPos.setScale(0,BigDecimal.ROUND_CEILING).intValue();
*/
}
private int getWidth() {
return calPanel.getWidth();
}
private int getHeight() {
return calPanel.getHeight();
}
private int getTimeHeight() throws Exception {
return getHeight() - getCaptionRowHeight() - getFooterHeight();
}
private int getFooterHeight() {
if (config.isShowDateFooter())
return PIXELS_PER_HOUR / 2;
return 0;
}
private class Layout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
try {
int width = dayCount * getModel().getSelectedCalendars().size()
* PREFERRED_DAY_WIDTH;
return new Dimension(width, getPreferredHeight());
} catch (Exception e) {
throw BizcalException.create(e);
}
}
public Dimension minimumLayoutSize(Container parent) {
return new Dimension(50, 100);
}
@SuppressWarnings("unchecked")
public void layoutContainer(Container parent0) {
try {
DayView.this.resetVerticalLines();
int width = getWidth();
int height = getHeight();
DateInterval day = getFirstInterval();
int numberOfCols = getColCount();
if (numberOfCols == 0)
numberOfCols = 1;
for (int i = 0; i < eventColList.size(); i++) {
int dayNo = i % dayCount;
int xpos = getXPos(i);
int captionYOffset = getCaptionRowHeight()
- CAPTION_ROW_HEIGHT0;
int colWidth = getXPos(i + 1) - getXPos(i);
// Obs. temporr lsning med korrigering med +2. Lgg till
// korrigeringen p rtt stlle
// kan hra ihop synkning av tidsaxel och muslyssnare
int vLineTop = captionYOffset + CAPTION_ROW_HEIGHT0 + 2;
if (dayNo == 0 && (getSelectedCalendars().size() > 1)) {
vLineTop = 0;
day = getFirstInterval();
}
Calendar startinterv = Calendar.getInstance(Locale
.getDefault());
startinterv.setTime(day.getStartDate());
if (i > 0) {
JLabel verticalLine = (JLabel) vLines.get(i-1);
int vLineHeight = height - vLineTop;
verticalLine.setBounds(xpos, vLineTop, 1, vLineHeight);
// add the line position to the list
addVerticalLine(verticalLine);
}
if (config.isShowDateFooter()) {
JLabel dayFooter = (JLabel) dateFooters.get(i);
dayFooter.setBounds(xpos, getTimeHeight(), colWidth, getFooterHeight());
}
DateInterval currIntervall = getInterval(dayNo);
FrameArea prevArea = null;
int overlapCol = 0;
int overlapColCount = 0;
// eventColList contains a list of ArrayLists that holds the
// events per day
// the same with the frameAreaCols
List events = (List) eventColList.get(i);
List<FrameArea> areas = frameAreaCols.get(i);
int overlapCols[] = new int[events.size()];
for (int j = 0; j < events.size(); j++) {
FrameArea area = (FrameArea) areas.get(j);
Event event = (Event) events.get(j);
// adapt the FrameArea according the appropriate event
// data
Date startTime = event.getStart();
if (startTime.before(currIntervall.getStartDate()))
startTime = currIntervall.getStartDate();
Date endTime = event.getEnd();
// if the events lasts longer than the current day, set
// 23:59 as end
if (endTime.after(currIntervall.getEndDate()))
endTime = currIntervall.getEndDate();
int y1 = getYPos(startTime, dayNo);
if (y1 < getCaptionRowHeight())
y1 = getCaptionRowHeight();
int y2 = getYPos(endTime, dayNo);
int dy = y2 - y1;
int x1 = xpos;
area.setBounds(x1, y1, colWidth, dy);
// Overlap logic
if (!event.isBackground()) {
if (prevArea != null) {
Rectangle r = prevArea.getBounds();
int prevY2 = r.y + r.height;
if (prevY2 > y1) {
// Previous event overlap
overlapCol++;
if (prevY2 < y2) {
// This events finish later than
// previous
prevArea = area;
}
} else {
overlapCol = 0;
prevArea = area;
}
} else
prevArea = area;
overlapCols[j] = overlapCol;
if (overlapCol > overlapColCount)
overlapColCount = overlapCol;
} else
overlapCols[j] = 0;
}
// Overlap logic. Loop the events/frameareas a second
// time and set the xpos and widths
if (overlapColCount > 0) {
int currWidth = colWidth;
for (int j = 0; j < areas.size(); j++) {
Event event = (Event) events.get(j);
if (event.isBackground())
continue;
FrameArea area = (FrameArea) areas.get(j);
int index = overlapCols[j];
if (index == 0)
currWidth = colWidth;
try {
if ( overlapCols[j+1] > 0){
// find greates in line
int curr = index;
for (int a = j+1; a < areas.size();a++) {
if (overlapCols[a] == 0)
break;
if (overlapCols[a] > curr)
curr = overlapCols[a];
}
currWidth = colWidth / (curr+1);
}
} catch (Exception e) {}
Rectangle r = area.getBounds();
area.setBounds(r.x + index*currWidth, r.y, currWidth, r.height);
}
}
}
// Loop the frameareas a third time
// and set areas that belong to an event to the same width
for (List<FrameArea> fAreas : frameAreaCols) {
if (fAreas != null)
for (FrameArea fa : fAreas) {
int sw = findSmallestFrameArea(fa);
int baseFAWidth;
try {
baseFAWidth = getBaseFrameArea(fa.getEvent()).getBounds().width;
} catch (Exception e) {
continue;
}
if (sw > baseFAWidth) {
sw = baseFAWidth;
}
fa.setBounds(fa.getBounds().x, fa.getBounds().y,
sw,
fa.getBounds().height);
// ensure, that the background events are really painted in the background!
if (fa.getEvent().isBackground())
calPanel.setComponentZOrder(fa, calPanel.getComponents().length-5);
}
}
// old obsolete
// // Overlap logic. Loop the events/frameareas a second
// // time and set the xpos and widths
// if (overlapColCount > 0) {
// int slotWidth = colWidth / (overlapColCount+1);
// for (int j = 0; j < areas.size(); j++) {
// Event event = (Event) events.get(j);
// if (event.isBackground())
// continue;
// FrameArea area = (FrameArea) areas.get(j);
// int index = overlapCols[j];
// Rectangle r = area.getBounds();
// area.setBounds(r.x + index*slotWidth, r.y, slotWidth, r.height);
if (dayCount > 1)
day = incDay(day);
Iterator i = timeLines.keySet().iterator();
while (i.hasNext()) {
Tuple key = (Tuple) i.next();
Date date = (Date) key.elementAt(0);
int minutes = Integer.parseInt((String) key.elementAt(1));
JLabel line = (JLabel) timeLines.get(key);
Date date1 = new Date(date.getTime() + minutes * 60 * 1000);
int y1 = getYPos(date1, 0);
int x1 = 0;
int lineheight = 1;
if (minutes > 0) {
// x1 = 25;
lineheight = 1;
}
line.setBounds(x1, y1, width, lineheight);
}
for (int iCal = 0; iCal < calBackgrounds.size(); iCal++) {
int x1 = getXPos(iCal * dayCount);
int x2 = getXPos((iCal + 1) * dayCount);
JPanel calBackground = (JPanel) calBackgrounds.get(iCal);
calBackground.setBounds(x1, getCaptionRowHeight(), x2 - x1,
getHeight());
}
} catch (Exception e) {
throw BizcalException.create(e);
}
}
}
/**
* Finds the smalles width of a framearea and its children
*
* @param fa
* @return
*/
private int findSmallestFrameArea(FrameArea fa) {
if (fa.getChildren() == null || fa.getChildren().size() < 1)
return fa.getBounds().width;
else {
int smallest = fa.getBounds().width;
for (FrameArea child : fa.getChildren()) {
if (child.getBounds().width < smallest)
smallest = child.getBounds().width;
}
return smallest;
}
}
protected Object getCalendarId(int x, int y) throws Exception {
return getCalendarId(getColumn(x));
}
private DayViewConfig getDesc() throws Exception {
DayViewConfig result = (DayViewConfig) getDescriptor();
if (result == null) {
result = new DayViewConfig();
setDescriptor(result);
}
return result;
}
public DayViewConfig getDayViewConfig() throws Exception {
return getDesc();
}
protected int getInitYPos() throws Exception {
double viewStart = getModel().getViewStart().getValue();
double ratio = viewStart / (24 * 3600 * 1000);
return (int) (ratio * this.config.getHours() * PIXELS_PER_HOUR);
// double viewStart = getModel().getViewStart().getValue();
// double ratio = viewStart / (24 * 3600 * 1000);
// return (int) (ratio * 24 * PIXELS_PER_HOUR);
}
private int getPreferredHeight() {
return this.config.getHours() * PIXELS_PER_HOUR + getFooterHeight();
}
public JComponent getComponent() {
return scrollPane;
}
public void initScroll() throws Exception {
scrollPane.getViewport().setViewPosition(new Point(0, getInitYPos()));
}
public void addListener(CalendarListener listener) {
super.addListener(listener);
columnHeader.addCalendarListener(listener);
}
}
|
package org.smart4j.plugin.mybatis;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.aop.AspectProxy;
import org.smart4j.framework.aop.annotation.Aspect;
import org.smart4j.framework.core.ConfigHelper;
import org.smart4j.framework.tx.annotation.Service;
@Aspect(annotation = Service.class)
public class MybatisSessionProxy extends AspectProxy {
private static final Logger logger = LoggerFactory.getLogger(MybatisSessionProxy.class);
private static final ThreadLocal<Short> flagContainer = new ThreadLocal<Short>() {
protected Short initialValue() {
return 0;
}
};
private static void incrementFlag() {
short flag = flagContainer.get();
flagContainer.set(++flag);
}
private static void decrementFlag() {
short flag = flagContainer.get();
flagContainer.set(--flag);
}
public static final String MYBATIS_SESSION = "mybatis.session.auto";
/**MybatisSessionfalseMybatisSession**/
public static final Boolean auto;
static {
Boolean _auto = false;
try {
_auto = ConfigHelper.getConfigBoolean(MYBATIS_SESSION);
}
catch (Exception ex){
_auto = false;
}
finally {
auto = _auto;
}
}
@Override
public void before(Class<?> cls, Method method, Object[] params) throws Throwable {
//Session
if (auto || method.isAnnotationPresent(MybatisSession.class)) {
// - Session
if (flagContainer.get() == 0) {
MybatisHelper.getSqlSession();
}
incrementFlag();
}
}
@Override
public void after(Class<?> cls, Method method, Object[] params, Object result) throws Throwable {
if (auto || method.isAnnotationPresent(MybatisSession.class)) {
decrementFlag();
}
}
@Override
public void error(Class<?> cls, Method method, Object[] params, Throwable e) {
//after-1
if (auto || method.isAnnotationPresent(MybatisSession.class)) {
decrementFlag();
}
//catch
if (flagContainer.get() == 0) {
MybatisHelper.rollback();
logger.error(",Mybatis,:"+e.getMessage());
}
}
@Override
public void end() {
if (flagContainer.get() == 0) {
flagContainer.remove();
MybatisHelper.closeSession();
}
}
}
|
package com.garpr.android.activities;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.garpr.android.R;
import com.garpr.android.calls.Regions;
import com.garpr.android.misc.Console;
import com.garpr.android.misc.Constants;
import com.garpr.android.misc.CrashlyticsManager;
import com.garpr.android.misc.ResponseOnUi;
import com.garpr.android.misc.Utils;
import com.garpr.android.models.Region;
import com.garpr.android.settings.Settings;
import java.util.ArrayList;
public class DeepLinkActivity extends BaseActivity {
private static final String TAG = "DeepLinkActivity";
private Button mRetry;
private LinearLayout mError;
private ProgressBar mProgress;
private void fetchRankings(final String regionId) {
// TODO
// 1. download regions and grab this particular one
// 2. go to rankings activity
Regions.get(new ResponseOnUi<ArrayList<Region>>(TAG, this) {
@Override
public void errorOnUi(final Exception e) {
showError();
}
@Override
public void successOnUi(final ArrayList<Region> regions) {
Region region = null;
for (final Region r : regions) {
if (r.getId().equalsIgnoreCase(regionId)) {
region = r;
break;
}
}
if (region != null) {
Settings.Region.set(region);
}
RankingsActivity.start(DeepLinkActivity.this);
finish();
}
}, false);
}
private void findViews() {
mError = (LinearLayout) findViewById(R.id.activity_url_handler_error);
mProgress = (ProgressBar) findViewById(R.id.activity_url_handler_progress);
mRetry = (Button) findViewById(R.id.activity_url_handler_retry);
}
@Override
public String getActivityName() {
return TAG;
}
@Override
protected int getContentView() {
return R.layout.activity_url_handler;
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViews();
prepareViews();
if (Settings.OnboardingComplete.get()) {
Console.d(TAG, "Attempting to deep link...");
if (getIntent() == null) {
Console.w(TAG, "Cancelling deep link because Intent is null");
RankingsActivity.start(this);
finish();
} else {
parseIntent();
}
} else {
Console.d(TAG, "Deep link cancelled because onboarding is incomplete");
OnboardingActivity.start(this);
finish();
}
}
private void parseIntent() {
final Intent intent = getIntent();
final Uri uri = intent.getData();
if (uri == null) {
Console.w(TAG, "Cancelling deep link because Uri is null");
RankingsActivity.start(this);
finish();
} else if (parseUri(uri)) {
// intentionally blank
} else {
RankingsActivity.start(this);
finish();
}
}
private boolean parseUri(final Uri uri) {
final String uriString = uri.toString();
if (!Utils.validStrings(uriString)) {
Console.w(TAG, "Deep link Uri String is invalid");
return false;
}
CrashlyticsManager.setString(Constants.DEEP_LINK_URL, uriString);
Console.d(TAG, "Deep link Uri: \"" + uriString + '"');
// http://garpr.com/#/norcal/rankings
if (!uriString.startsWith(Constants.WEB_URL)) {
Console.w(TAG, "Deep link Uri doesn't start with \"" + Constants.WEB_URL + '"');
return false;
}
final String path = uriString.substring(Constants.WEB_URL.length(), uriString.length());
if (path.contains("/")) {
// TODO split
final String[] paths = path.split("/");
} else {
fetchRankings(path);
}
return true;
}
private void prepareViews() {
mRetry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
Console.d(TAG, "Retrying deep link...");
showProgress();
parseIntent();
}
});
}
private void showError() {
mProgress.setVisibility(View.GONE);
mError.setVisibility(View.VISIBLE);
}
private void showProgress() {
mError.setVisibility(View.GONE);
mProgress.setVisibility(View.VISIBLE);
}
}
|
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
/**
* @author Mike
*/
public class CreateParameterFromUsageAction extends CreateVarFromUsageAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreateParameterFromUsageAction");
public CreateParameterFromUsageAction(PsiReferenceExpression referenceElement) {
super(referenceElement);
}
protected boolean isAvailableImpl(int offset) {
if (!super.isAvailableImpl(offset)) return false;
if(!!myReferenceExpression.isQualified()) return false;
PsiElement scope = PsiTreeUtil.getParentOfType(myReferenceExpression, PsiMethod.class, PsiClass.class);
return scope instanceof PsiMethod && ((PsiMethod)scope).getParameterList().isPhysical();
}
public String getText(String varName) {
return "Create Parameter '" + varName + "'";
}
protected void invokeImpl(PsiClass targetClass) {
if (CreateFromUsageUtils.isValidReference(myReferenceExpression, true)) {
return;
}
PsiManager psiManager = myReferenceExpression.getManager();
Project project = psiManager.getProject();
PsiElementFactory factory = psiManager.getElementFactory();
PsiType[] expectedTypes = CreateFromUsageUtils.guessType(myReferenceExpression, false);
PsiType type = expectedTypes[0];
String varName = myReferenceExpression.getReferenceName();
PsiMethod method = PsiTreeUtil.getParentOfType(myReferenceExpression, PsiMethod.class);
PsiParameter param;
try {
param = factory.createParameter(varName, type);
param.getModifierList().setModifierProperty(PsiModifier.FINAL, CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_PARAMETERS &&
!PsiUtil.isAccessedForWriting(myReferenceExpression));
PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameters.length > 0 && parameters[parameters.length - 1].isVarArgs()) {
param = (PsiParameter)method.getParameterList().addBefore(param, parameters[parameters.length - 1]);
} else {
param = (PsiParameter) method.getParameterList().add(param);
}
} catch (IncorrectOperationException e) {
LOG.error(e);
return;
}
TemplateBuilder builder = new TemplateBuilder (method);
builder.replaceElement(param.getTypeElement(), new TypeExpression(project, expectedTypes));
builder.setEndVariableAfter(method.getParameterList());
Template template = builder.buildTemplate();
Editor editor = positionCursor(project, method.getContainingFile(), method);
TextRange range = method.getTextRange();
editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
TemplateManager.getInstance(project).startTemplate(editor, template);
}
public String getFamilyName() {
return "Create Parameter from Usage";
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.util.CloseableIterator;
import org.broad.igv.Globals;
import org.broad.igv.PreferenceManager;
import org.broad.igv.sam.reader.AlignmentReader;
import org.broad.igv.sam.reader.AlignmentReaderFactory;
import org.broad.igv.sam.reader.ReadGroupFilter;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.TestUtils;
import org.junit.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author jrobinso
*/
public class CachingQueryReaderTest {
String testFile = "http:
String sequence = "chr1";
int start = 44680145;
int end = 44789983;
private boolean contained = false;
;
public CachingQueryReaderTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
TestUtils.setUpHeadless();
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getHeader method, of class CachingQueryReader. The test compares
* the results of CachingQueryReader with a non-caching reader which
* is assumed to be correct.
*/
@Test
public void testGetHeader() throws IOException {
ResourceLocator loc = new ResourceLocator(testFile);
AlignmentReader reader = AlignmentReaderFactory.getReader(loc);
SAMFileHeader expectedHeader = reader.getHeader();
reader.close();
reader = AlignmentReaderFactory.getReader(loc);
CachingQueryReader cachingReader = new CachingQueryReader(reader);
SAMFileHeader header = cachingReader.getHeader();
cachingReader.close();
assertTrue(header.equals(expectedHeader));
}
@Test
public void testQuery() throws IOException {
tstQuery(testFile, sequence, start, end, contained);
}
/**
* Test of query method, of class CachingQueryReader. The test compares
* the results of CachingQueryReader non-caching reader which
* is assumed to be correct.
*/
public void tstQuery(String testFile, String sequence, int start, int end, boolean contained) throws IOException {
ResourceLocator loc = new ResourceLocator(testFile);
AlignmentReader reader = AlignmentReaderFactory.getReader(loc);
CloseableIterator<Alignment> iter = reader.query(sequence, start, end, contained);
Map<String, Alignment> expectedResult = new HashMap();
while (iter.hasNext()) {
Alignment rec = iter.next();
// the following filters are applied in the Caching reader, so we need to apply them here.
boolean filterFailedReads = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS);
ReadGroupFilter filter = ReadGroupFilter.getFilter();
boolean showDuplicates = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES);
int qualityThreshold = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD);
if (!rec.isMapped() || (!showDuplicates && rec.isDuplicate()) ||
(filterFailedReads && rec.isVendorFailedRead()) ||
rec.getMappingQuality() < qualityThreshold ||
(filter != null && filter.filterAlignment(rec))) {
continue;
}
expectedResult.put(rec.getReadName(), rec);
if(contained){
assertTrue(rec.getStart() >= start);
}else{
//All we require is some overlap
boolean overlap = rec.getStart() >= start && rec.getStart() <= end;
overlap |= rec.getEnd() >= start && rec.getEnd() <= end;
assertTrue(overlap);
}
assertEquals(sequence, rec.getChr());
}
reader.close();
reader = AlignmentReaderFactory.getReader(loc);
CachingQueryReader cachingReader = new CachingQueryReader(reader);
CloseableIterator<Alignment> cachingIter = cachingReader.query(sequence, start, end, new ArrayList(),
new ArrayList(), Integer.MAX_VALUE / 1000, null, null);
List<Alignment> result = new ArrayList();
while (cachingIter.hasNext()) {
result.add(cachingIter.next());
}
cachingReader.close();
assertTrue(expectedResult.size() > 0);
assertEquals(expectedResult.size(), result.size());
for (int i = 0; i < result.size(); i++) {
Alignment rec = result.get(i);
if(contained){
assertTrue(rec.getStart() >= start);
}else{
//All we require is some overlap
boolean overlap = rec.getStart() >= start && rec.getStart() <= end;
overlap |= start >= rec.getStart() && start <= rec.getEnd();
assertTrue(overlap);
}
assertEquals(sequence, rec.getChr());
assertTrue(expectedResult.containsKey(rec.getReadName()));
Alignment exp = expectedResult.get(rec.getReadName());
assertEquals(exp.getAlignmentStart(), rec.getAlignmentStart());
assertEquals(exp.getAlignmentEnd(), rec.getAlignmentEnd());
}
}
@Ignore
@Test
public void testQueryLargeFile() throws Exception{
PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, "5");
String path = TestUtils.LARGE_DATA_DIR + "/ABCD_igvSample.bam";
String sequence = "chr12";
int start = 56815621;
int end = start + 2;
int expSize = 1066;
//tstSize(cachingReader, sequence, start, end, Integer.MAX_VALUE / 100, expSize);
sequence = "chr12";
start = 56815634;
end = start + 2;
expSize = 165;
tstQuery(path, sequence, start, end, false);
}
public List<Alignment> tstSize(CachingQueryReader cachingReader, String sequence, int start, int end, int maxDepth, int expSize){
CloseableIterator<Alignment> cachingIter = cachingReader.query(sequence, start, end, new ArrayList(),
new ArrayList(), maxDepth, null, null);
List<Alignment> result = new ArrayList();
while (cachingIter.hasNext()) {
result.add(cachingIter.next());
}
assertEquals(expSize, result.size());
return result;
}
}
|
package com.splicemachine.mrio.api.core;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.ResultSetMetaData;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import com.splicemachine.derby.test.framework.SpliceDataWatcher;
import com.splicemachine.derby.test.framework.SpliceNetConnection;
import com.splicemachine.derby.test.framework.SpliceSchemaWatcher;
import com.splicemachine.derby.test.framework.SpliceTableWatcher;
import com.splicemachine.derby.test.framework.SpliceWatcher;
// Ignore until mapr brakage is fixed
@Ignore
public class HiveIntegrationIT extends BaseMRIOTest {
private static final Logger LOG = Logger.getLogger(HiveIntegrationIT.class);
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
static {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected static SpliceWatcher spliceClassWatcher = new SpliceWatcher();
protected static SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(HiveIntegrationIT.class.getSimpleName());
protected static SpliceTableWatcher spliceTableWatcherA = new SpliceTableWatcher("A",HiveIntegrationIT.class.getSimpleName(),"(col1 int, col2 int, col3 int, primary key (col3, col1))");
protected static SpliceTableWatcher spliceTableWatcherB = new SpliceTableWatcher("B",HiveIntegrationIT.class.getSimpleName(),"(col1 char(20), col2 varchar(56), primary key (col1))");
protected static SpliceTableWatcher spliceTableWatcherC = new SpliceTableWatcher("C",HiveIntegrationIT.class.getSimpleName(),"("
+ "tinyint_col smallint,"
+ "smallint_col smallInt, "
+ "int_col int, "
+ "bigint_col bigint, "
+ "float_col float, "
+ "double_col double, "
+ "decimal_col decimal, "
+ "timestamp_col timestamp, "
+ "date_col date, "
+ "varchar_col varchar(32), "
+ "char_col char(32), "
+ "boolean_col boolean, "
+ "binary_col varchar(30))"
);
protected static SpliceTableWatcher spliceTableWatcherD = new SpliceTableWatcher("D",HiveIntegrationIT.class.getSimpleName(),"(id int, name varchar(10), gender char(1))");
protected static SpliceTableWatcher spliceTableWatcherE = new SpliceTableWatcher("E",HiveIntegrationIT.class.getSimpleName(),"("
+ "tinyint_col smallint,"
+ "smallint_col smallInt, "
+ "int_col int, "
+ "bigint_col bigint, "
+ "float_col float, "
+ "double_col double, "
+ "decimal_col decimal, "
+ "timestamp_col timestamp, "
+ "date_col date, "
+ "varchar_col varchar(32), "
+ "char_col char(32), "
+ "boolean_col boolean)"
);
@ClassRule
public static TestRule chain = RuleChain.outerRule(spliceClassWatcher)
.around(spliceSchemaWatcher)
.around(spliceTableWatcherA)
.around(spliceTableWatcherB)
.around(spliceTableWatcherC)
.around(spliceTableWatcherE)
.around(new SpliceDataWatcher(){
@Override
protected void starting(Description description) {
try {
PreparedStatement psA = spliceClassWatcher.prepareStatement("insert into "+ HiveIntegrationIT.class.getSimpleName() + ".A (col1,col2,col3) values (?,?,?)");
PreparedStatement psB = spliceClassWatcher.prepareStatement("insert into "+ HiveIntegrationIT.class.getSimpleName() + ".B (col1,col2) values (?,?)");
PreparedStatement psC = spliceClassWatcher.prepareStatement("insert into "+ HiveIntegrationIT.class.getSimpleName() + ".C ("
+ "tinyint_col,"
+ "smallint_col, "
+ "int_col, "
+ "bigint_col, "
+ "float_col, "
+ "double_col, "
+ "decimal_col, "
+ "timestamp_col, "
+ "date_col, "
+ "varchar_col, "
+ "char_col, "
+ "boolean_col, "
+ "binary_col) "
+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?)");
PreparedStatement psE = spliceClassWatcher.prepareStatement("insert into "+ HiveIntegrationIT.class.getSimpleName() + ".E ("
+ "decimal_col, "
+ "timestamp_col, "
+ "date_col, "
+ "varchar_col, "
+ "char_col)"
+ "values (?,?,?,?,?)");
for (int i = 0; i< 100; i++) {
psA.setInt(1,i);
psA.setInt(2,i+1);
psA.setInt(3,i+2);
psA.executeUpdate();
psB.setString(1,"Char " + i);
psB.setString(2, "Varchar " + i);
psB.executeUpdate();
psC.setInt(1, i);
psC.setInt(2, i);
psC.setInt(3, i);
psC.setInt(4, i);
psC.setFloat(5, (float) (i * 1.0));
psC.setDouble(6, i * 1.0);
psC.setBigDecimal(7, new BigDecimal(i*1.0));
psC.setTimestamp(8, new Timestamp(System.currentTimeMillis()));
psC.setDate(9, new Date(System.currentTimeMillis()));
psC.setString(10, "varchar " + i);
psC.setString(11, "char " + i);
psC.setBoolean(12, true);
psC.setString(13, "Binary " + i);
psC.executeUpdate();
psE.setBigDecimal(1, null);
psE.setTimestamp(2, null);
psE.setDate(3, null);
psE.setString(4, null);
psE.setString(5, null);
psE.executeUpdate();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.around(spliceTableWatcherD)
.around(new SpliceDataWatcher(){
@Override
protected void starting(Description description) {
try {
PreparedStatement psD = spliceClassWatcher.prepareStatement("insert into "+ HiveIntegrationIT.class.getSimpleName() + ".D (id,name,gender) values (?,?,?)");
psD.setInt(1,1);
psD.setString(2, null);
psD.setString(3,"M");
psD.execute();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
@Rule public SpliceWatcher methodWatcher = new SpliceWatcher();
@Test
public void testCompositePK() throws SQLException, IOException {
Connection con = DriverManager.getConnection("jdbc:hive:
Statement stmt = con.createStatement();
String createExternalExisting = "CREATE EXTERNAL TABLE A " +
"(COL1 INT, COL2 INT, COL3 INT) " +
"STORED BY 'com.splicemachine.mrio.api.hive.SMStorageHandler' " +
"TBLPROPERTIES (" +
"\"splice.jdbc\" = \""+SpliceNetConnection.getDefaultLocalURL()+"\","+
"\"splice.tableName\" = \"HIVEINTEGRATIONIT.A\""+
")";
stmt.execute(createExternalExisting);
ResultSet rs = stmt.executeQuery("select * from A");
int i = 0;
while (rs.next()) {
i++;
int v1 = rs.getInt(1);
int v2 = rs.getInt(2);
int v3 = rs.getInt(3);
Assert.assertNotNull("col1 did not return", v1);
Assert.assertNotNull("col1 did not return", v2);
Assert.assertNotNull("col1 did not return", v3);
Assert.assertTrue(v2==v1+1);
Assert.assertTrue(v3==v2+1);
}
Assert.assertEquals("incorrect number of rows returned", 100,i);
}
@Test
public void testVarchar() throws SQLException, IOException {
Connection con = DriverManager.getConnection("jdbc:hive:
Statement stmt = con.createStatement();
String createExternalExisting = "CREATE EXTERNAL TABLE B " +
"(col1 String, col2 VARCHAR(56)) " +
"STORED BY 'com.splicemachine.mrio.api.hive.SMStorageHandler' " +
"TBLPROPERTIES (" +
"\"splice.jdbc\" = \""+SpliceNetConnection.getDefaultLocalURL()+"\","+
"\"splice.tableName\" = \"HIVEINTEGRATIONIT.B\""+
")";
stmt.execute(createExternalExisting);
ResultSet rs = stmt.executeQuery("select * from B");
int i = 0;
while (rs.next()) {
i++;
Assert.assertNotNull("col1 did not return", rs.getString(1));
Assert.assertNotNull("col1 did not return", rs.getString(2));
}
Assert.assertEquals("incorrect number of rows returned", 100,i);
}
@Test
public void testNullColumnValue() throws SQLException, IOException {
Connection con = DriverManager.getConnection("jdbc:hive:
Statement stmt = con.createStatement();
String createExternalExisting = "CREATE EXTERNAL TABLE D " +
"(id int, name VARCHAR(10), gender char(1)) " +
"STORED BY 'com.splicemachine.mrio.api.hive.SMStorageHandler' " +
"TBLPROPERTIES (" +
"\"splice.jdbc\" = \""+SpliceNetConnection.getDefaultLocalURL()+"\","+
"\"splice.tableName\" = \"HIVEINTEGRATIONIT.D\""+
")";
stmt.execute(createExternalExisting);
ResultSet rs = stmt.executeQuery("select * from D");
int i = 0;
while (rs.next()) {
i++;
int id = rs.getInt(1);
String name = rs.getString(2);
String gender = rs.getString(3);
Assert.assertNotNull("col1 did not return", id);
Assert.assertNull("col2 did not return", name);
Assert.assertTrue("Incorrect gender value returned", gender.compareToIgnoreCase("M")==0);
}
Assert.assertEquals("incorrect number of rows returned", 1,i);
}
@Test
public void testDataTypes() throws SQLException, IOException {
Connection con = DriverManager.getConnection("jdbc:hive:
Statement stmt = con.createStatement();
String createExternalExisting = "CREATE EXTERNAL TABLE C ("
+ "tinyint_col tinyint,"
+ "smallint_col smallInt, "
+ "int_col int, "
+ "bigint_col bigint, "
+ "float_col float, "
+ "double_col double, "
+ "decimal_col decimal, "
+ "timestamp_col timestamp, "
+ "date_col date, "
+ "varchar_col varchar(32), "
+ "char_col char(32), "
+ "boolean_col boolean, "
+ "binary_col binary)" +
"STORED BY 'com.splicemachine.mrio.api.hive.SMStorageHandler' " +
"TBLPROPERTIES (" +
"\"splice.jdbc\" = \""+SpliceNetConnection.getDefaultLocalURL()+"\","+
"\"splice.tableName\" = \"HIVEINTEGRATIONIT.C\""+
")";
stmt.execute(createExternalExisting);
ResultSet rs = stmt.executeQuery("select * from C");
int i = 0;
while (rs.next()) {
i++;
Assert.assertNotNull("col1 did not return", rs.getByte(1));
Assert.assertNotNull("col2 did not return", rs.getShort(2));
Assert.assertNotNull("col3 did not return", rs.getInt(3));
Assert.assertNotNull("col4 did not return", rs.getLong(4));
Assert.assertNotNull("col5 did not return", rs.getFloat(5));
Assert.assertNotNull("col6 did not return", rs.getDouble(6));
Assert.assertNotNull("col7 did not return", rs.getBigDecimal(7));
Assert.assertNotNull("col8 did not return", rs.getTimestamp(8));
Assert.assertNotNull("col9 did not return", rs.getDate(9));
Assert.assertNotNull("col10 did not return", rs.getString(10));
Assert.assertNotNull("col11 did not return", rs.getString(11));
Assert.assertNotNull("col12 did not return", rs.getBoolean(12));
Assert.assertNotNull("col13 did not return", rs.getString(13));
}
Assert.assertEquals("incorrect number of rows returned", 100, i);
}
@Test
public void testNullColumnValues() throws SQLException, IOException {
Connection con = DriverManager.getConnection("jdbc:hive:
Statement stmt = con.createStatement();
String createExternalExisting = "CREATE EXTERNAL TABLE E ("
+ "tinyint_col tinyint,"
+ "smallint_col smallInt, "
+ "int_col int, "
+ "bigint_col bigint, "
+ "float_col float, "
+ "double_col double, "
+ "decimal_col decimal, "
+ "timestamp_col timestamp, "
+ "date_col date, "
+ "varchar_col varchar(32), "
+ "char_col char(32), "
+ "boolean_col boolean)" +
"STORED BY 'com.splicemachine.mrio.api.hive.SMStorageHandler' " +
"TBLPROPERTIES (" +
"\"splice.jdbc\" = \""+SpliceNetConnection.getDefaultLocalURL()+"\","+
"\"splice.tableName\" = \"HIVEINTEGRATIONIT.E\""+
")";
stmt.execute(createExternalExisting);
ResultSet rs = stmt.executeQuery("select * from E");
int i = 0;
while (rs.next()) {
i++;
Assert.assertTrue("col1 did not return", rs.getByte(1)==0);
Assert.assertTrue("col2 did not return", rs.getShort(2)==0);
Assert.assertTrue("col3 did not return", rs.getInt(3)==0);
Assert.assertTrue("col4 did not return", rs.getLong(4)==0);
Assert.assertTrue("col5 did not return", rs.getFloat(5)==0);
Assert.assertTrue("col6 did not return", rs.getDouble(6)==0);
//TODO - jyuan: Should this return a null?
Assert.assertTrue("col7 did not return", rs.getBigDecimal(7).toString().compareTo("0")==0);
Assert.assertNull("col8 did not return", rs.getTimestamp(8));
Assert.assertNull("col9 did not return", rs.getDate(9));
Assert.assertNull("col10 did not return", rs.getString(10));
Assert.assertNull("col11 did not return", rs.getString(11));
Assert.assertTrue("col12 did not return", rs.getBoolean(12)==false);
}
Assert.assertEquals("incorrect number of rows returned", 100, i);
}
}
|
package hudson.slaves;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlLabel;
import hudson.model.Descriptor.FormException;
import hudson.model.Slave;
import net.sf.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
/**
* @author Kohsuke Kawaguchi
*/
public class NodePropertyTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void invisibleProperty() throws Exception {
DumbSlave s = j.createSlave();
InvisibleProperty before = new InvisibleProperty();
s.getNodeProperties().add(before);
assertFalse(before.reconfigured);
DumbSlave s2 = j.configRoundtrip(s);
assertNotSame(s,s2);
InvisibleProperty after = s2.getNodeProperties().get(InvisibleProperty.class);
assertSame(before,after);
assertTrue(after.reconfigured);
}
public static class InvisibleProperty extends NodeProperty<Slave> {
boolean reconfigured = false;
@Override
public NodeProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws FormException {
reconfigured = true;
return this;
}
@TestExtension("invisibleProperty")
public static class DescriptorImpl extends NodePropertyDescriptor {
@Override
public String getDisplayName() {
return null;
}
}
}
@Test
public void basicConfigRoundtrip() throws Exception {
DumbSlave s = j.createSlave();
HtmlForm f = j.createWebClient().goTo("computer/" + s.getNodeName() + "/configure").getFormByName("config");
((HtmlLabel)DomNodeUtil.selectSingleNode(f, ".//LABEL[text()='Some Property']")).click();
j.submit(f);
PropertyImpl p = j.jenkins.getNode(s.getNodeName()).getNodeProperties().get(PropertyImpl.class);
assertEquals("Duke",p.name);
p.name = "Kohsuke";
j.configRoundtrip(s);
PropertyImpl p2 = j.jenkins.getNode(s.getNodeName()).getNodeProperties().get(PropertyImpl.class);
assertNotSame(p,p2);
j.assertEqualDataBoundBeans(p, p2);
}
public static class PropertyImpl extends NodeProperty<Slave> {
public String name;
@DataBoundConstructor
public PropertyImpl(String name) {
this.name = name;
}
@TestExtension("basicConfigRoundtrip")
public static class DescriptorImpl extends NodePropertyDescriptor {
@Override
public String getDisplayName() {
return "Some Property";
}
}
}
}
|
package socialite.dist.master;
import gnu.trove.map.hash.TIntFloatHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.security.UserGroupInformation;
import org.python.core.PyFunction;
import org.python.modules.synchronize;
import socialite.codegen.CodeGenMain;
import socialite.dist.ErrorRecord;
import socialite.dist.Host;
import socialite.dist.PathTo;
import socialite.dist.PortMap;
import socialite.dist.Status;
import socialite.dist.client.TupleSend;
import socialite.dist.worker.WorkerCmd;
import socialite.engine.Config;
import socialite.engine.DistEngine;
import socialite.eval.ClassFilesBlob;
import socialite.eval.EvalProgress;
import socialite.functions.PyInterp;
import socialite.functions.PyInvoke;
import socialite.parser.Rule;
import socialite.parser.Table;
import socialite.parser.Parser;
import socialite.resource.WorkerAddrMap;
import socialite.resource.WorkerAddrMapW;
import socialite.resource.SRuntime;
import socialite.resource.TableInstRegistry;
import socialite.resource.TableSliceMap;
import socialite.tables.QueryVisitor;
import socialite.util.IdFactory;
import socialite.util.Loader;
import socialite.util.SociaLiteException;
import socialite.util.SocialiteInputStream;
import socialite.util.SocialiteOutputStream;
public class QueryListener implements QueryProtocol {
public static final Log L = LogFactory.getLog(QueryListener.class);
String masterAddr;
int queryListenPort;
MasterNode master;
Config conf;
DistEngine distEngine;
public QueryListener(Config _conf, MasterNode _master) {
conf = _conf;
masterAddr = conf.portMap().masterAddr();
queryListenPort = conf.portMap().queryListen();
master = _master;
}
public void start() {
try {
int numHandlers = Runtime.getRuntime().availableProcessors();
if (numHandlers < 4) numHandlers = 4;
if (numHandlers > 32) numHandlers = 32;
Configuration hConf = new Configuration();
Server server = RPC.getServer(this, masterAddr, queryListenPort,numHandlers, false, hConf);
server.start();
} catch (IOException e) {
L.fatal("Exception while starting QueryListener:");
L.fatal(ExceptionUtils.getStackTrace(e));
}
}
String localExtLibPath() {
return PathTo.output("ext");
}
String localExtLibPath(String file) {
return PathTo.concat(localExtLibPath(), file);
}
@Override
public BooleanWritable addToClassPath(Text hdfsPathText) {
String filePath = hdfsPathText.toString();
String file = PathTo.basename(filePath);
try {
Configuration hConf = new Configuration();
FileSystem hdfs = FileSystem.get(hConf);
FileSystem localFs = FileSystem.getLocal(hConf);
Path hdfsPath = new Path(filePath);
Path localPath = new Path(localExtLibPath());
FileUtil.copy(hdfs, hdfsPath, localFs, localPath, false, true,
hConf);
String localFilePath = localExtLibPath(file);
Loader.addClassPath(new File(localFilePath));
return new BooleanWritable(true);
} catch (IOException e) {
L.error("Error while adding class path:" + e);
return new BooleanWritable(false);
}
}
@Override
public BooleanWritable removeFromClassPath(Text _file) {
String file = PathTo.basename(_file.toString());
try {
URL url = new File(localExtLibPath(file.toString())).toURI().toURL();
Loader.removeClassPath(url);
return new BooleanWritable(true);
} catch (MalformedURLException e) {
L.error("Malformed path[" + file + "]:" + e);
return new BooleanWritable(false);
}
}
boolean prevSessionExists() {
if (SRuntime.masterRt() == null)
return false;
return true;
}
@Override
public synchronized BooleanWritable beginSession(Text _path,
IntWritable _workerNodeNum) {
boolean newSession = true;
String path = _path.toString();
if (prevSessionExists()) {
if (path.equals(PathTo.cwd()))
newSession = false;
else endSession();
}
boolean loadSession = false;
int workerNodeNum = -1;
if (_workerNodeNum != null)
workerNodeNum = _workerNodeNum.get();
WorkerAddrMap workerAddrMap = master.makeWorkerAddrMap(workerNodeNum);
SRuntime.newMasterRt(master, workerAddrMap);
master.beginSession();
if (path.length() == 0)
path = PathTo.defaultDistCwd();
PathTo.setcwd(path);
prepareWorkSpace();
if (newSession) {
IdFactory.reset();
loadSession = loadTableMap(); // XXX: after loading, check the
// workers and table slices...
}
try {
Method begin = WorkerCmd.class.getMethod("beginSession",
new Class[] { Text.class, WorkerAddrMapW.class,
boolean.class });
Object p[] = new Object[]{ _path, new WorkerAddrMapW(workerAddrMap), loadSession};
MasterNode.callWorkers(workerAddrMap, begin, p);
} catch (Exception e) {
L.fatal("Exception while calling beginSession for workers");
}
return new BooleanWritable(true);
}
@Override
public synchronized BooleanWritable beginSession(Text path) {
return beginSession(path, null);
}
@Override
public BooleanWritable storeWorkspace() {
storeTableMap();
try {
Method begin = WorkerCmd.class.getMethod("storeSession",
new Class[] { Text.class });
Object p[] = new Object[] { new Text(PathTo.cwd()) };
MasterNode.callWorkers(begin, p);
} catch (Exception e) {
L.fatal("Exception while calling storeSession for workers");
}
return new BooleanWritable(true);
}
@Override
public BooleanWritable storeWorkspace(Text _path) {
String path = _path.toString();
PathTo.setcwd(path);
return storeWorkspace();
}
void deleteRecur(File dir) {
if (!dir.exists()) return;
assert dir.isDirectory();
for (File f : dir.listFiles()) {
if (f.isDirectory())
deleteRecur(f);
f.delete();
}
}
void prepareWorkSpace() {
// clean-up workspace in master's local-fs
String rootDir = PathTo.concat(PathTo.classOutput(), "socialite");
if (new File(rootDir).listFiles() != null) {
for (File f : new File(rootDir).listFiles()) {
if (f.isDirectory())
deleteRecur(f);
}
}
}
void cleanupLocalWorkSpace(String path) {
File ws = new File(path);
deleteRecur(ws);
}
@Override
public void cleanupTableIter(LongWritable id) {
try {
Method cleanup = WorkerCmd.class.getMethod("cleanupTableIter", new Class[] {LongWritable.class});
Object param[] = new Object[]{id};
MasterNode.callWorkers(cleanup, param);
} catch (Exception e) {
L.fatal("Exception while calling WorkerCmd.cleanupTableIter():" + e);
}
getEngine().cleanupTableIter(id.get());
}
@Override
public BooleanWritable endSession() {
shutdownEngine();
// cleanupLocalWorkSpace(PathTo.classOutput());
try {
Method endSession = WorkerCmd.class.getMethod("endSession", new Class[] {});
Object param[] = new Object[0];
MasterNode.callWorkers(endSession, param);
} catch (Exception e) {
L.fatal("Exception while calling WorkerCmd.endSession():" + e);
}
master.setEpochDone();
SRuntime.voidMasterRt();
PathTo.setcwd(null);
distEngine = null;
Loader.cleanup();
EvalProgress.getInst().clear();
CodeGenMain.clearCache();
return new BooleanWritable(true);
}
void printMemInfo(String prefix) {
long used = Runtime.getRuntime().totalMemory() -
Runtime.getRuntime().freeMemory();
L.info(prefix + " Used Memory:" + used / 1024 / 1024 + "M");
}
void shutdownEngine() {
if (distEngine!=null) {
distEngine.shutdown();
distEngine = null;
}
}
boolean engineExists() { return distEngine!=null;}
synchronized DistEngine getEngine() {
if (distEngine==null) {
SRuntime runtime = SRuntime.masterRt();
Config workerConf = runtime.getConf();
WorkerAddrMap addrMap = runtime.getWorkerAddrMap();
Map<InetAddress, WorkerCmd> workerMap = master.getWorkerCmdMap();
distEngine = new DistEngine(workerConf, addrMap, workerMap);
}
return distEngine;
}
void runReally(Text prog, TupleSend qv) throws RemoteException {
DistEngine en = null;
CodeGenMain codeMain=null;
synchronized(this) {
if (!prevSessionExists()) {
beginSession(new Text(PathTo.defaultDistCwd()));
}
String program = prog.toString();
en = getEngine();
try { codeMain = en.compile(program, qv); }
catch (Exception e) {
L.error("Error while compiling:");
L.error(ExceptionUtils.getStackTrace(e));
throw new RemoteException("SociaLiteException", e.getMessage());
}
}
String err=null;
try {
en.run(codeMain, qv);
err = ErrorRecord.getInst().getErrorMsg(codeMain);
ErrorRecord.getInst().clearError(codeMain);
} catch (Exception e) {
L.error("Error while running query ("+prog+"):");
L.error(ExceptionUtils.getStackTrace(e));
throw new RemoteException("SociaLiteException", e.getMessage());
}
if (err!=null) throw new RemoteException("SociaLiteException", err);
}
@Override
public void run(Text prog) throws RemoteException {
runReally(prog, (TupleSend)null);
}
@Override
public void run(Text prog, Text clientIp, IntWritable port) throws RemoteException {
TupleSend queryVisitor = new TupleSend("QueryListener", clientIp.toString(), port.get());
runReally(prog, queryVisitor);
}
@Override
public void run(Text prog, Text clientIp, IntWritable port, LongWritable id) throws RemoteException {
TupleSend queryVisitor= new TupleSend("QueryListener", clientIp.toString(), port.get(), id.get());
runReally(prog, queryVisitor);
}
@Override
public long getProtocolVersion(String arg0, long arg1) throws IOException {
return QueryProtocol.versionID;
}
public void addPyFunctions(BytesWritable bytesClassFilesBlob, BytesWritable bytesPyfuncs) throws RemoteException {
ClassFilesBlob classFilesBlob = ClassFilesBlob.fromBytesWritable(bytesClassFilesBlob);
Loader.loadFromBytes(classFilesBlob.names(), classFilesBlob.files());
for (String pyClassName:classFilesBlob.names()) {
try {
Class<?> pyClass=Loader.forName(pyClassName);
Constructor<?> constr = pyClass.getConstructor(new Class[]{String.class});
constr.newInstance(new Object[] {"<SociaLite>"});
} catch (Exception e) {
L.warn("Failed to make PyCode object:"+e);
continue;
}
}
List<PyFunction> pyfuncs=PyInterp.fromBytesWritable(bytesPyfuncs);
PyInterp.addFunctions(pyfuncs);
PyInvoke.update(pyfuncs);
try {
Method get = WorkerCmd.class.getMethod("addPyFunctions",
new Class[]{BytesWritable.class, BytesWritable.class});
Object p[] = new Object[]{bytesClassFilesBlob, bytesPyfuncs};
MasterNode.callWorkers(get, p);
} catch (Exception e) {
throw new RemoteException("SociaLiteException", e.getMessage());
}
}
public void addClassFiles(BytesWritable bytesClassFilesBlob) throws RemoteException {
ClassFilesBlob classFilesBlob = ClassFilesBlob.fromBytesWritable(bytesClassFilesBlob);
Loader.loadFromBytes(classFilesBlob.names(), classFilesBlob.files());
try {
Method add = WorkerCmd.class.getMethod("addClassFiles",
new Class[]{BytesWritable.class});
Object p[] = new Object[]{bytesClassFilesBlob};
MasterNode.callWorkers(add, p);
} catch (Exception e) {
throw new RemoteException("SociaLiteException", e.getMessage());
}
}
void storeTableMap() {
SRuntime rt = SRuntime.masterRt();
try {
FileSystem fs = FileSystem.get(new Configuration());
String mapFile = PathTo.cwd(TableInstRegistry.tableMapFile());
Path mapFilePath = new Path(mapFile);
FSDataOutputStream fsos = fs.create(mapFilePath, true);
SocialiteOutputStream sos = new SocialiteOutputStream(fsos);
TableInstRegistry reg = rt.getTableRegistry();
reg.storeTableMap(sos);
;
FileSystem localfs = FileSystem.getLocal(new Configuration());
// fs.delete(new Path(PathTo.cwd("_classes", "socialite",
// "tables")), true);
fs.setVerifyChecksum(false);
localfs.setVerifyChecksum(false);
fs.delete(new Path(PathTo.cwd("_classes", "socialite", "tables")),
true);
FileUtil.copy(localfs,
new Path(PathTo.classOutput("socialite", "tables")), fs,
new Path(PathTo.cwd("_classes", "socialite", "tables")),
false/* delete src */, true/* overwrite */,
new Configuration());
fs.close();
} catch (IOException e) {
L.error("Error while storing tables:" + e);
}
return;
}
boolean loadTableMap() {
SRuntime rt = SRuntime.masterRt();
Map<String, Table> _tableMap = null;
try {
String mapFile = PathTo.cwd(TableInstRegistry.tableMapFile());
FileSystem fs;
if (mapFile.startsWith("hdfs:
fs = FileSystem.get(new Configuration());
else
fs = FileSystem.getLocal(new Configuration());
Path mapFilePath = new Path(mapFile);
if (!fs.exists(mapFilePath))
return false;
FileSystem localfs = FileSystem.getLocal(new Configuration());
localfs.delete(new Path(PathTo.classOutput("socialite", "tables")),
true);
localfs.setVerifyChecksum(false);
fs.setVerifyChecksum(false);
FileUtil.copy(fs,
new Path(PathTo.cwd("_classes", "socialite", "tables")),
localfs,
new Path(PathTo.classOutput("socialite", "tables")),
false/* delete src */, true/* overwrite */,
new Configuration());
FSDataInputStream fsis = fs.open(mapFilePath);
SocialiteInputStream sis = new SocialiteInputStream(fsis);
TableInstRegistry reg = rt.getTableRegistry();
_tableMap = reg.loadTableMap(sis);
rt.getTableMap().putAll(_tableMap);
for (Table t : _tableMap.values()) {
rt.getSliceMap().addTable(t);
}
fs.close();
return true;
} catch (IOException e) {
L.error("Error while loading tables:" + e);
return false;
}
}
public BytesWritable status() {
return status(new IntWritable(0));
}
public BytesWritable status(IntWritable _verbose) {
int verbose = _verbose.get();
Status summary=new Status();
Object[] _workerStats;
WorkerAddrMap workerAddrMap = MasterNode.getCurrentWorkerAddrMap();
summary.putNodeNum(""+workerAddrMap.size());
try {
Method status = WorkerCmd.class.getMethod("status",new Class[]{IntWritable.class});
_workerStats=MasterNode.callWorkers(workerAddrMap, status, new Object[] {_verbose});
} catch (Exception e) {
L.error("Exception while getting status from workers:");
L.error(ExceptionUtils.getStackTrace(e));
return Status.toWritable(summary);
}
Status[] workerStats=new Status[_workerStats.length];
for (int i=0; i<_workerStats.length; i++) {
Status s=(Status)Status.fromWritable((BytesWritable)_workerStats[i]);
workerStats[i] = s;
}
memStatus(summary, workerAddrMap, workerStats, verbose);
tableStatus(summary);
progressStatus(summary, workerAddrMap, workerStats, verbose);
return Status.toWritable(summary);
}
void tableStatus(Status summary) {
if (!engineExists()) return;
DistEngine engine = getEngine();
Parser p = getEngine().getParser();
Map<String, Table> tableMap = p.getTableMap();
String tableInfo="";
boolean first=true;
for (String name:tableMap.keySet()) {
if (!first) tableInfo += "\n";
tableInfo += name;
first=false;
}
summary.putTableStatus(tableInfo);
}
void memStatus(Status summary, WorkerAddrMap workerAddrMap, Status[] workerStats, int verbose) {
int minFreeMB=Integer.MAX_VALUE, sumFreeMB=0;
String minFreeMemInfo="";
String allMemStat="";
for (int i=0; i<workerStats.length; i++) {
Status s=workerStats[i];
int freeMB=(int)((Long)s.getMemStatus()/1024.0/1024.0);
String freeMemInfo = workerAddrMap.get(i).getHostName()+":"+ freeMB+"MB\n";
allMemStat += freeMemInfo;
if (freeMB < minFreeMB) {
minFreeMB = freeMB;
minFreeMemInfo = freeMemInfo;
}
sumFreeMB += freeMB;
}
if (verbose==0) {
String memStat="Min free memory: " + minFreeMemInfo;
memStat += "Average free memory: "+ (sumFreeMB/workerStats.length)+"MB\n";
summary.putMemStatus(memStat);
} else { summary.putMemStatus(allMemStat); }
}
void progressStatus(Status summary, WorkerAddrMap workerAddrMap, Status[] workerStats, int verbose) {
if (workerStats.length==0) return;
if (!engineExists()) return;
TIntFloatHashMap progStats[] = new TIntFloatHashMap[workerStats.length];
for (int i=0; i<workerStats.length; i++)
progStats[i] = (TIntFloatHashMap )workerStats[i].getProgress();
String allEvalStat="", aggrEvalStat="";
int[] rules=progStats[0].keys();
Arrays.sort(rules);
next_rule:
for (int rule:rules) {
String ruleEvalStat="";
Rule r=getEngine().getParser().getRuleById(rule);
ruleEvalStat += r+"\n";
int minEval=Integer.MAX_VALUE;
String minEvalInfo="";
for (int i=0; i<progStats.length; i++) {
if (!progStats[i].contains(rule)) continue next_rule;
int x=(int)(progStats[i].get(rule)*100);
String evalInfo = workerAddrMap.get(i).getHostName()+":"+x+"%\n";
ruleEvalStat += " "+evalInfo;
if (x <= minEval) {
minEval = x;
minEvalInfo = " Min progress: "+evalInfo;
}
}
if (minEval==100) {
allEvalStat += r+": Finished\n";
aggrEvalStat += r+": Finished\n";
} else if (minEval<0) {
allEvalStat += r+": Finished (error thrown)\n";
aggrEvalStat += r+": Finished (error thrown)\n";
} else {
allEvalStat += ruleEvalStat;
aggrEvalStat += r+"\n"+minEvalInfo;
}
}
if (verbose==0) summary.putProgress(aggrEvalStat);
else summary.putProgress(allEvalStat);
}
@Override
public void showTableMap() {
SRuntime r = SRuntime.masterRt();
Map<String, Table> map = r.getTableMap();
TableSliceMap sliceMap = r.getSliceMap();
for (String name : map.keySet()) {
Table t = map.get(name);
if (t.isDistributed()) {
int sliceNum = sliceMap.virtualSliceNum(t.id());
System.out.println("Table:" + t.name());
for (int i = 0; i < sliceNum; i++) {
int range[] = sliceMap.getRange(t.id(), i);
System.out.println("\t[" + i + "]:" + range[0] + " - "
+ range[1]);
}
}
}
}
@Override
public void runGc() {
Method runGc = null;
try {
runGc = WorkerCmd.class.getMethod("runGc", new Class[] {});
int cmdPort = Config.dist().portMap().workerCmdListen();
WorkerAddrMap workerAddrMap = master.makeWorkerAddrMap(-1);
InetSocketAddress addrs[] = workerAddrMap.getSockAddrs(cmdPort)
.toArray(new InetSocketAddress[0]);
UserGroupInformation ugi;
ugi = UserGroupInformation.getCurrentUser();
Object params[][] = new Object[addrs.length][1];
Object p[] = new Object[] {};
Arrays.fill(params, p);
Configuration hconf = new Configuration();
RPC.call(runGc, params, addrs, ugi, hconf);
} catch (Exception e) {
L.error("Exception while calling WorkerCmd.runGc():" + e);
}
System.gc();
// printMemInfo("MasterNode, After System.gc():");
}
@Override
public void setVerbose(BooleanWritable verbose) {
Method setVerbose = null;
try {
setVerbose = WorkerCmd.class.getMethod("setVerbose",
new Class[] { BooleanWritable.class });
int cmdPort = Config.dist().portMap().workerCmdListen();
WorkerAddrMap workerAddrMap = master.makeWorkerAddrMap(-1);
InetSocketAddress addrs[] = workerAddrMap.getSockAddrs(cmdPort)
.toArray(new InetSocketAddress[0]);
UserGroupInformation ugi;
ugi = UserGroupInformation.getCurrentUser();
Object params[][] = new Object[addrs.length][1];
Object p[] = new Object[] { verbose };
Arrays.fill(params, p);
Configuration hconf = new Configuration();
RPC.call(setVerbose, params, addrs, ugi, hconf);
} catch (Exception e) {
L.error("Exception while calling WorkerCmd.setVerbose():" + e);
}
}
}
class IntStringMap {
TIntObjectHashMap<String> map;
IntStringMap(int size) {
map = new TIntObjectHashMap<String>(size);
}
public synchronized String put(int k, String v) {
return map.put(k, v);
}
public synchronized boolean containsValue(String v) {
return map.containsValue(v);
}
public synchronized boolean containsKey(int k) {
return map.containsKey(k);
}
public synchronized String get(int k) {
return map.get(k);
}
}
|
package org.pentaho.di.ui.repository.repositoryexplorer.controllers;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.ui.repository.repositoryexplorer.ContextChangeVetoer;
import org.pentaho.di.ui.repository.repositoryexplorer.ContextChangeVetoerCollection;
import org.pentaho.di.ui.repository.repositoryexplorer.ControllerInitializationException;
import org.pentaho.di.ui.repository.repositoryexplorer.IUISupportController;
import org.pentaho.di.ui.repository.repositoryexplorer.RepositoryExplorer;
import org.pentaho.di.ui.repository.repositoryexplorer.ContextChangeVetoer.TYPE;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIObjectCreationException;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIObjectRegistry;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIRepositoryContent;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIRepositoryDirectory;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIRepositoryObject;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIRepositoryObjects;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.BindingFactory;
import org.pentaho.ui.xul.binding.DefaultBindingFactory;
import org.pentaho.ui.xul.components.XulMessageBox;
import org.pentaho.ui.xul.components.XulPromptBox;
import org.pentaho.ui.xul.containers.XulTree;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.impl.AbstractXulEventHandler;
import org.pentaho.ui.xul.swt.custom.DialogConstant;
import org.pentaho.ui.xul.util.XulDialogCallback;
/**
*
* This is the XulEventHandler for the browse panel of the repository explorer. It sets up the bindings for
* browse functionality.
*
*/
public class BrowseController extends AbstractXulEventHandler implements IUISupportController, IBrowseController {
private ResourceBundle messages = new ResourceBundle() {
@Override
public Enumeration<String> getKeys() {
return null;
}
@Override
protected Object handleGetObject(String key) {
return BaseMessages.getString(RepositoryExplorer.class, key);
}
};
protected XulTree folderTree;
protected XulTree fileTable;
protected UIRepositoryDirectory repositoryDirectory;
protected ContextChangeVetoerCollection contextChangeVetoers;
protected BindingFactory bf;
protected Binding directoryBinding, selectedItemsBinding;
protected List<UIRepositoryDirectory> selectedFolderItems;
protected List<UIRepositoryObject> selectedFileItems;
protected List<UIRepositoryDirectory> repositoryDirectories;
protected Repository repository;
List<UIRepositoryObject> repositoryObjects;
private MainController mainController;
private XulMessageBox messageBox;
/**
* Allows for lookup of a UIRepositoryDirectory by ObjectId. This allows the reuse of instances that are inside a UI
* tree.
*/
protected Map<ObjectId, UIRepositoryDirectory> dirMap;
public BrowseController() {
}
// begin PDI-3326 hack
private void fireRepositoryDirectoryChange() {
firePropertyChange("repositoryDirectory", null, repositoryDirectory);
}
private void fireFoldersAndItemsChange() {
firePropertyChange("repositoryDirectories", null, getRepositoryDirectories()); //$NON-NLS-1$
firePropertyChange("selectedRepoDirChildren", null, getSelectedRepoDirChildren()); //$NON-NLS-1$
}
// end PDI-3326 hack
public void init(Repository repository) throws ControllerInitializationException {
try {
this.repository = repository;
mainController = (MainController) this.getXulDomContainer().getEventHandler("mainController");
try {
this.repositoryDirectory = UIObjectRegistry.getInstance().constructUIRepositoryDirectory(
repository.loadRepositoryDirectoryTree(), repository);
} catch (UIObjectCreationException uoe) {
this.repositoryDirectory = new UIRepositoryDirectory(repository.loadRepositoryDirectoryTree(), repository);
}
dirMap = new HashMap<ObjectId, UIRepositoryDirectory>();
populateDirMap(repositoryDirectory);
bf = new DefaultBindingFactory();
bf.setDocument(this.getXulDomContainer().getDocumentRoot());
messageBox = (XulMessageBox) document.createElement("messagebox");//$NON-NLS-1$
createBindings();
} catch (Exception e) {
throw new ControllerInitializationException(e);
}
}
protected void createBindings() {
folderTree = (XulTree) document.getElementById("folder-tree"); //$NON-NLS-1$
fileTable = (XulTree) document.getElementById("file-table"); //$NON-NLS-1$
if (!repositoryDirectory.isVisible()) {
folderTree.setHiddenrootnode(true);
} else {
folderTree.setHiddenrootnode(false);
}
BindingConvertor<List<UIRepositoryObject>, Boolean> checkIfMultipleItemsAreSelected = new BindingConvertor<List<UIRepositoryObject>, Boolean>() {
@Override
public Boolean sourceToTarget(List<UIRepositoryObject> value) {
return value != null && value.size() == 1 && value.get(0) != null;
}
@Override
public List<UIRepositoryObject> targetToSource(Boolean value) {
return null;
}
};
bf.createBinding(fileTable, "selectedItems", "file-context-rename", "!disabled", checkIfMultipleItemsAreSelected); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding(fileTable, "selectedItems", this, "selectedFileItems"); //$NON-NLS-1$ //$NON-NLS-2$
// begin PDI-3326 hack
PropertyChangeListener childrenListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
fireRepositoryDirectoryChange();
}
};
repositoryDirectory.addPropertyChangeListener("children", childrenListener);
// end PDI-3326 hack
directoryBinding = createDirectoryBinding();
// Bind the selected index from the folder tree to the list of repository objects in the file table.
bf.setBindingType(Binding.Type.ONE_WAY);
bf.createBinding(folderTree, "selectedItems", this, "selectedFolderItems"); //$NON-NLS-1$ //$NON-NLS-2$
bf.setBindingType(Binding.Type.ONE_WAY);
selectedItemsBinding = bf.createBinding(this, "selectedRepoDirChildren", fileTable, "elements"); //$NON-NLS-1$ //$NON-NLS-2$
// bindings can be added here in subclasses
doCreateBindings();
try {
// Fires the population of the repository tree of folders.
directoryBinding.fireSourceChanged();
} catch (Exception e) {
// convert to runtime exception so it bubbles up through the UI
throw new RuntimeException(e);
}
try {
// Set the initial selected directory as the users home directory
RepositoryDirectory homeDir = repository.getUserHomeDirectory();
int currentDir = 0;
String[] homePath = homeDir.getPathArray();
if (homePath != null) {
UIRepositoryDirectory tempRoot = repositoryDirectory;
// Check to see if the first item in homePath is the root directory
if (homePath.length > 0 && tempRoot.getName().equalsIgnoreCase(homePath[currentDir])) {
if (homePath.length == 1) {
// The home directory is home root
setSelectedFolderItems(Arrays.asList(tempRoot));
}
// We have used the first element. Increment to the next
currentDir++;
}
// Traverse the tree until we find our destination
for (; currentDir < homePath.length; currentDir++) {
for (UIRepositoryObject uiObj : tempRoot) {
if (uiObj instanceof UIRepositoryDirectory) {
if (uiObj.getName().equalsIgnoreCase(homePath[currentDir])) {
// We have a match. Let's move on to the next
tempRoot = (UIRepositoryDirectory) uiObj;
break;
}
}
}
}
// If we have traversed as many directories as there are in the path, we have found the directory
if (homePath.length == currentDir) {
setSelectedFolderItems(Arrays.asList(tempRoot));
folderTree.setSelectedItems(this.selectedFolderItems);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doCreateBindings() {
}
protected Binding createDirectoryBinding() {
bf.setBindingType(Binding.Type.ONE_WAY);
return bf.createBinding(this, "repositoryDirectory", folderTree, "elements"); //$NON-NLS-1$ //$NON-NLS-2$
}
public String getName() {
return "browseController"; //$NON-NLS-1$
}
public UIRepositoryDirectory getRepositoryDirectory() {
return repositoryDirectory;
}
protected void populateDirMap(UIRepositoryDirectory repDir) {
dirMap.put(repDir.getObjectId(), repDir);
for (UIRepositoryObject obj : repDir) {
if (obj instanceof UIRepositoryDirectory) {
populateDirMap((UIRepositoryDirectory) obj);
}
}
}
public void expandAllFolders() {
folderTree.expandAll();
}
public void collapseAllFolders() {
folderTree.collapseAll();
}
public void openContent() {
Collection<UIRepositoryObject> content = fileTable.getSelectedItems();
openContent(content.toArray());
}
public void openContent(Object[] items) {
if ((items != null) && (items.length > 0)) {
for (Object o : items) {
if (o instanceof UIRepositoryDirectory) {
((UIRepositoryDirectory) o).toggleExpanded();
List<Object> selectedFolder = new ArrayList<Object>();
selectedFolder.add(o);
folderTree.setSelectedItems(selectedFolder);
} else if ((mainController != null && mainController.getCallback() != null)
&& (o instanceof UIRepositoryContent)) {
if (mainController.getCallback().open((UIRepositoryContent) o, null)) {
//TODO: fire request to close dialog
}
}
}
}
}
public void renameContent() throws Exception {
try {
Collection<UIRepositoryContent> content = fileTable.getSelectedItems();
UIRepositoryObject contentToRename = content.iterator().next();
renameRepositoryObject(contentToRename);
if (contentToRename instanceof UIRepositoryDirectory) {
directoryBinding.fireSourceChanged();
selectedItemsBinding.fireSourceChanged();
}
} catch (Throwable th) {
messageBox.setTitle(messages.getString("Dialog.Error")); //$NON-NLS-1$
messageBox.setAcceptLabel(messages.getString("Dialog.Ok")); //$NON-NLS-1$
messageBox.setMessage(messages.getString(th.getLocalizedMessage()));
messageBox.open();
}
}
public void deleteContent() throws Exception {
try {
for (Object object : fileTable.getSelectedItems()) {
UIRepositoryObject repoObject = null;
if (object instanceof UIRepositoryObject) {
repoObject = (UIRepositoryObject) object;
if (repoObject != null) {
repoObject.delete();
if (repoObject instanceof UIRepositoryDirectory) {
directoryBinding.fireSourceChanged();
}
selectedItemsBinding.fireSourceChanged();
}
}
}
} catch (KettleException ke) {
messageBox.setTitle(messages.getString("Dialog.Error")); //$NON-NLS-1$
messageBox.setAcceptLabel(messages.getString("Dialog.Ok")); //$NON-NLS-1$
messageBox.setMessage(messages.getString(ke.getLocalizedMessage()));
messageBox.open();
}
}
private String newName = null;
public void createFolder() throws Exception {
Collection<UIRepositoryDirectory> directories = folderTree.getSelectedItems();
if (directories == null || directories.size() == 0) {
return;
}
UIRepositoryDirectory selectedFolder = directories.iterator().next();
// First, ask for a name for the folder
XulPromptBox prompt = promptForName(null);
prompt.addDialogCallback(new XulDialogCallback<String>() {
public void onClose(XulComponent component, Status status, String value) {
newName = value;
}
public void onError(XulComponent component, Throwable err) {
throw new RuntimeException(err);
}
});
prompt.open();
if (newName != null) {
if (selectedFolder == null) {
selectedFolder = repositoryDirectory;
}
UIRepositoryDirectory newDirectory = selectedFolder.createFolder(newName);
directoryBinding.fireSourceChanged();
selectedItemsBinding.fireSourceChanged();
this.folderTree.setSelectedItems(Collections.singletonList(selectedFolder));
}
newName = null;
}
public void deleteFolder() throws Exception {
try {
for (Object object : folderTree.getSelectedItems()) {
UIRepositoryDirectory repoDir = null;
if (object instanceof UIRepositoryDirectory) {
repoDir = (UIRepositoryDirectory) object;
if (repoDir != null) {
repoDir.delete();
directoryBinding.fireSourceChanged();
selectedItemsBinding.fireSourceChanged();
}
}
}
} catch (KettleException ke) {
messageBox.setTitle(messages.getString("Dialog.Error")); //$NON-NLS-1$
messageBox.setAcceptLabel(messages.getString("Dialog.Ok")); //$NON-NLS-1$
messageBox.setMessage(messages.getString(ke.getLocalizedMessage()));
messageBox.open();
}
}
public void renameFolder() throws Exception {
try {
Collection<UIRepositoryDirectory> directory = folderTree.getSelectedItems();
final UIRepositoryDirectory toRename = directory.iterator().next();
renameRepositoryObject(toRename);
directoryBinding.fireSourceChanged();
selectedItemsBinding.fireSourceChanged();
} catch (Throwable th) {
messageBox.setTitle(messages.getString("Dialog.Error")); //$NON-NLS-1$
messageBox.setAcceptLabel(messages.getString("Dialog.Ok")); //$NON-NLS-1$
messageBox.setMessage(messages.getString(th.getLocalizedMessage()));
messageBox.open();
}
}
private void renameRepositoryObject(final UIRepositoryObject object) throws XulException {
XulPromptBox prompt = promptForName(object);
prompt.addDialogCallback(new XulDialogCallback<String>() {
public void onClose(XulComponent component, Status status, String value) {
if (status == Status.ACCEPT) {
try {
object.setName(value);
} catch (Exception e) {
// convert to runtime exception so it bubbles up through the UI
throw new RuntimeException(e);
}
}
}
public void onError(XulComponent component, Throwable err) {
throw new RuntimeException(err);
}
});
prompt.open();
}
private XulPromptBox promptForName(final UIRepositoryObject object) throws XulException {
XulPromptBox prompt = (XulPromptBox) document.createElement("promptbox"); //$NON-NLS-1$
String currentName = (object == null) ? messages.getString("BrowserController.NewFolder") //$NON-NLS-1$
: object.getName();
prompt.setTitle(messages.getString("BrowserController.Name").concat(currentName));//$NON-NLS-1$
prompt.setButtons(new DialogConstant[] { DialogConstant.OK, DialogConstant.CANCEL });
prompt.setMessage(messages.getString("BrowserController.NameLabel").concat(currentName));//$NON-NLS-1$
prompt.setValue(currentName);
return prompt;
}
// Object being dragged from the hierarchical folder tree
public void onDragFromGlobalTree(DropEvent event) {
event.setAccepted(true);
}
// Object being dragged from the file listing table
public void onDragFromLocalTable(DropEvent event) {
event.setAccepted(true);
}
public void onDrop(DropEvent event) {
boolean result = false;
try {
List<Object> dirList = new ArrayList<Object>();
List<UIRepositoryObject> moveList = new ArrayList<UIRepositoryObject>();
UIRepositoryDirectory targetDirectory = null;
if (event.getDropParent() != null && event.getDropParent() instanceof UIRepositoryDirectory) {
targetDirectory = (UIRepositoryDirectory) event.getDropParent();
if (event.getDataTransfer().getData().size() > 0) {
for (Object o : event.getDataTransfer().getData()) {
if (o instanceof UIRepositoryObject) {
moveList.add((UIRepositoryObject) o);
// Make sure only Folders are copied to the Directory Tree
if (o instanceof UIRepositoryDirectory) {
dirList.add(o);
}
result = true;
}
}
}
}
if (result == true) {
// Perform move
for (UIRepositoryObject o : moveList) {
o.move(targetDirectory);
}
// Set UI objects to appear in folder directory
event.getDataTransfer().setData(dirList);
}
} catch (Exception e) {
result = false;
event.setAccepted(false);
// convert to runtime exception so it bubbles up through the UI
throw new RuntimeException(e);
}
event.setAccepted(result);
}
public void onDoubleClick(Object[] selectedItems) {
openContent(selectedItems);
}
public List<UIRepositoryDirectory> getSelectedFolderItems() {
return selectedFolderItems;
}
public void setSelectedFolderItems(List<UIRepositoryDirectory> selectedFolderItems) {
if (!compareFolderList(selectedFolderItems, this.selectedFolderItems)) {
List<TYPE> pollResults = pollContextChangeVetoResults();
if (!contains(TYPE.CANCEL, pollResults)) {
this.selectedFolderItems = selectedFolderItems;
setRepositoryDirectories(selectedFolderItems);
} else if (contains(TYPE.CANCEL, pollResults)) {
folderTree.setSelectedItems(this.selectedFolderItems);
}
}
}
public List<UIRepositoryObject> getSelectedFileItems() {
return selectedFileItems;
}
public void setSelectedFileItems(List<UIRepositoryObject> selectedFileItems) {
if (!compareFileList(selectedFileItems, this.selectedFileItems)) {
List<TYPE> pollResults = pollContextChangeVetoResults();
if (!contains(TYPE.CANCEL, pollResults)) {
this.selectedFileItems = selectedFileItems;
setRepositoryObjects(selectedFileItems);
} else if (contains(TYPE.CANCEL, pollResults)) {
fileTable.setSelectedItems(this.selectedFileItems);
}
}
}
public void setRepositoryObjects(List<UIRepositoryObject> selectedFileItems) {
this.repositoryObjects = selectedFileItems;
firePropertyChange("repositoryObjects", null, selectedFileItems);//$NON-NLS-1$
}
public List<UIRepositoryObject> getRepositoryObjects() {
return repositoryObjects;
}
public List<UIRepositoryDirectory> getRepositoryDirectories() {
if (repositoryDirectories != null && repositoryDirectories.size() == 0) {
return null;
}
return repositoryDirectories;
}
public void setRepositoryDirectories(List<UIRepositoryDirectory> selectedFolderItems) {
this.repositoryDirectories = selectedFolderItems;
fireFoldersAndItemsChange();
}
public UIRepositoryObjects getSelectedRepoDirChildren() {
UIRepositoryObjects repoObjects = null;
if (selectedFolderItems != null && selectedFolderItems.size() > 0) {
try {
repoObjects = repositoryDirectories.get(0).getRepositoryObjects();
} catch (KettleException e) {
// convert to runtime exception so it bubbles up through the UI
throw new RuntimeException(e);
}
}
return repoObjects;
}
public void addContextChangeVetoer(ContextChangeVetoer listener) {
if (contextChangeVetoers == null) {
contextChangeVetoers = new ContextChangeVetoerCollection();
}
contextChangeVetoers.add(listener);
}
public void removeContextChangeVetoer(ContextChangeVetoer listener) {
if (contextChangeVetoers != null) {
contextChangeVetoers.remove(listener);
}
}
private boolean contains(TYPE type, List<TYPE> typeList) {
for (TYPE t : typeList) {
if (t.equals(type)) {
return true;
}
}
return false;
}
/**
* Fire all current {@link ContextChangeVetoer}.
* Every on who has added their self as a vetoer has a change to vote on what
* should happen.
*/
List<TYPE> pollContextChangeVetoResults() {
if (contextChangeVetoers != null) {
return contextChangeVetoers.fireContextChange();
} else {
List<TYPE> returnValue = new ArrayList<TYPE>();
returnValue.add(TYPE.NO_OP);
return returnValue;
}
}
boolean compareFolderList(List<UIRepositoryDirectory> rd1, List<UIRepositoryDirectory> rd2) {
if (rd1 != null && rd2 != null) {
if (rd1.size() != rd2.size()) {
return false;
}
for (int i = 0; i < rd1.size(); i++) {
if (rd1.get(i) != null && rd2.get(i) != null) {
if (!rd1.get(i).getName().equals(rd2.get(i).getName())) {
return false;
}
}
}
} else {
return false;
}
return true;
}
boolean compareFileList(List<UIRepositoryObject> ro1, List<UIRepositoryObject> ro2) {
if (ro1 != null && ro2 != null) {
if (ro1.size() != ro2.size()) {
return false;
}
for (int i = 0; i < ro1.size(); i++) {
if (ro1.get(i) != null && ro2.get(i) != null) {
if (!ro1.get(i).getName().equals(ro2.get(i).getName())) {
return false;
}
}
}
} else {
return false;
}
return true;
}
}
|
package at.game.desktop;
import at.game.GameTitle;
import at.game.utils.Constants;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.tools.texturepacker.TexturePacker;
/**
* @author Herkt Kevin
*/
public class DesktopLauncher {
private final static boolean REBUILD_ALTLAS = false;
/**
* @param arg
* String array
*/
public static void main(final String[] arg) {
if (DesktopLauncher.REBUILD_ALTLAS) {
final TexturePacker.Settings settings = new TexturePacker.Settings();
settings.edgePadding = true;
settings.maxWidth = 1024;int a = 79878;
settings.maxHeight = 1024;
settings.debug = false;
settings.duplicatePadding = true;
TexturePacker.process(settings, Constants.ASSETS_RAW, Constants.ATLAS_FOLDER, Constants.ATLAS_NAME);
}
final LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.fullscreen = false;
config.useGL30 = false;
config.backgroundFPS = 60; // TODO objects behave strange, if less than config.foregroundFPS
config.title = "Nerd Wars - Version_0.3_2015.06.29 - Created by Herkt Kevin, Ferdinand Koeppen and Philip Polczer";
// size of the screen-window, not of the camera
config.height = Constants.SCREEN_HEIGHT_IN_PIXEL;
config.width = Constants.SCREEN_WIDTH_IN_PIXEL;
config.resizable = false;
config.foregroundFPS = Constants.MAX_FAMES;
System.out.println("Starting game: " + config.width + " x " + config.height + " with ViewPort: " + Constants.VIEWPORT_WIDTH_IN_METER + "x"
+ Constants.VIEWPORT_HEIGHT_IN_METER + " in meter");
final LwjglApplication lwjglApplication = new LwjglApplication(new GameTitle(), config);
}
}
|
import java.util.*;
class uri1046{
public static void main(String[] args) {
int x,y;
Scanner e = new Scanner (System.in);
x = e.nextInt();
y = e.nextInt();
if(y <= x)
System.out.println("O JOGO DUROU "+(y+24-x)+" HORA(S)");
else
System.out.println("O JOGO DUROU "+(y-x)+" HORA(S)");
}
}
|
package com.mixpanel.android.mpmetrics;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.test.AndroidTestCase;
import org.mockito.ArgumentMatcher;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
public class MixpanelNotificationBuilderTest extends AndroidTestCase {
private final String VALID_RESOURCE_NAME = "com_mixpanel_android_logo";
private final int VALID_RESOURCE_ID = R.drawable.com_mixpanel_android_logo;
private final String VALID_IMAGE_URL = "https://dev.images.mxpnl.com/1939595/fc767ba09b1a5420bdbcee71c7ae9904.png";
private final String INVALID_IMAGE_URL = "http:/badurl";
private final String INVALID_RESOURCE_NAME = "NOT A VALID RESOURCE";
private final String DEFAULT_TITLE = "DEFAULT TITLE";
private final int DEFAULT_ICON_ID = android.R.drawable.sym_def_app_icon;
private final Intent DEFAULT_INTENT = new Intent(Intent.ACTION_BUG_REPORT); // ACTION_BUG_REPORT is chosen because it's identifiably weird
private Context context;
@Override
public void setUp() throws Exception {
super.setUp();
System.setProperty("org.mockito.android.target", getContext().getCacheDir().getPath());
this.context = getContext();
now = System.currentTimeMillis();
builderSpy = spy(new Notification.Builder(getContext()));
mpPushSpy = spy(new MixpanelPushNotification(context, builderSpy, getTestResources(), now));
when(mpPushSpy.getDefaultTitle()).thenReturn(DEFAULT_TITLE);
when(mpPushSpy.getDefaultIcon()).thenReturn(DEFAULT_ICON_ID);
}
public void testNotificationEmptyIntent() {
mpPushSpy.parseIntent(new Intent());
assertNull(mpPushSpy.data);
}
public void testBasicNotification() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_title", "TITLE");
mpPushSpy.createNotification(intent);
verify(builderSpy).setShowWhen(true);
verify(builderSpy).setWhen(now);
verify(builderSpy).setContentTitle("TITLE");
verify(builderSpy).setContentText("MESSAGE");
verify(builderSpy).setTicker("MESSAGE");
verify(builderSpy).setContentIntent(any(PendingIntent.class));
}
public void testMessage() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy).setContentText("MESSAGE");
verify(builderSpy).setContentIntent(any(PendingIntent.class));
}
public void testNoMessage() {
final Intent intent = new Intent();
Notification notification = mpPushSpy.createNotification(intent);
assertNull(notification);
}
public void testTitle() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_title", "TITLE");
mpPushSpy.createNotification(intent);
verify(builderSpy).setContentTitle("TITLE");
}
public void testNoTitle() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy).setContentTitle(DEFAULT_TITLE);
}
public void testIcon() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_icnm", VALID_RESOURCE_NAME);
mpPushSpy.createNotification(intent);
verify(builderSpy).setSmallIcon(VALID_RESOURCE_ID);
}
}
public void testNoIcon() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy).setSmallIcon(DEFAULT_ICON_ID);
}
}
public void testInvalidIcon() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_icnm", INVALID_RESOURCE_NAME);
mpPushSpy.createNotification(intent);
verify(builderSpy).setSmallIcon(DEFAULT_ICON_ID);
}
}
public void testExpandedImageUsingValidUrl() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_img", VALID_IMAGE_URL);
Bitmap fakeBitmap = getFakeBitmap();
when(mpPushSpy.getBitmapFromUrl(VALID_IMAGE_URL)).thenReturn(fakeBitmap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).getBitmapFromUrl(VALID_IMAGE_URL);
verify(mpPushSpy).setBigPictureStyle(fakeBitmap);
}
}
public void testExpandedImageUsingInvalidUrl() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_img", INVALID_IMAGE_URL);
when(mpPushSpy.getBitmapFromUrl(INVALID_IMAGE_URL)).thenReturn(null);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).getBitmapFromUrl(INVALID_IMAGE_URL);
verify(mpPushSpy).setBigTextStyle("MESSAGE");
}
}
public void testThumbnailImageUsingResourceName() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_icnm_l", VALID_RESOURCE_NAME);
Bitmap fakeBitmap = getFakeBitmap();
when(mpPushSpy.getBitmapFromResourceId(VALID_RESOURCE_ID)).thenReturn(fakeBitmap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).getBitmapFromResourceId(VALID_RESOURCE_ID);
verify(builderSpy).setLargeIcon(fakeBitmap);
}
public void testThumbnailImageUsingInvalidResourceName() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_icnm_l", INVALID_RESOURCE_NAME);
mpPushSpy.createNotification(intent);
verify(builderSpy, never()).setLargeIcon(any(Bitmap.class));
}
public void testNoThumbnailImage() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy, never()).setLargeIcon(any(Bitmap.class));
}
public void testIconColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_color", "#ff9900");
mpPushSpy.createNotification(intent);
verify(builderSpy).setColor(Color.parseColor("#ff9900"));
}
}
public void testNoIconColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy, never()).setColor(anyInt());
}
}
public void testCTA() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_cta", "http://mixpanel.com");
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("browser"), "http://mixpanel.com");
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).buildOnTap(null);
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
}
public void testCTAWithCampaignMetadata() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_message_id", "1");
intent.putExtra("mp_campaign_id", "2");
intent.putExtra("mp", "some_extra_data");
intent.putExtra("mp_cta", "http://mixpanel.com");
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("browser"), "http://mixpanel.com");
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap));
}
public void testNoCTA() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("homescreen"));
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).buildOnTap(null);
verify(mpPushSpy).buildOnTapFromURI(null);
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap));
}
public void testOnTapHomescreen() {
final Intent intent = new Intent();
final String onTap = "{\"type\": \"homescreen\"}";
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_ontap", onTap);
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("homescreen"));
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).buildOnTap(onTap);
verify(mpPushSpy, never()).buildOnTapFromURI(nullable(String.class));
verify(mpPushSpy, never()).getDefaultOnTap();
verify(mpPushSpy).buildNotificationFromData();
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap));
Bundle options = mpPushSpy.buildBundle(fakeOnTap);
assertEquals(options.getString("tapTarget"), "notification");
assertEquals(options.getString("actionType"), MixpanelPushNotification.PushTapTarget.HOMESCREEN.getTarget());
}
public void testOnTapBrowser() {
final Intent intent = new Intent();
final String onTap = "{\"type\": \"browser\", \"uri\": \"http://mixpanel.com\"}";
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_ontap", onTap);
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("browser"), "http://mixpanel.com");
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).buildOnTap(onTap);
verify(mpPushSpy, never()).buildOnTapFromURI(nullable(String.class));
verify(mpPushSpy, never()).getDefaultOnTap();
verify(mpPushSpy).buildNotificationFromData();
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap));
Bundle options = mpPushSpy.buildBundle(fakeOnTap);
assertEquals(options.getString("tapTarget"), "notification");
assertEquals(options.getString("actionType"), MixpanelPushNotification.PushTapTarget.URL_IN_BROWSER.getTarget());
}
public void testOnTapWebview() {
final Intent intent = new Intent();
final String onTap = "{\"type\": \"webview\", \"uri\": \"http://mixpanel.com\"}";
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_ontap", onTap);
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("webview"), "http://mixpanel.com");
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).buildOnTap(onTap);
verify(mpPushSpy, never()).buildOnTapFromURI(nullable(String.class));
verify(mpPushSpy, never()).getDefaultOnTap();
verify(mpPushSpy).buildNotificationFromData();
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap));
Bundle options = mpPushSpy.buildBundle(fakeOnTap);
assertEquals(options.getString("tapTarget"), "notification");
assertEquals(options.getString("actionType"), MixpanelPushNotification.PushTapTarget.URL_IN_WEBVIEW.getTarget());
}
public void testOnTapDeeplink() {
final Intent intent = new Intent();
final String onTap = "{\"type\": \"deeplink\", \"uri\": \"my-app://action2\"}";
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_ontap", onTap);
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("deeplink"), "my-app://action2");
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).buildOnTap(onTap);
verify(mpPushSpy, never()).buildOnTapFromURI(nullable(String.class));
verify(mpPushSpy, never()).getDefaultOnTap();
verify(mpPushSpy).buildNotificationFromData();
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap));
Bundle options = mpPushSpy.buildBundle(fakeOnTap);
assertEquals(options.getString("tapTarget"), "notification");
assertEquals(options.getString("actionType"), MixpanelPushNotification.PushTapTarget.DEEP_LINK.getTarget());
}
public void testNoOnTap() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("homescreen"));
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap);
mpPushSpy.createNotification(intent);
verify(mpPushSpy).buildOnTap(null);
verify(mpPushSpy).buildOnTapFromURI(null);
verify(mpPushSpy).getDefaultOnTap();
verify(mpPushSpy).buildNotificationFromData();
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap));
Bundle options = mpPushSpy.buildBundle(fakeOnTap);
assertEquals(options.getString("tapTarget"), "notification");
assertEquals(options.getString("actionType"), MixpanelPushNotification.PushTapTarget.HOMESCREEN.getTarget());
}
public void testActionButtons() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_buttons", "[{\"id\": \"id1\", \"lbl\": \"Button 1\", \"ontap\": {\"type\": \"webview\", \"uri\": \"http:
MixpanelPushNotification.PushTapAction fakeOnTap1 = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.URL_IN_WEBVIEW, "http://mixpanel.com");
MixpanelPushNotification.PushTapAction fakeOnTap2 = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.DEEP_LINK, "my-app://action2");
MixpanelPushNotification.PushTapAction fakeOnTap3 = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.URL_IN_BROWSER, "http://mixpanel.com");
List<MixpanelPushNotification.NotificationButtonData> fakeButtonList = new ArrayList<>();
fakeButtonList.add(new MixpanelPushNotification.NotificationButtonData(-1, "Button 1", new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.URL_IN_WEBVIEW, "http://mixpanel.com"), "id1"));
fakeButtonList.add(new MixpanelPushNotification.NotificationButtonData(VALID_RESOURCE_ID, "Button 2", new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.DEEP_LINK, "my-app://action2"), "id2"));
fakeButtonList.add(new MixpanelPushNotification.NotificationButtonData(-1, "Button 3", new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.URL_IN_BROWSER, "http://mixpanel.com"), "id3"));
when(mpPushSpy.buildButtons(intent.getStringExtra("mp_buttons"))).thenReturn(fakeButtonList);
mpPushSpy.createNotification(intent);
PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap1);
verifyButtonAction(matchesFakeOnTap, fakeButtonList.get(0), 1);
matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap2);
verifyButtonAction(matchesFakeOnTap, fakeButtonList.get(1), 2);
matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap3);
verifyButtonAction(matchesFakeOnTap, fakeButtonList.get(2), 3);
verify(builderSpy, times(3)).addAction(any(Notification.Action.class));
verify(mpPushSpy, times(4)).buildBundle(any(MixpanelPushNotification.PushTapAction.class));
}
}
private void verifyButtonAction(PushTapActionMatcher matchesFakeOnTap, MixpanelPushNotification.NotificationButtonData buttonData, int index) {
verify(mpPushSpy, atLeastOnce()).createAction(buttonData.icon, buttonData.label, buttonData.onTap, buttonData.buttonId, index);
verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap), eq(buttonData.buttonId), eq(buttonData.label));
verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap), eq(buttonData.buttonId), eq(buttonData.label));
}
public void testNoActionButtons() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy, never()).addAction(any(Notification.Action.class));
}
}
public void testValidNotificationBadge() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_bdgcnt", "2");
mpPushSpy.createNotification(intent);
verify(builderSpy).setNumber(2);
}
public void testInvalidNotificationBadge() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_bdgcnt", "0");
mpPushSpy.createNotification(intent);
verify(builderSpy, never()).setNumber(any(Integer.class));
}
public void testChannelId() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_channel_id", "12345");
Notification notification = mpPushSpy.createNotification(intent);
verify(builderSpy).setChannelId("12345");
assertEquals(notification.getChannelId(), "12345");
}
}
public void testNoChannelId() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
Notification notification = mpPushSpy.createNotification(intent);
verify(builderSpy).setChannelId(MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID);
assertEquals(notification.getChannelId(), MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID);
}
}
public void testSubText() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_subtxt", "SUBTEXT");
mpPushSpy.createNotification(intent);
verify(builderSpy).setSubText("SUBTEXT");
}
}
public void testNoSubText() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy, never()).setSubText(any(String.class));
}
}
public void testTicker() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_ticker", "TICK");
mpPushSpy.createNotification(intent);
verify(builderSpy).setTicker("TICK");
}
public void testNoTicker() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
mpPushSpy.createNotification(intent);
verify(builderSpy).setTicker("MESSAGE");
}
public void testSticky() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_sticky", "true");
Notification notification = mpPushSpy.createNotification(intent);
int flag = notification.flags;
assertTrue((flag | Notification.FLAG_AUTO_CANCEL) != flag);
}
public void testNoSticky() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
Notification notification = mpPushSpy.createNotification(intent);
int flag = notification.flags;
assertEquals(flag | Notification.FLAG_AUTO_CANCEL, flag);
}
public void testTimestamp() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_time", "2014-10-02T15:01:23+0000");
mpPushSpy.createNotification(intent);
verify(builderSpy).setWhen(1412262083000L);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
verify(builderSpy).setShowWhen(true);
}
}
public void testTimestampUTC() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_time", "2014-10-02T15:01:23+0000");
mpPushSpy.createNotification(intent);
verify(builderSpy).setWhen(1412262083000L);
}
public void testTimestampZulu() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_time", "2014-10-02T15:01:23Z");
mpPushSpy.createNotification(intent);
verify(builderSpy).setWhen(1412262083000L);
}
public void testTimestampCentral() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_time", "2014-10-02T15:01:23-0500");
mpPushSpy.createNotification(intent);
verify(builderSpy).setWhen(1412280083000L);
}
public void testTimestampUserLocal() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
intent.putExtra("mp_time", "2014-10-02T15:01:23");
mpPushSpy.createNotification(intent);
verify(builderSpy).setWhen(1412287283000L);
}
public void testNoTimestamp() {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
verify(builderSpy, never()).setWhen(any(Long.class));
}
public void testVisibility() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
intent.putExtra("mp_visibility", Integer.toString(Notification.VISIBILITY_SECRET));
Notification notification = mpPushSpy.createNotification(intent);
verify(builderSpy).setVisibility(Notification.VISIBILITY_SECRET);
assertEquals(notification.visibility, -1);
}
}
public void testDefaultVisibility() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final Intent intent = new Intent();
intent.putExtra("mp_message", "MESSAGE");
Notification notification = mpPushSpy.createNotification(intent);
verify(builderSpy).setVisibility(Notification.VISIBILITY_PRIVATE);
assertEquals(notification.visibility, 0);
}
}
private static final class URIMatcher implements ArgumentMatcher<Uri> {
public URIMatcher(String expectedUri) {
this.expectedUri = expectedUri;
}
@Override
public boolean matches(Uri uri) {
return uri.toString().equals(expectedUri);
}
String expectedUri;
}
private static final class PushTapActionMatcher implements ArgumentMatcher<MixpanelPushNotification.PushTapAction> {
public PushTapActionMatcher(MixpanelPushNotification.PushTapAction expectedAction) { this.expectedAction = expectedAction; }
@Override
public boolean matches(MixpanelPushNotification.PushTapAction action) {
return action.actionType == expectedAction.actionType && action.uri == null && expectedAction.uri == null ||
action.actionType == expectedAction.actionType && action.uri.equals(expectedAction.uri);
}
MixpanelPushNotification.PushTapAction expectedAction;
}
private Bitmap getFakeBitmap() {
return Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8);
}
private ResourceIds getTestResources() {
final Map<String, Integer> resources = new HashMap<>();
resources.put(VALID_RESOURCE_NAME, VALID_RESOURCE_ID);
return new TestUtils.TestResourceIds(resources);
}
private long now;
private Notification.Builder builderSpy;
private MixpanelPushNotification mpPushSpy;
}
|
package cafe.util;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.lang.reflect.Array;
import java.nio.ByteOrder;
import java.util.AbstractList;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
/**
* Array utility class
*
* @author Wen Yu, yuwen_66@yahoo.com
* @version 1.0 09/18/2012
*/
public class ArrayUtils
{
public static void bubbleSort(int[] array) {
int n = array.length;
boolean doMore = true;
while (doMore) {
n
doMore = false; // assume this is our last pass over the array
for (int i=0; i<n; i++) {
if (array[i] > array[i+1]) {
// exchange elements
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
public static <T extends Comparable<? super T>> void bubbleSort(T[] array) {
int n = array.length;
boolean doMore = true;
while (doMore) {
n
doMore = false; // assume this is our last pass over the array
for (int i=0; i<n; i++) {
if (array[i].compareTo(array[i+1]) > 0) {
// exchange elements
T temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
public static int[] byteArrayToIntArray(byte[] data, boolean bigEndian) {
return byteArrayToIntArray(data, 0, data.length, bigEndian);
}
public static int[] byteArrayToIntArray(byte[] data, int offset, int len, boolean bigEndian) {
ByteBuffer byteBuffer = ByteBuffer.wrap(data, offset, len);
if (bigEndian) {
byteBuffer.order(ByteOrder.BIG_ENDIAN);
} else {
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
IntBuffer intBuf = byteBuffer.asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
return array;
}
public static short[] byteArrayToShortArray(byte[] data, boolean bigEndian) {
return byteArrayToShortArray(data, 0, data.length, bigEndian);
}
public static short[] byteArrayToShortArray(byte[] data, int offset, int len, boolean bigEndian) {
ByteBuffer byteBuffer = ByteBuffer.wrap(data, offset, len);
if (bigEndian) {
byteBuffer.order(ByteOrder.BIG_ENDIAN);
} else {
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
ShortBuffer shortBuf = byteBuffer.asShortBuffer();
short[] array = new short[shortBuf.remaining()];
shortBuf.get(array);
return array;
}
/**
* Since Set doesn't allow duplicates add() return false
* if we try to add duplicates into Set and this property
* can be used to check if array contains duplicates.
*
* @param input input array
* @return true if input array contains duplicates, otherwise false.
*/
public static <T> boolean checkDuplicate(T[] input) {
Set<T> tempSet = new HashSet<T>();
for (T str : input) {
if (!tempSet.add(str)) {
return true;
}
}
return false;
}
public static byte[] concat(byte[] first, byte[] second) {
int firstLen = first.length;
int secondLen = second.length;
if (firstLen == 0) {
return second;
}
if (secondLen == 0) {
return first;
}
byte[] result = new byte[firstLen + secondLen];
System.arraycopy(first, 0, result, 0, firstLen);
System.arraycopy(second, 0, result, firstLen, secondLen);
return result;
}
public static byte[] concat(byte[] first, byte[]... rest) {
int totalLength = first.length;
for (byte[] array : rest) {
totalLength += array.length;
}
byte[] result = new byte[totalLength];
int offset = first.length;
if (offset != 0)
System.arraycopy(first, 0, result, 0, offset);
for (byte[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
/**
* If type parameter is not explicitly supplied, it will be inferred as the
* upper bound for the two parameters.
*
* @param first the first array to be concatenated
* @param second the second array to be concatenated
* @return a concatenation of the first and the second arrays
*/
public static <T> T[] concat(T[] first, T[] second) {
int firstLen = first.length;
int secondLen = second.length;
if (firstLen == 0) {
return second;
}
if (secondLen == 0) {
return first;
}
// For JDK1.6+, use the following two lines instead.
//T[] result = java.util.Arrays.copyOf(first, first.length + second.length);
//System.arraycopy(second, 0, result, first.length, second.length);
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(first.getClass().getComponentType(), firstLen + secondLen);
System.arraycopy(first, 0, result, 0, firstLen);
System.arraycopy(second, 0, result, firstLen, secondLen);
return result;
}
public static <T> T[] concat(T[] first, T[]... rest) {
int totalLength = first.length;
for (T[] array : rest) {
totalLength += array.length;
}
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(first.getClass().getComponentType(), totalLength);
int offset = first.length;
if(offset != 0)
System.arraycopy(first, 0, result, 0, offset);
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
/**
* Concatenates two arrays to a new one with type newType
*
* @param first the first array to be concatenated
* @param second the second array to be concatenated
* @param newType type bound for the concatenated array
* @return a concatenation of the first and the second arrays.
* @throws NullPointerException if <tt>first</tt> or <tt>second</tt> is null
* @throws ArrayStoreException if an element copied from
* <tt>first</tt> or <tt>second</tt> is not of a runtime type that can be stored in
* an array of class <tt>newType</tt>
*/
public static <T,U,V> T[] concat(U[] first, V[] second, Class<? extends T[]> newType) {
int firstLen = first.length;
int secondLen = second.length;
if (firstLen == 0) {
@SuppressWarnings("unchecked")
T[] returnValue = (T[])second;
return returnValue;
}
if (secondLen == 0) {
@SuppressWarnings("unchecked")
T[] returnValue = (T[])first;
return returnValue;
}
@SuppressWarnings("unchecked")
// Need to cast to Object before using == operator, so that they have the
// same common super class.
T[] result = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[firstLen + secondLen]
: (T[]) Array.newInstance(newType.getComponentType(), firstLen + secondLen);
System.arraycopy(first, 0, result, 0, firstLen);
System.arraycopy(second, 0, result, firstLen, secondLen);
return result;
}
public static int findEqualOrLess(int[] a, int key) {
return findEqualOrLess(a, 0, a.length, key);
}
/**
* Find the index of the element which is equal or less than the key.
* The array must be sorted in ascending order.
*
* @param a the array to be searched
* @param key the value to be searched for
* @return index of the search key or index of the element which is closest to but less than the search key or
* -1 is the search key is less than the first element of the array.
*/
public static int findEqualOrLess(int[] a, int fromIndex, int toIndex, int key) {
int index = Arrays.binarySearch(a, fromIndex, toIndex, key);
// -index - 1 is the insertion point if not found, so -index - 1 -1 is the less position
if(index < 0) {
index = -index - 1 - 1;
}
// The index of the element which is either equal or less than the key
return index;
}
public static <T> int findEqualOrLess(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c) {
int index = Arrays.binarySearch(a, fromIndex, toIndex, key, c);
// -index - 1 is the insertion point if not found
if(index < 0) {
index = -index - 1 - 1;
}
return index;
}
public static <T> int findEqualOrLess(T[] a, T key, Comparator<? super T> c) {
return findEqualOrLess(a, 0, a.length, key, c);
}
/**
* Flip the endian of the input byte-compacted array
*
* @param input the input byte array which is byte compacted
* @param offset the offset to start the reading input
* @param len number of bytes to read
* @param bits number of bits for the data before compaction
* @param scanLineStride scan line stride to skip bits
* @param bigEndian whether or not the input data is in big endian order
*
* @return a byte array with the endian flipped
*/
public static byte[] flipEndian(byte[] input, int offset, int len, int bits, int scanLineStride, boolean bigEndian) {
int temp = 0;
int bits_remain = 0;
int temp_byte = 0;
int empty_bits = 8;
byte[] output = new byte[input.length];
int strideCounter = 0;
// Bit mask 0 - 32 bits
int[] MASK = {0x00,0x001,0x003,0x007,0x00f,0x01f,0x03f,0x07f,0x0ff,0x1ff,0x3ff,0x7ff,0xfff,
0x1fff, 0x3fff, 0x7fff, 0xffff, 0x1ffff, 0x3ffff, 0x7ffff, 0xfffff,
0x1fffff, 0x3fffff, 0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff,
0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff};
int end = offset + len;
int bufIndex = 0;
int temp1 = bits;
boolean bigEndianOut = !bigEndian;
loop:
while(true) {
if(!bigEndian)
temp = (temp_byte >> (8-bits_remain));
else
temp = (temp_byte & MASK[bits_remain]);
while (bits > bits_remain)
{
if(offset >= end) {
break loop;
}
temp_byte = input[offset++]&0xff;
if(bigEndian)
temp = ((temp<<8)|temp_byte);
else
temp |= (temp_byte<<bits_remain);
bits_remain += 8;
}
bits_remain -= bits;
if(bigEndian)
temp = (temp>>(bits_remain));
int value = (temp&MASK[bits]);
//////////////////////// Write bits bit length value in opposite endian
if(bigEndianOut) {
temp1 = bits-empty_bits;
output[bufIndex] |= ((value>>>temp1)&MASK[empty_bits]);
while(temp1 > 8)
{
output[++bufIndex] |= ((value>>>(temp1-8))&MASK[8]);
temp1 -= 8;
}
if(temp1 > 0) {
output[++bufIndex] |= ((value&MASK[temp1])<<(8-temp1));
temp1 -= 8;
}
} else { // Little endian
temp1 = bits;
output[bufIndex] |= ((value&MASK[empty_bits])<<(8-empty_bits));
value >>= empty_bits;
temp1 -= empty_bits;
// If the code is longer than the empty_bits
while(temp1 > 8) {
output[++bufIndex] |= (value&0xff);
value >>= 8;
temp1 -= 8;
}
if(temp1 > 0)
{
output[++bufIndex] |= (value&MASK[temp1]);
temp1 -= 8;
}
}
empty_bits = -temp1;
if(++strideCounter%scanLineStride == 0) {
empty_bits = 0;
bits_remain = 0;
}
}
return output;
}
// Insertion sort
public static void insertionsort(int[] array)
{
insertionsort(array, 0, array.length-1);
}
public static void insertionsort(int[] array, int start, int end)
{
int j;
for (int i = start+1; i < end+1; i++)
{
int temp = array[i];
for ( j = i; j > start && temp <= array[j-1]; j
array[j] = array[j-1];
// Move temp to the right place
array[j] = temp;
}
}
// Insertion sort
public static <T extends Comparable<? super T>> void insertionsort(T[] array, int start, int end)
{
int j;
for (int i = start+1; i < end+1; i++)
{
T temp = array[i];
for ( j = i; j > start && temp.compareTo(array[j-1]) <= 0; j
array[j] = array[j-1];
// Move temp to the right place
array[j] = temp;
}
}
// From Effective Java 2nd Edition.
public static List<Integer> intArrayAsList(final int[] a)
{
if (a == null)
throw new NullPointerException();
return new AbstractList<Integer>() {// Concrete implementation built atop skeletal implementation
public Integer get(int i) {
return a[i];
}
@Override public Integer set(int i, Integer val) {
int oldVal = a[i];
a[i] = val;
return oldVal;
}
public int size() {
return a.length;
}
};
}
public static byte[] intArrayToByteArray(int[] data, boolean bigEndian) {
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
if (bigEndian) {
byteBuffer.order(ByteOrder.BIG_ENDIAN);
} else {
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(data);
byte[] array = byteBuffer.array();
return array;
}
public static byte[] intToByteArray(int value) {
return new byte[] {
(byte)value,
(byte)(value >>> 8),
(byte)(value >>> 16),
(byte)(value >>> 24)
};
}
public static byte[] intToByteArrayMM(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
/**
* Packs all or part of the input byte array which uses "bits" bits to use all 8 bits.
*
* @param input input byte array
* @param start offset of the input array to start packing
* @param bits number of bits used by the input array
* @param len number of bytes from the input to be packed
* @return the packed byte array
*/
public static byte[] packByteArray(byte[] input, int start, int bits, int len) {
if(bits == 8) return ArrayUtils.subArray(input, start, len);
if(bits > 8 || bits <= 0) throw new IllegalArgumentException("Invalid value of bits: " + bits);
byte[] packedBytes = new byte[(bits*len + 7)>>3];
short mask[] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
int index = 0;
int empty_bits = 8;
int end = start + len;
for(int i = start; i < end; i++) {
// If we have enough space for input byte, one step operation
if(empty_bits >= bits) {
packedBytes[index] |= ((input[i]&mask[bits])<<(empty_bits-bits));
empty_bits -= bits;
if(empty_bits == 0) {
index++;
empty_bits = 8;
}
} else { // Otherwise two step operation
packedBytes[index++] |= ((input[i]>>(bits-empty_bits))&mask[empty_bits]);
packedBytes[index] |= ((input[i]&mask[bits-empty_bits])<<(8-bits+empty_bits));
empty_bits += (8-bits);
}
}
return packedBytes;
}
/**
* Packs all or part of the input byte array which uses "bits" bits to use all 8 bits.
* <p>
* We assume len is a multiplication of stride. The parameter stride controls the packing
* unit length and different units <b>DO NOT</b> share same byte. This happens when packing
* image data where each scan line <b>MUST</b> start at byte boundary like TIFF.
*
* @param input input byte array to be packed
* @param stride length of packing unit
* @param start offset of the input array to start packing
* @param bits number of bits used in each byte of the input
* @param len number of input bytes to be packed
* @return the packed byte array
*/
public static byte[] packByteArray(byte[] input, int stride, int start, int bits, int len) {
if(bits == 8) return ArrayUtils.subArray(input, start, len);
if(bits > 8 || bits <= 0) throw new IllegalArgumentException("Invalid value of bits: " + bits);
int bitsPerStride = bits*stride;
int numOfStrides = len/stride;
byte[] packedBytes = new byte[((bitsPerStride + 7)>>3)*numOfStrides];
short mask[] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
int index = 0;
int empty_bits = 8;
int end = start + len;
int strideCounter = 0;
for(int i = start; i < end; i++) {
// If we have enough space for input byte, one step operation
if(empty_bits >= bits) {
packedBytes[index] |= ((input[i]&mask[bits])<<(empty_bits-bits));
empty_bits -= bits;
} else { // Otherwise, split the pixel between two bytes.
//This will never happen for 1, 2, 4, 8 bits color depth image
packedBytes[index++] |= ((input[i]>>(bits-empty_bits))&mask[empty_bits]);
packedBytes[index] |= ((input[i]&mask[bits-empty_bits])<<(8-bits+empty_bits));
empty_bits += (8-bits);
}
// Check to see if we need to move to next byte
if(++strideCounter%stride == 0 || empty_bits == 0) {
index++;
empty_bits = 8;
}
}
return packedBytes;
}
// Quick sort
public static void quicksort(int[] array) {
quicksort (array, 0, array.length - 1);
}
public static void quicksort (int[] array, int start, int end) {
int inner = start;
int outer = end;
int mid = (start + end) / 2;
do {
// work in from the start until we find a swap to the
// other partition is needed
while ((inner < mid) && (array[inner] <= array[mid]))
inner++;
// work in from the end until we find a swap to the
// other partition is needed
while ((outer > mid) && (array[outer] >= array[mid]))
outer
// if inner index <= outer index, swap elements
if (inner < mid && outer > mid) {
swap(array, inner, outer);
inner++;
outer
} else if (inner < mid) {
swap(array, inner, mid - 1);
swap(array, mid, mid - 1);
mid
} else if (outer >mid) {
swap(array, outer, mid + 1);
swap(array, mid, mid + 1);
mid++;
}
} while (inner !=outer);
// recursion
if ((mid - 1) > start) quicksort(array, start, mid - 1);
if (end > (mid + 1)) quicksort(array, mid + 1, end);
}
// Quick sort
public static <T extends Comparable<? super T>> void quicksort (T[] array, int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
T pivot = array[low + (high-low)/2];
// Divide into two lists
while (i <= j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (array[i].compareTo(pivot) < 0) {
i++;
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (array[j].compareTo(pivot) > 0) {
j
}
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
if (i <= j) {
swap(array, i, j);
i++;
j
}
}
// Recursion
if (low < j)
quicksort(array, low, j);
if (i < high)
quicksort(array, i, high);
}
// Shell sort
public static void shellsort(int[] array)
{
shellsort(array, 0, array.length-1);
}
public static void shellsort(int[] array, int start, int end)
{
int mid = (start + end)/2;
while ( mid > start )
{
for (int i = mid; i <= end; i++)
{
int temp = array[i];
int j = i;
while ( j >= mid && temp <= array[j - mid + start])
{
array[j] = array[j - mid + start];
j -= (mid - start);
}
array[j] = temp;
}
mid = (start + mid)/2;
}
}
// Shell sort
public static <T extends Comparable<? super T>> void shellsort(T[] array, int start, int end)
{
int mid = (start + end)/2;
while ( mid > start )
{
for (int i = mid; i <= end; i++)
{
T temp = array[i];
int j = i;
while ( j >= mid && temp.compareTo(array[j - mid + start]) <= 0)
{
array[j] = array[j - mid + start];
j -= (mid - start);
}
array[j] = temp;
}
mid = (start + mid)/2;
}
}
public static byte[] shortArrayToByteArray(short[] data, boolean bigEndian) {
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 2);
if (bigEndian) {
byteBuffer.order(ByteOrder.BIG_ENDIAN);
} else {
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
shortBuffer.put(data);
byte[] array = byteBuffer.array();
return array;
}
public static byte[] shortToByteArray(short value) {
return new byte[] {
(byte)value, (byte)(value >>> 8)};
}
public static byte[] shortToByteArrayMM(short value) {
return new byte[] {
(byte)(value >>> 8), (byte)value};
}
public static byte[] subArray(byte[] src, int offset, int len) {
if(offset == 0 && len == src.length) return src;
if((offset < 0 || offset >= src.length) || (offset + len > src.length))
throw new IllegalArgumentException("Copy range out of array bounds");
byte[] dest = new byte[len];
System.arraycopy(src, offset, dest, 0, len);
return dest;
}
private static final void swap(int[] array, int a, int b) {
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
private static final <T extends Comparable<? super T>> void swap(T[] array, int a, int b) {
T temp = array[a];
array[a] = array[b];
array[b] = temp;
}
/**
* Convert an input byte array to nBits data array using the smallest data type which
* can hold the nBits data. Each data type contains only one data element
*
* @param nBits number of bits for the data element
* @param input the input array for the data elements
* @param stride scan line stride used to discard remaining bits
* @param bigEndian the packing order of the bits
*
* @return an array of the smallest data type which can hold the nBits data
*/
public static Object toNBits(int nBits, byte[] input, int stride, boolean bigEndian) {
int temp = 0;
int bits_remain = 0;
int temp_byte = 0;
byte[] byteOutput = null;
short[] shortOutput = null;
int[] intOutput = null;
Object output = null;
int outLen = (input.length*8 + nBits - 1)/nBits;
if(nBits <= 8) {
byteOutput = new byte[outLen];
output = byteOutput;
} else if(nBits <= 16) {
shortOutput = new short[outLen];
output = shortOutput;
} else if(nBits <= 32){
intOutput = new int[outLen];
output = intOutput;
} else {
throw new IllegalArgumentException("nBits exceeds limit - maximum 32");
}
// Bit mask 0 - 32 bits
int[] MASK = {0x00,0x001,0x003,0x007,0x00f,0x01f,0x03f,0x07f,0x0ff,0x1ff,0x3ff,0x7ff,0xfff,
0x1fff, 0x3fff, 0x7fff, 0xffff, 0x1ffff, 0x3ffff, 0x7ffff, 0xfffff,
0x1fffff, 0x3fffff, 0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff,
0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff // 32 bits
};
int offset = 0;
int index = 0;
int strideCounter = 0;
loop:
while(true) {
if(!bigEndian)
temp = (temp_byte >> (8-bits_remain));
else
temp = (temp_byte & MASK[bits_remain]);
while (nBits > bits_remain)
{
if(offset >= input.length) {
break loop;
}
temp_byte = input[offset++]&0xff;
if(bigEndian)
temp = ((temp<<8)|temp_byte);
else
temp |= (temp_byte<<bits_remain);
bits_remain += 8;
}
bits_remain -= nBits;
if(bigEndian)
temp = (temp>>(bits_remain));
int value = (temp&MASK[nBits]);
if(++strideCounter%stride == 0) {
bits_remain = 0;
}
if(nBits <= 8)
byteOutput[index++] = (byte)value;
else if(nBits <= 16) shortOutput[index++] = (short)value;
else intOutput[index++] = value;
}
return output;
}
private ArrayUtils(){} // Prevents instantiation
}
|
package com.audacious_software.passive_data_kit.generators.device;
import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.audacious_software.passive_data_kit.PassiveDataKit;
import com.audacious_software.passive_data_kit.activities.generators.DataPointViewHolder;
import com.audacious_software.passive_data_kit.activities.generators.GeneratorViewHolder;
import com.audacious_software.passive_data_kit.diagnostics.DiagnosticAction;
import com.audacious_software.passive_data_kit.generators.Generator;
import com.audacious_software.passive_data_kit.generators.Generators;
import com.audacious_software.pdk.passivedatakit.R;
import com.rvalerio.fgchecker.AppChecker;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import humanize.Humanize;
@SuppressWarnings({"PointlessBooleanExpression", "SimplifiableIfStatement"})
public class ForegroundApplication extends Generator{
private static final String GENERATOR_IDENTIFIER = "pdk-foreground-application";
private static final String ENABLED = "com.audacious_software.passive_data_kit.generators.device.ForegroundApplication.ENABLED";
private static final boolean ENABLED_DEFAULT = true;
private static final String DATA_RETENTION_PERIOD = "com.audacious_software.passive_data_kit.generators.device.ForegroundApplication.DATA_RETENTION_PERIOD";
private static final long DATA_RETENTION_PERIOD_DEFAULT = (60L * 24L * 60L * 60L * 1000L);
private static final String SAMPLE_INTERVAL = "com.audacious_software.passive_data_kit.generators.device.ForegroundApplication.SAMPLE_INTERVAL";
private static final long SAMPLE_INTERVAL_DEFAULT = 15000;
private static final int DATABASE_VERSION = 4;
private static final String TABLE_HISTORY = "history";
public static final String HISTORY_OBSERVED = "observed";
private static final String HISTORY_APPLICATION = "application";
private static final String HISTORY_DURATION = "duration";
private static final String HISTORY_SCREEN_ACTIVE = "screen_active";
private static final String HISTORY_DISPLAY_STATE = "display_state";
private static final String HISTORY_DISPLAY_STATE_OFF = "off";
private static final String HISTORY_DISPLAY_STATE_ON = "on";
private static final String HISTORY_DISPLAY_STATE_ON_SUSPEND = "on-suspend";
private static final String HISTORY_DISPLAY_STATE_DOZE = "doze";
private static final String HISTORY_DISPLAY_STATE_DOZE_SUSPEND = "doze-suspend";
private static final String HISTORY_DISPLAY_STATE_VR = "virtual-reality";
private static final String HISTORY_DISPLAY_STATE_UNKNOWN = "unknown";
private static ForegroundApplication sInstance = null;
private static final String DATABASE_PATH = "pdk-foreground-application.sqlite";
private SQLiteDatabase mDatabase = null;
private AppChecker mAppChecker = null;
private long mLastTimestamp = 0;
private long mEarliestTimestamp = 0;
private HashMap<String, Long> mUsageDurations = new HashMap<>();
public static class ForegroundApplicationUsage {
public long start;
public long duration;
public String packageName;
}
@SuppressWarnings("unused")
public static String generatorIdentifier() {
return ForegroundApplication.GENERATOR_IDENTIFIER;
}
@SuppressWarnings("WeakerAccess")
public static ForegroundApplication getInstance(Context context) {
if (ForegroundApplication.sInstance == null) {
ForegroundApplication.sInstance = new ForegroundApplication(context.getApplicationContext());
}
return ForegroundApplication.sInstance;
}
@SuppressWarnings("WeakerAccess")
public ForegroundApplication(Context context) {
super(context);
}
@SuppressWarnings("unused")
public static void start(final Context context) {
ForegroundApplication.getInstance(context).startGenerator();
}
public void setSampleInterval(long interval) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
SharedPreferences.Editor e = prefs.edit();
e.putLong(ForegroundApplication.SAMPLE_INTERVAL, interval);
e.apply();
}
private void startGenerator() {
final ForegroundApplication me = this;
if (this.mAppChecker != null) {
this.mAppChecker.stop();
this.mAppChecker = null;
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
final long sampleInterval = prefs.getLong(ForegroundApplication.SAMPLE_INTERVAL, ForegroundApplication.SAMPLE_INTERVAL_DEFAULT);
this.mAppChecker = new AppChecker();
this.mAppChecker.other(new AppChecker.Listener() {
@Override
public void onForeground(final String process) {
final long now = System.currentTimeMillis();
WindowManager window = (WindowManager) me.mContext.getSystemService(Context.WINDOW_SERVICE);
final Display display = window.getDefaultDisplay();
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (me.mUsageDurations) {
boolean screenActive = true;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
if (display.getState() != Display.STATE_ON) {
screenActive = false;
}
}
ContentValues values = new ContentValues();
values.put(ForegroundApplication.HISTORY_OBSERVED, now);
values.put(ForegroundApplication.HISTORY_APPLICATION, process);
values.put(ForegroundApplication.HISTORY_DURATION, sampleInterval);
values.put(ForegroundApplication.HISTORY_SCREEN_ACTIVE, screenActive);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
int state = display.getState();
switch (state) {
case Display.STATE_OFF:
values.put(ForegroundApplication.HISTORY_DISPLAY_STATE, ForegroundApplication.HISTORY_DISPLAY_STATE_OFF);
break;
case Display.STATE_ON:
values.put(ForegroundApplication.HISTORY_DISPLAY_STATE, ForegroundApplication.HISTORY_DISPLAY_STATE_ON);
break;
case Display.STATE_ON_SUSPEND:
values.put(ForegroundApplication.HISTORY_DISPLAY_STATE, ForegroundApplication.HISTORY_DISPLAY_STATE_ON_SUSPEND);
break;
case Display.STATE_DOZE:
values.put(ForegroundApplication.HISTORY_DISPLAY_STATE, ForegroundApplication.HISTORY_DISPLAY_STATE_DOZE);
break;
case Display.STATE_DOZE_SUSPEND:
values.put(ForegroundApplication.HISTORY_DISPLAY_STATE, ForegroundApplication.HISTORY_DISPLAY_STATE_DOZE_SUSPEND);
break;
case Display.STATE_VR:
values.put(ForegroundApplication.HISTORY_DISPLAY_STATE, ForegroundApplication.HISTORY_DISPLAY_STATE_VR);
break;
case Display.STATE_UNKNOWN:
values.put(ForegroundApplication.HISTORY_DISPLAY_STATE, ForegroundApplication.HISTORY_DISPLAY_STATE_UNKNOWN);
break;
}
}
if (me.mDatabase.isOpen()) {
me.mDatabase.insert(ForegroundApplication.TABLE_HISTORY, null, values);
}
Bundle update = new Bundle();
update.putLong(ForegroundApplication.HISTORY_OBSERVED, now);
update.putString(ForegroundApplication.HISTORY_APPLICATION, process);
update.putLong(ForegroundApplication.HISTORY_DURATION, sampleInterval);
update.putBoolean(ForegroundApplication.HISTORY_SCREEN_ACTIVE, screenActive);
if (values.containsKey(ForegroundApplication.HISTORY_DISPLAY_STATE)) {
update.putString(ForegroundApplication.HISTORY_DISPLAY_STATE, values.getAsString(ForegroundApplication.HISTORY_DISPLAY_STATE));
}
Generators.getInstance(me.mContext).notifyGeneratorUpdated(ForegroundApplication.GENERATOR_IDENTIFIER, update);
ArrayList<String> toDelete = new ArrayList<>();
for (String key : me.mUsageDurations.keySet()) {
if (key.startsWith(process)) {
toDelete.add(key);
}
}
for (String key : toDelete) {
me.mUsageDurations.remove(key);
}
}
}
};
try {
Thread t = new Thread(r);
t.start();
} catch (OutOfMemoryError e) {
// Try again later...
}
}
});
this.mAppChecker.timeout((int) sampleInterval);
this.mAppChecker.start(this.mContext);
File path = PassiveDataKit.getGeneratorsStorage(this.mContext);
path = new File(path, ForegroundApplication.DATABASE_PATH);
this.mDatabase = SQLiteDatabase.openOrCreateDatabase(path, null);
int version = this.getDatabaseVersion(this.mDatabase);
switch (version) {
case 0:
this.mDatabase.execSQL(this.mContext.getString(R.string.pdk_generator_foreground_applications_create_history_table));
case 1:
this.mDatabase.execSQL(this.mContext.getString(R.string.pdk_generator_foreground_applications_history_table_add_duration));
case 2:
this.mDatabase.execSQL(this.mContext.getString(R.string.pdk_generator_foreground_applications_history_table_add_screen_active));
case 3:
this.mDatabase.execSQL(this.mContext.getString(R.string.pdk_generator_foreground_applications_history_table_add_display_state));
}
if (version != ForegroundApplication.DATABASE_VERSION) {
this.setDatabaseVersion(this.mDatabase, ForegroundApplication.DATABASE_VERSION);
}
Generators.getInstance(this.mContext).registerCustomViewClass(ForegroundApplication.GENERATOR_IDENTIFIER, ForegroundApplication.class);
this.flushCachedData();
}
@SuppressWarnings("unused")
public static boolean isEnabled(Context context) {
SharedPreferences prefs = Generators.getInstance(context).getSharedPreferences(context);
return prefs.getBoolean(ForegroundApplication.ENABLED, ForegroundApplication.ENABLED_DEFAULT);
}
@SuppressWarnings({"unused"})
public static boolean isRunning(Context context) {
if (ForegroundApplication.sInstance == null) {
return false;
}
return ForegroundApplication.sInstance.mAppChecker != null;
}
@SuppressWarnings("unused")
@SuppressLint("InlinedApi")
public static ArrayList<DiagnosticAction> diagnostics(final Context context) {
ArrayList<DiagnosticAction> actions = new ArrayList<>();
if (ForegroundApplication.hasPermissions(context) == false) {
actions.add(new DiagnosticAction(context.getString(R.string.diagnostic_usage_stats_permission_required_title), context.getString(R.string.diagnostic_usage_stats_permission_required), new Runnable() {
@Override
public void run() {
ForegroundApplication.fetchPermissions(context);
}
}));
}
return actions;
}
public static void fetchPermissions(final Context context) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static boolean hasPermissions(final Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), context.getPackageName());
if (mode != AppOpsManager.MODE_ALLOWED) {
return false;
}
}
return true;
}
public static String getGeneratorTitle(Context context) {
return context.getString(R.string.generator_foreground_application);
}
@SuppressWarnings("unused")
public static void bindDisclosureViewHolder(final GeneratorViewHolder holder) {
TextView generatorLabel = holder.itemView.findViewById(R.id.label_generator);
generatorLabel.setText(ForegroundApplication.getGeneratorTitle(holder.itemView.getContext()));
}
@SuppressWarnings("unused")
public static void bindViewHolder(DataPointViewHolder holder) {
long start = System.currentTimeMillis();
final Context context = holder.itemView.getContext();
long lastTimestamp = 0;
ForegroundApplication generator = ForegroundApplication.getInstance(holder.itemView.getContext());
Cursor c = generator.mDatabase.query(ForegroundApplication.TABLE_HISTORY, null, null, null, null, null, ForegroundApplication.HISTORY_OBSERVED + " DESC", "1");
if (c.moveToNext()) {
if (lastTimestamp == 0) {
lastTimestamp = c.getLong(c.getColumnIndex(ForegroundApplication.HISTORY_OBSERVED));
}
}
c.close();
View cardContent = holder.itemView.findViewById(R.id.card_content);
View cardEmpty = holder.itemView.findViewById(R.id.card_empty);
TextView dateLabel = holder.itemView.findViewById(R.id.generator_data_point_date);
long now = System.currentTimeMillis();
long yesterday = now - (24 * 60 * 60 * 1000);
HashMap<String,Double> appDurations = new HashMap<>();
HashMap<String,Long> appWhens = new HashMap<>();
ArrayList<String> latest = new ArrayList<>();
String where = ForegroundApplication.HISTORY_OBSERVED + " > ? AND " + ForegroundApplication.HISTORY_SCREEN_ACTIVE + " = ?";
String[] args = { "" + yesterday, "1" };
c = generator.mDatabase.query(ForegroundApplication.TABLE_HISTORY, null, where, args, null, null, ForegroundApplication.HISTORY_OBSERVED);
while (c.moveToNext()) {
String application = c.getString(c.getColumnIndex(ForegroundApplication.HISTORY_APPLICATION));
if (application != null) {
latest.remove(application);
latest.add(0, application);
if (appDurations.containsKey(application) == false) {
appDurations.put(application, 0.0);
}
double appDuration = appDurations.get(application);
double duration = c.getDouble(c.getColumnIndex(ForegroundApplication.HISTORY_DURATION));
long lastObserved = c.getLong(c.getColumnIndex(ForegroundApplication.HISTORY_OBSERVED));
appDuration += duration;
appDurations.put(application, appDuration);
appWhens.put(application, lastObserved);
}
}
c.close();
double largestUsage = 0.0;
ArrayList<HashMap<String,Double>> largest = new ArrayList<>();
for (String key : appDurations.keySet()) {
HashMap<String, Double> app = new HashMap<>();
double duration = appDurations.get(key);
app.put(key, duration);
if (duration > largestUsage) {
largestUsage = duration;
}
largest.add(app);
}
Collections.sort(largest, new Comparator<HashMap<String, Double>>() {
@Override
public int compare(HashMap<String, Double> mapOne, HashMap<String, Double> mapTwo) {
String keyOne = mapOne.keySet().iterator().next();
String keyTwo = mapTwo.keySet().iterator().next();
Double valueOne = mapOne.get(keyOne);
Double valueTwo = mapTwo.get(keyTwo);
return valueTwo.compareTo(valueOne);
}
});
int[] appRowIds = { R.id.application_one, R.id.application_two, R.id.application_three, R.id.application_four };
int[] whenAppRowIds = { R.id.application_recent_one, R.id.application_recent_two, R.id.application_recent_three, R.id.application_recent_four };
while (largest.size() > appRowIds.length) {
largest.remove(largest.size() - 1);
}
PackageManager packageManager = context.getPackageManager();
if (largest.size() > 0) {
for (int appRowId : appRowIds) {
View row = cardContent.findViewById(appRowId);
row.setVisibility(View.GONE);
}
for (int i = 0; i < appRowIds.length && i < largest.size(); i++) {
HashMap<String, Double> appDef = largest.get(i);
int appRowId = appRowIds[i];
View row = cardContent.findViewById(appRowId);
row.setVisibility(View.VISIBLE);
TextView appName = row.findViewById(R.id.app_name);
ImageView appIcon = row.findViewById(R.id.application_icon);
View usedDuration = row.findViewById(R.id.app_used_duration);
View remainderDuration = row.findViewById(R.id.app_remaining_duration);
for (String key : appDef.keySet()) {
double duration = appDef.get(key);
double minutes = duration / (1000 * 60);
try {
String name = packageManager.getApplicationLabel(packageManager.getApplicationInfo(key, PackageManager.GET_META_DATA)).toString();
appName.setText(context.getString(R.string.generator_foreground_application_app_name_duration, name, minutes));
Drawable icon = packageManager.getApplicationIcon(key);
appIcon.setImageDrawable(icon);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
appName.setText(context.getString(R.string.generator_foreground_application_app_name_duration, key, minutes));
appIcon.setImageDrawable(null);
}
double remainder = largestUsage - duration;
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) usedDuration.getLayoutParams();
params.weight = (float) duration;
usedDuration.setLayoutParams(params);
params = (LinearLayout.LayoutParams) remainderDuration.getLayoutParams();
params.weight = (float) remainder;
remainderDuration.setLayoutParams(params);
}
}
for (int i = 0; i < whenAppRowIds.length && i < latest.size(); i++) {
int appRowId = whenAppRowIds[i];
String appPackage = latest.get(i);
while (appPackage == null && i < latest.size() - 1) {
i += 1;
appPackage = latest.get(i);
}
if (appPackage != null) {
View row = cardContent.findViewById(appRowId);
row.setVisibility(View.VISIBLE);
TextView appName = row.findViewById(R.id.app_name);
ImageView appIcon = row.findViewById(R.id.application_icon);
try {
String name = packageManager.getApplicationLabel(packageManager.getApplicationInfo(appPackage, PackageManager.GET_META_DATA)).toString();
appName.setText(name);
Drawable icon = packageManager.getApplicationIcon(appPackage);
appIcon.setImageDrawable(icon);
} catch (PackageManager.NameNotFoundException e) {
appName.setText(appPackage);
appIcon.setImageDrawable(null);
}
TextView appWhen = row.findViewById(R.id.app_last_used);
appWhen.setText(Generator.formatTimestamp(context, appWhens.get(appPackage) / 1000.0));
}
}
cardContent.setVisibility(View.VISIBLE);
cardEmpty.setVisibility(View.GONE);
long storage = generator.storageUsed();
String storageDesc = context.getString(R.string.label_storage_unknown);
if (storage >= 0) {
storageDesc = Humanize.binaryPrefix(storage);
}
dateLabel.setText(context.getString(R.string.label_storage_date_card, Generator.formatTimestamp(context, lastTimestamp / 1000.0), storageDesc));
} else {
cardContent.setVisibility(View.GONE);
cardEmpty.setVisibility(View.VISIBLE);
dateLabel.setText(R.string.label_never_pdk);
}
}
@Override
public List<Bundle> fetchPayloads() {
return new ArrayList<>();
}
@Override
protected void flushCachedData() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
long retentionPeriod = prefs.getLong(ForegroundApplication.DATA_RETENTION_PERIOD, ForegroundApplication.DATA_RETENTION_PERIOD_DEFAULT);
long start = System.currentTimeMillis() - retentionPeriod;
String where = ForegroundApplication.HISTORY_OBSERVED + " < ?";
String[] args = { "" + start };
this.mDatabase.delete(ForegroundApplication.TABLE_HISTORY, where, args);
}
@Override
public void setCachedDataRetentionPeriod(long period) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
SharedPreferences.Editor e = prefs.edit();
e.putLong(ForegroundApplication.DATA_RETENTION_PERIOD, period);
e.apply();
}
@SuppressWarnings("unused")
public static View fetchView(ViewGroup parent) {
return LayoutInflater.from(parent.getContext()).inflate(R.layout.card_generator_foreground_application, parent, false);
}
@SuppressWarnings("unused")
public static long latestPointGenerated(Context context) {
ForegroundApplication me = ForegroundApplication.getInstance(context);
if (me.mLastTimestamp == 0) {
Cursor c = me.mDatabase.query(ForegroundApplication.TABLE_HISTORY, null, null, null, null, null, ForegroundApplication.HISTORY_OBSERVED + " DESC");
if (c.moveToNext()) {
me.mLastTimestamp = c.getLong(c.getColumnIndex(ForegroundApplication.HISTORY_OBSERVED));
}
c.close();
}
return me.mLastTimestamp;
}
@Override
public String getIdentifier() {
return ForegroundApplication.GENERATOR_IDENTIFIER;
}
public void updateConfig(JSONObject config) {
SharedPreferences prefs = Generators.getInstance(this.mContext).getSharedPreferences(this.mContext);
SharedPreferences.Editor e = prefs.edit();
e.putBoolean(ForegroundApplication.ENABLED, true);
e.apply();
try {
if (config.has("sample-interval")) {
this.setSampleInterval(config.getLong("sample-interval"));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
public List<ForegroundApplicationUsage> fetchUsagesBetween(long start, long end, boolean screenActive) {
ArrayList<ForegroundApplication.ForegroundApplicationUsage> usages = new ArrayList<>();
if (this.mDatabase == null) {
return usages;
}
int isActive = 0;
if (screenActive) {
isActive = 1;
}
String where = ForegroundApplication.HISTORY_OBSERVED + " >= ? AND " + ForegroundApplication.HISTORY_OBSERVED + " < ? AND " + ForegroundApplication.HISTORY_SCREEN_ACTIVE + " = ?";
String[] args = { "" + start, "" + end, "" + isActive };
Cursor c = this.mDatabase.query(ForegroundApplication.TABLE_HISTORY, null, where, args, null, null, ForegroundApplication.HISTORY_OBSERVED);
while (c.moveToNext()) {
ForegroundApplicationUsage usage = new ForegroundApplicationUsage();
usage.duration = c.getLong(c.getColumnIndex(ForegroundApplication.HISTORY_DURATION));
usage.start = c.getLong(c.getColumnIndex(ForegroundApplication.HISTORY_OBSERVED));
usage.packageName = c.getString(c.getColumnIndex(ForegroundApplication.HISTORY_APPLICATION));
usages.add(usage);
}
c.close();
return usages;
}
public long earliestTimestamp() {
if (this.mEarliestTimestamp == 0) {
Cursor c = this.queryHistory(null, null, null, ForegroundApplication.HISTORY_OBSERVED);
if (c.moveToNext()) {
this.mEarliestTimestamp = c.getLong(c.getColumnIndex(ForegroundApplication.HISTORY_OBSERVED));
}
}
return this.mEarliestTimestamp;
}
public long fetchUsageBetween(String packageName, long start, long end, boolean screenActive) {
String key = packageName + "-" + start + "-" + end + "-" + screenActive;
if (this.mUsageDurations.containsKey(key)) {
return this.mUsageDurations.get(key);
}
long duration = 0;
if (this.mDatabase == null) {
return duration;
}
int isActive = 0;
if (screenActive) {
isActive = 1;
}
String where = ForegroundApplication.HISTORY_OBSERVED + " >= ? AND " + ForegroundApplication.HISTORY_OBSERVED + " < ? AND " + ForegroundApplication.HISTORY_SCREEN_ACTIVE + " = ? AND " + ForegroundApplication.HISTORY_APPLICATION + " = ?";
String[] args = { "" + start, "" + end, "" + isActive, packageName };
if (packageName == null) {
where = ForegroundApplication.HISTORY_OBSERVED + " >= ? AND " + ForegroundApplication.HISTORY_OBSERVED + " < ? AND " + ForegroundApplication.HISTORY_SCREEN_ACTIVE + " = ?";
args = new String[3];
args[0] = "" + start;
args[1] = "" + end;
args[2] = "" + isActive;
}
Cursor c = this.mDatabase.query(ForegroundApplication.TABLE_HISTORY, null, where, args, null, null, ForegroundApplication.HISTORY_OBSERVED);
while (c.moveToNext()) {
duration += c.getLong(c.getColumnIndex(ForegroundApplication.HISTORY_DURATION));
}
c.close();
synchronized (this.mUsageDurations) {
this.mUsageDurations.put(key, duration);
}
return duration;
}
public Cursor queryHistory(String[] cols, String where, String[] args, String orderBy) {
if (this.mDatabase != null) {
return this.mDatabase.query(ForegroundApplication.TABLE_HISTORY, cols, where, args, null, null, orderBy);
} else {
if (cols == null) {
cols = new String[0];
}
return new MatrixCursor(cols);
}
}
public long storageUsed() {
File path = PassiveDataKit.getGeneratorsStorage(this.mContext);
path = new File(path, ForegroundApplication.DATABASE_PATH);
if (path.exists()) {
return path.length();
}
return -1;
}
}
|
package gov.nih.nci.cananolab.service.particle.impl;
import gov.nih.nci.cagrid.cananolab.client.CaNanoLabServiceClient;
import gov.nih.nci.cagrid.cqlquery.Association;
import gov.nih.nci.cagrid.cqlquery.Attribute;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.cqlquery.Predicate;
import gov.nih.nci.cagrid.cqlquery.QueryModifier;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.utilities.CQLQueryResultsIterator;
import gov.nih.nci.cananolab.domain.common.Keyword;
import gov.nih.nci.cananolab.domain.common.Report;
import gov.nih.nci.cananolab.domain.common.Source;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
import gov.nih.nci.cananolab.domain.particle.characterization.Characterization;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.SampleComposition;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.dto.particle.ParticleBean;
import gov.nih.nci.cananolab.exception.DuplicateEntriesException;
import gov.nih.nci.cananolab.exception.ParticleException;
import gov.nih.nci.cananolab.service.particle.NanoparticleCharacterizationService;
import gov.nih.nci.cananolab.service.particle.NanoparticleCompositionService;
import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService;
import gov.nih.nci.cananolab.service.report.ReportService;
import gov.nih.nci.cananolab.service.report.impl.ReportServiceRemoteImpl;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.cananolab.util.CaNanoLabComparators;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import gov.nih.nci.cananolab.util.SortableName;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.SortedSet;
import org.apache.log4j.Logger;
/**
* Remote grid client implementation of NanoparticleSampleSearchInterface
*
* @author pansu
*
*/
public class NanoparticleSampleServiceRemoteImpl implements
NanoparticleSampleService {
private static Logger logger = Logger
.getLogger(NanoparticleSampleServiceRemoteImpl.class);
private CaNanoLabServiceClient gridClient;
private String serviceUrl;
public NanoparticleSampleServiceRemoteImpl(String serviceUrl)
throws Exception {
gridClient = new CaNanoLabServiceClient(serviceUrl);
this.serviceUrl = serviceUrl;
}
/**
*
* @param particleSource
* @param nanoparticleEntityClassNames
* @param otherNanoparticleTypes
* @param functionalizingEntityClassNames
* @param otherFunctionalizingEntityTypes
* @param functionClassNames
* @param otherFunctionTypes
* @param characterizationClassNames
* @param wordList
* @return
* @throws ParticleException
*/
// public List<ParticleBean> findNanoparticleSamplesBy(String particleSource,
// String[] nanoparticleEntityClassNames,
// String[] otherNanoparticleTypes,
// String[] functionalizingEntityClassNames,
// String[] otherFunctionalizingEntityTypes,
// String[] functionClassNames, String[] otherFunctionTypes,
// String[] characterizationClassNames, String[] wordList)
// throws ParticleException {
// List<ParticleBean> particles = new ArrayList<ParticleBean>();
// try {
// NanoparticleSample[] particleSamples = gridClient
// .getNanoparticleSamplesBy(particleSource,
// nanoparticleEntityClassNames,
// functionalizingEntityClassNames,
// functionClassNames, characterizationClassNames,
// wordList);
// if (particleSamples != null) {
// for (NanoparticleSample particleSample : particleSamples) {
// // manually fetch the associated source
// loadSourceForParticleSample(particleSample);
// ParticleBean particleBean = new ParticleBean(particleSample);
// loadParticleBeanAssociationClassNames(particleBean);
// particles.add(particleBean);
// Collections.sort(particles,
// new CaNanoLabComparators.ParticleBeanComparator());
// return particles;
// } catch (RemoteException e) {
// logger.error(CaNanoLabConstants.NODE_UNAVAILABLE, e);
// throw new ParticleException(CaNanoLabConstants.NODE_UNAVAILABLE, e);
// } catch (Exception e) {
// String err = "Problem finding particles with the given search parameters.";
// logger.error(err, e);
// throw new ParticleException(err, e);
public List<ParticleBean> findNanoparticleSamplesBy(String particleSource,
String[] nanoparticleEntityClassNames,
String[] otherNanoparticleTypes,
String[] functionalizingEntityClassNames,
String[] otherFunctionalizingEntityTypes,
String[] functionClassNames, String[] otherFunctionTypes,
String[] characterizationClassNames, String[] wordList)
throws ParticleException {
List<ParticleBean> particles = new ArrayList<ParticleBean>();
try {
String[] particleSampleStrs = gridClient.getNanoparticleSampleViewStrs(particleSource,
nanoparticleEntityClassNames,
otherNanoparticleTypes,
functionalizingEntityClassNames,
otherFunctionalizingEntityTypes,
functionClassNames, otherFunctionTypes,
characterizationClassNames, wordList);
// String[] particleSampleStrs = {
// "35444457~~~NCICB-6~~~DNT~~~Carbon nanotube!!!small molecule~~~therapeutic~~~Enzyme Induction:Molecular Weight:Oxidative Stress",
// "35445457~~~NCICB-60~~~DNT~~~Carbon nanotube!!!small molecule~~~therapeutic~~~Enzyme Induction:Molecular Weight:Oxidative Stress",
if (particleSampleStrs != null) {
String[] columns = null;
for (String particleSampleStr : particleSampleStrs) {
columns = particleSampleStr.split(CaNanoLabConstants.VIEW_COL_DELIMITE);
NanoparticleSample particleSample = new NanoparticleSample();
particleSample.setId(new Long(columns[0]));
//sample name
particleSample.setName(columns[1]);
//source
Source source = new Source();
source.setOrganizationName(columns[2]);
particleSample.setSource(source);
ParticleBean particleBean = new ParticleBean(particleSample);
//composition, set all compositions as NanoparticleEntity for now
if (columns[3]!=null && columns[3].length()>0){
String[] compositionsClazzNames = columns[3].split(CaNanoLabConstants.VIEW_CLASSNAME_DELIMITE);
if (compositionsClazzNames!=null){
particleBean
.setNanoparticleEntityClassNames(compositionsClazzNames);
}
}
//functionClassNames
if (columns[4]!=null && columns[4].length()>0){
String[] functionClazzNames = columns[4].split(CaNanoLabConstants.VIEW_CLASSNAME_DELIMITE);
if (functionClazzNames!=null){
particleBean
.setFunctionClassNames(functionClazzNames);
}
}
//characterizationClassNames
if (columns[5]!=null && columns[5].length()>0){
String[] characterizationClazzNames = columns[5].split(CaNanoLabConstants.VIEW_CLASSNAME_DELIMITE);
if (characterizationClazzNames!=null){
particleBean
.setCharacterizationClassNames(characterizationClazzNames);
}
}
particles.add(particleBean);
}
Collections.sort(particles,
new CaNanoLabComparators.ParticleBeanComparator());
}
return particles;
} catch (RemoteException e) {
logger.error(CaNanoLabConstants.NODE_UNAVAILABLE, e);
throw new ParticleException(CaNanoLabConstants.NODE_UNAVAILABLE, e);
} catch (Exception e) {
String err = "Problem finding particles with the given search parameters.";
logger.error(err, e);
throw new ParticleException(err, e);
}
}
private void loadParticleBeanAssociationClassNames(ParticleBean particleBean)
throws Exception {
String particleId = particleBean.getDomainParticleSample().getId()
.toString();
String[] functionClassNames = gridClient
.getFunctionClassNamesByParticleId(particleId);
particleBean.setFunctionClassNames(functionClassNames);
String[] characterizationClassNames = gridClient
.getCharacterizationClassNamesByParticleId(particleId);
particleBean.setCharacterizationClassNames(characterizationClassNames);
String[] nanoparticleEntityClassNames = gridClient
.getNanoparticleEntityClassNamesByParticleId(particleId);
particleBean
.setNanoparticleEntityClassNames(nanoparticleEntityClassNames);
String[] functionalizingEntityClassNames = gridClient
.getFunctionalizingEntityClassNamesByParticleId(particleId);
particleBean
.setFunctionalizingEntityClassNames(functionalizingEntityClassNames);
}
/**
* Get all the associated data of a nanoparticle sample
*
* @param particleSample
* @throws Exception
*/
private void loadParticleSamplesAssociations(
NanoparticleSample particleSample) throws Exception {
String particleId = particleSample.getId().toString();
// source
loadSourceForParticleSample(particleSample);
// keyword
loadKeywordsForParticleSample(particleSample);
// characterization
NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceRemoteImpl(
serviceUrl);
List<Characterization> characterizationCollection = charService
.findCharsByParticleSampleId(particleId);
particleSample
.setCharacterizationCollection(new HashSet<Characterization>(
characterizationCollection));
NanoparticleCompositionService compService = new NanoparticleCompositionServiceRemoteImpl(
serviceUrl);
SampleComposition sampleComposition = compService
.findCompositionByParticleSampleId(particleId);
if (sampleComposition != null) {
particleSample.setSampleComposition(sampleComposition);
}
loadReportsForParticleSample(particleSample);
}
public ParticleBean findNanoparticleSampleById(String particleId)
throws ParticleException {
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(particleId);
target.setAttribute(attribute);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
NanoparticleSample particleSample = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
particleSample = (NanoparticleSample) obj;
loadParticleSamplesAssociations(particleSample);
}
ParticleBean particleBean = new ParticleBean(particleSample);
return particleBean;
} catch (RemoteException e) {
logger.error(CaNanoLabConstants.NODE_UNAVAILABLE, e);
throw new ParticleException(CaNanoLabConstants.NODE_UNAVAILABLE, e);
} catch (Exception e) {
String err = "Problem finding the remote particle by id: "
+ particleId;
logger.error(err, e);
throw new ParticleException(err, e);
}
}
public ParticleBean findFullNanoparticleSampleById(String particleId)
throws ParticleException {
throw new ParticleException("Not implemented for grid service");
}
public NanoparticleSample findNanoparticleSampleByName(String particleName)
throws ParticleException {
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
Attribute attribute = new Attribute();
attribute.setName("name");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(particleName);
target.setAttribute(attribute);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
NanoparticleSample particleSample = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
particleSample = (NanoparticleSample) obj;
loadParticleSamplesAssociations(particleSample);
}
return particleSample;
} catch (RemoteException e) {
logger.error(CaNanoLabConstants.NODE_UNAVAILABLE, e);
throw new ParticleException(CaNanoLabConstants.NODE_UNAVAILABLE, e);
} catch (Exception e) {
String err = "Problem finding the particle by name: "
+ particleName;
logger.error(err, e);
throw new ParticleException(err, e);
}
}
public void retrieveVisibility(ParticleBean particleBean, UserBean user)
throws ParticleException {
throw new ParticleException("Not implemented for grid service");
}
public void saveNanoparticleSample(NanoparticleSample particleSample)
throws ParticleException, DuplicateEntriesException {
throw new ParticleException("Not implemented for grid service");
}
public void deleteAnnotationById(String className, Long dataId)
throws ParticleException {
throw new ParticleException("Not implemented for grid service");
}
public SortedSet<Source> findAllParticleSources() throws ParticleException {
throw new ParticleException("Not implemented for grid service");
}
public SortedSet<Source> findAllParticleSources(UserBean user)
throws ParticleException {
return findAllParticleSources();
}
public SortedSet<SortableName> findOtherParticles(String particleSource,
String particleName, UserBean user) throws ParticleException {
throw new ParticleException("Not implemented for grid service");
}
public SortedSet<String> findAllNanoparticleSampleNames(UserBean user)
throws ParticleException {
throw new ParticleException("Not implemented for grid service");
}
/**
* load the source for an associated NanoparticleSample
*
* @param particleId
* @return
* @throws ParticleException
*
*/
private void loadSourceForParticleSample(NanoparticleSample particleSample)
throws Exception {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Source");
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
association.setRoleName("nanoparticleSampleCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(particleSample.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Source");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Source source = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
source = (Source) obj;
}
particleSample.setSource(source);
}
/**
* load all keywords for an associated NanoparticleSample equal to
* particleId
*
*/
private void loadKeywordsForParticleSample(NanoparticleSample particleSample)
throws Exception {
Keyword[] keywords = gridClient
.getKeywordsByParticleSampleId(particleSample.getId()
.toString());
if (keywords != null && keywords.length > 0) {
particleSample.setKeywordCollection(new HashSet<Keyword>());
for (Keyword keyword : keywords) {
particleSample.getKeywordCollection().add(keyword);
}
}
}
/**
* load all keywords for an associated NanoparticleSample equal to
* particleId
*
*/
private void loadReportsForParticleSample(NanoparticleSample particleSample)
throws Exception {
ReportService reportService = new ReportServiceRemoteImpl(serviceUrl);
Report[] reports = reportService
.findReportsByParticleSampleId(particleSample.getId()
.toString());
if (reports != null && reports.length > 0) {
particleSample.setReportCollection(new HashSet<Report>());
for (Report report : reports) {
particleSample.getReportCollection().add(report);
}
}
}
public int getNumberOfPublicNanoparticleSamples() throws ParticleException {
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
query.setTarget(target);
QueryModifier modifier = new QueryModifier();
modifier.setCountOnly(true);
query.setQueryModifier(modifier);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
int count = 0;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
count = ((Long) obj).intValue();
}
return count;
} catch (Exception e) {
String err = "Error finding counts of remote public nanoparticle samples.";
logger.error(err, e);
throw new ParticleException(err, e);
}
}
public void assignAssociatedPublicVisibility(AuthorizationService authService,
ParticleBean particleSampleBean, String[] visibleGroups)
throws ParticleException {
throw new ParticleException("Not implemented for grid service");
}
}
|
package org.rstudio.studio.client.workbench.views.source.editors.text;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.animation.client.AnimationScheduler;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.PreElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import org.rstudio.core.client.CommandWithArg;
import org.rstudio.core.client.ElementIds;
import org.rstudio.core.client.ExternalJavaScriptLoader;
import org.rstudio.core.client.ExternalJavaScriptLoader.Callback;
import org.rstudio.core.client.Rectangle;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardShortcut.KeySequence;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.dom.WindowEx;
import org.rstudio.core.client.js.JsMap;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.js.JsUtil;
import org.rstudio.core.client.regex.Match;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.core.client.resources.StaticDataResource;
import org.rstudio.core.client.widget.DynamicIFrame;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.SuperDevMode;
import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations;
import org.rstudio.studio.client.common.debugging.model.Breakpoint;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.MainWindowObject;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ChangeTracker;
import org.rstudio.studio.client.workbench.model.EventBasedChangeTracker;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.snippets.SnippetHelper;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager.InitCompletionFilter;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionPopupPanel;
import org.rstudio.studio.client.workbench.views.console.shell.assist.NullCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.RCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.output.lint.DiagnosticsBackgroundPopup;
import org.rstudio.studio.client.workbench.views.output.lint.model.AceAnnotation;
import org.rstudio.studio.client.workbench.views.output.lint.model.LintItem;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceClickEvent.Handler;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceEditorCommandEvent.ExecutionPolicy;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Mode.InsertChunkInfo;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Renderer.ScreenCoordinates;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.CharClassifier;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.TokenPredicate;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.WordIterable;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionManager;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.ChunkDefinition;
import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.TextEditingTargetNotebook;
import org.rstudio.studio.client.workbench.views.source.events.CollabEditStartParams;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionEvent;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionHandler;
import org.rstudio.studio.client.workbench.views.source.events.SaveFileEvent;
import org.rstudio.studio.client.workbench.views.source.events.SaveFileHandler;
import org.rstudio.studio.client.workbench.views.source.model.DirtyState;
import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
public class AceEditor implements DocDisplay,
InputEditorDisplay,
NavigableSourceEditor
{
public enum NewLineMode
{
Windows("windows"),
Unix("unix"),
Auto("auto");
NewLineMode(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
private String type;
}
private class Filter implements InitCompletionFilter
{
public boolean shouldComplete(NativeEvent event)
{
// Never complete if there's an active selection
Range range = getSession().getSelection().getRange();
if (!range.isEmpty())
return false;
// Don't consider Tab to be a completion if we're at the start of a
// line (e.g. only zero or more whitespace characters between the
// beginning of the line and the cursor)
if (event != null && event.getKeyCode() != KeyCodes.KEY_TAB)
return true;
// Short-circuit if the user has explicitly opted in
if (uiPrefs_.allowTabMultilineCompletion().getValue())
return true;
int col = range.getStart().getColumn();
if (col == 0)
return false;
String line = getSession().getLine(range.getStart().getRow());
return line.substring(0, col).trim().length() != 0;
}
}
private class AnchoredSelectionImpl implements AnchoredSelection
{
private AnchoredSelectionImpl(Anchor start, Anchor end)
{
start_ = start;
end_ = end;
}
public String getValue()
{
return getSession().getTextRange(getRange());
}
public void apply()
{
getSession().getSelection().setSelectionRange(
getRange());
}
public Range getRange()
{
return Range.fromPoints(start_.getPosition(), end_.getPosition());
}
public void detach()
{
start_.detach();
end_.detach();
}
private final Anchor start_;
private final Anchor end_;
}
private class AceEditorChangeTracker extends EventBasedChangeTracker<Void>
{
private AceEditorChangeTracker()
{
super(AceEditor.this);
AceEditor.this.addFoldChangeHandler(new org.rstudio.studio.client.workbench.views.source.editors.text.events.FoldChangeEvent.Handler()
{
@Override
public void onFoldChange(FoldChangeEvent event)
{
changed_ = true;
}
});
AceEditor.this.addLineWidgetsChangedHandler(new org.rstudio.studio.client.workbench.views.source.editors.text.events.LineWidgetsChangedEvent.Handler() {
@Override
public void onLineWidgetsChanged(LineWidgetsChangedEvent event)
{
changed_ = true;
}
});
}
@Override
public ChangeTracker fork()
{
AceEditorChangeTracker forked = new AceEditorChangeTracker();
forked.changed_ = changed_;
return forked;
}
}
public static void preload()
{
load(null);
}
public static void load(final Command command)
{
aceLoader_.addCallback(new Callback()
{
public void onLoaded()
{
aceSupportLoader_.addCallback(new Callback()
{
public void onLoaded()
{
extLanguageToolsLoader_.addCallback(new Callback()
{
public void onLoaded()
{
vimLoader_.addCallback(new Callback()
{
public void onLoaded()
{
emacsLoader_.addCallback(new Callback()
{
public void onLoaded()
{
if (command != null)
command.execute();
}
});
}
});
}
});
}
});
}
});
}
@Inject
public AceEditor()
{
widget_ = new AceEditorWidget();
snippets_ = new SnippetHelper(this);
editorEventListeners_ = new ArrayList<HandlerRegistration>();
ElementIds.assignElementId(widget_.getElement(),
ElementIds.SOURCE_TEXT_EDITOR);
completionManager_ = new NullCompletionManager();
diagnosticsBgPopup_ = new DiagnosticsBackgroundPopup(this);
RStudioGinjector.INSTANCE.injectMembers(this);
backgroundTokenizer_ = new BackgroundTokenizer(this);
vim_ = new Vim(this);
widget_.addValueChangeHandler(new ValueChangeHandler<Void>()
{
public void onValueChange(ValueChangeEvent<Void> evt)
{
if (!valueChangeSuppressed_)
{
ValueChangeEvent.fire(AceEditor.this, null);
}
}
});
widget_.addFoldChangeHandler(new FoldChangeEvent.Handler()
{
@Override
public void onFoldChange(FoldChangeEvent event)
{
AceEditor.this.fireEvent(new FoldChangeEvent());
}
});
addPasteHandler(new PasteEvent.Handler()
{
@Override
public void onPaste(PasteEvent event)
{
if (completionManager_ != null)
completionManager_.onPaste(event);
final Position start = getSelectionStart();
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
Range range = Range.fromPoints(start, getSelectionEnd());
indentPastedRange(range);
}
});
}
});
// handle click events
addAceClickHandler(new AceClickEvent.Handler()
{
@Override
public void onClick(AceClickEvent event)
{
fixVerticalOffsetBug();
if (DomUtils.isCommandClick(event.getNativeEvent()))
{
// eat the event so ace doesn't do anything with it
event.preventDefault();
event.stopPropagation();
// set the cursor position
setCursorPosition(event.getDocumentPosition());
// go to function definition
fireEvent(new CommandClickEvent());
}
else
{
// if the focus in the Help pane or another iframe
// we need to make sure to get it back
WindowEx.get().focus();
}
}
});
lastCursorChangedTime_ = 0;
addCursorChangedHandler(new CursorChangedHandler()
{
@Override
public void onCursorChanged(CursorChangedEvent event)
{
fixVerticalOffsetBug();
clearLineHighlight();
lastCursorChangedTime_ = System.currentTimeMillis();
}
});
lastModifiedTime_ = 0;
addValueChangeHandler(new ValueChangeHandler<Void>()
{
@Override
public void onValueChange(ValueChangeEvent<Void> event)
{
lastModifiedTime_ = System.currentTimeMillis();
clearDebugLineHighlight();
}
});
widget_.addAttachHandler(new AttachEvent.Handler()
{
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (!event.isAttached())
{
for (HandlerRegistration handler : editorEventListeners_)
handler.removeHandler();
editorEventListeners_.clear();
if (completionManager_ != null)
{
completionManager_.detach();
completionManager_ = null;
}
}
}
});
widget_.addFocusHandler(new FocusHandler()
{
@Override
public void onFocus(FocusEvent event)
{
String id = AceEditor.this.getWidget().getElement().getId();
MainWindowObject.lastFocusedEditor().set(id);
}
});
events_.addHandler(
AceEditorCommandEvent.TYPE,
new AceEditorCommandEvent.Handler()
{
@Override
public void onEditorCommand(AceEditorCommandEvent event)
{
if (event.getExecutionPolicy() == ExecutionPolicy.FOCUSED &&
!AceEditor.this.isFocused())
{
return;
}
switch (event.getCommand())
{
case YANK_REGION: yankRegion(); break;
case YANK_BEFORE_CURSOR: yankBeforeCursor(); break;
case YANK_AFTER_CURSOR: yankAfterCursor(); break;
case PASTE_LAST_YANK: pasteLastYank(); break;
}
}
});
}
public void yankRegion()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
// no-op if there is no selection
String selectionValue = getSelectionValue();
if (StringUtil.isNullOrEmpty(selectionValue))
return;
if (Desktop.isDesktop())
commands_.cutDummy().execute();
else
{
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void yankBeforeCursor()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
Position cursorPos = getCursorPosition();
setSelectionRange(Range.fromPoints(
Position.create(cursorPos.getRow(), 0),
cursorPos));
if (Desktop.isDesktop())
commands_.cutDummy().execute();
else
{
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void yankAfterCursor()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
Position cursorPos = getCursorPosition();
int lineLength = getLine(cursorPos.getRow()).length();
setSelectionRange(Range.fromPoints(
cursorPos,
Position.create(cursorPos.getRow(), lineLength)));
if (Desktop.isDesktop())
commands_.cutDummy().execute();
else
{
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void pasteLastYank()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
if (Desktop.isDesktop())
commands_.pasteDummy().execute();
else
{
if (yankedText_ == null)
return;
replaceSelection(yankedText_);
setCursorPosition(getSelectionEnd());
}
}
private void indentPastedRange(Range range)
{
if (fileType_ == null ||
!fileType_.canAutoIndent() ||
!RStudioGinjector.INSTANCE.getUIPrefs().reindentOnPaste().getValue())
{
return;
}
String firstLinePrefix = getSession().getTextRange(
Range.fromPoints(Position.create(range.getStart().getRow(), 0),
range.getStart()));
if (firstLinePrefix.trim().length() != 0)
{
Position newStart = Position.create(range.getStart().getRow() + 1, 0);
if (newStart.compareTo(range.getEnd()) >= 0)
return;
range = Range.fromPoints(newStart, range.getEnd());
}
getSession().reindent(range);
}
public AceCommandManager getCommandManager()
{
return getWidget().getEditor().getCommandManager();
}
public void setEditorCommandBinding(String id, List<KeySequence> keys)
{
getWidget().getEditor().getCommandManager().rebindCommand(id, keys);
}
public void resetCommands()
{
AceCommandManager manager = AceCommandManager.create();
JsObject commands = manager.getCommands();
for (String key : JsUtil.asIterable(commands.keys()))
{
AceCommand command = commands.getObject(key);
getWidget().getEditor().getCommandManager().addCommand(command);
}
}
@Inject
void initialize(CodeToolsServerOperations server,
UIPrefs uiPrefs,
CollabEditor collab,
Commands commands,
EventBus events)
{
server_ = server;
uiPrefs_ = uiPrefs;
collab_ = collab;
commands_ = commands;
events_ = events;
}
public TextFileType getFileType()
{
return fileType_;
}
public void setFileType(TextFileType fileType)
{
setFileType(fileType, false);
}
public void setFileType(TextFileType fileType, boolean suppressCompletion)
{
fileType_ = fileType;
updateLanguage(suppressCompletion);
}
public void setFileType(TextFileType fileType,
CompletionManager completionManager)
{
fileType_ = fileType;
updateLanguage(completionManager);
}
@Override
public void setRnwCompletionContext(RnwCompletionContext rnwContext)
{
rnwContext_ = rnwContext;
}
@Override
public void setCppCompletionContext(CppCompletionContext cppContext)
{
cppContext_ = cppContext;
}
@Override
public void setRCompletionContext(RCompletionContext rContext)
{
rContext_ = rContext;
}
private void updateLanguage(boolean suppressCompletion)
{
if (fileType_ == null)
return;
CompletionManager completionManager;
if (!suppressCompletion)
{
if (fileType_.getEditorLanguage().useRCompletion())
{
completionManager = new RCompletionManager(
this,
this,
new CompletionPopupPanel(),
server_,
new Filter(),
rContext_,
fileType_.canExecuteChunks() ? rnwContext_ : null,
this,
false);
// if this is cpp then we use our own completion manager
// that can optionally delegate to the R completion manager
if (fileType_.isC() || fileType_.isRmd())
{
completionManager = new CppCompletionManager(
this,
new Filter(),
cppContext_,
completionManager);
}
}
else
completionManager = new NullCompletionManager();
}
else
completionManager = new NullCompletionManager();
updateLanguage(completionManager);
}
private void updateLanguage(CompletionManager completionManager)
{
clearLint();
if (fileType_ == null)
return;
if (completionManager_ != null)
{
completionManager_.detach();
completionManager_ = null;
}
completionManager_ = completionManager;
updateKeyboardHandlers();
syncCompletionPrefs();
syncDiagnosticsPrefs();
snippets_.ensureSnippetsLoaded();
getSession().setEditorMode(
fileType_.getEditorLanguage().getParserName(),
false);
handlers_.fireEvent(new EditorModeChangedEvent(getModeId()));
getSession().setUseWrapMode(fileType_.getWordWrap());
syncWrapLimit();
}
@Override
public void syncCompletionPrefs()
{
if (fileType_ == null)
return;
boolean enabled = fileType_.getEditorLanguage().useAceLanguageTools();
boolean live = uiPrefs_.codeCompleteOther().getValue().equals(
UIPrefsAccessor.COMPLETION_ALWAYS);
int characterThreshold = uiPrefs_.alwaysCompleteCharacters().getValue();
int delay = uiPrefs_.alwaysCompleteDelayMs().getValue();
widget_.getEditor().setCompletionOptions(
enabled,
uiPrefs_.enableSnippets().getValue(),
live,
characterThreshold,
delay);
}
@Override
public void syncDiagnosticsPrefs()
{
if (fileType_ == null)
return;
boolean useWorker = uiPrefs_.showDiagnosticsOther().getValue() &&
fileType_.getEditorLanguage().useAceLanguageTools();
getSession().setUseWorker(useWorker);
getSession().setWorkerTimeout(
uiPrefs_.backgroundDiagnosticsDelayMs().getValue());
}
private void syncWrapLimit()
{
// bail if there is no filetype yet
if (fileType_ == null)
return;
// We originally observed that large word-wrapped documents
// would cause Chrome on Liunx to freeze (bug #3207), eventually
// running of of memory. Running the profiler indicated that the
// time was being spent inside wrap width calculations in Ace.
// Looking at the Ace bug database there were other wrapping problems
// that were solvable by changing the wrap mode from "free" to a
// specific range. So, for Chrome on Linux we started syncing the
// wrap limit to the user-specified margin width.
// Unfortunately, this caused another problem whereby the ace
// horizontal scrollbar would show up over the top of the editor
// and the console (bug #3428). We tried reverting the fix to
// #3207 and sure enough this solved the horizontal scrollbar
// problem _and_ no longer froze Chrome (so perhaps there was a
// bug in Chrome).
// In the meantime we added user pref to soft wrap to the margin
// column, essentially allowing users to opt-in to the behavior
// we used to fix the bug. So the net is:
// (1) To fix the horizontal scrollbar problem we revereted
// the wrap mode behavior we added from Chrome (under the
// assumption that the issue has been fixed in Chrome)
// (2) We added another check for desktop mode (since we saw
// the problem in both Chrome and Safari) to prevent the
// application of the problematic wrap mode setting.
// Perhaps there is an ace issue here as well, so the next time
// we sync to Ace tip we should see if we can bring back the
// wrapping option for Chrome (note the repro for this
// is having a soft-wrapping source document in the editor that
// exceed the horizontal threshold)
// NOTE: we no longer do this at all since we observed the
// scollbar problem on desktop as well
}
private void updateKeyboardHandlers()
{
// clear out existing editor handlers (they will be refreshed if necessary)
for (HandlerRegistration handler : editorEventListeners_)
if (handler != null)
handler.removeHandler();
editorEventListeners_.clear();
// save and restore Vim marks as they can be lost when refreshing
// the keyboard handlers. this is necessary as keyboard handlers are
// regenerated on each document save, and clearing the Vim handler will
// clear any local Vim state.
JsMap<Position> marks = JsMap.create().cast();
if (useVimMode_)
marks = widget_.getEditor().getMarks();
// create a keyboard previewer for our special hooks
AceKeyboardPreviewer previewer = new AceKeyboardPreviewer(completionManager_);
// set default key handler
if (useVimMode_)
widget_.getEditor().setKeyboardHandler(KeyboardHandler.vim());
else if (useEmacsKeybindings_)
widget_.getEditor().setKeyboardHandler(KeyboardHandler.emacs());
else
widget_.getEditor().setKeyboardHandler(null);
// add the previewer
widget_.getEditor().addKeyboardHandler(previewer.getKeyboardHandler());
// Listen for command execution
editorEventListeners_.add(AceEditorNative.addEventListener(
widget_.getEditor().getCommandManager(),
"afterExec",
new CommandWithArg<JavaScriptObject>()
{
@Override
public void execute(JavaScriptObject event)
{
events_.fireEvent(new AceAfterCommandExecutedEvent(event));
}
}));
// Listen for keyboard activity
editorEventListeners_.add(AceEditorNative.addEventListener(
widget_.getEditor(),
"keyboardActivity",
new CommandWithArg<JavaScriptObject>()
{
@Override
public void execute(JavaScriptObject event)
{
events_.fireEvent(new AceKeyboardActivityEvent(event));
}
}));
if (useVimMode_)
widget_.getEditor().setMarks(marks);
}
public String getCode()
{
return getSession().getValue();
}
public void setCode(String code, boolean preserveCursorPosition)
{
// Calling setCode("", false) while the editor contains multiple lines of
// content causes bug 2928: Flickering console when typing. Empirically,
// first setting code to a single line of content and then clearing it,
// seems to correct this problem.
if (StringUtil.isNullOrEmpty(code))
doSetCode(" ", preserveCursorPosition);
doSetCode(code, preserveCursorPosition);
}
private void doSetCode(String code, boolean preserveCursorPosition)
{
// Filter out Escape characters that might have snuck in from an old
// bug in 0.95. We can choose to remove this when 0.95 ships, hopefully
// any documents that would be affected by this will be gone by then.
code = code.replaceAll("\u001B", "");
// Normalize newlines -- convert all of '\r', '\r\n', '\n\r' to '\n'.
code = StringUtil.normalizeNewLines(code);
final AceEditorNative ed = widget_.getEditor();
if (preserveCursorPosition)
{
final Position cursorPos;
final int scrollTop, scrollLeft;
cursorPos = ed.getSession().getSelection().getCursor();
scrollTop = ed.getRenderer().getScrollTop();
scrollLeft = ed.getRenderer().getScrollLeft();
// Setting the value directly on the document prevents undo/redo
// stack from being blown away
widget_.getEditor().getSession().getDocument().setValue(code);
ed.getSession().getSelection().moveCursorTo(cursorPos.getRow(),
cursorPos.getColumn(),
false);
ed.getRenderer().scrollToY(scrollTop);
ed.getRenderer().scrollToX(scrollLeft);
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
ed.getRenderer().scrollToY(scrollTop);
ed.getRenderer().scrollToX(scrollLeft);
}
});
}
else
{
ed.getSession().setValue(code);
ed.getSession().getSelection().moveCursorTo(0, 0, false);
}
}
public int getScrollLeft()
{
return widget_.getEditor().getRenderer().getScrollLeft();
}
public void scrollToX(int x)
{
widget_.getEditor().getRenderer().scrollToX(x);
}
public int getScrollTop()
{
return widget_.getEditor().getRenderer().getScrollTop();
}
public void scrollToY(int y, int animateMs)
{
// cancel any existing scroll animation
if (scrollAnimator_ != null)
scrollAnimator_.complete();
if (animateMs == 0)
widget_.getEditor().getRenderer().scrollToY(y);
else
scrollAnimator_ = new ScrollAnimator(y, animateMs);
}
public void insertCode(String code)
{
insertCode(code, false);
}
public void insertCode(String code, boolean blockMode)
{
widget_.getEditor().insert(StringUtil.normalizeNewLines(code));
}
public String getCode(Position start, Position end)
{
return getSession().getTextRange(Range.fromPoints(start, end));
}
@Override
public InputEditorSelection search(String needle,
boolean backwards,
boolean wrap,
boolean caseSensitive,
boolean wholeWord,
Position start,
Range range,
boolean regexpMode)
{
Search search = Search.create(needle,
backwards,
wrap,
caseSensitive,
wholeWord,
start,
range,
regexpMode);
Range resultRange = search.find(getSession());
if (resultRange != null)
{
return createSelection(resultRange.getStart(), resultRange.getEnd());
}
else
{
return null;
}
}
@Override
public void quickAddNext()
{
if (getNativeSelection().isEmpty())
{
getNativeSelection().selectWord();
return;
}
String needle = getSelectionValue();
Search search = Search.create(
needle,
false,
true,
true,
true,
getCursorPosition(),
null,
false);
Range range = search.find(getSession());
if (range == null)
return;
getNativeSelection().addRange(range, false);
centerSelection();
}
@Override
public void insertCode(InputEditorPosition position, String content)
{
insertCode(selectionToPosition(position), content);
}
public void insertCode(Position position, String content)
{
getSession().insert(position, content);
}
@Override
public String getCode(InputEditorSelection selection)
{
return getCode(((AceInputEditorPosition)selection.getStart()).getValue(),
((AceInputEditorPosition)selection.getEnd()).getValue());
}
@Override
public JsArrayString getLines()
{
return getLines(0, getSession().getLength());
}
@Override
public JsArrayString getLines(int startRow, int endRow)
{
return getSession().getLines(startRow, endRow);
}
public void focus()
{
widget_.getEditor().focus();
}
public boolean isFocused()
{
return widget_.getEditor().isFocused();
}
public void codeCompletion()
{
completionManager_.codeCompletion();
}
public void goToHelp()
{
completionManager_.goToHelp();
}
public void goToFunctionDefinition()
{
completionManager_.goToFunctionDefinition();
}
class PrintIFrame extends DynamicIFrame
{
public PrintIFrame(String code, double fontSize)
{
code_ = code;
fontSize_ = fontSize;
getElement().getStyle().setPosition(com.google.gwt.dom.client.Style.Position.ABSOLUTE);
getElement().getStyle().setLeft(-5000, Unit.PX);
}
@Override
protected void onFrameLoaded()
{
Document doc = getDocument();
PreElement pre = doc.createPreElement();
pre.setInnerText(code_);
pre.getStyle().setProperty("whiteSpace", "pre-wrap");
pre.getStyle().setFontSize(fontSize_, Unit.PT);
doc.getBody().appendChild(pre);
getWindow().print();
// Bug 1224: ace: print from source causes inability to reconnect
// This was caused by the iframe being removed from the document too
// quickly after the print job was sent. As a result, attempting to
// navigate away from the page at any point afterwards would result
// in the error "Document cannot change while printing or in Print
// Preview". The only thing you could do is close the browser tab.
// By inserting a 5-minute delay hopefully Firefox would be done with
// whatever print related operations are important.
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
public boolean execute()
{
PrintIFrame.this.removeFromParent();
return false;
}
}, 1000 * 60 * 5);
}
private final String code_;
private final double fontSize_;
}
public void print()
{
PrintIFrame printIFrame = new PrintIFrame(
getCode(),
RStudioGinjector.INSTANCE.getUIPrefs().fontSize().getValue());
RootPanel.get().add(printIFrame);
}
public String getText()
{
return getSession().getLine(
getSession().getSelection().getCursor().getRow());
}
public void setText(String string)
{
setCode(string, false);
getSession().getSelection().moveCursorFileEnd();
}
public boolean hasSelection()
{
return !getSession().getSelection().getRange().isEmpty();
}
public final Selection getNativeSelection() {
return widget_.getEditor().getSession().getSelection();
}
public InputEditorSelection getSelection()
{
Range selection = getSession().getSelection().getRange();
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), selection.getStart()),
new AceInputEditorPosition(getSession(), selection.getEnd()));
}
public String getSelectionValue()
{
return getSession().getTextRange(
getSession().getSelection().getRange());
}
public Position getSelectionStart()
{
return getSession().getSelection().getRange().getStart();
}
public Position getSelectionEnd()
{
return getSession().getSelection().getRange().getEnd();
}
@Override
public Range getSelectionRange()
{
return Range.fromPoints(getSelectionStart(), getSelectionEnd());
}
@Override
public void setSelectionRange(Range range)
{
getSession().getSelection().setSelectionRange(range);
}
public void setSelectionRanges(JsArray<Range> ranges)
{
int n = ranges.length();
if (n == 0)
return;
if (vim_.isActive())
vim_.exitVisualMode();
setSelectionRange(ranges.get(0));
for (int i = 1; i < n; i++)
getNativeSelection().addRange(ranges.get(i), false);
}
public int getLength(int row)
{
return getSession().getDocument().getLine(row).length();
}
public int getRowCount()
{
return getSession().getDocument().getLength();
}
@Override
public int getPixelWidth()
{
Element[] content = DomUtils.getElementsByClassName(
widget_.getElement(), "ace_content");
if (content.length < 1)
return widget_.getElement().getOffsetWidth();
else
return content[0].getOffsetWidth();
}
public String getLine(int row)
{
return getSession().getLine(row);
}
@Override
public Position getDocumentEnd()
{
int lastRow = getRowCount() - 1;
return Position.create(lastRow, getLength(lastRow));
}
@Override
public void setInsertMatching(boolean value)
{
widget_.getEditor().setInsertMatching(value);
}
@Override
public void setSurroundSelectionPref(String value)
{
widget_.getEditor().setSurroundSelectionPref(value);
}
@Override
public InputEditorSelection createSelection(Position pos1, Position pos2)
{
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), pos1),
new AceInputEditorPosition(getSession(), pos2));
}
@Override
public Position selectionToPosition(InputEditorPosition pos)
{
// HACK: This cast is gross, InputEditorPosition should just become
// AceInputEditorPosition
return Position.create((Integer) pos.getLine(), pos.getPosition());
}
@Override
public InputEditorPosition createInputEditorPosition(Position pos)
{
return new AceInputEditorPosition(getSession(), pos);
}
@Override
public Iterable<Range> getWords(TokenPredicate tokenPredicate,
CharClassifier charClassifier,
Position start,
Position end)
{
return new WordIterable(getSession(),
tokenPredicate,
charClassifier,
start,
end);
}
@Override
public String getTextForRange(Range range)
{
return getSession().getTextRange(range);
}
@Override
public Anchor createAnchor(Position pos)
{
return Anchor.createAnchor(getSession().getDocument(),
pos.getRow(),
pos.getColumn());
}
private void fixVerticalOffsetBug()
{
widget_.getEditor().getRenderer().fixVerticalOffsetBug();
}
@Override
public String debug_getDocumentDump()
{
return widget_.getEditor().getSession().getDocument().getDocumentDump();
}
@Override
public void debug_setSessionValueDirectly(String s)
{
widget_.getEditor().getSession().setValue(s);
}
public void setSelection(InputEditorSelection selection)
{
AceInputEditorPosition start = (AceInputEditorPosition)selection.getStart();
AceInputEditorPosition end = (AceInputEditorPosition)selection.getEnd();
getSession().getSelection().setSelectionRange(Range.fromPoints(
start.getValue(), end.getValue()));
}
public Rectangle getCursorBounds()
{
Range range = getSession().getSelection().getRange();
return toScreenCoordinates(range);
}
public Rectangle toScreenCoordinates(Range range)
{
Renderer renderer = widget_.getEditor().getRenderer();
ScreenCoordinates start = renderer.textToScreenCoordinates(
range.getStart().getRow(),
range.getStart().getColumn());
ScreenCoordinates end = renderer.textToScreenCoordinates(
range.getEnd().getRow(),
range.getEnd().getColumn());
return new Rectangle(start.getPageX(),
start.getPageY(),
end.getPageX() - start.getPageX(),
renderer.getLineHeight());
}
public Position toDocumentPosition(ScreenCoordinates coordinates)
{
return widget_.getEditor().getRenderer().screenToTextCoordinates(
coordinates.getPageX(),
coordinates.getPageY());
}
public Range toDocumentRange(Rectangle rectangle)
{
Renderer renderer = widget_.getEditor().getRenderer();
return Range.fromPoints(
renderer.screenToTextCoordinates(rectangle.getLeft(), rectangle.getTop()),
renderer.screenToTextCoordinates(rectangle.getRight(), rectangle.getBottom()));
}
@Override
public Rectangle getPositionBounds(Position position)
{
Renderer renderer = widget_.getEditor().getRenderer();
ScreenCoordinates start = renderer.textToScreenCoordinates(
position.getRow(),
position.getColumn());
return new Rectangle(start.getPageX(), start.getPageY(),
(int) Math.round(renderer.getCharacterWidth()),
(int) (renderer.getLineHeight() * 0.8));
}
@Override
public Rectangle getPositionBounds(InputEditorPosition position)
{
Position pos = ((AceInputEditorPosition) position).getValue();
return getPositionBounds(pos);
}
public Rectangle getBounds()
{
return new Rectangle(
widget_.getAbsoluteLeft(),
widget_.getAbsoluteTop(),
widget_.getOffsetWidth(),
widget_.getOffsetHeight());
}
public void setFocus(boolean focused)
{
if (focused)
widget_.getEditor().focus();
else
widget_.getEditor().blur();
}
public void replaceRange(Range range, String text) {
getSession().replace(range, text);
}
public String replaceSelection(String value, boolean collapseSelection)
{
Selection selection = getSession().getSelection();
String oldValue = getSession().getTextRange(selection.getRange());
replaceSelection(value);
if (collapseSelection)
{
collapseSelection(false);
}
return oldValue;
}
public boolean isSelectionCollapsed()
{
return getSession().getSelection().isEmpty();
}
public boolean isCursorAtEnd()
{
int lastRow = getRowCount() - 1;
Position cursorPos = getCursorPosition();
return cursorPos.compareTo(Position.create(lastRow,
getLength(lastRow))) == 0;
}
public void clear()
{
setCode("", false);
}
public boolean inMultiSelectMode()
{
return widget_.getEditor().inMultiSelectMode();
}
public void exitMultiSelectMode()
{
widget_.getEditor().exitMultiSelectMode();
}
public void clearSelection()
{
widget_.getEditor().clearSelection();
}
public void collapseSelection(boolean collapseToStart)
{
Selection selection = getSession().getSelection();
Range rng = selection.getRange();
Position pos = collapseToStart ? rng.getStart() : rng.getEnd();
selection.setSelectionRange(Range.fromPoints(pos, pos));
}
public InputEditorSelection getStart()
{
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), Position.create(0, 0)));
}
public InputEditorSelection getEnd()
{
EditSession session = getSession();
int rows = session.getLength();
Position end = Position.create(rows, session.getLine(rows).length());
return new InputEditorSelection(new AceInputEditorPosition(session, end));
}
public String getCurrentLine()
{
int row = getSession().getSelection().getRange().getStart().getRow();
return getSession().getLine(row);
}
public char getCharacterAtCursor()
{
Position cursorPos = getCursorPosition();
int column = cursorPos.getColumn();
String line = getLine(cursorPos.getRow());
if (column == line.length())
return '\0';
return line.charAt(column);
}
public char getCharacterBeforeCursor()
{
Position cursorPos = getCursorPosition();
int column = cursorPos.getColumn();
if (column == 0)
return '\0';
String line = getLine(cursorPos.getRow());
return line.charAt(column - 1);
}
public String getCurrentLineUpToCursor()
{
return getCurrentLine().substring(0, getCursorPosition().getColumn());
}
public int getCurrentLineNum()
{
Position pos = getCursorPosition();
return getSession().documentToScreenRow(pos);
}
public int getCurrentLineCount()
{
return getSession().getScreenLength();
}
@Override
public String getLanguageMode(Position position)
{
return getSession().getMode().getLanguageMode(position);
}
@Override
public String getModeId()
{
return getSession().getMode().getId();
}
public void replaceCode(String code)
{
int endRow, endCol;
endRow = getSession().getLength() - 1;
if (endRow < 0)
{
endRow = 0;
endCol = 0;
}
else
{
endCol = getSession().getLine(endRow).length();
}
Range range = Range.fromPoints(Position.create(0, 0),
Position.create(endRow, endCol));
getSession().replace(range, code);
}
public void replaceSelection(String code)
{
code = StringUtil.normalizeNewLines(code);
Range selRange = getSession().getSelection().getRange();
Position position = getSession().replace(selRange, code);
Range range = Range.fromPoints(selRange.getStart(), position);
getSession().getSelection().setSelectionRange(range);
}
public boolean moveSelectionToNextLine(boolean skipBlankLines)
{
int curRow = getSession().getSelection().getCursor().getRow();
while (++curRow < getSession().getLength())
{
String line = getSession().getLine(curRow);
Pattern pattern = Pattern.create("[^\\s]");
Match match = pattern.match(line, 0);
if (skipBlankLines && match == null)
continue;
int col = (match != null) ? match.getIndex() : 0;
getSession().getSelection().moveCursorTo(curRow, col, false);
getSession().unfold(curRow, true);
scrollCursorIntoViewIfNecessary();
return true;
}
return false;
}
@Override
public boolean moveSelectionToBlankLine()
{
int curRow = getSession().getSelection().getCursor().getRow();
// if the current row is the last row then insert a new row
if (curRow == (getSession().getLength() - 1))
{
int rowLen = getSession().getLine(curRow).length();
getSession().getSelection().moveCursorTo(curRow, rowLen, false);
insertCode("\n");
}
while (curRow < getSession().getLength())
{
String line = getSession().getLine(curRow);
if (line.length() == 0)
{
getSession().getSelection().moveCursorTo(curRow, 0, false);
getSession().unfold(curRow, true);
return true;
}
curRow++;
}
return false;
}
@Override
public void expandSelection()
{
widget_.getEditor().expandSelection();
}
@Override
public void shrinkSelection()
{
widget_.getEditor().shrinkSelection();
}
@Override
public void expandRaggedSelection()
{
if (!inMultiSelectMode())
return;
// TODO: It looks like we need to use an alternative API when
// using Vim mode.
if (isVimModeOn())
return;
boolean hasSelection = hasSelection();
Range[] ranges =
widget_.getEditor().getSession().getSelection().getAllRanges();
// Get the maximum columns for the current selection.
int colMin = Integer.MAX_VALUE;
int colMax = 0;
for (Range range : ranges)
{
colMin = Math.min(range.getStart().getColumn(), colMin);
colMax = Math.max(range.getEnd().getColumn(), colMax);
}
// For each range:
// 1. Set the left side of the selection to the minimum,
// 2. Set the right side of the selection to the maximum,
// moving the cursor and inserting whitespace as necessary.
for (Range range : ranges)
{
range.getStart().setColumn(colMin);
range.getEnd().setColumn(colMax);
String line = getLine(range.getStart().getRow());
if (line.length() < colMax)
{
insertCode(
Position.create(range.getStart().getRow(), line.length()),
StringUtil.repeat(" ", colMax - line.length()));
}
}
clearSelection();
Selection selection = getNativeSelection();
for (Range range : ranges)
{
if (hasSelection)
selection.addRange(range, true);
else
{
Range newRange = Range.create(
range.getEnd().getRow(),
range.getEnd().getColumn(),
range.getEnd().getRow(),
range.getEnd().getColumn());
selection.addRange(newRange, true);
}
}
}
@Override
public void clearSelectionHistory()
{
widget_.getEditor().clearSelectionHistory();
}
@Override
public void reindent()
{
boolean emptySelection = getSelection().isEmpty();
getSession().reindent(getSession().getSelection().getRange());
if (emptySelection)
moveSelectionToNextLine(false);
}
@Override
public void reindent(Range range)
{
getSession().reindent(range);
}
@Override
public void toggleCommentLines()
{
widget_.getEditor().toggleCommentLines();
}
public ChangeTracker getChangeTracker()
{
return new AceEditorChangeTracker();
}
// Because anchored selections create Ace event listeners, they
// must be explicitly detached (otherwise they will listen for
// edit events into perpetuity). The easiest way to facilitate this
// is to have anchored selection tied to the lifetime of a particular
// 'host' widget; this way, on detach, we can ensure that the associated
// anchors are detached as well.
public AnchoredSelection createAnchoredSelection(Widget hostWidget,
Position startPos,
Position endPos)
{
Anchor start = Anchor.createAnchor(getSession().getDocument(),
startPos.getRow(),
startPos.getColumn());
Anchor end = Anchor.createAnchor(getSession().getDocument(),
endPos.getRow(),
endPos.getColumn());
final AnchoredSelection selection = new AnchoredSelectionImpl(start, end);
if (hostWidget != null)
{
hostWidget.addAttachHandler(new AttachEvent.Handler()
{
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (!event.isAttached() && selection != null)
selection.detach();
}
});
}
return selection;
}
public AnchoredSelection createAnchoredSelection(Position start, Position end)
{
return createAnchoredSelection(null, start, end);
}
public void fitSelectionToLines(boolean expand)
{
Range range = getSession().getSelection().getRange();
Position start = range.getStart();
Position newStart = start;
if (start.getColumn() > 0)
{
if (expand)
{
newStart = Position.create(start.getRow(), 0);
}
else
{
String firstLine = getSession().getLine(start.getRow());
if (firstLine.substring(0, start.getColumn()).trim().length() == 0)
newStart = Position.create(start.getRow(), 0);
}
}
Position end = range.getEnd();
Position newEnd = end;
if (expand)
{
int endRow = end.getRow();
if (endRow == newStart.getRow() || end.getColumn() > 0)
{
// If selection ends at the start of a line, keep the selection
// there--unless that means less than one line will be selected
// in total.
newEnd = Position.create(
endRow, getSession().getLine(endRow).length());
}
}
else
{
while (newEnd.getRow() != newStart.getRow())
{
String line = getSession().getLine(newEnd.getRow());
if (line.substring(0, newEnd.getColumn()).trim().length() != 0)
break;
int prevRow = newEnd.getRow() - 1;
int len = getSession().getLine(prevRow).length();
newEnd = Position.create(prevRow, len);
}
}
getSession().getSelection().setSelectionRange(
Range.fromPoints(newStart, newEnd));
}
public int getSelectionOffset(boolean start)
{
Range range = getSession().getSelection().getRange();
if (start)
return range.getStart().getColumn();
else
return range.getEnd().getColumn();
}
public void onActivate()
{
Scheduler.get().scheduleFinally(new RepeatingCommand()
{
public boolean execute()
{
widget_.onResize();
widget_.onActivate();
return false;
}
});
}
public void onVisibilityChanged(boolean visible)
{
if (visible)
widget_.getEditor().getRenderer().updateFontSize();
}
public void onResize()
{
widget_.onResize();
}
public void setHighlightSelectedLine(boolean on)
{
widget_.getEditor().setHighlightActiveLine(on);
}
public void setHighlightSelectedWord(boolean on)
{
widget_.getEditor().setHighlightSelectedWord(on);
}
public void setShowLineNumbers(boolean on)
{
widget_.getEditor().getRenderer().setShowGutter(on);
}
public void setUseSoftTabs(boolean on)
{
getSession().setUseSoftTabs(on);
}
public void setScrollPastEndOfDocument(boolean enable)
{
widget_.getEditor().getRenderer().setScrollPastEnd(enable);
}
public void setHighlightRFunctionCalls(boolean highlight)
{
_setHighlightRFunctionCallsImpl(highlight);
widget_.getEditor().retokenizeDocument();
}
private native final void _setHighlightRFunctionCallsImpl(boolean highlight)
/*-{
var Mode = $wnd.require("mode/r_highlight_rules");
Mode.setHighlightRFunctionCalls(highlight);
}-*/;
public void enableSearchHighlight()
{
widget_.getEditor().enableSearchHighlight();
}
public void disableSearchHighlight()
{
widget_.getEditor().disableSearchHighlight();
}
/**
* Warning: This will be overridden whenever the file type is set
*/
public void setUseWrapMode(boolean useWrapMode)
{
getSession().setUseWrapMode(useWrapMode);
}
public void setTabSize(int tabSize)
{
getSession().setTabSize(tabSize);
}
public void setShowInvisibles(boolean show)
{
widget_.getEditor().getRenderer().setShowInvisibles(show);
}
public void setShowIndentGuides(boolean show)
{
widget_.getEditor().getRenderer().setShowIndentGuides(show);
}
public void setBlinkingCursor(boolean blinking)
{
widget_.getEditor().getRenderer().setBlinkingCursor(blinking);
}
public void setShowPrintMargin(boolean on)
{
widget_.getEditor().getRenderer().setShowPrintMargin(on);
}
@Override
public void setUseEmacsKeybindings(boolean use)
{
if (widget_.getEditor().getReadOnly())
return;
useEmacsKeybindings_ = use;
updateKeyboardHandlers();
}
@Override
public boolean isEmacsModeOn()
{
return useEmacsKeybindings_;
}
@Override
public void setUseVimMode(boolean use)
{
// no-op if the editor is read-only (since vim mode doesn't
// work for read-only ace instances)
if (widget_.getEditor().getReadOnly())
return;
useVimMode_ = use;
updateKeyboardHandlers();
}
@Override
public boolean isVimModeOn()
{
return useVimMode_;
}
@Override
public boolean isVimInInsertMode()
{
return useVimMode_ && widget_.getEditor().isVimInInsertMode();
}
public void setPadding(int padding)
{
widget_.getEditor().getRenderer().setPadding(padding);
}
public void setPrintMarginColumn(int column)
{
widget_.getEditor().getRenderer().setPrintMarginColumn(column);
syncWrapLimit();
}
@Override
public JsArray<AceFold> getFolds()
{
return getSession().getAllFolds();
}
@Override
public String getFoldState(int row)
{
AceFold fold = getSession().getFoldAt(row, 0);
if (fold == null)
return null;
Position foldPos = fold.getStart();
return getSession().getState(foldPos.getRow());
}
@Override
public void addFold(Range range)
{
getSession().addFold("...", range);
}
@Override
public void addFoldFromRow(int row)
{
FoldingRules foldingRules = getSession().getMode().getFoldingRules();
if (foldingRules == null)
return;
Range range = foldingRules.getFoldWidgetRange(getSession(),
"markbegin",
row);
if (range != null)
addFold(range);
}
@Override
public void unfold(AceFold fold)
{
getSession().unfold(Range.fromPoints(fold.getStart(), fold.getEnd()),
false);
}
@Override
public void unfold(int row)
{
getSession().unfold(row, false);
}
@Override
public void unfold(Range range)
{
getSession().unfold(range, false);
}
public void setReadOnly(boolean readOnly)
{
widget_.getEditor().setReadOnly(readOnly);
}
public HandlerRegistration addCursorChangedHandler(final CursorChangedHandler handler)
{
return widget_.addCursorChangedHandler(handler);
}
public HandlerRegistration addSaveCompletedHandler(SaveFileHandler handler)
{
return handlers_.addHandler(SaveFileEvent.TYPE, handler);
}
public HandlerRegistration addEditorFocusHandler(FocusHandler handler)
{
return widget_.addFocusHandler(handler);
}
public Scope getCurrentScope()
{
return getSession().getMode().getCodeModel().getCurrentScope(
getCursorPosition());
}
public Scope getScopeAtPosition(Position position)
{
return getSession().getMode().getCodeModel().getCurrentScope(position);
}
@Override
public String getNextLineIndent()
{
EditSession session = getSession();
Position cursorPosition = getCursorPosition();
int row = cursorPosition.getRow();
String state = getSession().getState(row);
String line = getCurrentLine().substring(
0, cursorPosition.getColumn());
String tab = session.getTabString();
int tabSize = session.getTabSize();
return session.getMode().getNextLineIndent(
state,
line,
tab,
tabSize,
row);
}
public Scope getCurrentChunk()
{
return getCurrentChunk(getCursorPosition());
}
@Override
public Scope getCurrentChunk(Position position)
{
return getSession().getMode().getCodeModel().getCurrentChunk(position);
}
@Override
public ScopeFunction getCurrentFunction(boolean allowAnonymous)
{
return getFunctionAtPosition(getCursorPosition(), allowAnonymous);
}
@Override
public ScopeFunction getFunctionAtPosition(Position position,
boolean allowAnonymous)
{
return getSession().getMode().getCodeModel().getCurrentFunction(
position, allowAnonymous);
}
@Override
public Scope getCurrentSection()
{
return getSectionAtPosition(getCursorPosition());
}
@Override
public Scope getSectionAtPosition(Position position)
{
return getSession().getMode().getCodeModel().getCurrentSection(position);
}
public Position getCursorPosition()
{
return getSession().getSelection().getCursor();
}
public Position getCursorPositionScreen()
{
return widget_.getEditor().getCursorPositionScreen();
}
public void setCursorPosition(Position position)
{
getSession().getSelection().setSelectionRange(
Range.fromPoints(position, position));
}
public void goToLineStart()
{
widget_.getEditor().getCommandManager().exec("gotolinestart", widget_.getEditor());
}
public void goToLineEnd()
{
widget_.getEditor().getCommandManager().exec("gotolineend", widget_.getEditor());
}
@Override
public void moveCursorNearTop(int rowOffset)
{
int screenRow = getSession().documentToScreenRow(getCursorPosition());
widget_.getEditor().scrollToRow(Math.max(0, screenRow - rowOffset));
}
@Override
public void moveCursorForward()
{
moveCursorForward(1);
}
@Override
public void moveCursorForward(int characters)
{
widget_.getEditor().moveCursorRight(characters);
}
@Override
public void moveCursorBackward()
{
moveCursorBackward(1);
}
@Override
public void moveCursorBackward(int characters)
{
widget_.getEditor().moveCursorLeft(characters);
}
@Override
public void moveCursorNearTop()
{
moveCursorNearTop(7);
}
@Override
public void ensureCursorVisible()
{
if (!widget_.getEditor().isRowFullyVisible(getCursorPosition().getRow()))
moveCursorNearTop();
}
@Override
public void ensureRowVisible(int row)
{
if (!widget_.getEditor().isRowFullyVisible(row))
setCursorPosition(Position.create(row, 0));
}
@Override
public void scrollCursorIntoViewIfNecessary(int rowsAround)
{
Position cursorPos = getCursorPosition();
int cursorRow = cursorPos.getRow();
if (cursorRow >= widget_.getEditor().getLastVisibleRow() - rowsAround)
{
Position alignPos = Position.create(cursorRow + rowsAround, 0);
widget_.getEditor().getRenderer().alignCursor(alignPos, 1);
}
else if (cursorRow <= widget_.getEditor().getFirstVisibleRow() + rowsAround)
{
Position alignPos = Position.create(cursorRow - rowsAround, 0);
widget_.getEditor().getRenderer().alignCursor(alignPos, 0);
}
}
@Override
public void scrollCursorIntoViewIfNecessary()
{
scrollCursorIntoViewIfNecessary(0);
}
@Override
public boolean isCursorInSingleLineString()
{
return StringUtil.isEndOfLineInRStringState(getCurrentLineUpToCursor());
}
public void gotoPageUp()
{
widget_.getEditor().gotoPageUp();
}
public void gotoPageDown()
{
widget_.getEditor().gotoPageDown();
}
public void scrollToBottom()
{
SourcePosition pos = SourcePosition.create(getCurrentLineCount() - 1, 0);
navigate(pos, false);
}
public void revealRange(Range range, boolean animate)
{
widget_.getEditor().revealRange(range, animate);
}
public CodeModel getCodeModel()
{
return getSession().getMode().getCodeModel();
}
public boolean hasCodeModel()
{
return getSession().getMode().hasCodeModel();
}
public boolean hasScopeTree()
{
return hasCodeModel() && getCodeModel().hasScopes();
}
public void buildScopeTree()
{
// Builds the scope tree as a side effect
if (hasScopeTree())
getScopeTree();
}
public int buildScopeTreeUpToRow(int row)
{
if (!hasScopeTree())
return 0;
return getSession().getMode().getRCodeModel().buildScopeTreeUpToRow(row);
}
public JsArray<Scope> getScopeTree()
{
return getSession().getMode().getCodeModel().getScopeTree();
}
@Override
public InsertChunkInfo getInsertChunkInfo()
{
return getSession().getMode().getInsertChunkInfo();
}
@Override
public void foldAll()
{
getSession().foldAll();
}
@Override
public void unfoldAll()
{
getSession().unfoldAll();
}
@Override
public void toggleFold()
{
getSession().toggleFold();
}
@Override
public void setFoldStyle(String style)
{
getSession().setFoldStyle(style);
}
@Override
public JsMap<Position> getMarks()
{
return widget_.getEditor().getMarks();
}
@Override
public void setMarks(JsMap<Position> marks)
{
widget_.getEditor().setMarks(marks);
}
@Override
public void jumpToMatching()
{
widget_.getEditor().jumpToMatching(false, false);
}
@Override
public void selectToMatching()
{
widget_.getEditor().jumpToMatching(true, false);
}
@Override
public void expandToMatching()
{
widget_.getEditor().jumpToMatching(true, true);
}
@Override
public void splitIntoLines()
{
widget_.getEditor().splitIntoLines();
}
@Override
public SourcePosition findFunctionPositionFromCursor(String functionName)
{
Scope func =
getSession().getMode().getCodeModel().findFunctionDefinitionFromUsage(
getCursorPosition(),
functionName);
if (func != null)
{
Position position = func.getPreamble();
return SourcePosition.create(position.getRow(), position.getColumn());
}
else
{
return null;
}
}
public JsArray<ScopeFunction> getAllFunctionScopes()
{
CodeModel codeModel = widget_.getEditor().getSession().getMode().getRCodeModel();
if (codeModel == null)
return null;
return codeModel.getAllFunctionScopes();
}
@Override
public void recordCurrentNavigationPosition()
{
fireRecordNavigationPosition(getCursorPosition());
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent)
{
navigateToPosition(position, recordCurrent, false);
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent,
boolean highlightLine)
{
if (recordCurrent)
recordCurrentNavigationPosition();
navigate(position, true, highlightLine);
}
@Override
public void restorePosition(SourcePosition position)
{
navigate(position, false);
}
@Override
public boolean isAtSourceRow(SourcePosition position)
{
Position currPos = getCursorPosition();
return currPos.getRow() == position.getRow();
}
@Override
public void highlightDebugLocation(SourcePosition startPosition,
SourcePosition endPosition,
boolean executing)
{
int firstRow = widget_.getEditor().getFirstVisibleRow();
int lastRow = widget_.getEditor().getLastVisibleRow();
// if the expression is large, let's just try to land in the middle
int debugRow = (int) Math.floor(startPosition.getRow() + (
endPosition.getRow() - startPosition.getRow())/2);
// if the row at which the debugging occurs is inside a fold, unfold it
getSession().unfold(debugRow, true);
// if the line to be debugged is past or near the edges of the screen,
// scroll it into view. allow some lines of context.
if (debugRow <= (firstRow + DEBUG_CONTEXT_LINES) ||
debugRow >= (lastRow - DEBUG_CONTEXT_LINES))
{
widget_.getEditor().scrollToLine(debugRow, true);
}
applyDebugLineHighlight(
startPosition.asPosition(),
endPosition.asPosition(),
executing);
}
@Override
public void endDebugHighlighting()
{
clearDebugLineHighlight();
}
@Override
public HandlerRegistration addBreakpointSetHandler(
BreakpointSetEvent.Handler handler)
{
return widget_.addBreakpointSetHandler(handler);
}
@Override
public HandlerRegistration addBreakpointMoveHandler(
BreakpointMoveEvent.Handler handler)
{
return widget_.addBreakpointMoveHandler(handler);
}
@Override
public void addOrUpdateBreakpoint(Breakpoint breakpoint)
{
widget_.addOrUpdateBreakpoint(breakpoint);
}
@Override
public void removeBreakpoint(Breakpoint breakpoint)
{
widget_.removeBreakpoint(breakpoint);
}
@Override
public void toggleBreakpointAtCursor()
{
widget_.toggleBreakpointAtCursor();
}
@Override
public void removeAllBreakpoints()
{
widget_.removeAllBreakpoints();
}
@Override
public boolean hasBreakpoints()
{
return widget_.hasBreakpoints();
}
public void setChunkLineExecState(int start, int end, int state)
{
widget_.setChunkLineExecState(start, end, state);
}
private void navigate(SourcePosition srcPosition, boolean addToHistory)
{
navigate(srcPosition, addToHistory, false);
}
private void navigate(SourcePosition srcPosition,
boolean addToHistory,
boolean highlightLine)
{
// get existing cursor position
Position previousCursorPos = getCursorPosition();
// set cursor to function line
Position position = Position.create(srcPosition.getRow(),
srcPosition.getColumn());
setCursorPosition(position);
// skip whitespace if necessary
if (srcPosition.getColumn() == 0)
{
int curRow = getSession().getSelection().getCursor().getRow();
String line = getSession().getLine(curRow);
int funStart = line.indexOf(line.trim());
position = Position.create(curRow, funStart);
setCursorPosition(position);
}
// scroll as necessary
if (srcPosition.getScrollPosition() != -1)
scrollToY(srcPosition.getScrollPosition(), 0);
else if (position.getRow() != previousCursorPos.getRow())
moveCursorNearTop();
else
ensureCursorVisible();
// set focus
focus();
if (highlightLine)
applyLineHighlight(position.getRow());
// add to navigation history if requested and our current mode
// supports history navigation
if (addToHistory)
fireRecordNavigationPosition(position);
}
private void fireRecordNavigationPosition(Position pos)
{
SourcePosition srcPos = SourcePosition.create(pos.getRow(),
pos.getColumn());
fireEvent(new RecordNavigationPositionEvent(srcPos));
}
@Override
public HandlerRegistration addRecordNavigationPositionHandler(
RecordNavigationPositionHandler handler)
{
return handlers_.addHandler(RecordNavigationPositionEvent.TYPE, handler);
}
@Override
public HandlerRegistration addCommandClickHandler(
CommandClickEvent.Handler handler)
{
return handlers_.addHandler(CommandClickEvent.TYPE, handler);
}
@Override
public HandlerRegistration addFindRequestedHandler(
FindRequestedEvent.Handler handler)
{
return handlers_.addHandler(FindRequestedEvent.TYPE, handler);
}
public void setFontSize(double size)
{
// No change needed--the AceEditorWidget uses the "normalSize" style
// However, we do need to resize the gutter
widget_.getEditor().getRenderer().updateFontSize();
widget_.forceResize();
}
public HandlerRegistration addValueChangeHandler(
ValueChangeHandler<Void> handler)
{
return handlers_.addHandler(ValueChangeEvent.getType(), handler);
}
public HandlerRegistration addFoldChangeHandler(
FoldChangeEvent.Handler handler)
{
return handlers_.addHandler(FoldChangeEvent.TYPE, handler);
}
public HandlerRegistration addLineWidgetsChangedHandler(
LineWidgetsChangedEvent.Handler handler)
{
return handlers_.addHandler(LineWidgetsChangedEvent.TYPE, handler);
}
public boolean isScopeTreeReady(int row)
{
return backgroundTokenizer_.isReady(row);
}
public HandlerRegistration addScopeTreeReadyHandler(ScopeTreeReadyEvent.Handler handler)
{
return handlers_.addHandler(ScopeTreeReadyEvent.TYPE, handler);
}
public HandlerRegistration addRenderFinishedHandler(RenderFinishedEvent.Handler handler)
{
return widget_.addHandler(handler, RenderFinishedEvent.TYPE);
}
public HandlerRegistration addDocumentChangedHandler(DocumentChangedEvent.Handler handler)
{
return widget_.addHandler(handler, DocumentChangedEvent.TYPE);
}
public HandlerRegistration addCapturingKeyDownHandler(KeyDownHandler handler)
{
return widget_.addCapturingKeyDownHandler(handler);
}
public HandlerRegistration addCapturingKeyPressHandler(KeyPressHandler handler)
{
return widget_.addCapturingKeyPressHandler(handler);
}
public HandlerRegistration addCapturingKeyUpHandler(KeyUpHandler handler)
{
return widget_.addCapturingKeyUpHandler(handler);
}
public HandlerRegistration addUndoRedoHandler(UndoRedoHandler handler)
{
return widget_.addUndoRedoHandler(handler);
}
public HandlerRegistration addPasteHandler(PasteEvent.Handler handler)
{
return widget_.addPasteHandler(handler);
}
public HandlerRegistration addAceClickHandler(Handler handler)
{
return widget_.addAceClickHandler(handler);
}
public HandlerRegistration addEditorModeChangedHandler(
EditorModeChangedEvent.Handler handler)
{
return handlers_.addHandler(EditorModeChangedEvent.TYPE, handler);
}
public JavaScriptObject getCleanStateToken()
{
return getSession().getUndoManager().peek();
}
public boolean checkCleanStateToken(JavaScriptObject token)
{
JavaScriptObject other = getSession().getUndoManager().peek();
if (token == null ^ other == null)
return false;
return token == null || other.equals(token);
}
public void fireEvent(GwtEvent<?> event)
{
handlers_.fireEvent(event);
}
public Widget asWidget()
{
return widget_;
}
public EditSession getSession()
{
return widget_.getEditor().getSession();
}
public HandlerRegistration addBlurHandler(BlurHandler handler)
{
return widget_.addBlurHandler(handler);
}
public HandlerRegistration addClickHandler(ClickHandler handler)
{
return widget_.addClickHandler(handler);
}
public HandlerRegistration addFocusHandler(FocusHandler handler)
{
return widget_.addFocusHandler(handler);
}
public AceEditorWidget getWidget()
{
return widget_;
}
public HandlerRegistration addKeyDownHandler(KeyDownHandler handler)
{
return widget_.addKeyDownHandler(handler);
}
public HandlerRegistration addKeyPressHandler(KeyPressHandler handler)
{
return widget_.addKeyPressHandler(handler);
}
public void autoHeight()
{
widget_.autoHeight();
}
public void forceCursorChange()
{
widget_.forceCursorChange();
}
public void scrollToCursor(ScrollPanel scrollPanel,
int paddingVert,
int paddingHoriz)
{
DomUtils.ensureVisibleVert(
scrollPanel.getElement(),
widget_.getEditor().getRenderer().getCursorElement(),
paddingVert);
DomUtils.ensureVisibleHoriz(
scrollPanel.getElement(),
widget_.getEditor().getRenderer().getCursorElement(),
paddingHoriz, paddingHoriz,
false);
}
public void scrollToLine(int row, boolean center)
{
widget_.getEditor().scrollToLine(row, center);
}
public void centerSelection()
{
widget_.getEditor().centerSelection();
}
public void alignCursor(Position position, double ratio)
{
widget_.getEditor().getRenderer().alignCursor(position, ratio);
}
public void forceImmediateRender()
{
widget_.getEditor().getRenderer().forceImmediateRender();
}
public void setNewLineMode(NewLineMode mode)
{
getSession().setNewLineMode(mode.getType());
}
public boolean isPasswordMode()
{
return passwordMode_;
}
public void setPasswordMode(boolean passwordMode)
{
passwordMode_ = passwordMode;
widget_.getEditor().getRenderer().setPasswordMode(passwordMode);
}
public void setDisableOverwrite(boolean disableOverwrite)
{
getSession().setDisableOverwrite(disableOverwrite);
}
private Integer createLineHighlightMarker(int line, String style)
{
return createRangeHighlightMarker(Position.create(line, 0),
Position.create(line+1, 0),
style);
}
private Integer createRangeHighlightMarker(
Position start,
Position end,
String style)
{
Range range = Range.fromPoints(start, end);
return getSession().addMarker(range, style, "text", false);
}
private void applyLineHighlight(int line)
{
clearLineHighlight();
if (!widget_.getEditor().getHighlightActiveLine())
{
lineHighlightMarkerId_ = createLineHighlightMarker(line,
"ace_find_line");
}
}
private void clearLineHighlight()
{
if (lineHighlightMarkerId_ != null)
{
getSession().removeMarker(lineHighlightMarkerId_);
lineHighlightMarkerId_ = null;
}
}
private void applyDebugLineHighlight(
Position startPos,
Position endPos,
boolean executing)
{
clearDebugLineHighlight();
lineDebugMarkerId_ = createRangeHighlightMarker(
startPos, endPos,
"ace_active_debug_line");
if (executing)
{
executionLine_ = startPos.getRow();
widget_.getEditor().getRenderer().addGutterDecoration(
executionLine_,
"ace_executing-line");
}
}
private void clearDebugLineHighlight()
{
if (lineDebugMarkerId_ != null)
{
getSession().removeMarker(lineDebugMarkerId_);
lineDebugMarkerId_ = null;
}
if (executionLine_ != null)
{
widget_.getEditor().getRenderer().removeGutterDecoration(
executionLine_,
"ace_executing-line");
executionLine_ = null;
}
}
public void setPopupVisible(boolean visible)
{
popupVisible_ = visible;
}
public boolean isPopupVisible()
{
return popupVisible_;
}
public void selectAll(String needle)
{
widget_.getEditor().findAll(needle);
}
public void selectAll(String needle, Range range, boolean wholeWord, boolean caseSensitive)
{
widget_.getEditor().findAll(needle, range, wholeWord, caseSensitive);
}
public void moveCursorLeft()
{
moveCursorLeft(1);
}
public void moveCursorLeft(int times)
{
widget_.getEditor().moveCursorLeft(times);
}
public void moveCursorRight()
{
moveCursorRight(1);
}
public void moveCursorRight(int times)
{
widget_.getEditor().moveCursorRight(times);
}
public void expandSelectionLeft(int times)
{
widget_.getEditor().expandSelectionLeft(times);
}
public void expandSelectionRight(int times)
{
widget_.getEditor().expandSelectionRight(times);
}
public int getTabSize()
{
return widget_.getEditor().getSession().getTabSize();
}
// TODO: Enable similar logic for C++ mode?
public int getStartOfCurrentStatement()
{
if (!DocumentMode.isSelectionInRMode(this))
return -1;
TokenCursor cursor =
getSession().getMode().getCodeModel().getTokenCursor();
if (!cursor.moveToPosition(getCursorPosition()))
return -1;
if (!cursor.moveToStartOfCurrentStatement())
return -1;
return cursor.getRow();
}
// TODO: Enable similar logic for C++ mode?
public int getEndOfCurrentStatement()
{
if (!DocumentMode.isSelectionInRMode(this))
return -1;
TokenCursor cursor =
getSession().getMode().getCodeModel().getTokenCursor();
if (!cursor.moveToPosition(getCursorPosition()))
return -1;
if (!cursor.moveToEndOfCurrentStatement())
return -1;
return cursor.getRow();
}
private boolean rowEndsInBinaryOp(int row)
{
// move to the last interesting token on this line
JsArray<Token> tokens = getSession().getTokens(row);
for (int i = tokens.length() - 1; i >= 0; i
{
Token t = tokens.get(i);
if (t.hasType("text", "comment"))
continue;
if (t.getType() == "keyword.operator" ||
t.getType() == "keyword.operator.infix" ||
t.getValue() == ",")
return true;
break;
}
return false;
}
@Override
public Range getMultiLineExpr(Position pos, int startRow, int endRow)
{
if (!DocumentMode.isSelectionInRMode(this))
return null;
// start with a point range at the beginning of the row
Range range = Range.create(pos.getRow(), 0, pos.getRow(), 0);
TokenCursor c = getSession().getMode().getCodeModel().getTokenCursor();
int row = pos.getRow();
// extend the range down until we encounter a line which doesn't end
// in a binary operator
while (row <= endRow)
{
// extend the range to include this entire line
range = range.extend(row, getLength(row));
// expand to include the current bracketed expression, if any
if (!c.moveToPosition(range.getEnd()) ||
c.getRow() != range.getEnd().getRow())
break;
if (c.findOpeningBracket(new String[]{"(", "[", "{"}, false))
{
// don't look upwards for { expressions (likely to be larger than
// we're looking for)
if (c.currentValue() != "{" || c.getRow() >= row)
{
range = range.extend(c.getRow(), 0);
if (c.fwdToMatchingToken())
range = range.extend(c.getRow(), getLength(c.getRow()));
row = range.getEnd().getRow();
}
}
// if we're looking at a binary operator, keep building
if (rowEndsInBinaryOp(row))
row++;
else
break;
}
// extend the range up to include lines which end with a binary operator
row = range.getStart().getRow() - 1;
while (row >= startRow)
{
if (rowEndsInBinaryOp(row))
{
// expand to include the current bracketed expression, if any--this
// is asymmetric with the above to avoid growing the range upwards
// to include large { blocks such as functions and loops
c.moveToStartOfRow(row);
if (c.findOpeningBracket(new String[]{"(", "["}, false))
{
range = range.extend(c.getRow(), 0);
if (c.fwdToMatchingToken())
range = range.extend(c.getRow(), getLength(c.getRow()));
row = range.getStart().getRow();
}
range = range.extend(row, 0);
row
}
else
break;
}
return range;
}
public JsArray<AceAnnotation> getAnnotations()
{
return widget_.getAnnotations();
}
public void setAnnotations(JsArray<AceAnnotation> annotations)
{
widget_.setAnnotations(annotations);
}
@Override
public void removeMarkersAtCursorPosition()
{
widget_.removeMarkersAtCursorPosition();
}
@Override
public void removeMarkersOnCursorLine()
{
widget_.removeMarkersOnCursorLine();
}
@Override
public void showLint(JsArray<LintItem> lint)
{
widget_.showLint(lint);
}
@Override
public void clearLint()
{
widget_.clearLint();
}
@Override
public void showInfoBar(String message)
{
if (infoBar_ == null)
{
infoBar_ = new AceInfoBar(widget_);
widget_.addKeyDownHandler(new KeyDownHandler()
{
@Override
public void onKeyDown(KeyDownEvent event)
{
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE)
infoBar_.hide();
}
});
}
infoBar_.setText(message);
infoBar_.show();
}
public Range createAnchoredRange(Position start,
Position end)
{
return widget_.getEditor().getSession().createAnchoredRange(start, end);
}
public void insertRoxygenSkeleton()
{
getSession().getMode().getCodeModel().insertRoxygenSkeleton();
}
public long getLastModifiedTime()
{
return lastModifiedTime_;
}
public long getLastCursorChangedTime()
{
return lastCursorChangedTime_;
}
public int getFirstVisibleRow()
{
return widget_.getEditor().getFirstVisibleRow();
}
public int getLastVisibleRow()
{
return widget_.getEditor().getLastVisibleRow();
}
public void blockOutdent()
{
widget_.getEditor().blockOutdent();
}
public Position screenCoordinatesToDocumentPosition(int pageX, int pageY)
{
return widget_.getEditor().getRenderer().screenToTextCoordinates(pageX, pageY);
}
public boolean isPositionVisible(Position position)
{
return widget_.getEditor().isRowFullyVisible(position.getRow());
}
public TokenIterator getTokenIterator(Position pos)
{
if (pos == null)
return TokenIterator.create(getSession());
else
return TokenIterator.create(getSession(),
pos.getRow(), pos.getColumn());
}
@Override
public void beginCollabSession(CollabEditStartParams params,
DirtyState dirtyState)
{
// suppress external value change events while the editor's contents are
// being swapped out for the contents of the collab session--otherwise
// there's going to be a lot of flickering as dirty state (etc) try to
// keep up
valueChangeSuppressed_ = true;
collab_.beginCollabSession(this, params, dirtyState, new Command()
{
@Override
public void execute()
{
valueChangeSuppressed_ = false;
}
});
}
@Override
public boolean hasActiveCollabSession()
{
return collab_.hasActiveCollabSession(this);
}
@Override
public boolean hasFollowingCollabSession()
{
return collab_.hasFollowingCollabSession(this);
}
public void endCollabSession()
{
collab_.endCollabSession(this);
}
@Override
public void setDragEnabled(boolean enabled)
{
widget_.setDragEnabled(enabled);
}
public boolean onInsertSnippet()
{
return snippets_.onInsertSnippet();
}
public void toggleTokenInfo()
{
toggleTokenInfo(widget_.getEditor());
}
private static final native void toggleTokenInfo(AceEditorNative editor) /*-{
if (editor.tokenTooltip && editor.tokenTooltip.destroy) {
editor.tokenTooltip.destroy();
} else {
var TokenTooltip = $wnd.require("ace/token_tooltip").TokenTooltip;
editor.tokenTooltip = new TokenTooltip(editor);
}
}-*/;
@Override
public void addLineWidget(LineWidget widget)
{
widget_.getLineWidgetManager().addLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public void removeLineWidget(LineWidget widget)
{
widget_.getLineWidgetManager().removeLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public void removeAllLineWidgets()
{
widget_.getLineWidgetManager().removeAllLineWidgets();
fireLineWidgetsChanged();
}
@Override
public void onLineWidgetChanged(LineWidget widget)
{
widget_.getLineWidgetManager().onWidgetChanged(widget);
fireLineWidgetsChanged();
}
@Override
public JsArray<LineWidget> getLineWidgets()
{
return widget_.getLineWidgetManager().getLineWidgets();
}
@Override
public LineWidget getLineWidgetForRow(int row)
{
return widget_.getLineWidgetManager().getLineWidgetForRow(row);
}
@Override
public JsArray<ChunkDefinition> getChunkDefs()
{
// chunk definitions are populated at render time, so don't return any
// if we haven't rendered yet
if (!isRendered())
return null;
JsArray<ChunkDefinition> chunks = JsArray.createArray().cast();
JsArray<LineWidget> lineWidgets = getLineWidgets();
ScopeList scopes = new ScopeList(this);
for (int i = 0; i<lineWidgets.length(); i++)
{
LineWidget lineWidget = lineWidgets.get(i);
if (lineWidget.getType().equals(ChunkDefinition.LINE_WIDGET_TYPE))
{
ChunkDefinition chunk = lineWidget.getData();
chunks.push(chunk.with(lineWidget.getRow(),
TextEditingTargetNotebook.getKnitrChunkLabel(
lineWidget.getRow(), this, scopes)));
}
}
return chunks;
}
@Override
public boolean isRendered()
{
return widget_.isRendered();
}
@Override
public boolean showChunkOutputInline()
{
return showChunkOutputInline_;
}
@Override
public void setShowChunkOutputInline(boolean show)
{
showChunkOutputInline_ = show;
}
private void fireLineWidgetsChanged()
{
AceEditor.this.fireEvent(new LineWidgetsChangedEvent());
}
private static class BackgroundTokenizer
{
public BackgroundTokenizer(final AceEditor editor)
{
editor_ = editor;
timer_ = new Timer()
{
@Override
public void run()
{
// Stop our timer if we've tokenized up to the end of the document.
if (row_ >= editor_.getRowCount())
{
editor_.fireEvent(new ScopeTreeReadyEvent(
editor_.getScopeTree(),
editor_.getCurrentScope()));
return;
}
row_ += ROWS_TOKENIZED_PER_ITERATION;
row_ = Math.max(row_, editor.buildScopeTreeUpToRow(row_));
timer_.schedule(DELAY_MS);
}
};
editor_.addDocumentChangedHandler(new DocumentChangedEvent.Handler()
{
@Override
public void onDocumentChanged(DocumentChangedEvent event)
{
row_ = event.getEvent().getRange().getStart().getRow();
timer_.schedule(DELAY_MS);
}
});
}
public boolean isReady(int row)
{
return row < row_;
}
private final AceEditor editor_;
private final Timer timer_;
private int row_ = 0;
private static final int DELAY_MS = 5;
private static final int ROWS_TOKENIZED_PER_ITERATION = 200;
}
private class ScrollAnimator
implements AnimationScheduler.AnimationCallback
{
public ScrollAnimator(int targetY, int ms)
{
targetY_ = targetY;
startY_ = widget_.getEditor().getRenderer().getScrollTop();
delta_ = targetY_ - startY_;
ms_ = ms;
handle_ = AnimationScheduler.get().requestAnimationFrame(this);
}
public void complete()
{
handle_.cancel();
scrollAnimator_ = null;
}
@Override
public void execute(double timestamp)
{
if (startTime_ < 0)
startTime_ = timestamp;
double elapsed = timestamp - startTime_;
if (elapsed >= ms_)
{
widget_.getEditor().getRenderer().scrollToY(targetY_);
complete();
return;
}
// ease-out exponential
widget_.getEditor().getRenderer().scrollToY(
(int)(delta_ * (-Math.pow(2, -10 * elapsed / ms_) + 1)) + startY_);
// request next frame
handle_ = AnimationScheduler.get().requestAnimationFrame(this);
}
private final int ms_;
private final int targetY_;
private final int startY_;
private final int delta_;
private double startTime_ = -1;
private AnimationScheduler.AnimationHandle handle_;
}
private static final int DEBUG_CONTEXT_LINES = 2;
private final HandlerManager handlers_ = new HandlerManager(this);
private final AceEditorWidget widget_;
private final SnippetHelper snippets_;
private ScrollAnimator scrollAnimator_;
private CompletionManager completionManager_;
private CodeToolsServerOperations server_;
private UIPrefs uiPrefs_;
private CollabEditor collab_;
private Commands commands_;
private EventBus events_;
private TextFileType fileType_;
private boolean passwordMode_;
private boolean useEmacsKeybindings_ = false;
private boolean useVimMode_ = false;
private RnwCompletionContext rnwContext_;
private CppCompletionContext cppContext_;
private RCompletionContext rContext_ = null;
private Integer lineHighlightMarkerId_ = null;
private Integer lineDebugMarkerId_ = null;
private Integer executionLine_ = null;
private boolean valueChangeSuppressed_ = false;
private AceInfoBar infoBar_;
private boolean showChunkOutputInline_ = false;
private BackgroundTokenizer backgroundTokenizer_;
private final Vim vim_;
private static final ExternalJavaScriptLoader getLoader(StaticDataResource release)
{
return getLoader(release, null);
}
private static final ExternalJavaScriptLoader getLoader(StaticDataResource release,
StaticDataResource debug)
{
if (debug == null || !SuperDevMode.isActive())
return new ExternalJavaScriptLoader(release.getSafeUri().asString());
else
return new ExternalJavaScriptLoader(debug.getSafeUri().asString());
}
private static final ExternalJavaScriptLoader aceLoader_ =
getLoader(AceResources.INSTANCE.acejs(), AceResources.INSTANCE.acejsUncompressed());
private static final ExternalJavaScriptLoader aceSupportLoader_ =
getLoader(AceResources.INSTANCE.acesupportjs());
private static final ExternalJavaScriptLoader vimLoader_ =
getLoader(AceResources.INSTANCE.keybindingVimJs(),
AceResources.INSTANCE.keybindingVimUncompressedJs());
private static final ExternalJavaScriptLoader emacsLoader_ =
getLoader(AceResources.INSTANCE.keybindingEmacsJs(),
AceResources.INSTANCE.keybindingEmacsUncompressedJs());
private static final ExternalJavaScriptLoader extLanguageToolsLoader_ =
getLoader(AceResources.INSTANCE.extLanguageTools(),
AceResources.INSTANCE.extLanguageToolsUncompressed());
private boolean popupVisible_;
private final DiagnosticsBackgroundPopup diagnosticsBgPopup_;
private long lastCursorChangedTime_;
private long lastModifiedTime_;
private String yankedText_ = null;
private final List<HandlerRegistration> editorEventListeners_;
}
|
package com.forgeessentials.core.preloader.mixin.entity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.EntityTrackerEntry;
import net.minecraft.util.IntHashMap;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(EntityTracker.class)
public abstract class MixinEntityTracker_01 implements EntityTrackerHelper
{
@Shadow
private IntHashMap trackedEntityHashTable = new IntHashMap();
@Override
public EntityTrackerEntry getEntityTrackerEntry(Entity entity)
{
return (EntityTrackerEntry) trackedEntityHashTable.lookup(entity.getEntityId());
}
}
|
package com.insightfullogic.honest_profiler.ports.javafx.model;
import static javafx.application.Platform.isFxApplicationThread;
import static javafx.application.Platform.runLater;
import java.util.concurrent.atomic.AtomicInteger;
import com.insightfullogic.honest_profiler.core.profiles.FlameGraph;
import com.insightfullogic.honest_profiler.core.profiles.FlameGraphListener;
import com.insightfullogic.honest_profiler.core.profiles.Profile;
import com.insightfullogic.honest_profiler.core.profiles.ProfileListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ProfileContext
{
public static enum ProfileMode
{
LIVE, LOG
}
private static final AtomicInteger counter = new AtomicInteger();
private final int id;
private final SimpleStringProperty name;
private final ProfileMode mode;
private final SimpleObjectProperty<Profile> profile;
private final SimpleObjectProperty<FlameGraph> flameGraph;
private boolean frozen;
// While frozen, incoming profiles/graphs are cached in the following 2
// instance properties.
private Profile cachedProfile;
private FlameGraph cachedFlameGraph;
public ProfileContext(String name, ProfileMode mode)
{
id = counter.incrementAndGet();
this.name = new SimpleStringProperty(name);
this.mode = mode;
profile = new SimpleObjectProperty<>();
flameGraph = new SimpleObjectProperty<>();
}
public int getId()
{
return id;
}
public String getName()
{
return name.get();
}
public ProfileMode getMode()
{
return mode;
}
public Profile getProfile()
{
return profile.get();
}
public StringProperty profileNameProperty()
{
return name;
}
public ObjectProperty<Profile> profileProperty()
{
return profile;
}
public ObjectProperty<FlameGraph> flameGraphProperty()
{
return flameGraph;
}
public boolean isFrozen()
{
return frozen;
}
// Call only on FX Thread !
public void setFrozen(boolean freeze)
{
this.frozen = freeze;
if (!freeze)
{
if (cachedProfile != null)
{
update(cachedProfile);
cachedProfile = null;
}
if (cachedFlameGraph != null)
{
update(cachedFlameGraph);
cachedFlameGraph = null;
}
}
}
public ProfileListener getProfileListener()
{
return new ProfileListener()
{
@Override
public void accept(Profile t)
{
if (isFxApplicationThread())
{
update(t);
}
else
{
runLater(() -> update(t));
}
}
};
}
public FlameGraphListener getFlameGraphListener()
{
return new FlameGraphListener()
{
@Override
public void accept(FlameGraph t)
{
if (isFxApplicationThread())
{
update(t);
}
else
{
runLater(() -> update(t));
}
}
};
}
// Call only on FX Thread !
private void update(Profile t)
{
if (frozen)
{
cachedProfile = t;
}
else
{
profile.set(t);
}
}
private void update(FlameGraph t)
{
if (frozen)
{
cachedFlameGraph = t;
}
else
{
flameGraph.set(t);
}
}
}
|
package org.mym.plog;
import org.json.JSONObject;
/**
* Builder style API; use this class to fit complicated needs.
* <p>
* NOTE: APIs in {@link PLog} class is for common scenarios and this class is for advanced usage.
* Some decor method in {@link PLog} will NOT be added into this class, e.g.
* {@link PLog#wtf(Throwable)}.
* </p>
*
* @author Muyangmin
* @since 2.0.0
*/
public final class LogRequest {
@PrintLevel
private int level;
private int stackOffset;
private String tag;
private Category category;
private String msg;
private Object[] params;
@PrintLevel
public int getLevel() {
return level;
}
public int getStackOffset() {
return stackOffset;
}
public String getTag() {
return tag;
}
public Category getCategory() {
return category;
}
public String getMsg() {
return msg;
}
public Object[] getParams() {
return params;
}
public void json(JSONObject jsonObject) {
params(jsonObject);
}
public void throwable(Throwable throwable) {
params(throwable);
}
public LogRequest level(@PrintLevel int level) {
this.level = level;
return this;
}
public LogRequest tag(String tag) {
this.tag = tag;
return this;
}
public LogRequest category(Category category) {
this.category = category;
return this;
}
public LogRequest msg(String msg) {
this.msg = msg;
return this;
}
public LogRequest params(Object... params) {
this.params = params;
return this;
}
public LogRequest stackOffset(int stackOffset) {
this.stackOffset = stackOffset;
return this;
}
public void execute() {
LogEngine.handleLogRequest(this);
}
}
|
package fr.ens.transcriptome.nividic.om.filters;
import fr.ens.transcriptome.nividic.om.BioAssay;
/**
* This class define a filter for double with a threshold and a comparator.
* @author Laurent Jourdren
*/
public class BioAssayDoubleThresholdFilter extends
BioAssayGenericDoubleFieldFilter {
private String field = BioAssay.FIELD_NAME_M;
private static final Comparator defaultComparator = Comparator.UPPER;
private double threshold;
private boolean absolute;
private Comparator comparator = Comparator.UPPER;
private enum Comparator {
LOWER, LOWEREQUALS, EQUALS, NOTEQUALS, UPPEREQUALS, UPPER;
public String toString() {
switch (this) {
case LOWER:
return "<";
case LOWEREQUALS:
return "<=";
case EQUALS:
return "=";
case NOTEQUALS:
return "!=";
case UPPEREQUALS:
return ">=";
case UPPER:
return ">";
default:
return "";
}
}
public static Comparator getComparator(final String comparatorString) {
if (comparatorString == null)
return defaultComparator;
String s = comparatorString.trim();
if (s.equals("<"))
return LOWER;
if (s.equals("<="))
return LOWEREQUALS;
if (s.equals("=") || s.equals("=="))
return EQUALS;
if (s.equals("!="))
return NOTEQUALS;
if (s.equals(">="))
return UPPEREQUALS;
if (s.equals(">"))
return UPPER;
return defaultComparator;
}
};
// Getter
/**
* Define the field to filter.
* @return the field to filter
*/
public String getFieldToFilter() {
return field;
}
/**
* Get the comparator.
* @return The comparator
*/
public String getComparator() {
return comparator.toString();
}
/**
* Get the threshold.
* @return The threshold
*/
public double getThreshold() {
return this.threshold;
}
/**
* test if the value to test is absolute.
* @return true if the value to test is absolute
*/
public boolean isAbsolute() {
return this.absolute;
}
// Setter
/**
* Set the field to filter.
* @param field Field to filter
*/
public void setFieldToFilter(final String field) {
this.field = field;
}
/**
* Set the comparator.
* @param comparator Comparator to set
*/
public void setComparator(final String comparator) {
this.comparator = Comparator.getComparator(comparator);
}
/**
* Set the threshold.
* @param threshold Threshold to set
*/
public void setThreshold(final double threshold) {
this.threshold = threshold;
}
/**
* Set if the value to test is absolute.
* @param absolute true to enable absolute values
*/
public void setAbsolute(final boolean absolute) {
this.absolute = absolute;
}
// Other methods
/**
* Test the value.
* @param value Value to test
* @return true if the test if positive
*/
@Override
public boolean test(final double value) {
final double threshold = this.threshold;
final double v = this.absolute ? Math.abs(value) : value;
if (this.absolute)
if (Double.isNaN(threshold))
return false;
switch (this.comparator) {
case LOWER:
return v < threshold;
case LOWEREQUALS:
return v <= threshold;
case EQUALS:
return v == threshold;
case NOTEQUALS:
return v != threshold;
case UPPEREQUALS:
return v >= threshold;
case UPPER:
return v > threshold;
default:
return false;
}
}
/**
* Get parameter filter information for the history
* @return a String with information about the parameter of the filter
*/
public String getParameterInfo() {
return "Field="
+ getFieldToFilter() + ";Comparator=" + getComparator() + ";Threshold="
+ getThreshold();
}
// Constructor
/**
* Public constructor.
* @param field Field to test
* @param threshold Threshold of the test
* @param comparator comparator to use
*/
public BioAssayDoubleThresholdFilter(final String field,
final double threshold, final String comparator) {
this(field, threshold, comparator, false);
}
/**
* Public constructor.
* @param field Field to test
* @param threshold Threshold of the test
* @param comparator comparator to use
*/
public BioAssayDoubleThresholdFilter(final String field,
final double threshold, final String comparator, final boolean absolute) {
setFieldToFilter(field);
setThreshold(threshold);
setComparator(comparator);
setAbsolute(absolute);
}
}
|
package jp.ac.nii.prl.mape.autoscaling.analysis.service;
import java.util.Collection;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jp.ac.nii.prl.mape.autoscaling.analysis.configuration.AnalysisProperties;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.Adaptation;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.Deployment;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.Instance;
import jp.ac.nii.prl.mape.autoscaling.analysis.repository.DeploymentRepository;
@Service("deploymentService")
public class DeploymentServiceImpl implements DeploymentService {
@Autowired
private DeploymentRepository deploymentRepository;
@Autowired
private InstanceService instanceService;
@Autowired
private AnalysisProperties analysisProperties;
@Override
public Deployment save(Deployment deployment) {
return deploymentRepository.save(deployment);
}
@Override
public Collection<Deployment> findAll() {
return deploymentRepository.findAll();
}
@Override
public Optional<Deployment> findById(Integer deploymentId) {
return deploymentRepository.findById(deploymentId);
}
@Override
public Adaptation analyse(Deployment deployment) {
double load = getAverageLoadPerCPU(deployment.getId());
Adaptation adaptation = new Adaptation();
if (load >= analysisProperties.getMaxThreshold()) {
adaptation.setAdapt(true);
adaptation.setScaleUp(true);
adaptation.setCpuCount(new Double(deployment.getNumberCPUs() * 0.1).intValue());
} else if ((load <= analysisProperties.getMinThreshold()) && (deployment.size() > 1)) {
adaptation.setAdapt(true);
adaptation.setScaleUp(false);
adaptation.setCpuCount(1);
} else {
adaptation.setAdapt(false);
}
return adaptation;
}
@Override
public Double getAverageLoadPerCPU(Integer deploymentId) {
Collection<Instance> instances = instanceService.findByDeploymentId(deploymentId);
Double load = 0d;
for (Instance instance:instances) {
load += instance.getInstLoad();
}
return load / instances.size();
}
}
|
package net.sf.taverna.t2.activities.beanshell;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import net.sf.taverna.t2.activities.dependencyactivity.AbstractAsynchronousDependencyActivity.FileExtFilter;
import net.sf.taverna.t2.visit.VisitReport;
import net.sf.taverna.t2.visit.VisitReport.Status;
import net.sf.taverna.t2.workflowmodel.Processor;
import net.sf.taverna.t2.workflowmodel.health.HealthCheck;
import net.sf.taverna.t2.workflowmodel.health.HealthChecker;
import bsh.ParseException;
import bsh.Parser;
public class BeanshellActivityHealthChecker implements HealthChecker<BeanshellActivity> {
public boolean canVisit(Object subject) {
return (subject!=null && subject instanceof BeanshellActivity);
}
public VisitReport visit(BeanshellActivity activity, List<Object> ancestors) {
Object subject = (Processor) VisitReport.findAncestor(ancestors, Processor.class);
if (subject == null) {
// Fall back to using the activity itself as the subject of the reports
subject = activity;
}
List<VisitReport> reports = new ArrayList<VisitReport>();
String script = activity.getConfiguration().getScript();
if (! script.trim().endsWith(";")) {
/** Missing ; on last line is not allowed by Parser,
* but is allowed by Interpreter.eval() used at runtime
*/
script = script + ";";
}
Parser parser = new Parser(new StringReader(script));
try {
while (!parser.Line());
reports.add(new VisitReport(HealthCheck.getInstance(), subject, "Script OK", HealthCheck.NO_PROBLEM, Status.OK));
} catch (ParseException e) {
VisitReport report = new VisitReport(HealthCheck.getInstance(), subject ,e.getMessage(), HealthCheck.INVALID_SCRIPT, Status.SEVERE);
report.setProperty("exception", e);
reports.add(report);
}
// Check if we can find all the Beanshell's dependencies
LinkedHashSet<String> localDependencies = new LinkedHashSet<String>();
localDependencies.addAll(activity.getConfiguration().getLocalDependencies());
if (!localDependencies.isEmpty()) {
String[] jarArray = BeanshellActivity.libDir.list(new FileExtFilter(".jar"));
if (jarArray != null) {
List<String> jarFiles = Arrays.asList(jarArray); // URLs of all jars found in the lib directory
for (String jar : localDependencies) {
if (jarFiles.contains(jar)){
localDependencies.remove(jar);
}
}
}
if (localDependencies.isEmpty()){ // all dependencies found
reports.add(new VisitReport(HealthCheck.getInstance(), subject, "Beanshell dependencies found", HealthCheck.NO_PROBLEM, Status.OK));
}
else{
VisitReport vr = new VisitReport(HealthCheck.getInstance(), subject, "Beanshell dependencies missing", HealthCheck.MISSING_DEPENDENCY, Status.SEVERE);
vr.setProperty("dependencies", localDependencies);
vr.setProperty("directory", BeanshellActivity.libDir);
reports.add(vr);
}
}
Status status = VisitReport.getWorstStatus(reports);
VisitReport report = new VisitReport(HealthCheck.getInstance(), subject, "Beanshell report", HealthCheck.NO_PROBLEM,
status, reports);
return report;
}
public boolean isTimeConsuming() {
return false;
}
}
|
// Cloud.java
package ed.cloud;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;
import ed.db.DBAddress;
import ed.js.*;
import ed.js.engine.*;
import ed.log.*;
public class Cloud extends JSObjectBase {
static final boolean FORCE_GRID = ed.util.Config.get().getBoolean( "FORCE-GRID" );
static Logger _log = Logger.getLogger( "cloud" );
static {
_log.setLevel( Level.INFO );
}
private static final Cloud INSTANCE;
static {
Cloud c = null;
try {
c = new Cloud();
}
catch ( Throwable t ){
t.printStackTrace();
System.err.println( "couldn't load cloud - dying" );
System.exit(-1);
}
finally {
INSTANCE = c;
}
}
public static synchronized Cloud getInstance(){
return INSTANCE;
}
public static Cloud getInstanceIfOnGrid(){
Cloud c = getInstance();
if ( c == null )
return null;
if ( ! c.isOnGrid() )
return null;
return c;
}
private Cloud(){
File cloudDir = new File( "src/main/ed/cloud/" );
_scope = Scope.newGlobal().child( "cloud" );
_bad = ! cloudDir.exists();
if ( _bad ){
System.err.println( "NO CLOUD" );
return;
}
_scope.set( "connect" , new Shell.ConnectDB() );
_scope.set( "openFile" , new ed.js.func.JSFunctionCalls1(){
public Object call( Scope s , Object fileName , Object crap[] ){
return new JSLocalFile( fileName.toString() );
}
} );
_scope.set( "Cloud" , this );
_scope.set( "log" , _log );
try {
_scope.set( "SERVER_NAME" , System.getProperty( "SERVER-NAME" , InetAddress.getLocalHost().getHostName() ) );
}
catch ( Exception e ){
throw new RuntimeException( "should be impossible : " + e );
}
List<File> toLoad = new ArrayList<File>();
for ( File f : cloudDir.listFiles() ){
if ( ! f.getName().matches( "\\w+\\.js" ) )
continue;
toLoad.add( f );
}
final Matcher numPattern = Pattern.compile( "(\\d+)\\.js$" ).matcher( "" );
Collections.sort( toLoad , new Comparator<File>(){
public int compare( File aFile , File bFile ){
int a = Integer.MAX_VALUE;
int b = Integer.MAX_VALUE;
numPattern.reset( aFile.getName() );
if ( numPattern.find() )
a = Integer.parseInt( numPattern.group(1) );
numPattern.reset( bFile.getName() );
if ( numPattern.find() )
b = Integer.parseInt( numPattern.group(1) );
return a - b;
}
public boolean equals( Object o ){
return o == this;
}
} );
for ( File f : toLoad ){
_log.debug( "loading file : " + f );
try {
_scope.eval( f );
}
catch ( IOException ioe ){
throw new RuntimeException( "can't load cloud js file : " + f , ioe );
}
}
_log.info( "isOnGrid : " + isOnGrid() );
}
public String getDBHost( String dbname ){
if ( _bad )
return null;
JSObject db = (JSObject)evalFunc( "Cloud.findDBByName" , dbname );
if ( db == null )
throw new RuntimeException( "can't find global db named [" + dbname + "]" );
Object machine = db.get( "machine" );
if ( machine == null )
throw new RuntimeException( "global db [" + dbname + "] doesn't have machine set" );
return machine.toString();
}
public DBAddress getDBAddressForSite( String siteName , String environment ){
if ( _bad )
return null;
JSObject site = findSite( siteName , false );
if ( site == null )
return null;
Object url = evalFunc( site , "getDBUrlForEnvironment" , environment );
if ( url == null )
return null;
try {
return new DBAddress( url.toString() );
}
catch ( UnknownHostException e ){
throw new RuntimeException( "bad db url [" + url + "] " + e );
}
}
public JSObject findSite( String name , boolean create ){
if ( _bad )
return null;
return (JSObject)(evalFunc( "Cloud.Site.forName" , name , create ));
}
public JSObject findEnvironment( String name , String env ){
if ( _bad )
return null;
JSObject s = findSite( name , false );
if ( s == null )
return null;
return (JSObject)(evalFunc( s , "findEnvironmentByName" , env ) );
}
public Zeus createZeus( String host , String user , String pass )
throws IOException {
return new Zeus( host , user , pass );
}
Object evalFunc( String funcName , Object ... args ){
return evalFunc( null , funcName , args );
}
Object evalFunc( JSObject t , String funcName , Object ... args ){
if ( args != null ){
for ( int i=0; i <args.length; i++ ){
if ( args[i] instanceof String )
args[i] = new JSString( (String)args[i] );
}
}
JSFunction func = null;
if ( func == null && t != null ){
func = (JSFunction)t.get( funcName );
}
if ( func == null )
func = (JSFunction)findObject( funcName );
if ( func == null )
throw new RuntimeException( "can't find func : " + funcName );
Scope s = _scope;
if ( t != null ){
s = _scope.child();
s.setThis( t );
}
return func.call( s , args );
}
Object findObject( String name ){
if ( ! name.matches( "[\\w\\.]+" ) )
throw new RuntimeException( "this is to complex for my stupid code [" + name + "]" );
String pcs[] = name.split( "\\." );
Object cur = this;
for ( int i=0; i<pcs.length; i++ ){
if ( i == 0 && pcs[i].equals( "Cloud" ) )
continue;
cur = ((JSObject)cur).get( pcs[i] );
if ( cur == null )
return null;
}
return cur;
}
public Scope getScope(){
return _scope;
}
public boolean isOnGrid(){
if ( FORCE_GRID )
return true;
if ( _bad )
return false;
JSObject me = (JSObject)(_scope.get("me"));
if ( me == null )
throw new RuntimeException( "why doesn't me exist" );
return ! JSInternalFunctions.JS_evalToBool( me.get( "bad" ) );
}
public String getModuleSymLink( String moduleName , String version ){
if ( _bad )
return null;
Object res = evalFunc( "Cloud.getModuleSymLink" , moduleName , version );
if ( res == null )
return null;
return res.toString();
}
public String toString(){
return "{ Cloud. ongrid: " + isOnGrid() + "}";
}
final Scope _scope;
final boolean _bad;
}
|
package org.chocosolver.solver.search.strategy.selectors.values;
import org.chocosolver.solver.Cause;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.ResolutionPolicy;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.search.strategy.assignments.DecisionOperator;
import org.chocosolver.solver.search.strategy.assignments.DecisionOperatorFactory;
import org.chocosolver.solver.variables.IntVar;
/**
* Value selector for optimization problems:
* Branches on the value with the best objective bound (evaluated each possible assignment)
*
* @author Jean-Guillaume FAGES
*/
public final class IntDomainBest implements IntValueSelector {
/**
* Maximum enumerated domain size this selector falls into.
* Otherwise, {@link #altern} is used.
*/
private int maxdom;
/**
* Alternative value selector when an enumerated variable domain exceeds {@link #maxdom}.
*/
private IntValueSelector altern;
/**
* The decision operator used to make the decision
*/
private DecisionOperator<IntVar> dop;
private enum Dec{
SPLIT, RSPLIT, OTHER
}
private Dec dec;
/**
* Create a value selector that returns the best value wrt to the objective to optimize. When an
* enumerated variable domain exceeds {@link #maxdom}, {@link #altern} value selector is used.
*
* @param maxdom a maximum domain size to satisfy to use this value selector.
* @param altern value selector to use when an enumerated variable domain exceed {@link
* #maxdom}.
* @param dop the decision operator used to make the decision
*/
public IntDomainBest(int maxdom, IntValueSelector altern, DecisionOperator<IntVar> dop) {
this.maxdom = maxdom;
this.altern = altern;
this.dop = dop;
if(dop == DecisionOperatorFactory.makeIntSplit()){
dec = Dec.SPLIT;
}else if(dop == DecisionOperatorFactory.makeIntReverseSplit()){
dec = Dec.RSPLIT;
}else{
dec = Dec.OTHER;
}
}
/**
* {@inheritDoc}
*/
@Override
public int selectValue(IntVar var) {
assert var.getModel().getObjective() != null;
if (var.hasEnumeratedDomain()) {
if (var.getDomainSize() < maxdom) {
int bestCost = Integer.MAX_VALUE;
int ub = var.getUB();
// if decision is '<=', default value is LB, UB in any other cases
int bestV = dec.equals(Dec.SPLIT) ? var.getLB() : ub;
for (int v = var.getLB(); v <= ub; v = var.nextValue(v)) {
int bound = bound(var, v);
if (bound < bestCost) {
bestCost = bound;
bestV = v;
}
}
return bestV;
} else {
return altern.selectValue(var);
}
} else {
int lbB = bound(var, var.getLB());
int ubB = bound(var, var.getUB());
// if values are equivalent
if(lbB == ubB){
// if decision is '<=', default value is LB, UB in any other cases
return dec.equals(Dec.SPLIT) ? var.getLB() : var.getUB();
}else {
return lbB < ubB ? var.getLB() : var.getUB();
}
}
}
private int bound(IntVar var, int val) {
Model model = var.getModel();
int cost;
// // if decision is '<=' ('>='), UB (LB) should be ignored to avoid infinite loop
if(dec.equals(Dec.SPLIT) && val == var.getUB() || dec.equals(Dec.RSPLIT) && val == var.getLB()){
return Integer.MAX_VALUE;
}
model.getEnvironment().worldPush();
try {
dop.apply(var, val, Cause.Null);
model.getSolver().getEngine().propagate();
ResolutionPolicy rp = model.getSolver().getObjectiveManager().getPolicy();
if (rp == ResolutionPolicy.SATISFACTION) {
cost = 1;
} else if (rp == ResolutionPolicy.MINIMIZE) {
cost = ((IntVar) model.getObjective()).getLB();
} else {
cost = -((IntVar) model.getObjective()).getUB();
}
} catch (ContradictionException cex) {
cost = Integer.MAX_VALUE;
}
model.getSolver().getEngine().flush();
model.getEnvironment().worldPop();
return cost;
}
}
|
package org.spongepowered.common.item.inventory.lens.impl.comp;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import org.spongepowered.api.item.inventory.Inventory;
import org.spongepowered.common.item.inventory.adapter.InventoryAdapter;
import org.spongepowered.common.item.inventory.adapter.impl.comp.HotbarAdapter;
import org.spongepowered.common.item.inventory.lens.Fabric;
import org.spongepowered.common.item.inventory.lens.SlotProvider;
import org.spongepowered.common.item.inventory.lens.comp.HotbarLens;
public class HotbarLensImpl extends InventoryRowLensImpl implements HotbarLens<IInventory, net.minecraft.item.ItemStack> {
public HotbarLensImpl(int base, int width, SlotProvider<IInventory, ItemStack> slots) {
this(base, width, 0, 0, HotbarAdapter.class, slots);
}
public HotbarLensImpl(int base, int width, Class<? extends Inventory> adapterType, SlotProvider<IInventory, ItemStack> slots) {
this(base, width, 0, 0, adapterType, slots);
}
public HotbarLensImpl(int base, int width, int xBase, int yBase, SlotProvider<IInventory, ItemStack> slots) {
this(base, width, xBase, yBase, HotbarAdapter.class, slots);
}
public HotbarLensImpl(int base, int width, int xBase, int yBase, Class<? extends Inventory> adapterType, SlotProvider<IInventory, ItemStack> slots) {
super(base, width, xBase, yBase, adapterType, slots);
}
@Override
public InventoryAdapter<IInventory, ItemStack> getAdapter(Fabric<IInventory> inv, Inventory parent) {
return new HotbarAdapter(inv, this, parent);
}
@Override
public int getSelectedSlotIndex(Fabric<IInventory> inv) {
for (IInventory inner : inv.allInventories()) {
if (inner instanceof InventoryPlayer) {
return ((InventoryPlayer) inner).currentItem;
}
}
return 0;
}
@Override
public void setSelectedSlotIndex(Fabric<IInventory> inv, int index) {
for (IInventory inner : inv.allInventories()) {
if (inner instanceof InventoryPlayer) {
((InventoryPlayer) inner).currentItem = index;
}
}
}
}
|
package org.synyx.urlaubsverwaltung.absence.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.synyx.urlaubsverwaltung.absence.AbsencePeriod;
import org.synyx.urlaubsverwaltung.absence.AbsenceService;
import org.synyx.urlaubsverwaltung.absence.DateRange;
import org.synyx.urlaubsverwaltung.department.Department;
import org.synyx.urlaubsverwaltung.department.DepartmentService;
import org.synyx.urlaubsverwaltung.period.DayLength;
import org.synyx.urlaubsverwaltung.person.Person;
import org.synyx.urlaubsverwaltung.person.PersonService;
import org.synyx.urlaubsverwaltung.publicholiday.PublicHoliday;
import org.synyx.urlaubsverwaltung.publicholiday.PublicHolidaysService;
import org.synyx.urlaubsverwaltung.settings.SettingsService;
import org.synyx.urlaubsverwaltung.workingtime.FederalState;
import java.time.Clock;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.lang.Integer.parseInt;
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toUnmodifiableList;
import static org.springframework.util.StringUtils.hasText;
import static org.synyx.urlaubsverwaltung.person.Role.BOSS;
import static org.synyx.urlaubsverwaltung.person.Role.OFFICE;
@RequestMapping("/web/absences")
@Controller
public class AbsenceOverviewViewController {
private final PersonService personService;
private final DepartmentService departmentService;
private final MessageSource messageSource;
private final Clock clock;
private final PublicHolidaysService publicHolidaysService;
private final SettingsService settingsService;
private final AbsenceService absenceService;
@Autowired
public AbsenceOverviewViewController(PersonService personService, DepartmentService departmentService,
MessageSource messageSource, Clock clock,
PublicHolidaysService publicHolidaysService, SettingsService settingsService,
AbsenceService absenceService) {
this.personService = personService;
this.departmentService = departmentService;
this.messageSource = messageSource;
this.clock = clock;
this.publicHolidaysService = publicHolidaysService;
this.settingsService = settingsService;
this.absenceService = absenceService;
}
@GetMapping
public String absenceOverview(
@RequestParam(required = false) Integer year,
@RequestParam(required = false) String month,
@RequestParam(name = "department", required = false, defaultValue = "") List<String> rawSelectedDepartments, Model model, Locale locale) {
final Person signedInUser = personService.getSignedInUser();
final List<Person> overviewPersons;
if (departmentService.getNumberOfDepartments() > 0) {
final List<Department> visibleDepartments;
if (signedInUser.hasRole(BOSS) || signedInUser.hasRole(OFFICE)) {
visibleDepartments = departmentService.getAllDepartments();
} else {
visibleDepartments = departmentService.getAllowedDepartmentsOfPerson(signedInUser);
}
model.addAttribute("visibleDepartments", visibleDepartments);
if (visibleDepartments.isEmpty()) {
overviewPersons = List.of(signedInUser);
} else {
final List<String> selectedDepartmentNames = getSelectedDepartmentNames(rawSelectedDepartments, visibleDepartments);
model.addAttribute("selectedDepartments", selectedDepartmentNames);
overviewPersons = visibleDepartments.stream()
.filter(department -> selectedDepartmentNames.contains(department.getName()))
.map(Department::getMembers)
.flatMap(List::stream)
.distinct()
.sorted(comparing(Person::getFirstName))
.collect(toList());
}
} else {
overviewPersons = personService.getActivePersons();
}
final LocalDate startDate = getStartDate(year, month);
final LocalDate endDate = getEndDate(year, month);
model.addAttribute("currentYear", Year.now(clock).getValue());
model.addAttribute("selectedYear", startDate.getYear());
final String selectedMonth = getSelectedMonth(month, startDate);
model.addAttribute("selectedMonth", selectedMonth);
final boolean isPrivilegedUser = signedInUser.isPrivileged();
model.addAttribute("isPrivileged", isPrivilegedUser);
final DateRange dateRange = new DateRange(startDate, endDate);
final List<AbsenceOverviewMonthDto> months = getAbsenceOverViewMonthModels(dateRange, overviewPersons, locale, isPrivilegedUser);
final AbsenceOverviewDto absenceOverview = new AbsenceOverviewDto(months);
model.addAttribute("absenceOverview", absenceOverview);
return "absences/absences_overview";
}
private List<String> getSelectedDepartmentNames(List<String> rawSelectedDepartments, List<Department> departments) {
final List<String> preparedSelectedDepartments = rawSelectedDepartments.stream().filter(StringUtils::hasText).collect(toList());
return preparedSelectedDepartments.isEmpty() ? List.of(departments.get(0).getName()) : preparedSelectedDepartments;
}
private List<AbsenceOverviewMonthDto> getAbsenceOverViewMonthModels(DateRange dateRange, List<Person> personList, Locale locale, boolean isPrivilegedUser) {
final LocalDate today = LocalDate.now(clock);
final List<AbsencePeriod> openAbsences = absenceService.getOpenAbsences(personList, dateRange.getStartDate(), dateRange.getEndDate());
final HashMap<Integer, AbsenceOverviewMonthDto> monthsByNr = new HashMap<>();
final FederalState defaultFederalState = settingsService.getSettings().getWorkingTimeSettings().getFederalState();
final Map<Person, List<AbsencePeriod.Record>> absencePeriodRecordsByPerson = openAbsences.stream()
.map(AbsencePeriod::getAbsenceRecords)
.flatMap(List::stream)
.collect(groupingBy(AbsencePeriod.Record::getPerson));
final Map<LocalDate, PublicHoliday> holidaysByDate =
publicHolidaysService.getPublicHolidays(dateRange.getStartDate(), dateRange.getEndDate(), defaultFederalState)
.stream()
.collect(
toMap(
PublicHoliday::getDate,
Function.identity()
)
);
for (LocalDate date : dateRange) {
final AbsenceOverviewMonthDto monthView = monthsByNr.computeIfAbsent(date.getMonthValue(),
monthValue -> this.initializeAbsenceOverviewMonthDto(date, personList, locale));
final AbsenceOverviewMonthDayDto tableHeadDay = tableHeadDay(date, defaultFederalState, today);
monthView.getDays().add(tableHeadDay);
final Map<AbsenceOverviewMonthPersonDto, Person> personByView = personList.stream()
.collect(
toMap(person -> monthView.getPersons().stream()
.filter(view -> view.getEmail().equals(person.getEmail()) &&
view.getFirstName().equals(person.getFirstName()) &&
view.getLastName().equals(person.getLastName())
)
.findFirst()
.orElse(null),Function.identity()
)
);
// create an absence day dto for every person of the department
for (AbsenceOverviewMonthPersonDto personView : monthView.getPersons()) {
final Person person = personByView.get(personView);
final List<AbsencePeriod.Record> personAbsenceRecordsForDate = Optional.ofNullable(absencePeriodRecordsByPerson.get(person))
.stream()
.flatMap(List::stream)
.filter(absenceRecord -> absenceRecord.getDate().isEqual(date))
.collect(toUnmodifiableList());
final AbsenceOverviewDayType personViewDayType = Optional.ofNullable(holidaysByDate.get(date))
.map(publicHoliday -> getAbsenceOverviewDayType(personAbsenceRecordsForDate, isPrivilegedUser, publicHoliday))
.orElseGet(() -> getAbsenceOverviewDayType(personAbsenceRecordsForDate, isPrivilegedUser))
.build();
personView.getDays().add(new AbsenceOverviewPersonDayDto(personViewDayType, isWeekend(date)));
}
}
return new ArrayList<>(monthsByNr.values());
}
private AbsenceOverviewMonthDto initializeAbsenceOverviewMonthDto(LocalDate date, List<Person> personList, Locale locale) {
final List<AbsenceOverviewMonthPersonDto> monthViewPersons = personList.stream()
.map(AbsenceOverviewViewController::initializeAbsenceOverviewMonthPersonDto)
.collect(toList());
return new AbsenceOverviewMonthDto(getMonthText(date, locale), new ArrayList<>(), monthViewPersons);
}
private static AbsenceOverviewMonthPersonDto initializeAbsenceOverviewMonthPersonDto(Person person) {
final String firstName = person.getFirstName();
final String lastName = person.getLastName();
final String email = person.getEmail();
final String gravatarUrl = person.getGravatarURL();
return new AbsenceOverviewMonthPersonDto(firstName, lastName, email, gravatarUrl, new ArrayList<>());
}
private AbsenceOverviewDayType.Builder getAbsenceOverviewDayType(List<AbsencePeriod.Record> absenceRecords, boolean isPrivileged, PublicHoliday publicHoliday) {
AbsenceOverviewDayType.Builder builder = getAbsenceOverviewDayType(absenceRecords, isPrivileged);
if (publicHoliday.getDayLength().equals(DayLength.MORNING)) {
builder = builder.publicHolidayMorning();
}
if (publicHoliday.getDayLength().equals(DayLength.NOON)) {
builder = builder.publicHolidayNoon();
}
if (publicHoliday.getDayLength().equals(DayLength.FULL)) {
builder = builder.publicHolidayFull();
}
return builder;
}
private AbsenceOverviewDayType.Builder getAbsenceOverviewDayType(List<AbsencePeriod.Record> absenceRecords, boolean isPrivileged) {
if (absenceRecords.isEmpty()) {
return AbsenceOverviewDayType.builder();
}
AbsenceOverviewDayType.Builder builder = AbsenceOverviewDayType.builder();
for (AbsencePeriod.Record absenceRecord : absenceRecords) {
if (absenceRecord.isHalfDayAbsence()) {
builder = getAbsenceOverviewDayTypeForHalfDay(builder, absenceRecord, isPrivileged);
} else {
builder = getAbsenceOverviewDayTypeForFullDay(builder, absenceRecord, isPrivileged);
}
}
return builder;
}
private AbsenceOverviewDayType.Builder getAbsenceOverviewDayTypeForHalfDay(AbsenceOverviewDayType.Builder builder, AbsencePeriod.Record absenceRecord, boolean isPrivileged) {
final AbsencePeriod.AbsenceType morningAbsenceType = absenceRecord.getMorning().map(AbsencePeriod.RecordInfo::getType).orElse(null);
final AbsencePeriod.AbsenceType noonAbsenceType = absenceRecord.getNoon().map(AbsencePeriod.RecordInfo::getType).orElse(null);
if (AbsencePeriod.AbsenceType.SICK.equals(morningAbsenceType)) {
return isPrivileged ? builder.sickNoteMorning() : builder.absenceMorning();
}
if (AbsencePeriod.AbsenceType.SICK.equals(noonAbsenceType)) {
return isPrivileged ? builder.sickNoteNoon() : builder.absenceNoon();
}
final boolean morningWaiting = absenceRecord.getMorning().map(AbsencePeriod.RecordInfo::hasStatusWaiting).orElse(false);
if (morningWaiting) {
return isPrivileged ? builder.waitingVacationMorning() : builder.absenceMorning();
}
final boolean morningAllowed = absenceRecord.getMorning().map(AbsencePeriod.RecordInfo::hasStatusAllowed).orElse(false);
if (morningAllowed) {
return isPrivileged ? builder.allowedVacationMorning() : builder.absenceMorning();
}
final boolean noonWaiting = absenceRecord.getNoon().map(AbsencePeriod.RecordInfo::hasStatusWaiting).orElse(false);
if (noonWaiting) {
return isPrivileged ? builder.waitingVacationNoon() : builder.absenceNoon();
}
return isPrivileged ? builder.allowedVacationNoon() : builder.absenceNoon();
}
private AbsenceOverviewDayType.Builder getAbsenceOverviewDayTypeForFullDay(AbsenceOverviewDayType.Builder builder, AbsencePeriod.Record absenceRecord, boolean isPrivileged) {
final Optional<AbsencePeriod.RecordInfo> morning = absenceRecord.getMorning();
final Optional<AbsencePeriod.RecordInfo> noon = absenceRecord.getNoon();
final Optional<AbsencePeriod.AbsenceType> morningType = morning.map(AbsencePeriod.RecordInfo::getType);
final Optional<AbsencePeriod.AbsenceType> noonType = noon.map(AbsencePeriod.RecordInfo::getType);
final boolean sickMorning = morningType.map(AbsencePeriod.AbsenceType.SICK::equals).orElse(false);
final boolean sickNoon = noonType.map(AbsencePeriod.AbsenceType.SICK::equals).orElse(false);
final boolean sickFull = sickMorning && sickNoon;
if (sickFull) {
return isPrivileged ? builder.sickNoteFull() : builder.absenceFull();
}
final boolean morningWaiting = morning.map(AbsencePeriod.RecordInfo::hasStatusWaiting).orElse(false);
final boolean noonWaiting = noon.map(AbsencePeriod.RecordInfo::hasStatusWaiting).orElse(false);
if (morningWaiting && noonWaiting) {
return isPrivileged ? builder.waitingVacationFull() : builder.absenceFull();
}
else if (!morningWaiting && !noonWaiting) {
return isPrivileged ? builder.allowedVacationFull() : builder.absenceFull();
}
return builder;
}
private AbsenceOverviewDayType.Builder getPublicHolidayType(DayLength dayLength) {
final AbsenceOverviewDayType.Builder builder = AbsenceOverviewDayType.builder();
switch (dayLength) {
case MORNING:
return builder.publicHolidayMorning();
case NOON:
return builder.publicHolidayNoon();
case FULL:
default:
return builder.publicHolidayFull();
}
}
private String getSelectedMonth(String month, LocalDate startDate) {
String selectedMonth = "";
if (month == null) {
selectedMonth = String.valueOf(startDate.getMonthValue());
} else if (hasText(month)) {
selectedMonth = month;
}
return selectedMonth;
}
private AbsenceOverviewMonthDayDto tableHeadDay(LocalDate date, FederalState defaultFederalState, LocalDate today) {
final String tableHeadDayText = String.format("%02d", date.getDayOfMonth());
final DayLength publicHolidayDayLength = publicHolidaysService.getAbsenceTypeOfDate(date, defaultFederalState);
AbsenceOverviewDayType publicHolidayType = null;
if (DayLength.ZERO.compareTo(publicHolidayDayLength) != 0) {
publicHolidayType = getPublicHolidayType(publicHolidayDayLength).build();
}
final boolean isToday = date.isEqual(today);
return new AbsenceOverviewMonthDayDto(publicHolidayType, tableHeadDayText, isWeekend(date), isToday);
}
private String getMonthText(LocalDate date, Locale locale) {
return messageSource.getMessage(getMonthMessageCode(date), new Object[]{}, locale);
}
private String getMonthMessageCode(LocalDate localDate) {
switch (localDate.getMonthValue()) {
case 1:
return "month.january";
case 2:
return "month.february";
case 3:
return "month.march";
case 4:
return "month.april";
case 5:
return "month.may";
case 6:
return "month.june";
case 7:
return "month.july";
case 8:
return "month.august";
case 9:
return "month.september";
case 10:
return "month.october";
case 11:
return "month.november";
case 12:
return "month.december";
default:
throw new IllegalStateException("month value not in range of 1 to 12 cannot be mapped to a message key.");
}
}
private LocalDate getStartDate(Integer year, String month) {
return getStartOrEndDate(year, month, TemporalAdjusters::firstDayOfYear, TemporalAdjusters::firstDayOfMonth);
}
private LocalDate getEndDate(Integer year, String month) {
return getStartOrEndDate(year, month, TemporalAdjusters::lastDayOfYear, TemporalAdjusters::lastDayOfMonth);
}
private LocalDate getStartOrEndDate(Integer year, String month, Supplier<TemporalAdjuster> firstOrLastOfYearSupplier,
Supplier<TemporalAdjuster> firstOrLastOfMonthSupplier) {
final LocalDate now = LocalDate.now(clock);
if (year != null) {
if (hasText(month)) {
return now.withYear(year).withMonth(parseInt(month)).with(firstOrLastOfMonthSupplier.get());
}
if ("".equals(month)) {
return now.withYear(year).with(firstOrLastOfYearSupplier.get());
}
return now.withYear(year).with(firstOrLastOfMonthSupplier.get());
}
if (hasText(month)) {
return now.withMonth(parseInt(month)).with(firstOrLastOfMonthSupplier.get());
}
return now.with(firstOrLastOfMonthSupplier.get());
}
private static boolean isWeekend(LocalDate date) {
final DayOfWeek dayOfWeek = date.getDayOfWeek();
return dayOfWeek == SATURDAY || dayOfWeek == SUNDAY;
}
}
|
package team1100.season2010.robot;
import team1100.season2010.robot.DashboardPacker;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.camera.AxisCameraException;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.NIVisionException;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.Watchdog;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Compressor;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot1100 extends IterativeRobot
{
//Counts how many periodic cycles have passed.
int m_count;
//AnalogChannel pot_1 = new AnalogChannel(7);
final int POT_CHANNEL_VAL = 7;
//Joystick joystick_1;
//Joystick joystick_2;
final int joystick_1_channel = 1;
final int joystick_2_channel = 2;
final int jag_1_channel = 1;
final int jag_2_channel = 5;
final int jag_3_channel = 2;
final int jag_4_channel = 6;
final int CRM_channel = 3;
//RobotDrive drive;
// final int POT_RANGE = 10;
// final int DIGPORT = 4;
// int prev_pot;
// final double JOYSTICK_DEADBAND = .5;
// double prev_speed;
// double setpt_speed;
// final double SPEED_ADJUST = .1;
// final int MOTOR_DIRECTION_ADJUST = -1;
//Jaguar front_right_motor;
//Jaguar front_left_motor;
//Jaguar back_right_motor;
//Jaguar back_left_motor;
//Jaguar chain_rotation_motor;
// double[] speed_array;
// final int NUM_SPEED_ARRAY = 10;
// int speed_array_index;
// double avg_speed_val;
// double[] dir_array;
// final int NUM_DIR_ARRAY = 10;
// int dir_array_index;
// double avg_dir_val;
// final int POT_MIN = 374;
// final int POT_MAX = 579;
// final int POT_CENTER = 483;
// final int POT_DEADBAND = 10;
//CRM = chain_rotation_motor
// double[] CRM_speed_array;
// final int NUM_CRM_SPEED_ARRAY = 10;
// int CRM_speed_array_index;
// double avg_CRM_speed_val;
// final double CRM_SPEED = .2;
RobotDriveController RDC;
//Jaguar testMotor = new Jaguar(3);
//PIDController pid;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit()
{
//Sets periodic call rate to 10 milisecond intervals, i.e. 100Hz.
this.setPeriod(0.01);
System.out.print("ROBOT STARTUP");
//drive = new RobotDrive(1,5);
//drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, false);
//drive.setInvertedMotor(RobotDrive.MotorType.kRearRight, false);
//pid = new PIDController(.1,.001,0, pot_1, testMotor);
//pid.setInputRange(0, 1024);
/*speed_array = new double[NUM_SPEED_ARRAY];
speed_array_index = 0;
avg_speed_val = 0;
CRM_speed_array = new double[NUM_CRM_SPEED_ARRAY];
CRM_speed_array_index = 0;
avg_CRM_speed_val = 0;
dir_array = new double[NUM_DIR_ARRAY];
dir_array_index = 0;
avg_dir_val = 0;*/
RDC = new RobotDriveController(0,joystick_1_channel,joystick_2_channel,
jag_1_channel,jag_2_channel,jag_3_channel,jag_4_channel,CRM_channel,4);
/*joystick_1 = new Joystick(1);
joystick_2 = new Joystick(2);
front_right_motor = new Jaguar(DIGPORT,1);
front_left_motor = new Jaguar(DIGPORT,5);
//back_right_motor = new Jaguar(DIGPORT,3);
//back_left_motor = new Jaguar(DIGPORT,4);
chain_rotation_motor = new Jaguar(DIGPORT,3);
prev_pot = pot_1.getAverageValue();*/
}
/**
* This function is called when the robot enters autonomous mode.
*/
public void autonomousInit()
{
m_count = 0;
System.out.println("Autonomous Init");
}
/**
* This function is called periodically (100Hz) during autonomous
*/
public void autonomousPeriodic()
{
m_count++;
//System.out.println("AutoCount: " + m_count);
//Runs periodically at 100Hz
{
}
//Runs periodically at 50Hz.
if (m_count % 2 == 0)
{
}
//Runs periodically at 25Hz.
if (m_count % 4 == 0)
{
}
//Runs periodically at 20Hz.
if (m_count % 5 == 0)
{
DashboardPacker.updateDashboard();
System.out.println("Packet Sent (Auto)");
}
//Runs periodically at 10Hz.
if (m_count % 10 == 0)
{
}
//Runs periodically at 5Hz.
if (m_count % 20 == 0)
{
}
}
/**
* This function is called when the robot enters teleop mode.
*/
public void teleopInit()
{
m_count = 0;
System.out.println("TeleOp Initialized.");
}
/**
* This function is called periodically (100Hz) during operator control
*/
public void teleopPeriodic()
{
m_count++;
//System.out.println("TeleOp: "+ m_count);
//drive.tankDrive(joystick_1, joystick_2);
//Runs periodically at 100Hz
{
}
//Runs periodically at 50Hz.
if (m_count % 2 == 0)
{
}
//Runs periodically at 25Hz.
if (m_count % 4 == 0)
{
}
//Runs periodically at 20Hz.
if (m_count % 5 == 0)
{
Watchdog.getInstance().feed();
DashboardPacker.updateDashboard();
if(RDC.joystick_1.getRawButton(6)||RDC.joystick_1.getRawButton(7))
RDC.setDriveType(0);
if(RDC.joystick_1.getRawButton(8)||RDC.joystick_1.getRawButton(9))
RDC.setDriveType(1);
if(RDC.joystick_1.getRawButton(10)||RDC.joystick_1.getRawButton(11))
RDC.setDriveType(2);
RDC.drive();
/*System.out.println(pot_1.getAverageValue());
chain_rotation_motor.set(joystick_2.getY());
//target speed determination
avg_speed_val = avg_speed_val*NUM_SPEED_ARRAY;
avg_speed_val -= speed_array[speed_array_index%NUM_SPEED_ARRAY];
avg_speed_val += joystick_2.getY();
avg_speed_val = avg_speed_val/NUM_SPEED_ARRAY;
speed_array[speed_array_index%NUM_SPEED_ARRAY]=joystick_2.getY();
speed_array_index++;
//motor speed assignment
front_right_motor.set(MOTOR_DIRECTION_ADJUST * avg_speed_val);
front_left_motor.set(MOTOR_DIRECTION_ADJUST * avg_speed_val);
//back_right_motor.set(avgval);
//back_left_motor.set(avgval);
//find averaged direction to go to
avg_dir_val = avg_dir_val*NUM_DIR_ARRAY;
avg_dir_val -= dir_array[dir_array_index%NUM_DIR_ARRAY];
avg_dir_val += joystick_1.getX();
avg_dir_val = avg_dir_val/NUM_DIR_ARRAY;
dir_array[dir_array_index%NUM_DIR_ARRAY]=joystick_1.getX();
dir_array_index++;
//avg_dir_val = setpoint *ANGLE*
//pot_1.getAverageValue() = actual value
//assign x-val setpoint based on potentiometer value
double avg_dir_setpt = 512.0 * (avg_dir_val + 1);
double newspeed;
if(avg_dir_setpt > pot_1.getAverageValue() + POT_DEADBAND)
newspeed = -CRM_SPEED;
else if (avg_dir_setpt < pot_1.getAverageValue() - POT_DEADBAND)
newspeed = CRM_SPEED;
else newspeed = 0;
if(pot_1.getAverageValue() >= POT_MAX + POT_DEADBAND)
newspeed = -1;
else if(pot_1.getAverageValue() <= POT_MIN - POT_DEADBAND)
newspeed = 1;
else if(pot_1.getAverageValue() >= POT_MAX - POT_DEADBAND)
newspeed = 0;
else if(pot_1.getAverageValue() <= POT_MIN + POT_DEADBAND)
newspeed = 0;
System.out.println("Pot Val: " + pot_1.getAverageValue());
System.out.println("\tTarget: " + avg_dir_setpt);
//CRM = chain_rotation_motor
//find averaged speed for CRM in order to not blow it out
avg_CRM_speed_val = avg_CRM_speed_val*NUM_CRM_SPEED_ARRAY;
avg_CRM_speed_val -= CRM_speed_array[CRM_speed_array_index%NUM_CRM_SPEED_ARRAY];
avg_CRM_speed_val += newspeed;
avg_CRM_speed_val = avg_CRM_speed_val/NUM_CRM_SPEED_ARRAY;
CRM_speed_array[CRM_speed_array_index%NUM_CRM_SPEED_ARRAY] = newspeed;
CRM_speed_array_index++;
chain_rotation_motor.set(avg_CRM_speed_val);*/
}
//Runs periodically at 10Hz.
if (m_count % 10 == 0)
{
}
//Runs periodically at 5Hz.
if (m_count % 20 == 0)
{
}
}
/**
* This function is called when the robot enters disabled mode.
*/
public void disabledInit()
{
m_count = 0;
// System.out.println("Disabled Init 1100 version");
}
/**
* This function is called periodically (100Hz) during disabled mode.
*/
public void disabledPeriodic()
{
m_count++;
// System.out.println("Mcount =" + m_count);
//Runs periodically at 100Hz
{
}
//Runs periodically at 50Hz.
if (m_count % 2 == 0)
{
}
//Runs periodically at 25Hz.
if (m_count % 4 == 0)
{
}
//Runs periodically at 20Hz.
if (m_count % 5 == 0)
{
DashboardPacker.updateDashboard();
System.out.println("Packet Sent (D)");
}
//Runs periodically at 10Hz.
if (m_count % 10 == 0)
{
}
//Runs periodically at 5Hz.
if (m_count % 20 == 0)
{
}
//Runs periodically at 1/5 Hz.
if (m_count % 500 == 0)
{
// System.out.println("Hello, world! in Disable mode...");
}
}
}
|
package org.mtransit.parser.ca_richelieu_citvr_bus;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MSpec;
import org.mtransit.parser.mt.data.MTrip;
public class ValleeDuRichelieuCITVRBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-richelieu-citvr-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new ValleeDuRichelieuCITVRBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("Generating CITVR bus data...\n");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("Generating CITVR bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.route_long_name;
routeLongName = MSpec.SAINT.matcher(routeLongName).replaceAll(MSpec.SAINT_REPLACEMENT);
return MSpec.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR = "ABBE00";
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String DASH = " - ";
@Override
public void setTripHeadsign(MRoute route, MTrip mTrip, GTrip gTrip) {
String stationName = cleanTripHeadsign(gTrip.trip_headsign);
int directionId = gTrip.direction_id;
if (mTrip.getRouteId() == 7l) {
if (directionId == 1) {
stationName += " 2";
}
} else if (mTrip.getRouteId() == 30l) {
stationName = stationName.substring(stationName.indexOf(DASH) + DASH.length());
}
mTrip.setHeadsignString(stationName, directionId);
}
private static final Pattern DIRECTION = Pattern.compile("(direction )", Pattern.CASE_INSENSITIVE);
private static final String DIRECTION_REPLACEMENT = "";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = DIRECTION.matcher(tripHeadsign).replaceAll(DIRECTION_REPLACEMENT);
return MSpec.cleanLabelFR(tripHeadsign);
}
private static final Pattern START_WITH_FACE_A = Pattern.compile("^(face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE_AU = Pattern.compile("^(face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE = Pattern.compile("^(face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_FACE_A = Pattern.compile("( face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE_AU = Pattern.compile("( face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE = Pattern.compile("( face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern[] START_WITH_FACES = new Pattern[] { START_WITH_FACE_A, START_WITH_FACE_AU, START_WITH_FACE };
private static final Pattern[] SPACE_FACES = new Pattern[] { SPACE_FACE_A, SPACE_WITH_FACE_AU, SPACE_WITH_FACE };
private static final Pattern AVENUE = Pattern.compile("( avenue)", Pattern.CASE_INSENSITIVE);
private static final String AVENUE_REPLACEMENT = " av.";
@Override
public String cleanStopName(String gStopName) {
gStopName = AVENUE.matcher(gStopName).replaceAll(AVENUE_REPLACEMENT);
gStopName = Utils.replaceAll(gStopName, START_WITH_FACES, MSpec.SPACE);
gStopName = Utils.replaceAll(gStopName, SPACE_FACES, MSpec.SPACE);
return super.cleanStopNameFR(gStopName);
}
@Override
public String getStopCode(GStop gStop) {
if ("0".equals(gStop.stop_code)) {
return null;
}
return super.getStopCode(gStop);
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
@Override
public int getStopId(GStop gStop) {
String stopCode = getStopCode(gStop);
if (stopCode != null && stopCode.length() > 0) {
return Integer.valueOf(stopCode); // using stop code as stop ID
}
Matcher matcher = DIGITS.matcher(gStop.stop_id);
matcher.find();
int digits = Integer.parseInt(matcher.group());
int stopId;
if (gStop.stop_id.startsWith("BEL")) {
stopId = 100000;
} else if (gStop.stop_id.startsWith("MMS")) {
stopId = 200000;
} else if (gStop.stop_id.startsWith("MSH")) {
stopId = 300000;
} else if (gStop.stop_id.startsWith("OTP")) {
stopId = 400000;
} else if (gStop.stop_id.startsWith("SBA")) {
stopId = 500000;
} else if (gStop.stop_id.startsWith("SJU")) {
stopId = 600000;
} else if (gStop.stop_id.startsWith("SHY")) {
stopId = 700000;
} else {
System.out.println("Stop doesn't have an ID (start with)! " + gStop);
System.exit(-1);
stopId = -1;
}
if (gStop.stop_id.endsWith("A")) {
stopId += 1000;
} else if (gStop.stop_id.endsWith("B")) {
stopId += 2000;
} else if (gStop.stop_id.endsWith("C")) {
stopId += 3000;
} else if (gStop.stop_id.endsWith("D")) {
stopId += 4000;
} else if (gStop.stop_id.endsWith("E")) {
stopId += 5000;
} else if (gStop.stop_id.endsWith("F")) {
stopId += 6000;
} else if (gStop.stop_id.endsWith("G")) {
stopId += 7000;
} else if (gStop.stop_id.endsWith("H")) {
stopId += 8000;
} else {
System.out.println("Stop doesn't have an ID (end with)! " + gStop);
System.exit(-1);
}
return stopId + digits;
}
}
|
package com.maxmind.db;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.IllegalAccessException;
import java.lang.InstantiationException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
public class ReaderTest {
private Reader testReader;
@Before
public void setupReader() {
this.testReader = null;
}
@After
public void teardownReader() throws IOException {
if (this.testReader != null) {
this.testReader.close();
}
}
@Test
public void test()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
for (long recordSize : new long[]{24, 28, 32}) {
for (int ipVersion : new int[]{4, 6}) {
File file = getFile("MaxMind-DB-test-ipv" + ipVersion + "-" + recordSize + ".mmdb");
try (Reader reader = new Reader(file)) {
this.testMetadata(reader, ipVersion, recordSize);
if (ipVersion == 4) {
this.testIpV4(reader, file);
} else {
this.testIpV6(reader, file);
}
}
}
}
}
static class GetRecordTest {
InetAddress ip;
File db;
String network;
boolean hasRecord;
GetRecordTest(String ip, String file, String network, boolean hasRecord) throws UnknownHostException {
this.ip = InetAddress.getByName(ip);
db = getFile(file);
this.network = network;
this.hasRecord = hasRecord;
}
}
@Test
public void testGetRecord()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
GetRecordTest[] mapTests = {
new GetRecordTest("1.1.1.1", "MaxMind-DB-test-ipv6-32.mmdb", "1.0.0.0/8", false),
new GetRecordTest("::1:ffff:ffff", "MaxMind-DB-test-ipv6-24.mmdb", "0:0:0:0:0:1:ffff:ffff/128", true),
new GetRecordTest("::2:0:1", "MaxMind-DB-test-ipv6-24.mmdb", "0:0:0:0:0:2:0:0/122", true),
new GetRecordTest("1.1.1.1", "MaxMind-DB-test-ipv4-24.mmdb", "1.1.1.1/32", true),
new GetRecordTest("1.1.1.3", "MaxMind-DB-test-ipv4-24.mmdb", "1.1.1.2/31", true),
new GetRecordTest("1.1.1.3", "MaxMind-DB-test-decoder.mmdb", "1.1.1.0/24", true),
new GetRecordTest("::ffff:1.1.1.128", "MaxMind-DB-test-decoder.mmdb", "1.1.1.0/24", true),
new GetRecordTest("::1.1.1.128", "MaxMind-DB-test-decoder.mmdb", "0:0:0:0:0:0:101:100/120", true),
};
for (GetRecordTest test : mapTests) {
try (Reader reader = new Reader(test.db)) {
Record record = reader.getRecord(test.ip, Map.class);
assertEquals(test.network, record.getNetwork().toString());
if (test.hasRecord) {
assertNotNull(record.getData());
} else {
assertNull(record.getData());
}
}
}
GetRecordTest[] stringTests = {
new GetRecordTest("200.0.2.1", "MaxMind-DB-no-ipv4-search-tree.mmdb", "0.0.0.0/0", true),
new GetRecordTest("::200.0.2.1", "MaxMind-DB-no-ipv4-search-tree.mmdb", "0:0:0:0:0:0:0:0/64", true),
new GetRecordTest("0:0:0:0:ffff:ffff:ffff:ffff", "MaxMind-DB-no-ipv4-search-tree.mmdb", "0:0:0:0:0:0:0:0/64", true),
new GetRecordTest("ef00::", "MaxMind-DB-no-ipv4-search-tree.mmdb", "8000:0:0:0:0:0:0:0/1", false)
};
for (GetRecordTest test : stringTests) {
try (Reader reader = new Reader(test.db)) {
Record record = reader.getRecord(test.ip, String.class);
assertEquals(test.network, record.getNetwork().toString());
if (test.hasRecord) {
assertNotNull(record.getData());
} else {
assertNull(record.getData());
}
}
}
}
@Test
public void testNoIpV4SearchTreeFile()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getFile("MaxMind-DB-no-ipv4-search-tree.mmdb"));
this.testNoIpV4SearchTree(this.testReader);
}
@Test
public void testNoIpV4SearchTreeStream()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getStream("MaxMind-DB-no-ipv4-search-tree.mmdb"));
this.testNoIpV4SearchTree(this.testReader);
}
private void testNoIpV4SearchTree(Reader reader)
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
assertEquals("::0/64", reader.get(InetAddress.getByName("1.1.1.1"), String.class));
assertEquals("::0/64", reader.get(InetAddress.getByName("192.1.1.1"), String.class));
}
@Test
public void testDecodingTypesFile()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getFile("MaxMind-DB-test-decoder.mmdb"));
this.testDecodingTypes(this.testReader);
}
@Test
public void testDecodingTypesStream()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getStream("MaxMind-DB-test-decoder.mmdb"));
this.testDecodingTypes(this.testReader);
}
private void testDecodingTypes(Reader reader)
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
Map<String, Object> record = reader.get(InetAddress.getByName("::1.1.1.0"), Map.class);
assertTrue((boolean) record.get("boolean"));
assertArrayEquals(new byte[]{0, 0, 0, (byte) 42}, (byte[]) record
.get("bytes"));
assertEquals("unicode! - ", (String) record.get("utf8_string"));
Object[] array = (Object[]) record.get("array");
assertEquals(3, array.length);
assertEquals(1, (long) array[0]);
assertEquals(2, (long) array[1]);
assertEquals(3, (long) array[2]);
Map map = (Map) record.get("map");
assertEquals(1, map.size());
Map mapX = (Map) map.get("mapX");
assertEquals(2, mapX.size());
Object[] arrayX = (Object[]) mapX.get("arrayX");
assertEquals(3, arrayX.length);
assertEquals(7, (long) arrayX[0]);
assertEquals(8, (long) arrayX[1]);
assertEquals(9, (long) arrayX[2]);
assertEquals("hello", (String) mapX.get("utf8_stringX"));
assertEquals(42.123456, (double) record.get("double"), 0.000000001);
assertEquals(1.1, (float) record.get("float"), 0.000001);
assertEquals(-268435456, (int) record.get("int32"));
assertEquals(100, (int) record.get("uint16"));
assertEquals(268435456, (long) record.get("uint32"));
assertEquals(new BigInteger("1152921504606846976"), (BigInteger) record
.get("uint64"));
assertEquals(new BigInteger("1329227995784915872903807060280344576"),
(BigInteger) record.get("uint128"));
}
@Test
public void testZerosFile()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getFile("MaxMind-DB-test-decoder.mmdb"));
this.testZeros(this.testReader);
}
@Test
public void testZerosStream()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getFile("MaxMind-DB-test-decoder.mmdb"));
this.testZeros(this.testReader);
}
private void testZeros(Reader reader)
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
Map record = reader.get(InetAddress.getByName("::"), Map.class);
assertFalse((boolean) record.get("boolean"));
assertArrayEquals(new byte[0], (byte[]) record.get("bytes"));
assertEquals("", (String) record.get("utf8_string"));
Object[] array = (Object[]) record.get("array");
assertEquals(0, array.length);
Map map = (Map) record.get("map");
assertEquals(0, map.size());
assertEquals(0, (double) record.get("double"), 0.000000001);
assertEquals(0, (float) record.get("float"), 0.000001);
assertEquals(0, (int) record.get("int32"));
assertEquals(0, (int) record.get("uint16"));
assertEquals(0, (long) record.get("uint32"));
assertEquals(BigInteger.ZERO, (BigInteger) record.get("uint64"));
assertEquals(BigInteger.ZERO, (BigInteger) record.get("uint128"));
}
@Test
public void testBrokenDatabaseFile()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getFile("GeoIP2-City-Test-Broken-Double-Format.mmdb"));
this.testBrokenDatabase(this.testReader);
}
@Test
public void testBrokenDatabaseStream()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getStream("GeoIP2-City-Test-Broken-Double-Format.mmdb"));
this.testBrokenDatabase(this.testReader);
}
private void testBrokenDatabase(Reader reader) {
InvalidDatabaseException ex = assertThrows(
InvalidDatabaseException.class,
() -> reader.get(InetAddress.getByName("2001:220::"), Map.class));
assertThat(ex.getMessage(), containsString("The MaxMind DB file's data section contains bad data"));
}
@Test
public void testBrokenSearchTreePointerFile()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getFile("MaxMind-DB-test-broken-pointers-24.mmdb"));
this.testBrokenSearchTreePointer(this.testReader);
}
@Test
public void testBrokenSearchTreePointerStream()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getStream("MaxMind-DB-test-broken-pointers-24.mmdb"));
this.testBrokenSearchTreePointer(this.testReader);
}
private void testBrokenSearchTreePointer(Reader reader) {
InvalidDatabaseException ex = assertThrows(InvalidDatabaseException.class,
() -> reader.get(InetAddress.getByName("1.1.1.32"), Map.class));
assertThat(ex.getMessage(), containsString("The MaxMind DB file's search tree is corrupt"));
}
@Test
public void testBrokenDataPointerFile()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getFile("MaxMind-DB-test-broken-pointers-24.mmdb"));
this.testBrokenDataPointer(this.testReader);
}
@Test
public void testBrokenDataPointerStream()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
this.testReader = new Reader(getStream("MaxMind-DB-test-broken-pointers-24.mmdb"));
this.testBrokenDataPointer(this.testReader);
}
private void testBrokenDataPointer(Reader reader) {
InvalidDatabaseException ex = assertThrows(InvalidDatabaseException.class,
() -> reader.get(InetAddress.getByName("1.1.1.16"), Map.class));
assertThat(ex.getMessage(), containsString("The MaxMind DB file's data section contains bad data"));
}
@Test
public void testClosedReaderThrowsException()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
Reader reader = new Reader(getFile("MaxMind-DB-test-decoder.mmdb"));
reader.close();
ClosedDatabaseException ex = assertThrows(ClosedDatabaseException.class,
() -> reader.get(InetAddress.getByName("1.1.1.16"), Map.class));
assertEquals("The MaxMind DB has been closed.", ex.getMessage());
}
private void testMetadata(Reader reader, int ipVersion, long recordSize) {
Metadata metadata = reader.getMetadata();
assertEquals("major version", 2, metadata.getBinaryFormatMajorVersion());
assertEquals(0, metadata.getBinaryFormatMinorVersion());
assertEquals(ipVersion, metadata.getIpVersion());
assertEquals("Test", metadata.getDatabaseType());
String[] languages = new String[2];
languages[0] = "en";
languages[1] = "zh";
assertArrayEquals(languages, metadata.getLanguages());
Map<String, String> description = new HashMap<>();
description.put("en", "Test Database");
description.put("zh", "Test Database Chinese");
assertEquals(description, metadata.getDescription());
assertEquals(recordSize, metadata.getRecordSize());
Calendar cal = Calendar.getInstance();
cal.set(2014, Calendar.JANUARY, 1);
assertTrue(metadata.getBuildDate().compareTo(cal.getTime()) > 0);
}
private void testIpV4(Reader reader, File file)
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
for (int i = 0; i <= 5; i++) {
String address = "1.1.1." + (int) Math.pow(2, i);
Map<String, String> data = new HashMap<>();
data.put("ip", address);
assertEquals("found expected data record for " + address + " in "
+ file, data, reader.get(InetAddress.getByName(address), Map.class));
}
Map<String, String> pairs = new HashMap<>();
pairs.put("1.1.1.3", "1.1.1.2");
pairs.put("1.1.1.5", "1.1.1.4");
pairs.put("1.1.1.7", "1.1.1.4");
pairs.put("1.1.1.9", "1.1.1.8");
pairs.put("1.1.1.15", "1.1.1.8");
pairs.put("1.1.1.17", "1.1.1.16");
pairs.put("1.1.1.31", "1.1.1.16");
for (String address : pairs.keySet()) {
Map<String, String> data = new HashMap<>();
data.put("ip", pairs.get(address));
assertEquals("found expected data record for " + address + " in "
+ file, data, reader.get(InetAddress.getByName(address), Map.class));
}
for (String ip : new String[]{"1.1.1.33", "255.254.253.123"}) {
assertNull(reader.get(InetAddress.getByName(ip), Map.class));
}
}
// XXX - logic could be combined with above
private void testIpV6(Reader reader, File file)
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
String[] subnets = new String[]{"::1:ffff:ffff", "::2:0:0",
"::2:0:40", "::2:0:50", "::2:0:58"};
for (String address : subnets) {
Map<String, String> data = new HashMap<>();
data.put("ip", address);
assertEquals("found expected data record for " + address + " in "
+ file, data, reader.get(InetAddress.getByName(address), Map.class));
}
Map<String, String> pairs = new HashMap<>();
pairs.put("::2:0:1", "::2:0:0");
pairs.put("::2:0:33", "::2:0:0");
pairs.put("::2:0:39", "::2:0:0");
pairs.put("::2:0:41", "::2:0:40");
pairs.put("::2:0:49", "::2:0:40");
pairs.put("::2:0:52", "::2:0:50");
pairs.put("::2:0:57", "::2:0:50");
pairs.put("::2:0:59", "::2:0:58");
for (String address : pairs.keySet()) {
Map<String, String> data = new HashMap<>();
data.put("ip", pairs.get(address));
assertEquals("found expected data record for " + address + " in "
+ file, data, reader.get(InetAddress.getByName(address), Map.class));
}
for (String ip : new String[]{"1.1.1.33", "255.254.253.123", "89fa::"}) {
assertNull(reader.get(InetAddress.getByName(ip), Map.class));
}
}
static File getFile(String name) {
return new File(ReaderTest.class.getResource("/maxmind-db/test-data/" + name).getFile());
}
static InputStream getStream(String name) {
return ReaderTest.class.getResourceAsStream("/maxmind-db/test-data/" + name);
}
}
|
package org.pentaho.platform.dataaccess.datasource.wizard;
import java.util.List;
import org.pentaho.agilebi.modeler.ModelerPerspective;
import org.pentaho.agilebi.modeler.gwt.BogoPojo;
import org.pentaho.agilebi.modeler.services.IModelerServiceAsync;
import org.pentaho.agilebi.modeler.services.impl.GwtModelerServiceImpl;
import org.pentaho.database.model.IDatabaseConnection;
import org.pentaho.database.model.IDatabaseType;
import org.pentaho.database.util.DatabaseTypeHelper;
import org.pentaho.gwt.widgets.client.dialogs.GlassPane;
import org.pentaho.gwt.widgets.client.dialogs.GlassPaneNativeListener;
import org.pentaho.gwt.widgets.client.filechooser.JsonToRepositoryFileTreeConverter;
import org.pentaho.metadata.model.Domain;
import org.pentaho.platform.dataaccess.datasource.DatasourceType;
import org.pentaho.platform.dataaccess.datasource.IDatasourceInfo;
import org.pentaho.platform.dataaccess.datasource.beans.LogicalModelSummary;
import org.pentaho.platform.dataaccess.datasource.modeler.ModelerDialog;
import org.pentaho.platform.dataaccess.datasource.ui.admindialog.GwtDatasourceAdminDialog;
import org.pentaho.platform.dataaccess.datasource.ui.importing.AnalysisImportDialogController;
import org.pentaho.platform.dataaccess.datasource.ui.importing.AnalysisImportDialogModel;
import org.pentaho.platform.dataaccess.datasource.ui.importing.GwtImportDialog;
import org.pentaho.platform.dataaccess.datasource.ui.importing.MetadataImportDialogModel;
import org.pentaho.platform.dataaccess.datasource.ui.selectdialog.GwtDatasourceManageDialog;
import org.pentaho.platform.dataaccess.datasource.ui.selectdialog.GwtDatasourceSelectionDialog;
import org.pentaho.platform.dataaccess.datasource.ui.service.DSWUIDatasourceService;
import org.pentaho.platform.dataaccess.datasource.ui.service.JSUIDatasourceService;
import org.pentaho.platform.dataaccess.datasource.ui.service.JdbcDatasourceService;
import org.pentaho.platform.dataaccess.datasource.ui.service.MetadataUIDatasourceService;
import org.pentaho.platform.dataaccess.datasource.ui.service.MondrianUIDatasourceService;
import org.pentaho.platform.dataaccess.datasource.ui.service.UIDatasourceServiceManager;
import org.pentaho.platform.dataaccess.datasource.wizard.controllers.ConnectionController;
import org.pentaho.platform.dataaccess.datasource.wizard.controllers.WizardConnectionController;
import org.pentaho.platform.dataaccess.datasource.wizard.controllers.MessageHandler;
import org.pentaho.platform.dataaccess.datasource.wizard.jsni.WAQRTransport;
import org.pentaho.platform.dataaccess.datasource.wizard.models.DatasourceModel;
import org.pentaho.platform.dataaccess.datasource.wizard.models.GuiStateModel;
import org.pentaho.platform.dataaccess.datasource.wizard.models.ModelInfo;
import org.pentaho.platform.dataaccess.datasource.wizard.service.IXulAsyncDSWDatasourceService;
import org.pentaho.platform.dataaccess.datasource.wizard.service.IXulAsyncDatasourceServiceManager;
import org.pentaho.platform.dataaccess.datasource.wizard.service.gwt.ICsvDatasourceService;
import org.pentaho.platform.dataaccess.datasource.wizard.service.gwt.ICsvDatasourceServiceAsync;
import org.pentaho.platform.dataaccess.datasource.wizard.service.impl.AnalysisDatasourceServiceGwtImpl;
import org.pentaho.platform.dataaccess.datasource.wizard.service.impl.DSWDatasourceServiceGwtImpl;
import org.pentaho.platform.dataaccess.datasource.wizard.service.impl.DatasourceServiceManagerGwtImpl;
import org.pentaho.platform.dataaccess.datasource.wizard.service.impl.MetadataDatasourceServiceGwtImpl;
import org.pentaho.ui.database.event.DatabaseDialogListener;
import org.pentaho.ui.database.event.IConnectionAutoBeanFactory;
import org.pentaho.ui.database.event.IDatabaseConnectionList;
import org.pentaho.ui.database.gwt.GwtDatabaseDialog;
import org.pentaho.ui.database.gwt.GwtXulAsyncDatabaseDialectService;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulServiceCallback;
import org.pentaho.ui.xul.components.XulConfirmBox;
import org.pentaho.ui.xul.gwt.util.AsyncConstructorListener;
import org.pentaho.ui.xul.stereotype.Bindable;
import org.pentaho.ui.xul.util.DialogController.DialogListener;
import org.pentaho.ui.xul.util.XulDialogCallback;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.google.web.bindery.autobean.shared.AutoBeanUtils;
/**
* Creates the singleton datasource wizard and sets up native JavaScript functions to show the wizard.
*/
public class GwtDatasourceEditorEntryPoint implements EntryPoint {
private static final String OVERWRITE_8 = "8";
private static final String SUCCESS_3 = "3";
private EmbeddedWizard wizard;
// TODO: make this lazily loaded when the modelerMessages issue is fixed
private ModelerDialog modeler;
private IXulAsyncDSWDatasourceService datasourceService;
// private IXulAsyncConnectionService connectionService;
private IModelerServiceAsync modelerService;
private IXulAsyncDatasourceServiceManager datasourceServiceManager;
private ICsvDatasourceServiceAsync csvService;
private GwtDatasourceSelectionDialog gwtDatasourceSelectionDialog;
private GwtDatabaseDialog gwtDatabaseDialog;
private DatabaseTypeHelper databaseTypeHelper;
private DatabaseConnectionConverter databaseConnectionConverter;
private EmbeddedWizard gwtDatasourceEditor;
private GwtDatasourceManageDialog manageDialog;
private GwtDatasourceSelectionDialog selectDialog ;
private GwtDatasourceAdminDialog adminDialog;
private GwtImportDialog importDialog;
private boolean asyncConstructorDone;
private boolean hasPermissions;
private boolean isAdmin;
private Timer timer;
// private GwtXulAsyncDatabaseConnectionService connService = new GwtXulAsyncDatabaseConnectionService();
private GwtXulAsyncDatabaseDialectService dialectService = new GwtXulAsyncDatabaseDialectService();
private IConnectionAutoBeanFactory connectionAutoBeanFactory = GWT.create(IConnectionAutoBeanFactory.class);
public void onModuleLoad() {
datasourceServiceManager = new DatasourceServiceManagerGwtImpl();
datasourceServiceManager.isAdmin(new XulServiceCallback<Boolean>() {
public void error(String message, Throwable error) {
}
public void success(Boolean retVal) {
isAdmin = retVal;
datasourceService = new DSWDatasourceServiceGwtImpl();
modelerService = new GwtModelerServiceImpl();
BogoPojo bogo = new BogoPojo();
modelerService.gwtWorkaround(bogo, new XulServiceCallback<BogoPojo>(){
public void success(BogoPojo retVal) {
}
public void error(String message, Throwable error) {
}
});
datasourceService.hasPermission(new XulServiceCallback<Boolean>() {
public void error(String message, Throwable error) {
setupStandardNativeHooks(GwtDatasourceEditorEntryPoint.this);
initDashboardButtons(false);
}
public void success(Boolean retVal) {
hasPermissions = retVal;
setupStandardNativeHooks(GwtDatasourceEditorEntryPoint.this);
if (isAdmin || hasPermissions) {
// connectionService = new ConnectionServiceGwtImpl();
csvService = (ICsvDatasourceServiceAsync) GWT.create(ICsvDatasourceService.class);
setupPrivilegedNativeHooks(GwtDatasourceEditorEntryPoint.this);
loadOverlay("startup.dataaccess");
}
initDashboardButtons(retVal);
}
});
}
});
XulServiceCallback<List<IDatabaseType>> callback = new XulServiceCallback<List<IDatabaseType>>() {
public void error(String message, Throwable error) {
error.printStackTrace();
}
public void success(List<IDatabaseType> retVal) {
databaseTypeHelper = new DatabaseTypeHelper(retVal);
databaseConnectionConverter = new DatabaseConnectionConverter(databaseTypeHelper);
}
};
dialectService.getDatabaseTypes(callback);
UIDatasourceServiceManager manager = UIDatasourceServiceManager.getInstance();
manager.registerService(new JdbcDatasourceService());
manager.registerService(new MondrianUIDatasourceService(datasourceServiceManager));
manager.registerService(new MetadataUIDatasourceService(datasourceServiceManager));
manager.registerService(new DSWUIDatasourceService(datasourceServiceManager));
manager.getIds(null);
}
private native static void loadOverlay( String overlayId) /*-{
if(!$wnd.mantle_loadOverlay){
setTimeout(function(){
@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::loadOverlay(Ljava/lang/String;)(overlayId);
}, 200);
return;
}
$wnd.mantle_loadOverlay(overlayId)
}-*/;
private native void removeOverlay(String overlayId) /*-{
if($wnd.mantle_removeOverlay)
$wnd.mantle_removeOverlay(overlayId)
}-*/;
public native void initDashboardButtons(boolean val) /*-{
if($wnd.initDataAccess){
$wnd.initDataAccess(val);
}
}-*/;
private native void setupStandardNativeHooks(GwtDatasourceEditorEntryPoint wizard)/*-{
if(!$wnd.pho){
$wnd.pho = {};
}
$wnd.addDataAccessGlassPaneListener = function(callback) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::addGlassPaneListener(Lcom/google/gwt/core/client/JavaScriptObject;)(callback);
}
$wnd.pho.showDatasourceSelectionDialog = function(context, callback) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showSelectionDialog(Ljava/lang/String;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(context,"true", callback);
}
$wnd.pho.showDatabaseDialog = function(callback) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showDatabaseDialog(Lcom/google/gwt/core/client/JavaScriptObject;)(callback);
}
$wnd.gwtConfirm = function(message, callback, options){
var title = options.title || $wnd.pho_messages.getMessage("prompt","Prompt");
var accept = options.acceptLabel || $wnd.pho_messages.getMessage("okButton","OK");
var cancel = options.cancelLabel || $wnd.pho_messages.getMessage("cancelButton","Cancel");
try{
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showConfirm(Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)(callback, message, title, accept, cancel);
} catch(e) {
// if it fails just show browser prompt
callback.okOk($wnd.confirm(message));
}
}
}-*/;
private native void setupPrivilegedNativeHooks(GwtDatasourceEditorEntryPoint wizard)/*-{
$wnd.pho.openDatasourceEditor= function(callback, reportingOnlyValid) {
if(typeof reportingOnlyValid == "undefined"){
reportingOnlyValid = true;
}
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showWizard(ZLcom/google/gwt/core/client/JavaScriptObject;)(reportingOnlyValid, callback);
}
$wnd.pho.openEditDatasourceEditor= function(domainId, modelId, callback, perspective, reportingOnlyValid) {
if(typeof reportingOnlyValid == "undefined"){
reportingOnlyValid = true;
}
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showWizardEdit(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLcom/google/gwt/core/client/JavaScriptObject;)(domainId, modelId, perspective, reportingOnlyValid, callback);
}
$wnd.pho.deleteModel=function(domainId, modelName, callback) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::deleteLogicalModel(Ljava/lang/String;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(domainId, modelName, callback);
}
$wnd.pho.showDatasourceManageDialog = function(callback) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showSelectionDialog(Ljava/lang/String;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)("manage", "false", callback);
}
$wnd.pho.showMetadataImportDialog = function(callback) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showMetadataImportDialog(Lcom/google/gwt/core/client/JavaScriptObject;)(callback);
}
$wnd.pho.showAnalysisImportDialog = function(callback) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::showAnalysisImportDialog(Lcom/google/gwt/core/client/JavaScriptObject;)(callback);
}
$wnd.pho.registerUIDatasourceService = function(jsDatasourceService) {
wizard.@org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint::registerDatasourceService(Lcom/google/gwt/core/client/JavaScriptObject;)(jsDatasourceService);
}
}-*/;
private void registerDatasourceService(JavaScriptObject javascriptObject) {
JSUIDatasourceService datasourceService = new JSUIDatasourceService(javascriptObject);
UIDatasourceServiceManager.getInstance().registerService(datasourceService);
}
public void showConfirm(final JavaScriptObject callback, String message, String title, String okText, String cancelText) throws XulException{
XulConfirmBox confirm = (XulConfirmBox) wizard.getMainWizardContainer().getDocumentRoot().createElement("confirmbox");
confirm.setTitle(title);
confirm.setMessage(message);
confirm.setAcceptLabel(okText);
confirm.setCancelLabel(cancelText);
confirm.addDialogCallback(new XulDialogCallback<String>(){
public void onClose(XulComponent component, Status status, String value) {
if(status == XulDialogCallback.Status.ACCEPT){
notifyDialogCallbackSuccess(callback, value);
}
}
public void onError(XulComponent component, Throwable err) {
notifyDialogCallbackError(callback, err.getMessage());
}
});
confirm.open();
}
/**
* used to handle the overwrite in repository message
* @param parentFormPanel
* @param message
* @param controller
*/
public void overwriteFileDialog(final FormPanel parentFormPanel,String message,final AnalysisImportDialogController controller) {
//Experiment
XulConfirmBox confirm = null;
try {
confirm = (XulConfirmBox) wizard.getMainWizardContainer().getDocumentRoot().createElement("confirmbox");
} catch (XulException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
confirm.setTitle("Confirmation");
confirm.setMessage(message);
confirm.setAcceptLabel("Ok");
confirm.setCancelLabel("Cancel");
confirm.addDialogCallback(new XulDialogCallback<String>() {
public void onClose(XulComponent component, Status status, String value) {
if (status == XulDialogCallback.Status.ACCEPT) {
controller.setOverwrite(true);
controller.removeHiddenPanels();
controller.buildAndSetParameters();
parentFormPanel.submit();
}
}
public void onError(XulComponent component, Throwable err) {
return;
}
});
confirm.open();
}
@SuppressWarnings("unused")
private void addGlassPaneListener(JavaScriptObject obj) {
GlassPane.getInstance().addGlassPaneListener(new GlassPaneNativeListener(obj));
}
public void showWizard(final boolean relationalOnlyValid, final DialogListener<Domain> listener) {
if(wizard == null){
wizard = new EmbeddedWizard(false);
wizard.setDatasourceService(datasourceService);
// wizard.setConnectionService(connectionService);
wizard.setCsvDatasourceService(csvService);
wizard.setReportingOnlyValid(relationalOnlyValid);
wizard.init(new AsyncConstructorListener<EmbeddedWizard>() {
@Override
public void asyncConstructorDone(EmbeddedWizard source) {
wizard.addDialogListener(listener);
wizard.showDialog();
}
});
} else {
wizard.addDialogListener(listener);
wizard.setReportingOnlyValid(relationalOnlyValid);
wizard.showDialog();
}
}
/**
* Entry-point from Javascript, responds to provided callback with the following:
*
* onOk(String JSON, String mqlString);
* onCancel();
* onError(String errorMessage);
*
* @param callback
*
*/
private void showWizard(final boolean relationalOnlyValid, final JavaScriptObject callback) {
final DialogListener<Domain> listener = new DialogListener<Domain>(){
public void onDialogCancel() {
wizard.removeDialogListener(this);
if(callback != null) {
notifyCallbackCancel(callback);
}
}
public void onDialogAccept(final Domain domain) {
MessageHandler.getInstance().closeWaitingDialog();
wizard.removeDialogListener(this);
WAQRTransport transport = WAQRTransport.createFromMetadata(domain);
notifyCallbackSuccess(callback, true, transport);
notifyDialogCallbackSuccess(callback, domain.getId());
}
public void onDialogReady() {
if(callback != null) {
notifyCallbackReady(callback);
}
}
@Override
public void onDialogError(String errorMessage) {
notifyCallbackError(callback, errorMessage);
}
};
showWizard(relationalOnlyValid, listener);
}
public void showWizardEdit(final String domainId, final String modelId, boolean relationalOnlyValid, final DialogListener<Domain> listener) {
showWizardEdit(domainId, modelId, ModelerPerspective.REPORTING.name(), relationalOnlyValid, listener);
}
public void showWizardEdit(final String domainId, final String modelId, final String perspective, boolean relationalOnlyValid, final DialogListener<Domain> listener) {
final String modelPerspective;
if (perspective == null) {
modelPerspective = ModelerPerspective.REPORTING.name();
} else {
modelPerspective = perspective;
}
modeler = ModelerDialog.getInstance(wizard, new AsyncConstructorListener<ModelerDialog>(){
public void asyncConstructorDone(ModelerDialog dialog) {
ModelerPerspective modelerPerspective;
try {
modelerPerspective = ModelerPerspective.valueOf(modelPerspective);
} catch (IllegalArgumentException e) {
modelerPerspective = ModelerPerspective.REPORTING;
}
dialog.addDialogListener(listener);
dialog.showDialog(domainId, modelId, modelerPerspective);
}
});
}
private void showWizardEdit(final String domainId, final String modelId, boolean relationalOnlyValid, final JavaScriptObject callback) {
showWizardEdit(domainId, modelId, ModelerPerspective.REPORTING.name(), relationalOnlyValid, callback);
}
/**
* edit entry-point from Javascript, responds to provided callback with the following:
*
* onOk(String JSON, String mqlString);
* onCancel();
* onError(String errorMessage);
*
* @param callback
*
*/
private void showWizardEdit(final String domainId, final String modelId, final String perspective, boolean relationalOnlyValid, final JavaScriptObject callback) {
final DialogListener<Domain> listener = new DialogListener<Domain>(){
public void onDialogCancel() {
modeler.removeDialogListener(this);
if(callback != null) {
notifyCallbackCancel(callback);
}
}
public void onDialogAccept(final Domain domain) {
modeler.removeDialogListener(this);
WAQRTransport transport = WAQRTransport.createFromMetadata(domain);
notifyCallbackSuccess(callback, true, transport);
}
public void onDialogReady() {
if(callback != null) {
notifyCallbackReady(callback);
}
}
@Override
public void onDialogError(String errorMessage) {
notifyCallbackError(callback, errorMessage);
}
};
}
/**
* Deletes the selected model
*
* onOk(Boolean value);
* onCancel();
* onError(String errorMessage);
*
* @param callback
*
*/
private void deleteLogicalModel(String domainId, String modelName, final JavaScriptObject callback) {
datasourceService.deleteLogicalModel(domainId, modelName, new XulServiceCallback<Boolean>(){
public void success(Boolean value) {
notifyCallbackSuccess(callback, value);
}
public void error(String s, Throwable throwable) {
notifyCallbackError(callback, throwable.getMessage());
}
});
}
private void showAdminDialog(final DialogListener<IDatasourceInfo> listener) {
if(adminDialog == null) {
final AsyncConstructorListener<GwtDatasourceAdminDialog> constructorListener = getAdminDialogListener(listener);
asyncConstructorDone = false;
adminDialog = new GwtDatasourceAdminDialog(datasourceServiceManager, modelerService, datasourceService, this, constructorListener);
} else {
adminDialog.addDialogListener(listener);
adminDialog.showDialog();
}
}
@SuppressWarnings("unused")
private void showAdminDialog(final JavaScriptObject callback) {
final DialogListener<IDatasourceInfo> listener = new DialogListener<IDatasourceInfo>(){
public void onDialogCancel() {
adminDialog.removeDialogListener(this);
asyncConstructorDone = false;
notifyCallbackCancel(callback);
}
public void onDialogAccept(final IDatasourceInfo genericDatasourceInfo) {
adminDialog.removeDialogListener(this);
asyncConstructorDone = false;
notifyCallbackSuccess(callback, genericDatasourceInfo.getId(), genericDatasourceInfo.getType());
}
public void onDialogReady() {
}
@Override
public void onDialogError(String errorMessage) {
notifyCallbackError(callback, errorMessage);
}
};
showAdminDialog(listener);
}
private void showSelectionOrAdminDialog(
final String context, final String selectDatasource,
final JavaScriptObject callback,
final DialogListener<LogicalModelSummary> listener
){
if("manage".equals(context) && isAdmin) {
showAdminDialog(callback);
} else {
showSelectionDialog(context, Boolean.valueOf(selectDatasource), listener);
}
}
@SuppressWarnings("unused")
private void showSelectionDialog(final String context, final String selectDatasource, final JavaScriptObject callback) {
final DialogListener<LogicalModelSummary> listener = new DialogListener<LogicalModelSummary>(){
public void onDialogCancel() {
selectDialog.removeDialogListener(this);
asyncConstructorDone = false;
notifyCallbackCancel(callback);
}
public void onDialogAccept(final LogicalModelSummary logicalModelSummary) {
selectDialog.removeDialogListener(this);
asyncConstructorDone = false;
notifyCallbackSuccess(callback, logicalModelSummary.getDomainId(), logicalModelSummary.getModelId(),logicalModelSummary.getModelName());
}
public void onDialogReady() {
}
public void onDialogError(String errorMessage) {
notifyDialogCallbackError(callback, errorMessage);
}
};
if(wizard == null && this.hasPermissions){
wizard = new EmbeddedWizard(false);
wizard.setDatasourceService(datasourceService);
// wizard.setConnectionService(connectionService);
wizard.setCsvDatasourceService(csvService);
wizard.init(new AsyncConstructorListener<EmbeddedWizard>() {
public void asyncConstructorDone(EmbeddedWizard source) {
showSelectionOrAdminDialog(context, selectDatasource, callback, listener);
}
});
} else {
showSelectionOrAdminDialog(context, selectDatasource, callback, listener);
}
}
private void showMetadataImportDialog(final JavaScriptObject callback) {
final DialogListener<MetadataImportDialogModel> listener = new DialogListener<MetadataImportDialogModel>(){
public void onDialogCancel() {
}
public void onDialogAccept(final MetadataImportDialogModel importDialogModel) {
MetadataDatasourceServiceGwtImpl service = new MetadataDatasourceServiceGwtImpl();
service.importMetadataDatasource(importDialogModel.getDomainId(),
importDialogModel.getUploadedFile(), importDialogModel.getLocalizedBundleEntries(), new XulServiceCallback<String>() {
@Override
public void success(String retVal) {
notifyDialogCallbackSuccess(callback, retVal);
}
@Override
public void error(String message, Throwable error) {
notifyDialogCallbackError(callback, message);
}
});
}
public void onDialogReady() {
}
@Override
public void onDialogError(String errorMessage) {
// TODO Auto-generated method stub
}
};
showAnalysisImportDialog(listener);
}
public void showMetadataImportDialog(final DialogListener listener) {
final DialogListener<MetadataImportDialogModel> importDialoglistener = new DialogListener<MetadataImportDialogModel>(){
public void onDialogCancel() {
}
public void onDialogAccept(final MetadataImportDialogModel importDialogModel) {
final FormPanel metaDataFormPanel = importDialog.getMetadataImportDialogController().getFormPanel();
metaDataFormPanel.removeFromParent();
RootPanel.get().add(metaDataFormPanel);
metaDataFormPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String results = event.getResults();
if (!results.contains("SUCCESS")) {
listener.onDialogError(results);
}
metaDataFormPanel.removeFromParent();
listener.onDialogAccept(null);
}
});
metaDataFormPanel.submit();
}
public void onDialogReady() {
}
@Override
public void onDialogError(String errorMessage) {
listener.onDialogError(errorMessage);
}
};
final AsyncConstructorListener<GwtImportDialog> constructorListener = new AsyncConstructorListener<GwtImportDialog>() {
public void asyncConstructorDone(GwtImportDialog dialog) {
dialog.showMetadataImportDialog(importDialoglistener);
}
};
if(importDialog == null){
importDialog = new GwtImportDialog(constructorListener);
} else {
importDialog.showMetadataImportDialog(importDialoglistener);
}
}
private void showAnalysisImportDialog(final JavaScriptObject callback) {
final DialogListener<AnalysisImportDialogModel> listener = new DialogListener<AnalysisImportDialogModel>(){
public void onDialogCancel() {
}
public void onDialogAccept(final AnalysisImportDialogModel importDialogModel) {
AnalysisDatasourceServiceGwtImpl service = new AnalysisDatasourceServiceGwtImpl();
service.importAnalysisDatasource(importDialogModel.getUploadedFile(),
importDialogModel.getConnection().getName(), importDialogModel.getParameters(), new XulServiceCallback<String>() {
@Override
public void success(String retVal) {
notifyDialogCallbackSuccess(callback, retVal);
}
@Override
public void error(String message, Throwable error) {
notifyDialogCallbackError(callback, message);
}
});
}
public void onDialogReady() {
}
@Override
public void onDialogError(String errorMessage) {
// TODO Auto-generated method stub
}
};
showAnalysisImportDialog(listener);
}
public void showAnalysisImportDialog(final DialogListener listener) {
final DialogListener<AnalysisImportDialogModel> importDialoglistener = new DialogListener<AnalysisImportDialogModel>(){
public void onDialogCancel() {
}
public void onDialogAccept(final AnalysisImportDialogModel importDialogModel) {
final AnalysisImportDialogController controller = importDialog.getAnalysisImportDialogController();
final FormPanel analysisDataFormPanel = controller.getFormPanel();
controller.removeHiddenPanels();
controller.buildAndSetParameters();
analysisDataFormPanel.removeFromParent();
RootPanel.get().add(analysisDataFormPanel);
analysisDataFormPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String results = event.getResults();
String message = controller.convertToNLSMessage(results, controller.getFileName());
if (!SUCCESS_3.equals(results)) {
if(OVERWRITE_8.equals(results)){
overwriteFileDialog(analysisDataFormPanel,message,controller);
} else {
listener.onDialogError(message);
}
} else {
analysisDataFormPanel.removeFromParent();
listener.onDialogAccept(null);
}
}
});
analysisDataFormPanel.submit();
}
public void onDialogReady() {
}
@Override
public void onDialogError(String errorMessage) {
listener.onDialogError(errorMessage);
}
};
final AsyncConstructorListener<GwtImportDialog> constructorListener = new AsyncConstructorListener<GwtImportDialog>() {
public void asyncConstructorDone(GwtImportDialog dialog) {
dialog.showAnalysisImportDialog(importDialoglistener);
}
};
if(importDialog == null){
importDialog = new GwtImportDialog(constructorListener);
} else {
importDialog.showAnalysisImportDialog(importDialoglistener);
}
}
private void showSelectionDialog(final String context, final boolean selectDs, final DialogListener<LogicalModelSummary> listener) {
if (selectDs) {
// selection dialog
if (selectDialog == null) {
final AsyncConstructorListener<GwtDatasourceSelectionDialog> constructorListener = getSelectionDialogListener(listener);
asyncConstructorDone = false;
selectDialog = new GwtDatasourceSelectionDialog(context, datasourceService, wizard, constructorListener);
} else {
selectDialog.addDialogListener(listener);
selectDialog.reset();
selectDialog.setContext(context);
selectDialog.showDialog();
}
} else {
// manage dialog
if (manageDialog == null) {
final AsyncConstructorListener<GwtDatasourceSelectionDialog> constructorListener = getSelectionDialogListener(listener);
asyncConstructorDone = false;
manageDialog = new GwtDatasourceManageDialog(datasourceService, wizard, constructorListener);
} else {
manageDialog.reset();
manageDialog.showDialog();
}
}
}
private AsyncConstructorListener<GwtDatasourceSelectionDialog> getSelectionDialogListener(final DialogListener<LogicalModelSummary> listener){
return new AsyncConstructorListener<GwtDatasourceSelectionDialog>() {
public void asyncConstructorDone(GwtDatasourceSelectionDialog dialog) {
dialog.removeDialogListener(listener);
dialog.addDialogListener(listener);
if (!asyncConstructorDone) {
dialog.showDialog();
}
asyncConstructorDone = true;
}
};
}
private AsyncConstructorListener<GwtDatasourceAdminDialog> getAdminDialogListener(final DialogListener<IDatasourceInfo> listener){
return new AsyncConstructorListener<GwtDatasourceAdminDialog>() {
public void asyncConstructorDone(GwtDatasourceAdminDialog dialog) {
dialog.removeDialogListener(listener);
dialog.addDialogListener(listener);
if (!asyncConstructorDone) {
dialog.showDialog();
}
asyncConstructorDone = true;
}
};
}
private void showDatabaseDialog(final JavaScriptObject callback) {
final DialogListener<IDatabaseConnection> listener = new DialogListener<IDatabaseConnection>(){
public void onDialogCancel() {
if(callback != null) {
notifyCallbackCancel(callback);
}
}
public void onDialogAccept(final IDatabaseConnection connection) {
if(callback != null) {
notifyCallbackSuccess(callback, true);
}
}
public void onDialogReady() {
if(callback != null) {
notifyCallbackCancel(callback);
}
}
@Override
public void onDialogError(String errorMessage) {
if(callback != null) {
notifyCallbackError(callback, errorMessage);
}
}
};
showDatabaseDialog(listener);
}
public void showDatabaseDialog(final DialogListener<IDatabaseConnection> listener) {
ConnectionController connectionController = wizard.getConnectionController();
//WizardConnectionController connectionController = wizard.getConnectionController();
connectionController.init();
DatasourceModel datasourceModel = new DatasourceModel();
connectionController.setDatasourceModel(datasourceModel);
connectionController.showAddConnectionDialog(listener);
}
public void showEditDatabaseDialog(final DialogListener dialogListener, final String databaseName) {
String url = ConnectionController.getServiceURL("get", new String[][]{
{"name", databaseName}
});
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
builder.setHeader("Accept", "application/json");
try {
builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert(exception.toString());
}
@SuppressWarnings("deprecation")
public void onResponseReceived(Request request, Response response) {
IDatabaseConnection conn = null;
if (response.getStatusCode() == Response.SC_OK) {
AutoBean<IDatabaseConnection> bean = AutoBeanCodex.decode(connectionAutoBeanFactory,
IDatabaseConnection.class, response.getText());
conn = bean.as();
}
ConnectionController connectionController = wizard.getConnectionController();
//WizardConnectionController connectionController = wizard.getConnectionController();
connectionController.init();
DatasourceModel datasourceModel = connectionController.getDatasourceModel();
if (datasourceModel == null) {
datasourceModel = new DatasourceModel();
connectionController.setDatasourceModel(datasourceModel);
}
datasourceModel.setSelectedRelationalConnection(conn);
connectionController.setDatasourceModel(datasourceModel);
connectionController.showEditConnectionDialog(dialogListener);
}
});
} catch (Exception e) {
Window.alert("Cannot edit datasource");
}
}
private native void notifyCallbackSuccess(JavaScriptObject callback, String domainId, String modelId, String modelName) /*-{
callback.onFinish(domainId, modelId, modelName);
}-*/;
private native void notifyCallbackSuccess(JavaScriptObject callback, String domainId, String modelId) /*-{
callback.onFinish(domainId, modelId);
}-*/;
private native void notifyCallbackSuccess(JavaScriptObject callback, Boolean value, WAQRTransport transport)/*-{
callback.onFinish(value, transport);
}-*/;
private native void notifyCallbackSuccess(JavaScriptObject callback, Boolean value)/*-{
callback.onFinish(value);
}-*/;
private native void notifyCallbackError(JavaScriptObject callback, String error)/*-{
callback.onError(error);
}-*/;
private native void notifyCallbackCancel(JavaScriptObject callback)/*-{
callback.onCancel();
}-*/;
private native void notifyCallbackReady(JavaScriptObject callback)/*-{
callback.onReady();
}-*/;
private native void notifyDialogCallbackSuccess(JavaScriptObject callback, Object value)/*-{
callback.onOk(value);
}-*/;
private native void notifyDialogCallbackCancel(JavaScriptObject callback)/*-{
callback.onCancel();
}-*/;
private native void notifyDialogCallbackError(JavaScriptObject callback, String error)/*-{
callback.onError(error);
}-*/;
}
|
//@@author A0142102E
package guitests;
import seedu.tasklist.testutil.TypicalTestTasks;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ClearCommandTest extends TaskListGuiTest {
@Test
public void clear() {
//verify a non-empty list can be cleared
assertClearCommandSuccess();
//verify other commands can work after a clear command
commandBox.runCommand(TypicalTestTasks.task8.getAddCommand());
commandBox.runCommand("delete 1");
assertListSize(0);
//verify clear command works when the list is empty
assertClearCommandSuccess();
}
private void assertClearCommandSuccess() {
commandBox.runCommand("clear");
assertListSize(0);
assertResultMessage("Your Smart Scheduler has been cleared!");
}
}
|
package me.coley.recaf;
import me.coley.recaf.search.*;
import me.coley.recaf.workspace.*;
import org.junit.jupiter.api.*;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import static me.coley.recaf.search.StringMatchMode.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests for the Search api.
*
* @author Matt
*/
public class SearchTest extends Base {
private static JavaResource base;
private static Workspace workspace;
@BeforeAll
public static void setup() {
try {
base = new JarResource(getClasspathFile("calc.jar"));
workspace = new Workspace(base);
} catch(IOException ex) {
fail(ex);
}
}
@Test
public void testStringResultContext() {
// Setup search - String "EVAL: " in Calculator.evaluate(int, String)
SearchCollector collector = SearchBuilder.in(workspace).skipDebug()
.query(new StringQuery("EVAL", STARTS_WITH)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(1, results.size());
StringResult res = (StringResult) results.get(0);
assertEquals("EVAL: ", res.getText());
// Assert context shows the string is in the expected method
// - res context is of the LDC insn
// - parent is of the method containing the String
contextEquals(res.getContext().getParent(), "calc/Calculator", "evaluate", "(ILjava/lang/String;)D");
}
@Test
public void testValue() {
// Setup search - Calculator.MAX_DEPTH = 30
// - Javac inlines constants, but keeps the field constant value attribute
// - So there should be the field const and the inline value in results
SearchCollector collector = SearchBuilder.in(workspace).skipDebug()
.query(new ValueQuery(30)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(2, results.size());
ValueResult resField = (ValueResult) results.get(0);
contextEquals(resField.getContext(), "calc/Calculator", "MAX_DEPTH", "I");
ValueResult resInsn = (ValueResult) results.get(1);
contextEquals(resInsn.getContext().getParent(), "calc/Calculator", "evaluate", "(ILjava/lang/String;)D");
}
@Test
public void testOverlappingResultsInMethodCode() {
// Setup search - two queries that have results in the same method:
// - Calculator.evaluate(int, String)
SearchCollector collector = SearchBuilder.in(workspace).skipDebug()
.query(new ValueQuery(30))
.query(new StringQuery("EVAL: ", STARTS_WITH))
.build();
// Show results
List<SearchResult> results = collector.getOverlappingResults();
assertEquals(2, results.size());
boolean isValFirst = results.get(0) instanceof ValueResult;
ValueResult resVal = isValFirst ?
(ValueResult) results.get(0) : (ValueResult) results.get(1);
StringResult resStr = isValFirst ?
(StringResult) results.get(1) : (StringResult) results.get(0);
assertEquals(30, resVal.getValue());
assertEquals("EVAL: ", resStr.getText());
contextEquals(resVal.getContext().getParent(), "calc/Calculator", "evaluate", "(ILjava/lang/String;)D");
contextEquals(resStr.getContext().getParent(), "calc/Calculator", "evaluate", "(ILjava/lang/String;)D");
}
@Test
public void testOverlapExcludesOtherClasses() {
// Setup search - fetch all strings and only return them if they're sharing the
// same context as the "30" value result.
SearchCollector collector = SearchBuilder.in(workspace).skipDebug()
.query(new ValueQuery(30))
.query(new StringQuery("", CONTAINS))
.build();
// Show results
List<SearchResult> results = collector.getOverlappingResults();
// All results should be instruction-level in the method Calculator.evaluate(int, String)
// So asserting that all results parents are in this method should be valid
for (SearchResult result : results) {
contextEquals(result.getContext().getParent(), "calc/Calculator", "evaluate", "(ILjava/lang/String;)D");
}
}
@Test
public void testMemberDefAnyInClass() {
// Setup search - Any member in "Expression"
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new MemberDefinitionQuery("calc/Expression", null, null, EQUALS)).build();
// Show results - should be given four (field + 3 methods)
Set<String> results = collector.getAllResults().stream()
.map(Object::toString)
.collect(Collectors.toSet());
assertEquals(4, results.size());
assertTrue(results.contains("calc/Expression.i I"));
assertTrue(results.contains("calc/Expression.<init>(I)V"));
assertTrue(results.contains("calc/Expression.accept(Ljava/lang/String;)D"));
assertTrue(results.contains("calc/Expression.evaluate(Ljava/lang/String;)D"));
}
@Test
public void testMemberDefAnyIntField() {
// Setup search - Any int member in any class
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new MemberDefinitionQuery(null, null, "I", EQUALS)).build();
// Show results - should be the given three
Set<String> results = collector.getAllResults().stream()
.map(Object::toString)
.collect(Collectors.toSet());
assertEquals(3, results.size());
assertTrue(results.contains("calc/Parenthesis.LEVEL_UNSET I"));
assertTrue(results.contains("calc/Calculator.MAX_DEPTH I"));
assertTrue(results.contains("calc/Expression.i I"));
}
@Test
public void testClassReference() {
// Setup search - References to the "Exponent" class
// - Should be 3 references in "Calculator" and three self references in "Exponent"
SearchCollector collector = SearchBuilder.in(workspace)
.query(new ClassReferenceQuery("calc/Exponent")).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(6, results.size());
int calc = 0, exp = 0;
for (SearchResult res : results) {
Context.InsnContext insnContext = (Context.InsnContext) res.getContext();
String owner = insnContext.getParent().getParent().getName();
switch(owner) {
case "calc/Calculator": calc++; break;
case "calc/Exponent": exp++; break;
default: fail("Unexpected result in: " + owner);
}
}
// Three self-references (same method, 3 times)
// - INVOKE evaluate(String)
// - INVOKE evaluate(String)
// - INVOKE evaluate(String)
assertEquals(3, exp);
// Three references in Calculator
// - NEW Exponent
// - INVOKE Exponent.<init>
// - INVOKE Exponent.accept(String)
assertEquals(3, calc);
}
@Test
public void testMemberReference() {
// Setup search - References to the "Calculator.log(int, String)" method
SearchCollector collector = SearchBuilder.in(workspace).skipDebug()
.query(new MemberReferenceQuery("calc/Calculator", "log", null, EQUALS)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(2, results.size());
for (SearchResult res : results) {
Context.InsnContext insnContext = (Context.InsnContext) res.getContext();
String owner = insnContext.getParent().getParent().getName();
if (!owner.equals("calc/Calculator")) {
fail("Unexpected result in: " + owner);
}
}
}
@Test
public void testNoMemberReferenceWhenCodeSkipped() {
// Setup search - References to the "Calculator.log(int, String)" method
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new MemberReferenceQuery("calc/Calculator", "log", null, EQUALS)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(0, results.size());
}
@Test
public void testClassNameEquals() {
// Setup search - Equality for "Start"
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new ClassNameQuery("Start", EQUALS)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(1, results.size());
assertEquals("Start", ((ClassResult)results.get(0)).getName());
}
@Test
public void testClassNameStartsWith() {
// Setup search - Starts with for "Start"
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new ClassNameQuery("S", STARTS_WITH)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(1, results.size());
assertEquals("Start", ((ClassResult)results.get(0)).getName());
}
@Test
public void testClassNameEndsWith() {
// Setup search - Ends with for "ParenTHESIS"
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new ClassNameQuery("thesis", ENDS_WITH)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(1, results.size());
assertEquals("calc/Parenthesis", ((ClassResult)results.get(0)).getName());
}
@Test
public void testClassNameRegex() {
// Setup search - Regex for "Start" by matching only word characters (no package splits)
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new ClassNameQuery("^\\w+$", REGEX)).build();
// Show results
List<SearchResult> results = collector.getAllResults();
assertEquals(1, results.size());
assertEquals("Start", ((ClassResult)results.get(0)).getName());
}
@Test
public void testClassInheritance() {
// Setup search - All implementations of "Expression"
SearchCollector collector = SearchBuilder.in(workspace).skipDebug().skipCode()
.query(new ClassInheritanceQuery(workspace, "calc/Expression")).build();
// Show results
Set<String> results = collector.getAllResults().stream()
.map(res -> ((ClassResult)res).getName())
.collect(Collectors.toSet());
assertEquals(5, results.size());
assertTrue(results.contains("calc/Parenthesis"));
assertTrue(results.contains("calc/Exponent"));
assertTrue(results.contains("calc/MultAndDiv"));
assertTrue(results.contains("calc/AddAndSub"));
assertTrue(results.contains("calc/Constant"));
}
private static void contextEquals(Context<?> context, String owner, String name, String desc) {
assertTrue(context instanceof Context.MemberContext);
Context.MemberContext member = (Context.MemberContext) context;
assertEquals(owner, member.getParent().getName());
assertEquals(name, member.getName());
assertEquals(desc, member.getDesc());
}
}
|
package pdp.web;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.net.HttpHeaders;
import org.apache.openaz.xacml.api.Attribute;
import org.apache.openaz.xacml.api.IdReference;
import org.apache.openaz.xacml.api.Request;
import org.apache.openaz.xacml.api.RequestAttributes;
import org.apache.openaz.xacml.api.Response;
import org.apache.openaz.xacml.api.Result;
import org.apache.openaz.xacml.api.pdp.PDPEngine;
import org.apache.openaz.xacml.pdp.policy.Policy;
import org.apache.openaz.xacml.std.IdentifierImpl;
import org.apache.openaz.xacml.std.StdAttribute;
import org.apache.openaz.xacml.std.StdAttributeValue;
import org.apache.openaz.xacml.std.StdMutableAttribute;
import org.apache.openaz.xacml.std.StdMutableRequest;
import org.apache.openaz.xacml.std.StdMutableRequestAttributes;
import org.apache.openaz.xacml.std.StdRequest;
import org.apache.openaz.xacml.std.json.JSONRequest;
import org.apache.openaz.xacml.std.json.JSONResponse;
import org.apache.openaz.xacml.util.Wrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.support.TaskUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pdp.JsonMapper;
import pdp.PdpPolicyException;
import pdp.PolicyNotFoundException;
import pdp.access.PolicyAccess;
import pdp.access.PolicyIdpAccessEnforcer;
import pdp.conflicts.PolicyConflictService;
import pdp.domain.EntityMetaData;
import pdp.domain.JsonPolicyRequest;
import pdp.domain.PdpPolicy;
import pdp.domain.PdpPolicyDefinition;
import pdp.domain.PdpPolicyViolation;
import pdp.mail.MailBox;
import pdp.manage.Manage;
import pdp.policies.PolicyMissingServiceProviderValidator;
import pdp.repositories.PdpPolicyRepository;
import pdp.repositories.PdpPolicyViolationRepository;
import pdp.stats.StatsContext;
import pdp.stats.StatsContextHolder;
import pdp.xacml.PDPEngineHolder;
import pdp.xacml.PdpPolicyDefinitionParser;
import pdp.xacml.PolicyTemplateEngine;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.apache.openaz.xacml.api.Decision.DENY;
import static org.apache.openaz.xacml.api.Decision.INDETERMINATE;
import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.OPTIONS;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import static pdp.access.PolicyAccess.READ;
import static pdp.access.PolicyAccess.VIOLATIONS;
import static pdp.access.PolicyAccess.WRITE;
import static pdp.util.StreamUtils.singletonCollector;
import static pdp.util.StreamUtils.singletonOptionalCollector;
@RestController
@RequestMapping(headers = {"Content-Type=application/json"}, produces = {"application/json"})
public class PdpController implements JsonMapper, IPAddressProvider {
private final static Logger LOG = LoggerFactory.getLogger(PdpController.class);
private final PDPEngineHolder pdpEngineHolder;
private final PdpPolicyViolationRepository pdpPolicyViolationRepository;
private final PdpPolicyRepository pdpPolicyRepository;
private final PolicyTemplateEngine policyTemplateEngine = new PolicyTemplateEngine();
private final PdpPolicyDefinitionParser pdpPolicyDefinitionParser = new PdpPolicyDefinitionParser();
private final PolicyConflictService policyConflictService = new PolicyConflictService();
private final Manage manage;
private final PolicyIdpAccessEnforcer policyIdpAccessEnforcer = new PolicyIdpAccessEnforcer();
private final PDPEngine playgroundPdpEngine;
private final boolean cachePolicies;
private final MailBox mailBox;
private final PolicyMissingServiceProviderValidator policyMissingServiceProviderValidator;
private final List<String> loaLevels;
// Can't be final as we need to swap this reference for reloading policies in production
private volatile PDPEngine pdpEngine;
@Autowired
public PdpController(@Value("${period.policies.refresh.minutes}") int period,
@Value("${policies.cachePolicies}") boolean cachePolicies,
@Value("${loa.levels}") String loaLevelsCommaSeparated,
PdpPolicyViolationRepository pdpPolicyViolationRepository,
PdpPolicyRepository pdpPolicyRepository,
PDPEngineHolder pdpEngineHolder,
Manage manage,
MailBox mailBox,
PolicyMissingServiceProviderValidator policyMissingServiceProviderValidator) {
this.cachePolicies = cachePolicies;
this.loaLevels = Stream.of(loaLevelsCommaSeparated.split(",")).map(String::trim).collect(toList());
this.pdpEngineHolder = pdpEngineHolder;
this.playgroundPdpEngine = pdpEngineHolder.newPdpEngine(false, true);
this.pdpEngine = pdpEngineHolder.newPdpEngine(cachePolicies, false);
this.pdpPolicyViolationRepository = pdpPolicyViolationRepository;
this.pdpPolicyRepository = pdpPolicyRepository;
this.manage = manage;
this.mailBox = mailBox;
this.policyMissingServiceProviderValidator = policyMissingServiceProviderValidator;
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
TaskUtils.decorateTaskWithErrorHandler(this::refreshPolicies, t -> LOG.error("Exception in refreshPolicies task", t), true),
period, period, TimeUnit.MINUTES);
}
@RequestMapping(method = RequestMethod.POST, value = "/decide/policy")
public String decide(@RequestBody String payload) throws Exception {
return doDecide(payload, false);
}
@RequestMapping(method = RequestMethod.POST, value = "/internal/decide/policy")
public String decideInternal(@RequestBody String payload) throws Exception {
refreshPolicies();
return doDecide(payload, true);
}
private String doDecide(String payload, boolean isPlayground) throws Exception {
StatsContext stats = StatsContextHolder.getContext();
long start = System.currentTimeMillis();
LOG.debug("decide request: {}", payload);
Request request = JSONRequest.load(payload);
addStatsDetails(stats, request);
returnPolicyIdInList(request);
Response pdpResponse = isPlayground ? playgroundPdpEngine.decide(request) : pdpEngine.decide(request);
String response = JSONResponse.toString(pdpResponse, LOG.isDebugEnabled());
long took = System.currentTimeMillis() - start;
stats.setResponseTimeMs(took);
LOG.debug("decide response: {} took: {} ms", response, took);
reportPossiblePolicyViolation(pdpResponse, response, payload, isPlayground);
provideStatsContext(stats, pdpResponse);
return response;
}
private void returnPolicyIdInList(Request request) {
StdRequest.class.cast(request);
Field field = ReflectionUtils.findField(Wrapper.class, "wrappedObject");
ReflectionUtils.makeAccessible(field);
StdMutableRequest mutableRequest = StdMutableRequest.class.cast(ReflectionUtils.getField(field, request));
mutableRequest.setReturnPolicyIdList(true);
StdMutableRequestAttributes requestAttributes = (StdMutableRequestAttributes) mutableRequest.getRequestAttributes().stream().filter(requestAttribute ->
requestAttribute.getCategory().getUri().toString().equals("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"))
.findFirst().get();
Collection<Attribute> attributes = requestAttributes.getAttributes();
boolean clientIDPresent = attributes.stream().anyMatch(attribute -> attribute.getAttributeId().getUri().toString().equals("ClientID"));
if (!clientIDPresent) {
requestAttributes.add(new StdAttribute(
new StdMutableAttribute(
new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"),
new IdentifierImpl("ClientID"),
new StdAttributeValue<>(
new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string"),
"EngineBlock")
)));
}
}
private void provideStatsContext(StatsContext stats, Response pdpResponse) {
Result result = pdpResponse.getResults().iterator().next();
stats.setDecision(result.getDecision().toString());
Optional<String> optionalLoa = getOptionalLoa(pdpResponse);
optionalLoa.ifPresent(stats::setLoa);
Optional<IdReference> optionalPolicyId = getPolicyId(result);
optionalPolicyId.ifPresent(policyId -> stats.setPolicyId(policyId.getId().getUri().toString()));
}
@RequestMapping(method = OPTIONS, value = "/protected/policies")
public ResponseEntity<Void> options(HttpServletResponse response) {
response.setHeader(HttpHeaders.ALLOW, Joiner.on(",").join(ImmutableList.of(GET, POST, PUT, DELETE)));
return new ResponseEntity<>(HttpStatus.OK);
}
@RequestMapping(method = GET, value = {"/internal/policies", "/protected/policies"})
public List<PdpPolicyDefinition> policyDefinitions() {
List<PdpPolicyDefinition> policies = pdpPolicyRepository.findAll().stream()
.map(policy -> {
PdpPolicyDefinition pdpPolicyDefinition = pdpPolicyDefinitionParser.parse(policy);
return addAccessRules(policy, pdpPolicyDefinition);
}).collect(toList());
policies = policyMissingServiceProviderValidator.addEntityMetaData(policies);
policies = policies.stream().filter(policy -> !policy.isServiceProviderInvalidOrMissing()).collect(toList());
List<Object[]> countPerPolicyId = pdpPolicyViolationRepository.findCountPerPolicyId();
Map<Long, Long> countPerPolicyIdMap = countPerPolicyId.stream().collect(toMap((obj) -> (Long) obj[0], (obj) -> (Long) obj[1]));
policies.forEach(policy -> policy.setNumberOfViolations(countPerPolicyIdMap.getOrDefault(policy.getId(), 0L).intValue()));
List<Object[]> revisionCountPerId = pdpPolicyRepository.findRevisionCountPerId();
Map<Number, Number> revisionCountPerIdMap = revisionCountPerId.stream().collect(toMap((obj) -> (Number) obj[0], (obj) -> (Number) obj[1]));
policies.forEach(policy -> policy.setNumberOfRevisions(revisionCountPerIdMap.getOrDefault(policy.getId().intValue(), 0).intValue()));
return policyIdpAccessEnforcer.filterPdpPolicies(policies);
}
@RequestMapping(method = GET, value = {"/internal/conflicts", "/protected/conflicts"})
public Map<String, List<PdpPolicyDefinition>> conflicts() {
return doConflicts(true);
}
private Map<String, List<PdpPolicyDefinition>> doConflicts(boolean includeInvalid) {
List<PdpPolicyDefinition> policies = pdpPolicyRepository.findAll().stream()
.map(policy -> pdpPolicyDefinitionParser.parse(policy)).collect(toList());
policies = policyMissingServiceProviderValidator.addEntityMetaData(policies);
Map<String, List<PdpPolicyDefinition>> conflicts = policyConflictService.conflicts(policies);
if (includeInvalid) {
List<PdpPolicyDefinition> invalid = policies.stream()
.filter(PdpPolicyDefinition::isServiceProviderInvalidOrMissing).collect(toList());
if (!invalid.isEmpty()) {
conflicts.put("EntityID not present in Manage", invalid);
}
}
return conflicts;
}
@RequestMapping(method = {PUT, POST}, value = {"/internal/policies", "/protected/policies"})
public PdpPolicy createPdpPolicy(@RequestBody PdpPolicyDefinition pdpPolicyDefinition) {
String policyXml = policyTemplateEngine.createPolicyXml(pdpPolicyDefinition);
//if this works then we know the input was correct
Policy parsedPolicy = pdpPolicyDefinitionParser.parsePolicy(policyXml);
Assert.notNull(parsedPolicy, "ParsedPolicy is not valid");
PdpPolicy policy;
if (pdpPolicyDefinition.getId() != null) {
PdpPolicy fromDB = findPolicyById(pdpPolicyDefinition.getId(), WRITE);
policy = fromDB.getParentPolicy() != null ? fromDB.getParentPolicy() : fromDB;
//Cascade.ALL
PdpPolicy.revision(pdpPolicyDefinition.getName(), policy, policyXml, policyIdpAccessEnforcer.username(),
policyIdpAccessEnforcer.userDisplayName(), pdpPolicyDefinition.isActive());
} else {
policy = new PdpPolicy(policyXml, pdpPolicyDefinition.getName(), true, policyIdpAccessEnforcer.username(),
policyIdpAccessEnforcer.authenticatingAuthority(), policyIdpAccessEnforcer.userDisplayName(), pdpPolicyDefinition.isActive(),
pdpPolicyDefinition.getType());
//this will throw an Exception if it is not allowed
policyIdpAccessEnforcer.actionAllowed(policy, PolicyAccess.WRITE, pdpPolicyDefinition.getServiceProviderId(), pdpPolicyDefinition.getIdentityProviderIds());
}
try {
PdpPolicy saved = pdpPolicyRepository.save(policy);
LOG.info("{} PdpPolicy {}", policy.getId() != null ? "Updated" : "Created", saved.getPolicyXml());
checkConflicts(pdpPolicyDefinition);
return saved;
} catch (DataIntegrityViolationException e) {
if (e.getMessage().contains("pdp_policy_name_revision_unique")) {
throw new PdpPolicyException("name", "Policy name must be unique. " + pdpPolicyDefinition.getName() + " is already taken");
} else {
throw e;
}
}
}
private void checkConflicts(PdpPolicyDefinition pdpPolicyDefinition) {
Map<String, List<PdpPolicyDefinition>> conflicts = this.doConflicts(false);
Optional<EntityMetaData> entityMetaData = manage.serviceProviderOptionalByEntityId(pdpPolicyDefinition.getServiceProviderId());
if (entityMetaData.isPresent() && conflicts.containsKey(entityMetaData.get().getNameEn())) {
this.mailBox.sendConflictsMail(conflicts);
}
}
@RequestMapping(method = GET, value = {"/internal/policies/{id}", "/protected/policies/{id}"})
public PdpPolicyDefinition policyDefinition(@PathVariable Long id) {
PdpPolicy policyById = findPolicyById(id, READ);
PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(policyById);
policyDefinition = policyMissingServiceProviderValidator.addEntityMetaData(Collections.singletonList(policyDefinition)).get(0);
if (policyDefinition.getType().equals("step")) {
policyDefinition.getLoas().forEach(loa -> loa.getCidrNotations()
.forEach(notation -> notation.setIpInfo(getIpInfo(notation.getIpAddress(), notation.getPrefix()))));
}
if (!policyById.isLatestRevision()) {
PdpPolicy latestPolicy =
policyById.getRevisions().stream().max(Comparator.comparing(PdpPolicy::getRevisionNbr)).get();
policyDefinition.setParentId(latestPolicy.getId());
}
return policyDefinition;
}
@RequestMapping(method = DELETE, value = {"/internal/policies/{id}", "/protected/policies/{id}"})
public void deletePdpPolicy(@PathVariable Long id) {
PdpPolicy policy = findPolicyById(id, PolicyAccess.WRITE);
LOG.info("Deleting PdpPolicy {}", policy.getName());
policy = policy.getParentPolicy() != null ? policy.getParentPolicy() : policy;
pdpPolicyRepository.delete(policy);
}
@RequestMapping(method = GET, value = "/internal/default-policy/{type}")
public PdpPolicyDefinition defaultPolicy(@PathVariable String type) {
PdpPolicyDefinition pdpPolicyDefinition = new PdpPolicyDefinition();
pdpPolicyDefinition.setType(type);
return pdpPolicyDefinition;
}
@RequestMapping(method = GET, value = "/internal/policies/sp")
public List<PdpPolicyDefinition> policyDefinitionsByServiceProvider(@RequestParam String serviceProvider) {
List<PdpPolicyDefinition> policies = policyDefinitions();
List<PdpPolicyDefinition> filterBySp = policies.stream().filter(policy -> policy.getServiceProviderId().equals(serviceProvider)).collect(toList());
return policyIdpAccessEnforcer.filterPdpPolicies(filterBySp);
}
@RequestMapping(method = GET, value = "/internal/violations")
public Iterable<PdpPolicyViolation> violations() {
Iterable<PdpPolicyViolation> violations = pdpPolicyViolationRepository.findAll();
return policyIdpAccessEnforcer.filterViolations(violations);
}
@RequestMapping(method = GET, value = "/internal/violations/{id}")
public Iterable<PdpPolicyViolation> violationsByPolicyId(@PathVariable Long id) {
Set<PdpPolicyViolation> violations = findPolicyById(id, VIOLATIONS).getViolations();
return policyIdpAccessEnforcer.filterViolations(violations);
}
@RequestMapping(method = GET, value = {"/internal/revisions/{id}", "/protected/revisions/{id}"})
public List<PdpPolicyDefinition> revisionsByPolicyId(@PathVariable Long id) {
PdpPolicy policy = findPolicyById(id, PolicyAccess.READ);
PdpPolicy parent = (policy.getParentPolicy() != null ? policy.getParentPolicy() : policy);
Set<PdpPolicy> policies = parent.getRevisions();
policies.add(parent);
List<PdpPolicyDefinition> definitions = policies.stream().map(rev -> {
PdpPolicyDefinition def = pdpPolicyDefinitionParser.parse(rev);
return addAccessRules(rev, def);
}).collect(toList());
return policyMissingServiceProviderValidator.addEntityMetaData(definitions);
}
@RequestMapping(method = GET, value = {"/internal/loas", "/protected/loas"})
public List<String> allowedLevelOfAssurances() {
return this.loaLevels;
}
@RequestMapping(method = GET, value = {"/internal/attributes", "/protected/attributes"})
public List<JsonPolicyRequest.Attribute> allowedAttributes() throws IOException {
InputStream inputStream = new ClassPathResource("xacml/attributes/allowed_attributes.json").getInputStream();
CollectionType type = objectMapper.getTypeFactory().constructCollectionType(List.class, JsonPolicyRequest.Attribute.class);
return objectMapper.readValue(inputStream, type);
}
@RequestMapping(method = GET, value = "/internal/saml-attributes")
public List<JsonPolicyRequest.Attribute> allowedSamlAttributes() throws IOException {
InputStream inputStream = new ClassPathResource("xacml/attributes/extra_saml_attributes.json").getInputStream();
CollectionType type = objectMapper.getTypeFactory().constructCollectionType(List.class, JsonPolicyRequest.Attribute.class);
List<JsonPolicyRequest.Attribute> attributes = objectMapper.readValue(inputStream, type);
attributes.addAll(allowedAttributes());
return attributes;
}
private PdpPolicy findPolicyById(Long id, PolicyAccess policyAccess) {
PdpPolicy policy = pdpPolicyRepository.findOne(id);
if (policy == null) {
throw new PolicyNotFoundException("PdpPolicy with id " + id + " not found");
}
PdpPolicyDefinition definition = pdpPolicyDefinitionParser.parse(policy);
//this will throw an Exception if it is not allowed
policyIdpAccessEnforcer.actionAllowed(policy, policyAccess, definition.getServiceProviderId(), definition.getIdentityProviderIds());
return policy;
}
private PdpPolicyDefinition addAccessRules(PdpPolicy policy, PdpPolicyDefinition pd) {
boolean actionsAllowed = policyIdpAccessEnforcer.actionAllowedIndicator(policy, PolicyAccess.WRITE, pd.getServiceProviderId(), pd.getIdentityProviderIds());
pd.setActionsAllowed(actionsAllowed);
return pd;
}
private void addStatsDetails(StatsContext stats, Request request) {
RequestAttributes req = request.getRequestAttributes().stream()
.filter(ra -> ra.getCategory().getUri().toString().equals("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"))
.collect(singletonCollector());
Collection<Attribute> attributes = req.getAttributes();
stats.setIdentityProvider(getAttributeValue(attributes, "IDPentityID").orElse(""));
stats.setServiceProvicer(getAttributeValue(attributes, "SPentityID").orElse(""));
}
private Optional<String> getAttributeValue(Collection<Attribute> attributes, String attributeId) {
Optional<Attribute> attribute = attributes.stream().filter(attr -> attr.getAttributeId().getUri().toString().equals(attributeId)).collect(singletonOptionalCollector());
return attribute.map(attr -> (String) attr.getValues().iterator().next().getValue());
}
private void reportPossiblePolicyViolation(Response pdpResponse, String response, String payload, boolean isPlayground) {
Collection<Result> results = pdpResponse.getResults();
Optional<Result> deniesOrIndeterminate = results.stream().filter(result ->
result.getDecision().equals(DENY) || result.getDecision().equals(INDETERMINATE)).findAny();
deniesOrIndeterminate.ifPresent(result -> {
Optional<IdReference> idReferenceOptional = getPolicyId(result);
idReferenceOptional.ifPresent(idReference -> {
String policyId = idReference.getId().stringValue();
Optional<PdpPolicy> policyOptional = pdpPolicyRepository.findFirstByPolicyIdAndLatestRevision(policyId, true);
policyOptional.ifPresent(policy -> pdpPolicyViolationRepository.save(new PdpPolicyViolation(policy, payload, response, isPlayground)));
});
});
}
private Optional<String> getOptionalLoa(Response pdpResponse) {
return pdpResponse.getResults().stream().map(result -> result.getObligations().stream()
.map(obligation -> obligation.getAttributeAssignments().stream()
.map(attributeAssignment -> String.class.cast(attributeAssignment.getAttributeValue().getValue()))))
.flatMap(Function.identity())
.flatMap(Function.identity())
.max(Comparator.naturalOrder());
}
private Optional<IdReference> getPolicyId(Result deniesOrIndeterminate) {
Collection<IdReference> policyIdentifiers = deniesOrIndeterminate.getPolicyIdentifiers();
Collection<IdReference> policySetIdentifiers = deniesOrIndeterminate.getPolicySetIdentifiers();
return !CollectionUtils.isEmpty(policyIdentifiers) ?
policyIdentifiers.stream().collect(singletonOptionalCollector()) :
policySetIdentifiers.stream().collect(singletonOptionalCollector());
}
private void refreshPolicies() {
LOG.info("Starting reloading policies");
long start = System.currentTimeMillis();
this.pdpEngine = pdpEngineHolder.newPdpEngine(cachePolicies, false);
LOG.info("Finished reloading policies in {} ms", System.currentTimeMillis() - start);
}
}
|
package org.mvel.tests;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.mvel.MVEL;
public class DroolsTest extends TestCase {
public void test1() throws Exception {
MVEL.executeExpression( MVEL.compileExpression( "new Integer(5)" ),
null, new HashMap() );
}
public void test2() throws Exception {
String str = (String) MVEL.executeExpression( MVEL.compileExpression( "\"hello2\"" ),
null,
new HashMap());
System.out.println( str );
}
public void test3() throws Exception {
String str = (String) MVEL.executeExpression( MVEL.compileExpression( "new String(\"hello2\")" ),
null,
new HashMap());
System.out.println( str );
}
}
|
package net.sf.clirr.event;
import java.util.Locale;
import junit.framework.TestCase;
/**
* Tests for the Message and MessageManager classes.
* <p>
* It is assumed here that the other unit tests have forced every Check
* class to be loaded into memory, hence all the static Message objects
* have been created and registered with the MessageManager.
*/
public class MessageTest extends TestCase
{
/**
* This test verifies that none of the check classes has used
* a message-id which is already in use elsewhere. It is assumed
* that the other unit tests will already have caused every available
* check class to be loaded into memory, therefore causing all the
* static Message objects to be created.
*/
public void testUnique()
{
MessageManager.getInstance().checkUnique();
}
/**
* This test verifies that the default resource bundle contains an
* entry for every known message.
* <p>
* Unfortunately, it is not possible to check whether, for example,
* the "de" locale has a complete set of translations. This is because
* the ResourceBundle implementation simply returns a string from an
* inherited "parent" resource bundle if the key is not found in a
* locale-specific bundle, and there is no way of telling which
* bundle the message was retrieved from.
*/
public void testComplete()
{
java.util.Collection messages = MessageManager.getInstance().getMessages();
// check the english locale
MessageTranslator translator = new MessageTranslator();
translator.setLocale(Locale.ENGLISH);
translator.checkComplete(messages);
}
}
|
package com.baidu.cafe.record;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import com.baidu.cafe.local.LocalLib;
import com.baidu.cafe.local.Log;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
/**
* @author luxiaoyu01@baidu.com
* @date 2012-11-8
* @version
* @todo
*/
public class ViewRecorder {
private HashMap<String, OnClickListener> mOnClickListeners = new HashMap<String, OnClickListener>();
private HashMap<String, OnLongClickListener> mOnLongClickListeners = new HashMap<String, OnLongClickListener>();
private HashMap<String, OnTouchListener> mOnTouchListeners = new HashMap<String, OnTouchListener>();
private HashMap<String, OnKeyListener> mOnKeyListeners = new HashMap<String, OnKeyListener>();
private HashMap<String, OnItemClickListener> mOnItemClickListeners = new HashMap<String, OnItemClickListener>();
private HashMap<String, OnItemLongClickListener> mOnItemLongClickListeners = new HashMap<String, OnItemLongClickListener>();
private HashMap<String, OnItemSelectedListener> mOnItemSelectedListeners = new HashMap<String, OnItemSelectedListener>();
private ArrayList<String> mAllViews = new ArrayList<String>();
private ArrayList<Integer> mAllListenerHashcodes = new ArrayList<Integer>();
private ArrayList<EditText> mAllEditTexts = new ArrayList<EditText>();
private Queue<RecordMotionEvent> mMotionEventQueue = new LinkedList<RecordMotionEvent>();
private LocalLib local = null;
private File mRecord = null;
public ViewRecorder(LocalLib local) {
this.local = local;
init();
}
class RecordMotionEvent {
public View view;
public float x;
public float y;
public int action;
public RecordMotionEvent(View view, int action, float x, float y) {
this.view = view;
this.x = x;
this.y = y;
this.action = action;
}
@Override
public String toString() {
return String
.format("RecordMotionEvent(%s, action=%s, x=%s, y=%s)", view, action, x, y);
}
}
class printEvent {
// public
}
private void print(String message) {
if (Log.IS_DEBUG) {
Log.i("ViewRecorder", message);
}
}
private void init() {
String path = "/data/data/" + local.getCurrentActivity().getPackageName() + "/cafe";
File cafe = new File(path);
if (!cafe.exists()) {
cafe.mkdir();
local.executeOnDevice("chmod 777 " + path, "/");
}
mRecord = new File(path + "/record");
if (mRecord.exists()) {
mRecord.delete();
}
}
/**
* add listeners on all views for generating cafe code automatically
*/
public void beginRecordCode() {
// keep hooking new views
new Thread(new Runnable() {
public void run() {
while (true) {
ArrayList<View> newViews = getTargetViews(local.getCurrentViews());
// print("newViews=" + newViews.size());
for (View view : newViews) {
try {
setHookListenerOnView(view);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
handleRecordMotionEventQueue();
}
private ArrayList<View> getTargetViews(ArrayList<View> views) {
ArrayList<View> targetViews = new ArrayList<View>();
for (View view : views) {
// get new views
String viewID = getViewID(view);
if (!mAllViews.contains(viewID)) {
targetViews.add(view);
mAllViews.add(viewID);
} else {
// get views who have unhooked listeners
if (hasUnhookedListener(view)) {
targetViews.add(view);
}
}
}
return targetViews;
}
private boolean hasUnhookedListener(View view) {
String[] listenerNames = new String[] { "mOnItemClickListener", "mOnClickListener",
"mOnTouchListener" };
for (String listenerName : listenerNames) {
Object listener = local.getListener(view, listenerName);
if (listener != null && !mAllListenerHashcodes.contains(listener.hashCode())) {
// print("has unhooked " + listenerName + ": " + view);
return true;
}
}
return false;
}
private boolean hasHookedListener(View view, String listenerName) {
Object listener = local.getListener(view, listenerName);
if (listener != null && mAllListenerHashcodes.contains(listener.hashCode())) {
return true;
}
return false;
}
private void setHookListenerOnView(View view) {
if (view instanceof AdapterView) {
print("AdapterView [" + view + "]");
hookOnItemClickListener((AdapterView) view);
// adapterView.setOnItemLongClickListener(listener);
// adapterView.setOnItemSelectedListener(listener);
// MenuItem.OnMenuItemClickListener
}
if (view instanceof EditText) {
print("EditText [" + view + "]");
hookEditText((EditText) view);
return;
}
if (!hookOnClickListener(view)) {
// If view has ClickListener, do not add a TouchListener.
hookOnTouchListener(view);
}
/*
mOnLongClickListener = (OnLongClickListener) local.getListener(view, "mOnLongClickListener");
if (null != mOnLongClickListener) {
view.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
print("id:" + v.getId() + "\t long_click");
mOnLongClickListener.onLongClick(v);
return false;
}
});
}
*/
}
private void hookEditText(EditText editText) {
if (mAllEditTexts.contains(editText)) {
return;
}
// all TextWatcher works at the same time
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
print("text:" + s);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
print("hookEditText [" + editText + "]");
mAllEditTexts.add(editText);
}
private boolean hookOnClickListener(View view) {
if (hasHookedListener(view, "mOnClickListener")) {
return true;
}
OnClickListener onClickListener = (OnClickListener) local.getListener(view,
"mOnClickListener");
if (null != onClickListener) {
print("hookClickListener [" + view + "(" + local.getViewText(view) + ")]");
// save old listener
mOnClickListeners.put(getViewID(view), onClickListener);
// set hook listener
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String code = "//view.text=" + local.getViewText(v) + "\n" + "clickOnView(" + v
+ ");";
print(code);
writeToFile(String.format("local.clickOn(viewClass, index);", v.getClass(),
local.getCurrentViewIndex(v)));
OnClickListener onClickListener = mOnClickListeners.get(getViewID(v));
if (onClickListener != null) {
onClickListener.onClick(v);
} else {
print("onClickListener == null");
}
}
});
// save hashcode of hooked listener
OnClickListener onClickListenerHooked = (OnClickListener) local.getListener(view,
"mOnClickListener");
if (onClickListenerHooked != null) {
mAllListenerHashcodes.add(onClickListenerHooked.hashCode());
}
return true;
}
return false;
}
private void hookOnTouchListener(View view) {
if (hasHookedListener(view, "mOnTouchListener")) {
return;
}
OnTouchListener onTouchListener = (OnTouchListener) local.getListener(view,
"mOnTouchListener");
// print("hookOnTouchListener [" + view + "(" + local.getViewText(view) + ")]"
// + (view instanceof ViewGroup ? "ViewGroup" : "View"));
if (null != onTouchListener) {
// save old listener
mOnTouchListeners.put(getViewID(view), onTouchListener);
// set hook listener
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
OnTouchListener onTouchListener = mOnTouchListeners.get(getViewID(v));
addEvent(v, event);
if (onTouchListener != null) {
onTouchListener.onTouch(v, event);
} else {
print("onTouchListener == null");
}
return false;
}
});
} else {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
addEvent(v, event);
return false;
}
});
}
// save hashcode of hooked listener
OnTouchListener onTouchListenerHooked = (OnTouchListener) local.getListener(view,
"mOnTouchListener");
if (onTouchListenerHooked != null) {
mAllListenerHashcodes.add(onTouchListenerHooked.hashCode());
}
}
private void hookOnItemClickListener(AdapterView view) {
if (hasHookedListener(view, "mOnItemClickListener")) {
return;
}
OnItemClickListener onItemClickListener = (OnItemClickListener) local.getListener(view,
"mOnItemClickListener");
if (null != onItemClickListener) {
print("hook AdapterView [" + view + "]");
// save old listener
mOnItemClickListeners.put(getViewID(view), onItemClickListener);
// set hook listener
view.setOnItemClickListener(new OnItemClickListener() {
/**
* Callback method to be invoked when an item in this
* AdapterView has been clicked.
* <p>
* Implementers can call getItemAtPosition(position) if they
* need to access the data associated with the selected item.
*
* @param parent
* The AdapterView where the click happened.
* @param view
* The view within the AdapterView that was clicked
* (this will be a view provided by the adapter)
* @param position
* The position of the view in the adapter.
* @param id
* The row id of the item that was clicked.
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
print("parent: " + parent + " view: " + view + " position: " + position
+ " click ");
writeToFile(String.format("local.clickInList(%s, %s, false);", position,
local.getCurrentViewIndex(parent)));
OnItemClickListener onItemClickListener = mOnItemClickListeners
.get(getViewID(parent));
if (onItemClickListener != null) {
onItemClickListener.onItemClick(parent, view, position, id);
} else {
print("onItemClickListener == null");
}
}
});
// save hashcode of hooked listener
OnItemClickListener onItemClickListenerHooked = (OnItemClickListener) local
.getListener(view, "mOnItemClickListener");
if (onItemClickListenerHooked != null) {
mAllListenerHashcodes.add(onItemClickListenerHooked.hashCode());
}
} else {
print("onItemClickListener == null at [" + view + "]");
}
}
private void hookOnLongClickListener(View view) {
OnLongClickListener onLongClickListener = (OnLongClickListener) local.getListener(view,
"mOnLongClickListener");
if (null != onLongClickListener) {
print("hookOnLongClickListener [" + view + "(" + local.getViewText(view) + ")]");
mOnLongClickListeners.put(getViewID(view), onLongClickListener);
view.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return false;
}
});
}
}
private void addEvent(View v, MotionEvent event) {
if (!mMotionEventQueue.offer(new RecordMotionEvent(v, event.getAction(), event.getRawX(),
event.getRawY()))) {
print("Add to mMotionEventQueue Failed! view:" + v + "\t" + event.toString()
+ "mMotionEventQueue.size=" + mMotionEventQueue.size());
}
}
/**
* check mMotionEventQueue and merge MotionEvent to drag
*/
private void handleRecordMotionEventQueue() {
new Thread(new Runnable() {
@Override
public void run() {
ArrayList<RecordMotionEvent> events = new ArrayList<RecordMotionEvent>();
while (true) {
// find MotionEvent with ACTION_UP
RecordMotionEvent e = null;
boolean isUp = false;
while ((e = mMotionEventQueue.poll()) != null) {
events.add(e);
// print("" + e);
if (MotionEvent.ACTION_UP == e.action) {
isUp = true;
break;
}
}
if (isUp) {
// remove other views
View targetView = events.get(events.size() - 1).view;
ArrayList<RecordMotionEvent> aTouch = new ArrayList<RecordMotionEvent>();
for (RecordMotionEvent recordMotionEvent : events) {
if (recordMotionEvent.view.equals(targetView)) {
aTouch.add(recordMotionEvent);
}
}
mergeMotionEvents(aTouch);
events.clear();
}
try {
Thread.sleep(50);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}).start();
}
/**
* Merge events from ACTION_DOWN to ACTION_UP.
*
* @param events
*/
private void mergeMotionEvents(ArrayList<RecordMotionEvent> events) {
RecordMotionEvent down = events.get(0);
RecordMotionEvent up = events.get(events.size() - 1);
int stepCount = events.size() - 2;
print(String.format("Drag [%s] from (%s,%s) to (%s, %s) by step count %s", down.view,
down.x, down.y, up.x, up.y, stepCount));
writeToFile(String.format("local.drag(%s, %s, %s, %s, %s);", down.x, up.x, down.y, up.y,
stepCount));
}
private void hookOnItemSelectedListener(AdapterView view) {
}
/**
* for KeyEvent
*
* @param editText
*/
private void hookOnKeyListener(EditText editText) {
OnKeyListener onKeyListener = (OnKeyListener) local.getListener(editText, "mOnKeyListener");
if (null != onKeyListener) {
print("hookOnKeyListener [" + editText + "]");
mOnKeyListeners.put(getViewID(editText), onKeyListener);
editText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
OnKeyListener onKeyListener = mOnKeyListeners.get(getViewID(v));
print(event + " on " + v);
if (null != onKeyListener) {
onKeyListener.onKey(v, keyCode, event);
} else {
print("onKeyListener == null");
}
return false;
}
});
} else {
editText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
print(event + " new on " + v);
return false;
}
});
}
}
private String getViewID(View view) {
String viewString = view.toString();
return viewString.substring(viewString.indexOf("@"));
}
private void writeToFile(String line) {
if (null == line) {
return;
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(mRecord));
writer.write(line);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
|
package com.cloudbees.plugins.credentials;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.cloudbees.plugins.credentials.impl.BaseStandardCredentials;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.ExtensionList;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Job;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.StreamBuildListener;
import hudson.model.TaskListener;
import hudson.scm.ChangeLogParser;
import hudson.scm.ChangeLogSet;
import hudson.scm.PollingResult;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.tasks.Builder;
import hudson.triggers.SCMTrigger;
import hudson.triggers.Trigger;
import hudson.util.Secret;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.xml.sax.SAXException;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class CredentialsUnavailableExceptionTest {
@Rule
public JenkinsRule r = new JenkinsRule();
private CredentialsStore systemStore;
@Before
public void setUp() throws Exception {
SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(
SystemCredentialsProvider.ProviderImpl.class);
systemStore = system.getStore(r.getInstance());
List<Domain> domainList = new ArrayList<Domain>(systemStore.getDomains());
domainList.remove(Domain.global());
for (Domain d : domainList) {
systemStore.removeDomain(d);
}
List<Credentials> credentialsList = new ArrayList<Credentials>(systemStore.getCredentials(Domain.global()));
for (Credentials c : credentialsList) {
systemStore.removeCredentials(Domain.global(), c);
}
}
@Test
public void buildFailure() throws Exception {
systemStore.addCredentials(Domain.global(), new UsernameUnavailablePasswordImpl("buildFailure", "test", "foo"));
FreeStyleProject project = r.createFreeStyleProject();
project.getBuildersList().add(new PasswordBuildStep("buildFailure"));
FreeStyleBuild build = project.scheduleBuild2(0).get();
this.r.assertBuildStatus(Result.FAILURE, build);
this.r.assertLogContains("username: foo", build);
this.r.assertLogContains("Property 'password' is currently unavailable", build);
this.r.assertLogNotContains("Could not find", build);
this.r.assertLogNotContains("Extracted secret", build);
}
@Test
public void checkoutFailure() throws Exception {
systemStore.addCredentials(Domain.global(), new UsernameUnavailablePasswordImpl("checkoutFailure", "test", "bar"));
FreeStyleProject project = r.createFreeStyleProject();
project.setScm(new PasswordSCM("checkoutFailure"));
FreeStyleBuild build = project.scheduleBuild2(0).get();
this.r.assertBuildStatus(Result.FAILURE, build);
this.r.assertLogContains("user: bar", build);
this.r.assertLogContains("Property 'password' is currently unavailable", build);
this.r.assertLogNotContains("Could not find", build);
this.r.assertLogNotContains("Checking out with password", build);
}
@Test
public void pollingFailure() throws Exception {
UsernameUnavailablePasswordImpl credentials =
new UsernameUnavailablePasswordImpl("pollingFailure", "test", "manchu");
systemStore.addCredentials(Domain.global(),
credentials);
FreeStyleProject project = r.createFreeStyleProject();
project.setQuietPeriod(0);
// ensure we have a build so that polling doesn't trigger a build by accident
r.buildAndAssertSuccess(project);
project.setScm(new PasswordSCM("pollingFailure"));
SCMTrigger trigger = new SCMTrigger("* * * * *");
project.addTrigger(trigger);
trigger.start(project, true);
GregorianCalendar cal = new GregorianCalendar();
cal.add(Calendar.MINUTE, 1);
int number = project.getLastBuild().getNumber();
// now we trigger polling the first time...
Trigger.checkTriggers(cal);
// we should get here without an exception being thrown or else core is handling the runtime exceptions poorly
r.waitUntilNoActivity();
SCMTrigger.SCMAction action = getScmAction(trigger);
assertThat(action.getLog(), allOf(
containsString("Checking remote revision as user: manchu"),
containsString("Property 'password' is currently unavailable")));
assertThat("No new builds", project.getLastBuild().getNumber(), is(number));
cal.add(Calendar.MINUTE, 1);
// now we trigger polling the second time to verify that polling is not stuck
Trigger.checkTriggers(cal);
r.waitUntilNoActivity();
action = getScmAction(trigger);
assertThat(action.getLog(), allOf(
containsString("Checking remote revision as user: manchu"),
containsString("Property 'password' is currently unavailable")));
assertThat("No new builds", project.getLastBuild().getNumber(), is(number));
systemStore.updateCredentials(Domain.global(), credentials, new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "pollingFailure", "working", "manchu", "secret"));
// now we trigger polling the third time... now with working credentials
Trigger.checkTriggers(cal);
r.waitUntilNoActivity();
action = getScmAction(trigger);
assertThat(action.getLog(), allOf(
containsString("Checking remote revision as user: manchu"),
not(containsString("Property 'password' is currently unavailable")),
containsString("Checking remote revision with password: secret")));
assertThat("New build", project.getLastBuild().getNumber(), greaterThan(number));
}
private SCMTrigger.SCMAction getScmAction(SCMTrigger trigger) {
Collection<? extends Action> actions = trigger.getProjectActions();
for (Action a : actions) {
if (a instanceof SCMTrigger.SCMAction) {
return (SCMTrigger.SCMAction)a;
}
}
return null;
}
public static class PasswordSCM extends SCM {
private final String id;
public PasswordSCM(String id) {
this.id = id;
}
@Override
public boolean supportsPolling() {
return true;
}
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
@Override
public void checkout(@Nonnull Run<?, ?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace,
@Nonnull TaskListener listener, @javax.annotation.CheckForNull File changelogFile,
@javax.annotation.CheckForNull SCMRevisionState baseline)
throws IOException, InterruptedException {
StandardUsernamePasswordCredentials credentials =
CredentialsProvider.findCredentialById(this.id, StandardUsernamePasswordCredentials.class, build);
if (credentials == null) {
listener.getLogger().printf("Could not find credentials with id '%s'%n", id);
build.setResult(Result.UNSTABLE);
} else {
listener.getLogger().printf("Checking out as user: %s%n", credentials.getUsername());
Secret password = credentials.getPassword();
listener.getLogger().printf("Checking out with password: %s%n", password.getPlainText());
}
}
@Override
public SCMRevisionState calcRevisionsFromBuild(@Nonnull Run<?, ?> build, @Nullable FilePath workspace,
@Nullable Launcher launcher, @Nonnull TaskListener listener)
throws IOException, InterruptedException {
return new SCMRevisionState() {
@Override
public String getIconFileName() {
return "mock.png";
}
@Override
public String getDisplayName() {
return "mock";
}
@Override
public String getUrlName() {
return "mock";
}
};
}
@Override
public PollingResult compareRemoteRevisionWith(@Nonnull Job<?, ?> project, @Nullable Launcher launcher,
@Nullable FilePath workspace, @Nonnull TaskListener listener,
@Nonnull SCMRevisionState baseline)
throws IOException, InterruptedException {
StandardUsernamePasswordCredentials credentials = CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, project,
CredentialsProvider.getDefaultAuthenticationOf(project),
Collections.<DomainRequirement>emptyList()), CredentialsMatchers.withId(id));
if (credentials == null) {
throw new IOException(String.format("Could not find credentials with id '%s'", id));
} else {
listener.getLogger().printf("Checking remote revision as user: %s%n", credentials.getUsername());
Secret password = credentials.getPassword();
listener.getLogger()
.printf("Checking remote revision with password: %s%n", password.getPlainText());
}
return PollingResult.SIGNIFICANT;
}
@Override
public ChangeLogParser createChangeLogParser() {
return new ChangeLogParser() {
@Override
public ChangeLogSet<? extends ChangeLogSet.Entry> parse(Run build, RepositoryBrowser<?> browser,
File changelogFile)
throws IOException, SAXException {
return ChangeLogSet.createEmpty(build);
}
};
}
@TestExtension
public static class DescriptorImpl extends SCMDescriptor<PasswordSCM> {
public DescriptorImpl() {
super(RepositoryBrowser.class);
}
@Override
public String getDisplayName() {
return "Password SCM";
}
}
}
public static class PasswordBuildStep extends Builder {
private final String id;
public PasswordBuildStep(String id) {
this.id = id;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
StandardUsernamePasswordCredentials credentials =
CredentialsProvider.findCredentialById(this.id, StandardUsernamePasswordCredentials.class, build);
if (credentials == null) {
listener.getLogger().printf("Could not find credentials with id '%s'%n", id);
build.setResult(Result.UNSTABLE);
} else {
listener.getLogger().printf("Credentials with id '%s', username: %s%n", id, credentials.getUsername());
Secret password = credentials.getPassword();
listener.getLogger().printf("Extracted secret: %s%n", password.getPlainText());
}
return true;
}
@TestExtension
public static class DescriptorImpl extends Descriptor<Builder> {
@Override
public String getDisplayName() {
return "Password buildstep";
}
}
}
public static class UsernameUnavailablePasswordImpl extends BaseStandardCredentials implements StandardUsernamePasswordCredentials {
private final String username;
public UsernameUnavailablePasswordImpl(@CheckForNull String id, @CheckForNull String description,
String username) {
super(id, description);
this.username = username;
}
public UsernameUnavailablePasswordImpl(@CheckForNull CredentialsScope scope, @CheckForNull String id,
@CheckForNull String description, String username) {
super(scope, id, description);
this.username = username;
}
@NonNull
@Override
public Secret getPassword() {
throw new CredentialsUnavailableException("password");
}
@NonNull
@Override
public String getUsername() {
return username;
}
@TestExtension
public static class DescriptorImpl extends BaseStandardCredentialsDescriptor {
@Override
public String getDisplayName() {
return "Username and unavailable password";
}
}
}
}
|
/**
@author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
package cc.mallet.util;
// Math and statistics functions
public final class Maths {
// From libbow, dirichlet.c
// Written by Tom Minka <minka@stat.cmu.edu>
public static final double logGamma (double x)
{
double result, y, xnum, xden;
int i;
final double d1 = -5.772156649015328605195174e-1;
final double p1[] = {
4.945235359296727046734888e0, 2.018112620856775083915565e2,
2.290838373831346393026739e3, 1.131967205903380828685045e4,
2.855724635671635335736389e4, 3.848496228443793359990269e4,
2.637748787624195437963534e4, 7.225813979700288197698961e3
};
final double q1[] = {
6.748212550303777196073036e1, 1.113332393857199323513008e3,
7.738757056935398733233834e3, 2.763987074403340708898585e4,
5.499310206226157329794414e4, 6.161122180066002127833352e4,
3.635127591501940507276287e4, 8.785536302431013170870835e3
};
final double d2 = 4.227843350984671393993777e-1;
final double p2[] = {
4.974607845568932035012064e0, 5.424138599891070494101986e2,
1.550693864978364947665077e4, 1.847932904445632425417223e5,
1.088204769468828767498470e6, 3.338152967987029735917223e6,
5.106661678927352456275255e6, 3.074109054850539556250927e6
};
final double q2[] = {
1.830328399370592604055942e2, 7.765049321445005871323047e3,
1.331903827966074194402448e5, 1.136705821321969608938755e6,
5.267964117437946917577538e6, 1.346701454311101692290052e7,
1.782736530353274213975932e7, 9.533095591844353613395747e6
};
final double d4 = 1.791759469228055000094023e0;
final double p4[] = {
1.474502166059939948905062e4, 2.426813369486704502836312e6,
1.214755574045093227939592e8, 2.663432449630976949898078e9,
2.940378956634553899906876e10, 1.702665737765398868392998e11,
4.926125793377430887588120e11, 5.606251856223951465078242e11
};
final double q4[] = {
2.690530175870899333379843e3, 6.393885654300092398984238e5,
4.135599930241388052042842e7, 1.120872109616147941376570e9,
1.488613728678813811542398e10, 1.016803586272438228077304e11,
3.417476345507377132798597e11, 4.463158187419713286462081e11
};
final double c[] = {
-1.910444077728e-03, 8.4171387781295e-04,
-5.952379913043012e-04, 7.93650793500350248e-04,
-2.777777777777681622553e-03, 8.333333333333333331554247e-02,
5.7083835261e-03
};
final double a = 0.6796875;
if((x <= 0.5) || ((x > a) && (x <= 1.5))) {
if(x <= 0.5) {
result = -Math.log(x);
/* Test whether X < machine epsilon. */
if(x+1 == 1) {
return result;
}
}
else {
result = 0;
x = (x - 0.5) - 0.5;
}
xnum = 0;
xden = 1;
for(i=0;i<8;i++) {
xnum = xnum * x + p1[i];
xden = xden * x + q1[i];
}
result += x*(d1 + x*(xnum/xden));
}
else if((x <= a) || ((x > 1.5) && (x <= 4))) {
if(x <= a) {
result = -Math.log(x);
x = (x - 0.5) - 0.5;
}
else {
result = 0;
x -= 2;
}
xnum = 0;
xden = 1;
for(i=0;i<8;i++) {
xnum = xnum * x + p2[i];
xden = xden * x + q2[i];
}
result += x*(d2 + x*(xnum/xden));
}
else if(x <= 12) {
x -= 4;
xnum = 0;
xden = -1;
for(i=0;i<8;i++) {
xnum = xnum * x + p4[i];
xden = xden * x + q4[i];
}
result = d4 + x*(xnum/xden);
}
/* X > 12 */
else {
y = Math.log(x);
result = x*(y - 1) - y*0.5 + .9189385332046727417803297;
x = 1/x;
y = x*x;
xnum = c[6];
for(i=0;i<6;i++) {
xnum = xnum * y + c[i];
}
xnum *= x;
result += xnum;
}
return result;
}
// This is from "Numeric Recipes in C"
public static double oldLogGamma (double x) {
int j;
double y, tmp, ser;
double [] cof = {76.18009172947146, -86.50532032941677 ,
24.01409824083091, -1.231739572450155 ,
0.1208650973866179e-2, -0.5395239384953e-5};
y = x;
tmp = x + 5.5 - (x + 0.5) * Math.log (x + 5.5);
ser = 1.000000000190015;
for (j = 0; j <= 5; j++)
ser += cof[j] / ++y;
return Math.log (2.5066282746310005 * ser / x) - tmp;
}
public static double logBeta (double a, double b) {
return logGamma(a)+logGamma(b)-logGamma(a+b);
}
public static double beta (double a, double b) {
return Math.exp (logBeta(a,b));
}
public static double gamma (double x) {
return Math.exp (logGamma(x));
}
public static double factorial (int n) {
return Math.exp (logGamma(n+1));
}
public static double logFactorial (int n) {
return logGamma(n+1);
}
/**
* Computes p(x;n,p) where x~B(n,p)
*/
// Copied as the "classic" method from Catherine Loader.
// Fast and Accurate Computation of Binomial Probabilities.
// 2001. (This is not the fast and accurate version.)
public static double logBinom (int x, int n, double p)
{
return logFactorial (n) - logFactorial (x) - logFactorial (n - x)
+ (x*Math.log (p)) + ((n-x)*Math.log (1-p));
}
/**
* Vastly inefficient O(x) method to compute cdf of B(n,p)
*/
public static double pbinom (int x, int n, double p) {
double sum = Double.NEGATIVE_INFINITY;
for (int i = 0; i <= x; i++) {
sum = sumLogProb (sum, logBinom (i, n, p));
}
return Math.exp (sum);
}
public static double sigmod(double beta){
return (double)1.0/(1.0+Math.exp(-beta));
}
public static double sigmod_rev(double sig){
return (double)Math.log(sig/(1-sig));
}
public static double logit (double p)
{
return Math.log (p / (1 - p));
}
// Combination?
public static double numCombinations (int n, int r) {
return Math.exp (logFactorial(n)-logFactorial(r)-logFactorial(n-r));
}
// Permutation?
public static double numPermutations (int n, int r) {
return Math.exp (logFactorial(n)-logFactorial(r));
}
public static double cosh (double a)
{
if (a < 0)
return 0.5 * (Math.exp(-a) + Math.exp(a));
else
return 0.5 * (Math.exp(a) + Math.exp(-a));
}
public static double tanh (double a)
{
return (Math.exp(a) - Math.exp(-a)) / (Math.exp(a) + Math.exp(-a));
}
/**
* Numbers that are closer than this are considered equal
* by almostEquals.
*/
public static double EPSILON = 0.000001;
public static boolean almostEquals (double d1, double d2)
{
return almostEquals (d1, d2, EPSILON);
}
public static boolean almostEquals (double d1, double d2, double epsilon)
{
return Math.abs (d1 - d2) < epsilon;
}
public static boolean almostEquals (double[] d1, double[] d2, double eps)
{
for (int i = 0; i < d1.length; i++) {
double v1 = d1[i];
double v2 = d2[i];
if (!almostEquals (v1, v2, eps)) return false;
}
return true;
}
// gsc
/**
* Checks if <tt>min <= value <= max</tt>.
*/
public static boolean checkWithinRange(double value, double min, double max) {
return (value > min || almostEquals(value, min, EPSILON)) &&
(value < max || almostEquals(value, max, EPSILON));
}
public static final double log2 = Math.log(2);
// gsc
/**
* Returns the KL divergence, K(p1 || p2).
*
* The log is w.r.t. base 2. <p>
*
* *Note*: If any value in <tt>p2</tt> is <tt>0.0</tt> then the KL-divergence
* is <tt>infinite</tt>. Limin changes it to zero instead of infinite.
*
*/
public static double klDivergence(double[] p1, double[] p2) {
assert(p1.length == p2.length);
double klDiv = 0.0;
for (int i = 0; i < p1.length; ++i) {
if (p1[i] == 0) { continue; }
if (p2[i] == 0.0) { continue; } // Limin
klDiv += p1[i] * Math.log( p1[i] / p2[i] );
}
return klDiv / log2; // moved this division out of the loop -DM
}
// gsc
/**
* Returns the Jensen-Shannon divergence.
*/
public static double jensenShannonDivergence(double[] p1, double[] p2) {
assert(p1.length == p2.length);
double[] average = new double[p1.length];
for (int i = 0; i < p1.length; ++i) {
average[i] += (p1[i] + p2[i])/2;
}
return (klDivergence(p1, average) + klDivergence(p2, average))/2;
}
/**
* Returns the sum of two doubles expressed in log space,
* that is,
* <pre>
* sumLogProb = log (e^a + e^b)
* = log e^a(1 + e^(b-a))
* = a + log (1 + e^(b-a))
* </pre>
*
* By exponentiating <tt>b-a</tt>, we obtain better numerical precision than
* we would if we calculated <tt>e^a</tt> or <tt>e^b</tt> directly.
* <P>
* Note: This function is just like
* {@link cc.mallet.fst.Transducer#sumNegLogProb sumNegLogProb}
* in <TT>Transducer</TT>,
* except that the logs aren't negated.
*/
public static double sumLogProb (double a, double b)
{
if (a == Double.NEGATIVE_INFINITY)
return b;
else if (b == Double.NEGATIVE_INFINITY)
return a;
else if (b < a)
return a + Math.log (1 + Math.exp(b-a));
else
return b + Math.log (1 + Math.exp(a-b));
}
// Below from Stanford NLP package, SloppyMath.java
private static final double LOGTOLERANCE = 30.0;
/**
* Sums an array of numbers log(x1)...log(xn). This saves some of
* the unnecessary calls to Math.log in the two-argument version.
* <p>
* Note that this implementation IGNORES elements of the input
* array that are more than LOGTOLERANCE (currently 30.0) less
* than the maximum element.
* <p>
* Cursory testing makes me wonder if this is actually much faster than
* repeated use of the 2-argument version, however -cas.
* @param vals An array log(x1), log(x2), ..., log(xn)
* @return log(x1+x2+...+xn)
*/
public static double sumLogProb (double[] vals)
{
double max = Double.NEGATIVE_INFINITY;
int len = vals.length;
int maxidx = 0;
for (int i = 0; i < len; i++) {
if (vals[i] > max) {
max = vals[i];
maxidx = i;
}
}
boolean anyAdded = false;
double intermediate = 0.0;
double cutoff = max - LOGTOLERANCE;
for (int i = 0; i < maxidx; i++) {
if (vals[i] >= cutoff) {
anyAdded = true;
intermediate += Math.exp(vals[i] - max);
}
}
for (int i = maxidx + 1; i < len; i++) {
if (vals[i] >= cutoff) {
anyAdded = true;
intermediate += Math.exp(vals[i] - max);
}
}
if (anyAdded) {
return max + Math.log(1.0 + intermediate);
} else {
return max;
}
}
/**
* Returns the difference of two doubles expressed in log space,
* that is,
* <pre>
* sumLogProb = log (e^a - e^b)
* = log e^a(1 - e^(b-a))
* = a + log (1 - e^(b-a))
* </pre>
*
* By exponentiating <tt>b-a</tt>, we obtain better numerical precision than
* we would if we calculated <tt>e^a</tt> or <tt>e^b</tt> directly.
* <p>
* Returns <tt>NaN</tt> if b > a (so that log(e^a - e^b) is undefined).
*/
public static double subtractLogProb (double a, double b)
{
if (b == Double.NEGATIVE_INFINITY)
return a;
else
return a + Math.log (1 - Math.exp(b-a));
}
public static double getEntropy(double[] dist) {
double entropy = 0;
for (int i = 0; i < dist.length; i++) {
if (dist[i] != 0) {
entropy -= dist[i] * Math.log(dist[i]);
}
}
return entropy;
}
}
|
package Game;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Team {
private List<Player> players;
private List<Panel> panels;
private String name;
private List<Instruction> activeInstructions;
private int lives = 3;
private int time = 9;
/**
* @param name
*/
public Team(String name) {
this.name = name;
players = new ArrayList<Player>();
panels = new ArrayList<Panel>();
throw new UnsupportedOperationException();
}
public List<Player> getPlayers() {
return this.players;
}
public Collection<Panel> getPanels() {
return this.panels;
}
public String getName() {
return this.name;
}
public List<Instruction> getActiveInstructions() {
return this.activeInstructions;
}
public int getLives() {
return this.lives;
}
public int getTime() {
return this.time;
}
/**
* Checks if the list is empty or if the player is already in the team
* if there is a team and the person is not in it, the player is added to the team
* @param player
*/
public Player addPlayer(Player player) {
if (players.size() == 0 || !players.contains(player)) {
players.add(player);
player.setTeam(this);
return player;
}
player = null;
return player;
}
/**
* Removes player if it is in the team
* @param player
*/
public Player removePlayer(Player player) {
if (players.contains(player)) {
players.remove(player);
}
return player;
}
/**
* This method generates panels for the team based on the amount of players
* It can't contain the same panels.
*
* @param gamePanels this is a list of panels gotten from the Game
* @return panels this is a list of panels that is given to a team
*/
public List<Panel> generatePanels(List<Panel> gamePanels) {
for (Player player : players) {
List<Panel> panels = player.generatePanels(gamePanels);
gamePanels.removeAll(panels);
}
return panels;
}
/**
* @param amount
*/
public void changeLives(int amount) {
lives += amount;
}
/**
* @param amount
*/
public int changeTime(int amount) {
return time += amount;
}
public boolean hasChanged() {
// TODO - implement Team.hasChanged
throw new UnsupportedOperationException();
}
public boolean isAlive() {
// TODO - implement Team.isAlive
throw new UnsupportedOperationException();
}
}
|
package main.java;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import main.python.PyInterpreter;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.JList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.awt.event.ActionEvent;
public class HomeFrame extends JFrame {
private JPanel contentPane;
private JLabel lblYourGroceryList;
private JList list_recipe;
private JButton btnEdit;
private JButton btnDelete;
private JTextArea textArea_Url;
DefaultListModel recipeModel;
private JButton btnPaste;
/**
* Create the frame.
*/
public HomeFrame(final ListManager recipeManager) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{100, 180, 180, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblInstructions = new JLabel("Instructions:");
GridBagConstraints gbc_lblInstructions = new GridBagConstraints();
gbc_lblInstructions.insets = new Insets(0, 0, 5, 5);
gbc_lblInstructions.gridx = 0;
gbc_lblInstructions.gridy = 0;
contentPane.add(lblInstructions, gbc_lblInstructions);
lblYourGroceryList = new JLabel("Your Grocery List:");
GridBagConstraints gbc_lblYourGroceryList = new GridBagConstraints();
gbc_lblYourGroceryList.gridwidth = 2;
gbc_lblYourGroceryList.insets = new Insets(0, 0, 5, 0);
gbc_lblYourGroceryList.gridx = 1;
gbc_lblYourGroceryList.gridy = 0;
contentPane.add(lblYourGroceryList, gbc_lblYourGroceryList);
JLabel lblPasteUrlsInto = new JLabel("Paste URLs into the box below");
GridBagConstraints gbc_lblPasteUrlsInto = new GridBagConstraints();
gbc_lblPasteUrlsInto.anchor = GridBagConstraints.WEST;
gbc_lblPasteUrlsInto.insets = new Insets(0, 0, 5, 5);
gbc_lblPasteUrlsInto.gridx = 0;
gbc_lblPasteUrlsInto.gridy = 1;
contentPane.add(lblPasteUrlsInto, gbc_lblPasteUrlsInto);
recipeModel = recipeManager.getListModel();
list_recipe = new JList(recipeModel);
list_recipe.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list_recipe.setLayoutOrientation(JList.VERTICAL);
GridBagConstraints gbc_list_recipe = new GridBagConstraints();
gbc_list_recipe.gridwidth = 2;
gbc_list_recipe.insets = new Insets(0, 0, 5, 0);
gbc_list_recipe.gridheight = 2;
gbc_list_recipe.fill = GridBagConstraints.BOTH;
gbc_list_recipe.gridx = 1;
gbc_list_recipe.gridy = 1;
contentPane.add(list_recipe, gbc_list_recipe);
textArea_Url = new JTextArea();
textArea_Url.setLineWrap(true);
GridBagConstraints gbc_textArea_Url = new GridBagConstraints();
gbc_textArea_Url.insets = new Insets(0, 0, 5, 5);
gbc_textArea_Url.fill = GridBagConstraints.BOTH;
gbc_textArea_Url.gridx = 0;
gbc_textArea_Url.gridy = 2;
contentPane.add(textArea_Url, gbc_textArea_Url);
btnPaste = new JButton("Paste");
GridBagConstraints gbc_btnPaste = new GridBagConstraints();
gbc_btnPaste.insets = new Insets(0, 0, 0, 5);
gbc_btnPaste.gridx = 0;
gbc_btnPaste.gridy = 3;
contentPane.add(btnPaste, gbc_btnPaste);
btnEdit = new JButton("Edit...");
btnEdit.setEnabled(false);
GridBagConstraints gbc_btnEdit = new GridBagConstraints();
gbc_btnEdit.insets = new Insets(0, 0, 0, 5);
gbc_btnEdit.gridx = 1;
gbc_btnEdit.gridy = 3;
contentPane.add(btnEdit, gbc_btnEdit);
btnDelete = new JButton("Delete...");
btnDelete.setEnabled(false);
GridBagConstraints gbc_btnDelete = new GridBagConstraints();
gbc_btnDelete.gridx = 2;
gbc_btnDelete.gridy = 3;
contentPane.add(btnDelete, gbc_btnDelete);
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EditItemDialog dialog = new EditItemDialog();
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = list_recipe.getSelectedIndex();
recipeModel.remove(index);
int size = recipeModel.getSize();
if (size == 0){
btnDelete.setEnabled(false);
}
else{
if (index == size) { index
}
}
});
final Clipboard clipboard = this.getToolkit().getSystemClipboard();
btnPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Transferable clipData = clipboard.getContents(clipboard);
if (clipData != null) {
try {
if
(clipData.isDataFlavorSupported
(DataFlavor.stringFlavor)) {
String s = (String)(clipData.getTransferData(
DataFlavor.stringFlavor));
textArea_Url.replaceSelection(s);
}
} catch (UnsupportedFlavorException ufe) {
System.err.println("Flavor unsupported: " + ufe);
} catch (IOException ioe) {
System.err.println("Data not available: " + ioe);
}
}
}
});
class UrlListener implements DocumentListener{
private boolean isRunning;
public void changedUpdate(DocumentEvent e){check();}
public void removeUpdate(DocumentEvent e) {check();}
public void insertUpdate(DocumentEvent e) {check();}
private void check(){
if(isRunning){return;}
isRunning = true;
recipeManager.addUrl(textArea_Url.getText(), textArea_Url);
// SwingUtilities.invokeLater(new Runnable()
// public void run()
// textArea_Url.setText("");
// reset();
}
// protected void reset() {
// isRunning = false;
}
UrlListener urlListener = new UrlListener();
textArea_Url.getDocument().addDocumentListener(urlListener);
list_recipe.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list_recipe.getSelectedIndex() == -1) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
}
}
});
}
}
|
import java.io.IOException;
import java.util.Scanner;
public class PitRunner {
public void runMutation() throws IOException, InterruptedException {
String cp, OS = System.getProperty("os.name").toLowerCase();
if(OS.contains("win")){
|
package com.maven8919.chesschallenge.fengenerator.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.maven8919.chesschallenge.fengenerator.domain.Fen;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PgnToFenServiceTest {
@Autowired
private PgnToFenService pgnToFenService;
private File TWIC1157 = readPgnFileFromClasspath("/twic1157.pgn");
private String exampleGame = "1. d4 d5 2. Bf4 c5 3. e3 Nc6 4. c3 Nf6 5. Nd2 a6 6. Ngf3 cxd4 7. exd4 g6 8. h3 Bg7 9. Be2 O-O 10. O-O Ne8 11. Re1 Kh8 12. Bf1 f6 13. Qb3 e6 14. a4 Nd6 15. Rad1 Nf7 16. Bg3 b6 17. c4 Nh6 18. cxd5 exd5 19. Rc1 Bb7 20. Re6";
private String shortExampleGame = "1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 O-O 5. a3 Bxc3+ 6. Qxc3 d5 7. Nf3 b6";
@Test
public void twic1157ShouldReturn3043Games() {
assertEquals(3043, pgnToFenService.getAllGames(TWIC1157).size());
}
@Test
public void twic1157NumberOfGamesLongerThan10MovesShouldBe3020() {
List<String> allGames = pgnToFenService.getAllGames(TWIC1157);
assertEquals(3020, pgnToFenService.getGamesLongerThan10Moves(allGames).size());
assertThat(allGames.stream().map(String::trim).collect(Collectors.toList()).contains(exampleGame));
}
@Test
public void exampleGameShouldReturn21Fens() {
List<Fen> fens = pgnToFenService.getAllFens(exampleGame);
assertEquals(21, fens.size());
}
@Test
public void gameShorterThan10MovesShouldReturnEmptyList() {
List<Fen> fens = pgnToFenService.getAllFens(shortExampleGame);
assertEquals(0, fens.size());
}
private File readPgnFileFromClasspath(String pgnFileName) {
URL url = this.getClass().getResource(pgnFileName);
return new File(url.getFile());
}
}
|
package net.kerflyn.broceliand.test.configuration;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.jpa.JpaPersistModule;
import net.kerflyn.broceliand.configuration.ControllerModule;
import net.kerflyn.broceliand.configuration.RepositoryModule;
import net.kerflyn.broceliand.configuration.ServiceModule;
public class BroceliandTestConfiguration {
public static Injector newGuiceInjector() {
Injector injector = Guice.createInjector(
new JpaPersistModule("test-manager-pu"),
new ControllerModule(),
new ServiceModule(),
new RepositoryModule());
injector.getInstance(PersistenceInitializer.class);
return injector;
}
private static class PersistenceInitializer {
@Inject
public PersistenceInitializer(PersistService service) {
service.start();
}
}
}
|
package com.pdsuk.cordova.bluetoothle;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.UUID;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.io.UnsupportedEncodingException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.util.Base64;
import android.util.Log;
public class BluetoothLePlugin extends CordovaPlugin {
private CallbackContext connectCallback;
private CallbackContext disconnectCallback;
private CallbackContext onDeviceAddedCallback;
private CallbackContext onDeviceDroppedCallback;
private CallbackContext onAdapterStateChangedCallback;
private CallbackContext onCharacteristicValueChangedCallback;
private CallbackContext rssiCallback;
private CallbackContext deviceInfoCallback;
private Map<CallbackKey, CallbackContext> readWriteCallbacks;
private Map<String, BluetoothGatt> connectedGattServers;
private Context mContext;
private boolean mRegisteredReceiver = false;
private boolean mRegisteredPairingReceiver = false;
//Client Configuration UUID for notifying/indicating
private final UUID clientConfigurationDescriptorUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.connectedGattServers = new HashMap<String, BluetoothGatt>();
this.readWriteCallbacks = new HashMap<CallbackKey, CallbackContext>();
cordova.getActivity().registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
private String getLongUUID(String uuid) {
if (uuid.length() == 4) {
return "0000" + uuid + "-0000-1000-8000-00805f9b34fb";
}
return uuid;
}
@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callback) throws JSONException {
try {
if ("getAdapterState".equals(action)) {
getAdapterState(callback);
} else if ("startDiscovery".equals(action)) {
startDiscovery(callback);
} else if ("stopDiscovery".equals(action)) {
stopDiscovery(callback);
} else if ("connect".equals(action)) {
connect(args.getString(0), callback);
} else if ("disconnect".equals(action)) {
disconnect(args.getString(0), callback);
} else if ("isSupported".equals(action)) {
JSONObject result = new JSONObject();
result.put("isSupported", isSupported());
callback.success(result);
} else if ("isConnected".equals(action)) {
JSONObject result = new JSONObject();
result.put("isConnected", isConnected(args.getString(0)));
callback.success(result);
} else if ("_close".equals(action)) {
close(args.getString(0), callback);
} else if ("getService".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
getService(address, serviceId, callback);
} else if ("getServices".equals(action)) {
String address = args.getString(0);
getServices(address, callback);
} else if ("getDevice".equals(action)) {
String address = args.getString(0);
getDeviceInfo(address, callback);
} else if ("getCharacteristic".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
getCharacteristic(address, serviceId, characteristicId, callback);
} else if ("getCharacteristics".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
getCharacteristics(address, serviceId, callback);
} else if ("getIncludedServices".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
getIncludedServices(address, serviceId, callback);
} else if ("getDescriptor".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
String descriptorId = getLongUUID(args.getString(3));
getDescriptor(address, serviceId, characteristicId, descriptorId, callback);
} else if ("getDescriptors".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
getDescriptors(address, serviceId, characteristicId, callback);
} else if ("readCharacteristicValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
readCharacteristicValue(address, serviceId, characteristicId, callback);
} else if ("writeCharacteristicValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
byte[] value = Base64.decode(args.getString(3), Base64.NO_WRAP);
writeCharacteristicValue(address, serviceId, characteristicId, value, callback);
} else if ("startCharacteristicNotifications".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
startCharacteristicNotifications(address, serviceId, characteristicId, callback);
} else if ("stopCharacteristicNotifications".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
stopCharacteristicNotifications(address, serviceId, characteristicId, callback);
} else if ("readDescriptorValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
String descriptorId = getLongUUID(args.getString(3));
readDescriptorValue(address, serviceId, characteristicId, descriptorId, callback);
} else if ("writeDescriptorValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
String descriptorId = getLongUUID(args.getString(3));
byte[] value = Base64.decode(args.getString(3), Base64.NO_WRAP);
writeDescriptorValue(address, serviceId, characteristicId, descriptorId, value, callback);
} else if ("onDeviceAdded".equals(action)) {
onDeviceAddedCallback = callback;
} else if ("onDeviceDropped".equals(action)) {
onDeviceDroppedCallback = callback;
} else if ("onAdapterStateChanged".equals(action)) {
onAdapterStateChangedCallback = callback;
} else if ("onCharacteristicValueChanged".equals(action)) {
onCharacteristicValueChangedCallback = callback;
} else {
return false;
}
} catch (Exception e) {
callback.error(JSONObjects.asError(e));
}
return true;
}
private BluetoothManager getBluetoothManager() {
return (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
}
private BluetoothDevice getDevice(String address) throws Exception {
BluetoothManager bluetoothManager = (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothDevice device = bluetoothManager.getAdapter().getRemoteDevice(address);
if (device == null) {
throw new Exception("Unable to find device with address " + address);
}
return device;
}
private void getDeviceInfo(String address, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
deviceInfoCallback = callback;
boolean result = gatt.readRemoteRssi();
if (!result) {
throw new Exception("Could not initiate BluetoothGatt#readRemoteRssi. Android didn't tell us why either.");
}
}
private void getAdapterState(CallbackContext callback) {
BluetoothManager bluetoothManager = (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
callback.success(JSONObjects.asAdapter(bluetoothManager.getAdapter()));
}
private BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] ad) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
JSONObject obj = JSONObjects.asDevice(device, rssi, ad);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
pluginResult.setKeepCallback(true);
onDeviceAddedCallback.sendPluginResult(pluginResult);
}
});
}
};
private void startDiscovery(CallbackContext callback) throws Exception {
BluetoothManager bluetoothManager = getBluetoothManager();
boolean result = bluetoothManager.getAdapter().startLeScan(scanCallback);
if (!result) {
throw new Exception("Could not start scan (BluetoothAdapter#startLeScan). Android didn't tell us why either.");
}
callback.success();
}
private void stopDiscovery(CallbackContext callback) {
BluetoothManager bluetoothManager = getBluetoothManager();
bluetoothManager.getAdapter().stopLeScan(scanCallback);
callback.success();
}
private boolean isSupported() {
if (android.os.Build.VERSION.SDK_INT >= 18) {
return cordova.getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
return false;
}
private boolean isConnected(String address) {
BluetoothManager bluetoothManager = getBluetoothManager();
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER);
for (BluetoothDevice device : devices) {
if (device.getAddress().equals(address)) {
return true;
}
}
return false;
}
private BluetoothDevice getPairedDevice(final BluetoothAdapter adapter, String address) {
Set<BluetoothDevice> devices = adapter.getBondedDevices();
Iterator<BluetoothDevice> it = devices.iterator();
while (it.hasNext()) {
BluetoothDevice device = (BluetoothDevice) it.next();
if (address.equals(device.getAddress()))
return device;
}
return null;
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = BluetoothDevice.class.getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
Log.i("bluetoothle", "BondedDevice : removeBond()");
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
}
void pairDevice(BluetoothDevice device) {
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device, true);
byte[] passkey = ByteBuffer.allocate(6).putInt(000000).array();
Log.i("bluetoothle", "Passkey : " + passkey.toString());
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, passkey);
Method bond = device.getClass().getMethod("createBond", (Class[]) null);
bond.invoke(device, (Object[]) null);
Log.i("bluetoothle", "Bonded Device : remove()");
} catch (Exception e) {
e.printStackTrace();
}
}
private void connect(String address, CallbackContext callback) throws Exception {
if (isConnected(address)) {
callback.success();
return;
}
connectCallback = callback;
BluetoothDevice device = getDevice(address);
if (device.getBondState() == 12) {
}
BluetoothGatt gatt = device.connectGatt(cordova.getActivity().getApplicationContext(), false, gattCallback);
connectedGattServers.put(gatt.getDevice().getAddress(), gatt);
}
private void disconnect(String address, CallbackContext callback) throws Exception {
if (!isConnected(address)) {
callback.success();
return;
}
disconnectCallback = callback;
BluetoothGatt gatt = connectedGattServers.get(address);
gatt.disconnect();
}
private void close(String address, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
connectedGattServers.remove(gatt.getDevice().getAddress());
gatt.close();
if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED) {
connectedGattServers.remove(address);
}
callback.success();
}
private void getService(String address, String uuid, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(uuid));
if (service == null) {
throw new Exception(String.format("No service found with the given UUID %s", uuid));
}
callback.success(JSONObjects.asService(service, gatt.getDevice()));
}
private void getServices(String address, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
JSONArray result = new JSONArray();
for (BluetoothGattService s : gatt.getServices()) {
result.put(JSONObjects.asService(s, gatt.getDevice()));
}
callback.success(result);
}
private void getCharacteristic(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
if (characteristic == null) {
throw new Exception(String.format("No characteristic found with the given UUID %s", characteristicId));
}
callback.success(JSONObjects.asCharacteristic(characteristic));
}
private void getCharacteristics(String address, String serviceId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
JSONArray result = new JSONArray();
for (BluetoothGattCharacteristic c : service.getCharacteristics()) {
result.put(JSONObjects.asCharacteristic(c));
}
callback.success(result);
}
private void getIncludedServices(String address, String serviceId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
JSONArray result = new JSONArray();
for (BluetoothGattService s : service.getIncludedServices()) {
result.put(JSONObjects.asService(s, gatt.getDevice()));
}
callback.success(result);
}
private void getDescriptor(String address, String serviceId, String characteristicId, String descriptorId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(descriptorId));
if (descriptor == null) {
throw new Exception(String.format("No descriptor found with the given UUID %s", descriptorId));
}
callback.success(JSONObjects.asDescriptor(descriptor));
}
private void getDescriptors(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
JSONArray result = new JSONArray();
for (BluetoothGattDescriptor d : characteristic.getDescriptors()) {
result.put(JSONObjects.asDescriptor(d));
}
callback.success(result);
}
private void readCharacteristicValue(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
CallbackKey key = new CallbackKey(gatt, characteristic, "readCharacteristicValue");
readWriteCallbacks.put(key, callback);
boolean result = gatt.readCharacteristic(characteristic);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception(String.format("Could not initiate characteristic read operation for %s", characteristicId));
}
}
private void writeCharacteristicValue(String address, String serviceId, String characteristicId, byte[] value, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
boolean result = characteristic.setValue(value);
if (!result) {
throw new Exception("Could not store characteristic value");
}
CallbackKey key = new CallbackKey(gatt, characteristic, "writeCharacteristicValue");
readWriteCallbacks.put(key, callback);
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) {
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0) {
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
}
result = gatt.writeCharacteristic(characteristic);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate characteristic write operation");
}
}
private void startCharacteristicNotifications(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(clientConfigurationDescriptorUuid);
boolean result = false;
result = gatt.setCharacteristicNotification(characteristic, true);
if (!result) {
throw new Exception("Could not set enable notifications/indications");
}
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
result = descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
result = descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
} else {
throw new Exception("The device does not support notifications/indications on the given characteristic.");
}
if (!result) {
gatt.setCharacteristicNotification(characteristic, false);
throw new Exception("Could not store notification/indication value on the characteristic's configuration descriptor");
}
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
readWriteCallbacks.put(key, callback);
result = gatt.writeDescriptor(descriptor);
if (!result) {
gatt.setCharacteristicNotification(characteristic, false);
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate writing the notification/indication value on the characteristic's configuration descriptor");
}
}
private void stopCharacteristicNotifications(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(clientConfigurationDescriptorUuid);
boolean result = false;
result = gatt.setCharacteristicNotification(characteristic, false);
if (!result) {
throw new Exception("Could not disable notifications/indications");
}
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
result = descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
// yes, supposedly disabling "indications" is done the same as disabling "notifications"
result = descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
} else {
throw new Exception("The device does not support notifications/indications on the given characteristic.");
}
if (!result) {
throw new Exception("Could not store notification/indication value on the characteristic's configuration descriptor");
}
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
readWriteCallbacks.put(key, callback);
result = gatt.writeDescriptor(descriptor);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate writing the notification/indication value on the characteristic's configuration descriptor");
}
}
private void readDescriptorValue(String address, String serviceId, String characteristicId, String descriptorId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(descriptorId));
CallbackKey key = new CallbackKey(gatt, descriptor, "readDescriptorValue");
readWriteCallbacks.put(key, callback);
boolean result = gatt.readDescriptor(descriptor);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate reading descriptor");
}
}
private void writeDescriptorValue(String address, String serviceId, String characteristicId, String descriptorId, byte[] value, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(descriptorId));
boolean result = descriptor.setValue(value);
if (!result) {
throw new Exception("Could not store descriptor value");
}
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
readWriteCallbacks.put(key, callback);
result = gatt.writeDescriptor(descriptor);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception(String.format("Failed on BluetoothGatt#writeDescriptor for descriptor %s. Android didn't tell us why either.", descriptorId));
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
JSONObject obj = JSONObjects.asDevice(gatt, getBluetoothManager());
if (disconnectCallback == null) {
// the user didn't ask for a disconnect, meaning we were dropped
Log.v("bluetoothle", onDeviceDroppedCallback.getCallbackId());
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
pluginResult.setKeepCallback(true);
onDeviceDroppedCallback.sendPluginResult(pluginResult);
return;
}
disconnectCallback.success(obj);
disconnectCallback = null;
}
}
});
}
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (status == BluetoothGatt.GATT_SUCCESS) {
for (BluetoothGattService service : gatt.getServices()) {
for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
characteristic.getDescriptors();
}
}
connectCallback.success(JSONObjects.asDevice(gatt, getBluetoothManager()));
connectCallback = null;
} else {
connectCallback.error(JSONObjects.asError(new Exception("Device discovery failed")));
}
connectCallback = null;
}
});
}
@Override
public void onCharacteristicRead(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, characteristic, "readCharacteristicValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Characteristic " + characteristic.getUuid().toString() + " was read, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(Base64.encodeToString(characteristic.getValue(), Base64.NO_WRAP));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to read characteristic")));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
if (onCharacteristicValueChangedCallback == null) {
return;
}
PluginResult result = new PluginResult(PluginResult.Status.OK, JSONObjects.asCharacteristic(characteristic));
result.setKeepCallback(true);
onCharacteristicValueChangedCallback.sendPluginResult(result);
}
@Override
public void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, characteristic, "writeCharacteristicValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Characteristic " + characteristic.getUuid().toString() + " was written, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(JSONObjects.asCharacteristic(characteristic));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to write characteristic")));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onDescriptorRead(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, descriptor, "readDescriptorValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Descriptor " + descriptor.getUuid().toString() + " was read, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(JSONObjects.asDescriptor(descriptor));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to read descriptor " + descriptor.getUuid().toString())));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onDescriptorWrite(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Descriptor " + descriptor.getUuid().toString() + " was written, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(JSONObjects.asDescriptor(descriptor));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to write descriptor " + descriptor.getUuid().toString())));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onReadRemoteRssi(final BluetoothGatt gatt, final int rssi, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
BluetoothManager bluetoothManager = (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
if (rssiCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
rssiCallback.success(rssi);
} else {
rssiCallback.error(JSONObjects.asError(new Exception("Received an error after attempting to read RSSI for device " + gatt.getDevice().getAddress())));
}
rssiCallback = null;
} else if (deviceInfoCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
deviceInfoCallback.success(JSONObjects.asDevice(gatt, bluetoothManager, rssi));
} else {
deviceInfoCallback.error(JSONObjects.asError(new Exception("Received an error after attempting to read RSSI for device " + gatt.getDevice().getAddress())));
}
deviceInfoCallback = null;
} else {
return;
}
}
});
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (onAdapterStateChangedCallback == null) {
return;
}
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
connectedGattServers = new HashMap<String, BluetoothGatt>();
}
if (state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_ON) {
JSONObject obj = JSONObjects.asAdapter(getBluetoothManager().getAdapter());
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
pluginResult.setKeepCallback(true);
onAdapterStateChangedCallback.sendPluginResult(pluginResult);
}
}
}
});
}
};
private BroadcastReceiver mPairingBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
BluetoothDevice remoteDevice = (BluetoothDevice) intent.getExtras().get(BluetoothDevice.EXTRA_DEVICE);
// TODO - Hardcoded for now
String mPasskey = "123456";
try {
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
byte[] pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class)
.invoke(BluetoothDevice.class, mPasskey);
BluetoothDevice.class.getMethod("setPin", byte[].class)
.invoke(remoteDevice, pin);
BluetoothDevice.class.getMethod("setPairingConfirmation", boolean.class)
.invoke(remoteDevice, true);
Log.d("bluetoothle", "Success to set passkey.");
final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
cordova.getActivity().registerReceiver(mBondingBroadcastReceiver, filter);
}
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
cordova.getActivity().unregisterReceiver(this);
mRegisteredPairingReceiver = false;
}
};
private BroadcastReceiver mBondingBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
final int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
Log.d("bluetoothle", "Bond state changed for: " + device.getAddress() +
" new state: " + bondState +
" previous: " + previousBondState);
if (bondState == BluetoothDevice.BOND_BONDED) {
try {
BluetoothDevice.class.getMethod("cancelPairingUserInput").invoke(mGatt.getDevice());
Log.d("bluetoothle", "Cancel user input");
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
cordova.getActivity().unregisterReceiver(this);
}
}
};
/**
*
* @param callbackContext
* @param message
*/
private void keepCallback(final CallbackContext callbackContext, JSONObject message) {
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
/**
*
* @param callbackContext
* @param message
*/
private void keepCallback(final CallbackContext callbackContext, String message) {
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
/**
*
* @param callbackContext
* @param message
*/
private void keepCallback(final CallbackContext callbackContext, byte[] message) {
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
// TODO - Hardcoded for now
String mPasskey = "123456";
if (status == BluetoothGatt.GATT_SUCCESS) {
//if (!this.mPasskey.isEmpty()) {
if (!mPasskey.isEmpty()) {
if (!mRegisteredPairingReceiver) {
final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
cordova.getActivity().registerReceiver(mPairingBroadcastReceiver, filter);
mRegisteredPairingReceiver = true;
}
try {
Method createBond = BluetoothDevice.class.getMethod("createBond", (Class[]) null);
createBond.invoke(gatt.getDevice(), (Object[]) null);
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
}
try {
JSONObject obj = new JSONObjects.asDevice(gatt, getBluetoothManager());
connectCallback.success();
} catch (JSONException e) {
e.printStackTrace();
assert (false);
}
} else {
connectCallback.error(status);
}
//refresh(gatt);
}
// Used as keys for the `readWriteOperations` Map
private class CallbackKey {
private BluetoothGatt gatt;
private Object scd; // service, characteristic, or descriptor
private String operation;
public CallbackKey(BluetoothGatt gatt, Object scd, String operation) {
this.gatt = gatt;
this.scd = scd;
this.operation = operation;
}
@Override
public int hashCode() {
int hash = 1;
hash = 31 * hash + gatt.hashCode();
hash = 31 * hash + scd.hashCode();
hash = 31 * hash + operation.hashCode();
return hash;
}
public boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CallbackKey)) {
return false;
}
return
equals(((CallbackKey) obj).gatt, gatt) &&
equals(((CallbackKey) obj).scd, scd) &&
equals(((CallbackKey) obj).operation, operation);
}
}
}
|
package com.jgeppert.struts2.jquery.radio;
import com.jgeppert.struts2.jquery.selenium.JQueryIdleCondition;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@RunWith(Parameterized.class)
public class RadioTagIT {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "http://localhost:8080/regular" },
{ "http://localhost:8080/uncompressed" },
{ "http://localhost:8080/loadatonce" },
{ "http://localhost:8080/loadfromgoogle" }
});
}
private static final JQueryIdleCondition JQUERY_IDLE = new JQueryIdleCondition();
private String baseUrl;
public RadioTagIT(final String baseUrl) {
this.baseUrl = baseUrl;
}
@Test
public void testInlineData() {
WebDriver driver = new HtmlUnitDriver(true);
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get(baseUrl + "/radio/inlinedata.action");
wait.until(JQUERY_IDLE);
List<WebElement> radiobuttons = driver.findElements(By.xpath("//div[@id='radiobuttonset']/input[@type='radio'][@name='day']"));
Assert.assertEquals(7, radiobuttons.size());
}
@Test
public void testRemoteListData() {
WebDriver driver = new HtmlUnitDriver(true);
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get(baseUrl + "/radio/remotelist.action");
wait.until(JQUERY_IDLE);
List<WebElement> radiobuttons = driver.findElements(By.xpath("//div[@id='radiobuttonset']/input[@type='radio'][@name='letter']"));
Assert.assertEquals(26, radiobuttons.size());
}
}
|
package com.cordova.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.pass.Spass;
import com.samsung.android.sdk.pass.SpassFingerprint;
import com.samsung.android.sdk.pass.SpassInvalidStateException;
public class SamsungPassPlugin extends CordovaPlugin {
private Spass mSpass;
private SpassFingerprint mSpassFingerprint;
private boolean isFeatureEnabled = false;
private static final String TAG = "SamsungPassPlugin";
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
mSpass = new Spass();
try {
mSpass.initialize(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "Spass was Initialized");
} catch (SsdkUnsupportedException e) {
Log.d(TAG, "Spass could not initialize" + e);
}
isFeatureEnabled = mSpass.isFeatureEnabled(Spass.DEVICE_FINGERPRINT);
if (isFeatureEnabled) {
mSpassFingerprint = new SpassFingerprint(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "mSpassFingerprint was Initialized");
} else {
Log.d(TAG, "Fingerprint Service is not supported in the device.");
}
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "Plugin Method Called: " + action);
if (action.equals("checkSamsungPassSupport")) {
this.checkSamsungPassSupport(args, callbackContext);
} else if (action.equals("checkForRegisteredFingers")) {
this.checkForRegisteredFingers(args, callbackContext);
} else if (action.equals("startIdentifyWithDialog")) {
this.startIdentifyWithDialog(args, callbackContext);
}
else {
return false;
}
return true;
}
private void checkSamsungPassSupport(JSONArray args, CallbackContext callbackContext) {
Log.d(TAG, "checkSamsungPassSupport");
if (isFeatureEnabled) {
callbackContext.success();
} else {
callbackContext.error("Error");
}
}
private void checkForRegisteredFingers(JSONArray args, CallbackContext callbackContext) {
Log.d(TAG, "checkForRegisteredFingers");
boolean mHasRegisteredFinger = mSpassFingerprint.hasRegisteredFinger();
if (mHasRegisteredFinger) {
callbackContext.success();
} else {
callbackContext.error("Error");
}
}
private void startIdentifyWithDialog(JSONArray args, CallbackContext callbackContext) {
mSpassFingerprint.setDialogTitle("Authentificate yourself!", 0xff0000);
SpassFingerprint.IdentifyListener listener = new SpassFingerprint.IdentifyListener() {
@Override
public void onFinished(int eventStatus) {
Log.d(TAG, "identify finished : reason=" + eventStatus);
if (eventStatus == SpassFingerprint.STATUS_AUTHENTIFICATION_SUCCESS) {
Log.d(TAG, "onFinished() : Identify authentification Success");
//callbackContext.success();
} else if (eventStatus == SpassFingerprint.STATUS_AUTHENTIFICATION_PASSWORD_SUCCESS) {
//callbackContext.success();
} else {
Log.d(TAG, "onFinished() : Authentification Fail for identify");
//callbackContext.error("Error");
}
}
@Override
public void onReady() {}
@Override
public void onStarted() {}
};
mSpassFingerprint.startIdentifyWithDialog(this.cordova.getActivity().getApplicationContext(), listener, false);
}
}
|
package org.strangeforest.tcb.stats.spring;
import java.io.*;
import org.springframework.boot.actuate.health.*;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.*;
import ch.qos.logback.core.util.*;
@Component
@Profile("openshift")
public class MemoryHealthIndicator extends OpenShiftHealthIndicator {
@Override protected String getCommand() {
return "oo-cgroup-read memory.usage_in_bytes; oo-cgroup-read memory.max_usage_in_bytes; oo-cgroup-read memory.limit_in_bytes; " +
"oo-cgroup-read memory.memsw.usage_in_bytes; oo-cgroup-read memory.memsw.max_usage_in_bytes; oo-cgroup-read memory.memsw.limit_in_bytes";
}
@Override protected void parseOutput(BufferedReader reader, Health.Builder builder) throws IOException {
if (!readMemoryDetail(reader, builder, "usageInBytes")) return;
if (!readMemoryDetail(reader, builder, "maxUsageInBytes")) return;
if (!readMemoryDetail(reader, builder, "limitInBytes")) return;
if (!readMemoryDetail(reader, builder, "memsw.usageInBytes")) return;
if (!readMemoryDetail(reader, builder, "memsw.maxUsageInBytes")) return;
if (!readMemoryDetail(reader, builder, "memsw.limitInBytes")) return;
builder.up();
}
private static boolean readMemoryDetail(BufferedReader reader, Health.Builder builder, String name) throws IOException {
String usageInBytes = reader.readLine();
if (usageInBytes != null) {
builder.withDetail(name, new FileSize(Integer.parseInt(usageInBytes.trim())));
return true;
}
else
return false;
}
}
|
package org.b3mn.poem;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.b3mn.poem.business.Model;
import org.b3mn.poem.business.User;
import org.b3mn.poem.handler.HandlerBase;
import org.b3mn.poem.util.AccessRight;
import org.b3mn.poem.util.ExportInfo;
import org.b3mn.poem.util.HandlerInfo;
public class Dispatcher extends HttpServlet {
private static final long serialVersionUID = -9128262564769832181L;
private static String publicUser = "public";
private static String backendRootPath = "/backend/"; // Root path of the backend war file
private static String oryxRootPath = "/oryx/"; // Root path of the oryx war file
private static String handlerRootPath = backendRootPath + "poem/"; // Root url of all server handlers
private static String filterBrowserRedirectUrl = handlerRootPath + "repository";
private static String filterModelRedirectErrorUrl = "/error";
private static String filterBrowserRegexPattern = "MSIE \\d+\\.\\d+;";
protected Map<String, HandlerInfo> knownHandlers = new Hashtable<String, HandlerInfo>();
protected Collection<ExportInfo> exportInfos = new ArrayList<ExportInfo>();
public static String getPublicUser() {
return publicUser;
}
public static String getBackendRootPath() {
return backendRootPath;
}
public static String getOryxRootPath() {
return oryxRootPath;
}
public static String getHandlerRootPath() {
return handlerRootPath;
}
public Dispatcher() {
HandlerBase.setDispatcher(this);
}
@Override
public void init() throws ServletException {
super.init();
loadHandlerInfo();
//reloadFriendTable(); // ToDo: implement a bootloader. this operation isn't necessary at each start
}
protected void reloadFriendTable() {
Persistance.getSession().createSQLQuery("SELECT * FROM friend_init()").list();
Persistance.commit();
}
protected String getErrorPage(String stacktrace) {
String page = "<html><head><title>ORYX: Error</title><body><h1>We're sorry, but an server error occurred.</h1>" + stacktrace +"</body></head></html>";
return page;
}
public Collection<ExportInfo> getExportInfos() {
return this.exportInfos;
}
public Method getFilterMethod(String filterName) {
if (HandlerInfo.getFilterMapping() != null) {
return HandlerInfo.getFilterMapping().get(filterName);
} else return null;
}
public Method getSortMethod(String sortName) {
if (HandlerInfo.getSortMapping() != null) {
return HandlerInfo.getSortMapping().get(sortName);
} else return null;
}
public Collection<String> getHandlerClassNames() {
File handlerDir = new File(this.getServletContext().
getRealPath("/WEB-INF/classes/org/b3mn/poem/handler"));
Collection<String> classNames = new ArrayList<String>();
for (File source : handlerDir.listFiles()) {
if (source.getName().endsWith(".class")) {
classNames.add("org.b3mn.poem.handler." +
source.getName().substring(0, source.getName().lastIndexOf(".")));
}
}
return classNames;
}
// Read all annotation data of all handler, but do not initialize them
public void loadHandlerInfo() {
for (String className : this.getHandlerClassNames()) {
try {
HandlerInfo info = new HandlerInfo(className);
if (info != null) {
// The reflection logic is implemented in the HandlerInfo.load() method
this.knownHandlers.put(info.getUri(), info);
if (info.getExportInfo() != null)
this.exportInfos.add(info.getExportInfo());
}
} catch (Exception e) {} // Ignore handler if an exception occurs
}
}
// Returns the identity of the model that is referenced in the request URL or null if
// the request doesn't contain an id
protected Identity getObjectIdentity(String modelUri) {
if (modelUri != null) return Identity.instance(Integer.parseInt(modelUri));
else return null;
}
private String getModelUri(String path) {
// Extract id from the request URL
Pattern pattern = Pattern.compile("(\\/model\\/([0-9]+))?(\\/[^\\/]+\\/?)$");
Matcher matcher = pattern.matcher(new StringBuffer(path));
matcher.find();
String modelUri = matcher.group(1);
return modelUri;
}
private String getHandlerUri(String path) {
// Extract handler uri from the request URL
Pattern pattern = Pattern.compile("(\\/model\\/([0-9]+))?(\\/[^\\/]+\\/?)$");
Matcher matcher = pattern.matcher(new StringBuffer(path));
matcher.find();
String uri = matcher.group(3);
return uri;
}
// Returns an initialized instance of the requested handler
protected HandlerBase getHandler(String uri) {
try {
// Is the handler instance already initalized?
if (this.knownHandlers.get(uri).getHandlerInstance() != null) {
return this.knownHandlers.get(uri).getHandlerInstance();
} else {
Constructor<? extends HandlerBase> constructor = this.knownHandlers.get(uri).getHandlerClass().getConstructor((Class[])null);
HandlerBase handler = (HandlerBase) constructor.newInstance();
handler.setServletContext(this.getServletContext()); // Initialize handler with ServletContext
handler.init(); // Initialize the handler
this.knownHandlers.get(uri).setHandlerInstance(handler); // Store the handler instance in ModelInfo
return handler;
}
} catch (Exception e) { return null; }
}
protected boolean checkAccess(HandlerInfo handlerInfo, Identity subject, Model model, String requestMethod) {
try {
// Read access right for the user from the requested model
AccessRight userRight = model.getAccessRight(subject.getUri());
// Read required access right from the handler
AccessRight modelRestriction = handlerInfo.getAccessRestriction(requestMethod);
// User needs the same or a higher privilege then required by the handler
return userRight.compareTo(modelRestriction) >= 0;
} catch(Exception e) { return false; }
}
protected boolean checkBrowser(HandlerInfo handlerInfo, HttpServletRequest request, HttpServletResponse response) {
// Validate Browser
if (handlerInfo.isFilterBrowser()) {
// Extract handler uri from the request URL
Pattern pattern = Pattern.compile(filterBrowserRegexPattern);
return !pattern.matcher(new StringBuffer((String)request.getHeader("user-agent"))).find();
} return true;
}
// The dispatching magic goes here. Each exception is caught and the tomcat stackstrace page
// is replaced by a custom oryx error page.
protected void dispatch(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
response.setCharacterEncoding("UTF-8");
// Parse request uri to extract handler uri and model uri
String modelUri = this.getModelUri(request.getPathInfo());
String handlerUri = this.getHandlerUri(request.getPathInfo());
// Validate request: handler uri has to be different from null
if (handlerUri == null) throw new Exception("Dispatching failed: Handler uri is missing!");
Model model = null;
// Try to get the model if an handler uri is provided by the request
if (modelUri != null) {
try {
model = new Model(modelUri);
} catch (Exception e) {
throw new Exception("Dispatching failed: Invalid model uri", e);
}
}
// If you want to disable OpenID login, hard code the openId here.
// You can use any name without spaces as openId
// For example:
// String openId = "OryxUser";
String openId = (String) request.getSession().getAttribute("openid"); // Retrieve open id from session
User user = null;
// If the user isn't logged in, set the OpenID to public
if (openId == null) {
openId = HandlerBase.getPublicUser();
request.getSession().setAttribute("openid", openId);
user = new User(openId);
user.login(request, response);
} else {
Identity subject = Identity.ensureSubject(openId);
user = new User(subject);
}
String requestMethod = request.getMethod();
HandlerInfo handlerInfo = this.knownHandlers.get(handlerUri); // Get meta information of the requested handler
if (handlerInfo == null) throw new Exception("Dispatching failed: The requested handler doesn't exist.");
// If the requesting browser cannot handle the response (IE)
if (!this.checkBrowser(handlerInfo, request, response)) {
if( model == null ){
response.sendRedirect(filterBrowserRedirectUrl);
} else {
response.sendRedirect(handlerRootPath + model.getUri() + filterModelRedirectErrorUrl);
}
return;
}
// Verify that the handler is only executed if the context is valid
if ((model == null) && (handlerInfo.isNeedsModelContext())) {
throw new Exception("Dispatching failed: The handler requires a model context.");
}
if ((model != null) && (!handlerInfo.isNeedsModelContext())) {
throw new Exception("Dispatching failed: The handler cannot be called in a model context.");
}
// Check if the user is allowed to do this operation on this model with the requested handler
if ((model != null) && (!checkAccess(handlerInfo, user.getIdentity(), model, requestMethod)) ||
(handlerInfo.isPermitPublicUserAccess() && openId.equals(publicUser))) {
response.setStatus(403); // Access forbidden
return;
}
HandlerBase handler = this.getHandler(handlerUri); // Retrieve handler instance
Identity object = null;
if (model != null) object = model.getIdentity();
if (requestMethod.equals("GET")) {
handler.doGet(request, response, user.getIdentity(), object);
}
if (requestMethod.equals("POST")) {
handler.doPost(request, response, user.getIdentity(), object);
}
if (requestMethod.equals("PUT")) {
handler.doPut(request, response, user.getIdentity(), object);
}
if (requestMethod.equals("DELETE")) {
handler.doDelete(request, response, user.getIdentity(), object);
}
} catch (Exception e) {
// response.reset(); // Undo all changes --> this may cause some trouble because of a SUN bug
e.printStackTrace();
try {
response.sendRedirect("http://bpt.hpi.uni-potsdam.de/Oryx/503");
} catch (IOException e1) {
e1.printStackTrace();
}
// throw new ServletException(e);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
dispatch(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
dispatch(request,response);
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
dispatch(request,response);
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
dispatch(request,response);
}
}
|
package cc.lupine.quicksocial.shareutils;
import java.io.File;
import org.acra.ACRA;
import twitter4j.AsyncTwitter;
import twitter4j.AsyncTwitterFactory;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.TwitterAdapter;
import twitter4j.TwitterException;
import twitter4j.TwitterListener;
import twitter4j.conf.Configuration;
import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import cc.lupine.quicksocial.utils.ConfigurationBuilders;
import cc.lupine.quicksocial.utils.StaticUtilities;
public class Twitter extends SharingAdapter {
private Bundle params;
private OnShare event;
private Activity act;
public Twitter(Activity activity, Bundle postParams)
throws IllegalArgumentException {
if (postParams == null
|| (!postParams.containsKey("message")
&& !postParams.containsKey("image") && !postParams
.containsKey("link"))
|| !postParams.containsKey("user"))
throw new IllegalArgumentException(
"Bundle does not contain required keys");
params = postParams;
act = activity;
}
/**
* OnShare class instance containing listeners for common sharing events
*
* @param listener
* instance of the {@link OnShare} class with overriden abstract
* methods
* @see OnShare
*/
@Override
public void setOnShareListener(OnShare listener) {
event = listener;
}
/**
* Start asynchronous sharing in a new thread. No Exception can be thrown
* there, as the errors are now passed to the
* {@link OnShare#onError(String)} method.
*
* @see OnShare
*/
@Override
public void shareAsync() {
try {
if (params == null)
throw new IllegalStateException("No post bundle provided");
Configuration configuration = ConfigurationBuilders
.getTwitterConfig();
AsyncTwitterFactory factory = new AsyncTwitterFactory(configuration);
AsyncTwitter twitter = factory.getInstance();
twitter.setOAuthAccessToken(StaticUtilities
.getTwtTokensForUser(params.getString("user")));
String statusText = params.getString("message");
if (params.containsKey("link"))
statusText += " " + params.getString(params.getString("link"));
StatusUpdate status = new StatusUpdate(statusText);
if (params.containsKey("image"))
status.setMedia(new File(params.getString("image")));
twitter.addListener(getTwitterCallback());
event.onSharingStarted();
twitter.updateStatus(status);
} catch (IllegalStateException e) {
e.printStackTrace();
event.onError(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
event.onError("Unexpected exception: " + e.getLocalizedMessage());
ACRA.getErrorReporter().handleException(e);
}
}
/**
* Handle asynchronous response from twitter4j and call (in the UI thread)
* {@link OnShare#onShared(String)} if the post has been shared or
* {@link OnShare#onError(String)} when an error occurred.
*
* @return instance of a {@link com.facebook.Request.Callback} class
*/
private TwitterListener getTwitterCallback() {
TwitterListener listener = new TwitterAdapter() {
@Override
public void updatedStatus(final Status status) {
act.runOnUiThread(new Runnable() {
@Override
public void run() {
event.onShared(String.valueOf(status.getId()));
}
});
}
@Override
public void onException(final TwitterException e,
final twitter4j.TwitterMethod method) {
act.runOnUiThread(new Runnable() {
@Override
public void run() {
if (method == twitter4j.TwitterMethod.UPDATE_STATUS) {
e.printStackTrace();
event.onError(e.getLocalizedMessage());
} else {
e.printStackTrace();
event.onError("Unknown Twitter method, this should not happen: "
+ e.getLocalizedMessage());
ACRA.getErrorReporter().handleException(e);
}
}
});
}
};
return listener;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.text;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.font.LineWrapMode;
import com.jme3.font.Rectangle;
import com.jme3.input.KeyInput;
import com.jme3.input.event.KeyInputEvent;
import com.jme3.input.event.MouseButtonEvent;
import com.jme3.input.event.MouseMotionEvent;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector4f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import java.util.ArrayList;
import java.util.List;
import tonegod.gui.core.Element;
import tonegod.gui.core.ElementManager;
import tonegod.gui.core.Screen;
import tonegod.gui.core.utils.BitmapTextUtil;
import tonegod.gui.core.utils.UIDUtil;
import tonegod.gui.effects.Effect;
import tonegod.gui.listeners.KeyboardListener;
import tonegod.gui.listeners.MouseButtonListener;
import tonegod.gui.listeners.MouseFocusListener;
import tonegod.gui.listeners.TabFocusListener;
/**
*
* @author t0neg0d
*/
public class TextField extends Element implements Control, KeyboardListener, TabFocusListener, MouseFocusListener, MouseButtonListener {
public static enum Type {
DEFAULT,
ALPHA,
ALPHA_NOSPACE,
NUMERIC,
ALPHANUMERIC,
ALPHANUMERIC_NOSPACE,
EXCLUDE_SPECIAL,
EXCLUDE_CUSTOM,
INCLUDE_CUSTOM
};
private String validateAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
private String validateAlphaNoSpace = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private String validateNumeric = "0123456789.-";
private String validateSpecChar = "`~!@
private String validateCustom = "";
private String testString = "Gg|/X";
private Element caret;
private Material caretMat;
protected int caretIndex = 0, head = 0, tail = 0;
protected int rangeHead = -1, rangeTail = -1;
protected int visibleHead = -1, visibleTail = -1;
protected List<String> textFieldText = new ArrayList();
protected String finalText = "", visibleText = "", textRangeText = "";
protected BitmapText widthTest;
private boolean hasTabFocus = false;
protected float caretX = 0;
private Type type = Type.DEFAULT;
private boolean ctrl = false, shift = false, alt = false, meta = false;
private boolean isEnabled = true;
private boolean forceUpperCase = false, forceLowerCase = false;
private int maxLength = 0;
private String nextChar;
private boolean valid;
private boolean copy = true, paste = true;
private float firstClick = 0, secondClick = 0, compareClick = 0;
private float firstClickDiff = 0, secondClickDiff = 0;
private boolean doubleClick = false, tripleClick = false;
private int clickCount = 0;
private boolean isPressed = false;
/**
* Creates a new instance of the TextField control
*
* @param screen The screen control the Element is to be added to
* @param position A Vector2f containing the x/y position of the Element
*/
public TextField(ElementManager screen, Vector2f position) {
this(screen, UIDUtil.getUID(), position,
screen.getStyle("TextField").getVector2f("defaultSize"),
screen.getStyle("TextField").getVector4f("resizeBorders"),
screen.getStyle("TextField").getString("defaultImg")
);
}
/**
* Creates a new instance of the TextField control
*
* @param screen The screen control the Element is to be added to
* @param position A Vector2f containing the x/y position of the Element
* @param dimensions A Vector2f containing the width/height dimensions of the Element
*/
public TextField(ElementManager screen, Vector2f position, Vector2f dimensions) {
this(screen, UIDUtil.getUID(), position, dimensions,
screen.getStyle("TextField").getVector4f("resizeBorders"),
screen.getStyle("TextField").getString("defaultImg")
);
}
/**
* Creates a new instance of the TextField control
*
* @param screen The screen control the Element is to be added to
* @param position A Vector2f containing the x/y position of the Element
* @param dimensions A Vector2f containing the width/height dimensions of the Element
* @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S)
* @param defaultImg The default image to use for the TextField
*/
public TextField(ElementManager screen, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) {
this(screen, UIDUtil.getUID(), position, dimensions, resizeBorders, defaultImg);
}
/**
* Creates a new instance of the TextField control
*
* @param screen The screen control the Element is to be added to
* @param UID A unique String identifier for the Element
* @param position A Vector2f containing the x/y position of the Element
*/
public TextField(ElementManager screen, String UID, Vector2f position) {
this(screen, UID, position,
screen.getStyle("TextField").getVector2f("defaultSize"),
screen.getStyle("TextField").getVector4f("resizeBorders"),
screen.getStyle("TextField").getString("defaultImg")
);
}
/**
* Creates a new instance of the TextField control
*
* @param screen The screen control the Element is to be added to
* @param UID A unique String identifier for the Element
* @param position A Vector2f containing the x/y position of the Element
* @param dimensions A Vector2f containing the width/height dimensions of the Element
*/
public TextField(ElementManager screen, String UID, Vector2f position, Vector2f dimensions) {
this(screen, UID, position, dimensions,
screen.getStyle("TextField").getVector4f("resizeBorders"),
screen.getStyle("TextField").getString("defaultImg")
);
}
/**
* Creates a new instance of the TextField control
*
* @param screen The screen control the Element is to be added to
* @param UID A unique String identifier for the Element
* @param position A Vector2f containing the x/y position of the Element
* @param dimensions A Vector2f containing the width/height dimensions of the Element
* @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S)
* @param defaultImg The default image to use for the Slider's track
*/
public TextField(ElementManager screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) {
super(screen, UID, position, dimensions, resizeBorders, defaultImg);
this.setScaleEW(true);
this.setScaleNS(false);
this.setDockN(true);
this.setDockW(true);
compareClick = screen.getApplication().getTimer().getTimeInSeconds();
float padding = screen.getStyle("TextField").getFloat("textPadding");
this.setFontSize(screen.getStyle("TextField").getFloat("fontSize"));
this.setTextPadding(padding);
this.setTextWrap(LineWrapMode.valueOf(screen.getStyle("TextField").getString("textWrap")));
this.setTextAlign(BitmapFont.Align.valueOf(screen.getStyle("TextField").getString("textAlign")));
this.setTextVAlign(BitmapFont.VAlign.valueOf(screen.getStyle("TextField").getString("textVAlign")));
this.setMinDimensions(dimensions.clone());
caret = new Element(screen, UID + ":Caret", new Vector2f(padding,padding), new Vector2f(dimensions.x-(padding*2), dimensions.y-(padding*2)), new Vector4f(0,0,0,0), null);
caretMat = caret.getMaterial().clone();
caretMat.setBoolean("IsTextField", true);
caretMat.setTexture("ColorMap", null);
caretMat.setColor("Color", getFontColor());
caret.setLocalMaterial(caretMat);
caret.setIgnoreMouse(true);
// caret.setlockToParentBounds(true);
caret.setScaleEW(true);
caret.setScaleNS(false);
caret.setDockS(true);
caret.setDockW(true);
setTextFieldFontColor(screen.getStyle("TextField").getColorRGBA("fontColor"));
this.addChild(caret);
this.updateText("");
populateEffects("TextField");
}
// Validation
/**
* Sets the TextField.Type of the text field. This can be used to enfoce rules on the inputted text
* @param type Type
*/
public void setType(Type type) {
this.type = type;
}
/**
* Returns the current Type of the TextField
* @return Type
*/
public Type getType() {
return this.type;
}
/**
* Sets a custom validation rule for the TextField.
* @param grabBag String A list of character to either allow or diallow as input
*/
public void setCustomValidation(String grabBag) {
validateCustom = grabBag;
}
/**
* Attempts to parse an int from the inputted text of the TextField
* @return int
* @throws NumberFormatException
*/
public int parseInt() throws NumberFormatException {
return Integer.parseInt(getText());
}
/**
* Attempts to parse a float from the inputted text of the TextField
* @return float
* @throws NumberFormatException
*/
public float parseFloat() throws NumberFormatException {
return Float.parseFloat(getText());
}
/**
* Attempts to parse a short from the inputted text of the TextField
* @return short
* @throws NumberFormatException
*/
public short parseShort() throws NumberFormatException {
return Short.parseShort(getText());
}
/**
* Attempts to parse a double from the inputted text of the TextField
* @return double
* @throws NumberFormatException
*/
public double parseDouble() throws NumberFormatException {
return Double.parseDouble(getText());
}
/**
* Attempts to parse a long from the inputted text of the TextField
* @return long
* @throws NumberFormatException
*/
public long parseLong() throws NumberFormatException {
return Long.parseLong(getText());
}
// Interaction
@Override
public void onKeyPress(KeyInputEvent evt) {
if (evt.getKeyCode() == KeyInput.KEY_F1 || evt.getKeyCode() == KeyInput.KEY_F2 ||
evt.getKeyCode() == KeyInput.KEY_F3 || evt.getKeyCode() == KeyInput.KEY_F4 ||
evt.getKeyCode() == KeyInput.KEY_F5 || evt.getKeyCode() == KeyInput.KEY_F6 ||
evt.getKeyCode() == KeyInput.KEY_F7 || evt.getKeyCode() == KeyInput.KEY_F8 ||
evt.getKeyCode() == KeyInput.KEY_F9 || evt.getKeyCode() == KeyInput.KEY_CAPITAL ||
evt.getKeyCode() == KeyInput.KEY_ESCAPE || evt.getKeyCode() == KeyInput.KEY_TAB) {
} else if (evt.getKeyCode() == KeyInput.KEY_LCONTROL || evt.getKeyCode() == KeyInput.KEY_RCONTROL) {
ctrl = true;
} else if (evt.getKeyCode() == KeyInput.KEY_LSHIFT || evt.getKeyCode() == KeyInput.KEY_RSHIFT) {
shift = true;
} else if (evt.getKeyCode() == KeyInput.KEY_LMENU || evt.getKeyCode() == KeyInput.KEY_RMENU) {
alt = true;
} else if (evt.getKeyCode() == KeyInput.KEY_LMETA || evt.getKeyCode() == KeyInput.KEY_RMETA) {
meta = true;
} else if (evt.getKeyCode() == KeyInput.KEY_RETURN) {
} else if (evt.getKeyCode() == KeyInput.KEY_DELETE) {
if (rangeHead != -1 && rangeTail != -1) editTextRangeText("");
else {
if (caretIndex < finalText.length()) textFieldText.remove(caretIndex);
}
} else if (evt.getKeyCode() == KeyInput.KEY_BACK) {
if (rangeHead != -1 && rangeTail != -1) {
editTextRangeText("");
} else {
if (caretIndex > 0) {
textFieldText.remove(caretIndex-1);
caretIndex
}
}
} else if (evt.getKeyCode() == KeyInput.KEY_LEFT) {
if (!shift) resetTextRange();
if (caretIndex > -1) {
if (Screen.isMac()) {
if (meta) {
caretIndex = 0;
getVisibleText();
if (shift) setTextRangeEnd(caretIndex);
else {
resetTextRange();
setTextRangeStart(caretIndex);
}
return;
}
}
if ((Screen.isMac() && !alt) ||
(Screen.isWindows() && !ctrl) ||
(Screen.isUnix() && !ctrl) ||
(Screen.isSolaris() && !ctrl))
caretIndex
else {
int cIndex = caretIndex;
if (cIndex > 0)
if (finalText.charAt(cIndex-1) == ' ')
cIndex
int index = 0;
if (cIndex > 0) index = finalText.substring(0,cIndex).lastIndexOf(' ')+1;
if (index < 0) index = 0;
caretIndex = index;
}
if (caretIndex < 0)
caretIndex = 0;
if (!shift) setTextRangeStart(caretIndex);
}
} else if (evt.getKeyCode() == KeyInput.KEY_RIGHT) {
if (!shift) resetTextRange();
if (caretIndex <= textFieldText.size()) {
if (Screen.isMac()) {
if (meta) {
caretIndex = textFieldText.size();
getVisibleText();
if (shift) setTextRangeEnd(caretIndex);
else {
resetTextRange();
setTextRangeStart(caretIndex);
}
return;
}
}
if ((Screen.isMac() && !alt) ||
(Screen.isWindows() && !ctrl) ||
(Screen.isUnix() && !ctrl) ||
(Screen.isSolaris() && !ctrl))
caretIndex++;
else {
int cIndex = caretIndex;
if (cIndex < finalText.length())
if (finalText.charAt(cIndex) == ' ')
cIndex++;
int index;
if (cIndex < finalText.length()) {
index = finalText.substring(cIndex, finalText.length()).indexOf(' ');
if (index == -1) index = finalText.length();
else index += cIndex;
} else {
index = finalText.length();
}
caretIndex = index;
}
if (caretIndex > finalText.length())
caretIndex = finalText.length();
if (!shift) {
if (caretIndex < textFieldText.size()) setTextRangeStart(caretIndex);
else setTextRangeStart(textFieldText.size());
}
}
} else if (evt.getKeyCode() == KeyInput.KEY_END || evt.getKeyCode() == KeyInput.KEY_NEXT || evt.getKeyCode() == KeyInput.KEY_DOWN) {
caretIndex = textFieldText.size();
getVisibleText();
if (shift) setTextRangeEnd(caretIndex);
else {
resetTextRange();
setTextRangeStart(caretIndex);
}
} else if (evt.getKeyCode() == KeyInput.KEY_HOME || evt.getKeyCode() == KeyInput.KEY_PRIOR || evt.getKeyCode() == KeyInput.KEY_UP) {
caretIndex = 0;
getVisibleText();
if (shift) setTextRangeEnd(caretIndex);
else {
resetTextRange();
setTextRangeStart(caretIndex);
}
} else {
if (ctrl) {
if (evt.getKeyCode() == KeyInput.KEY_C) {
if (copy)
screen.setClipboardText(textRangeText);
} else if (evt.getKeyCode() == KeyInput.KEY_V) {
if (paste)
this.pasteTextInto();
}
} else {
if (isEnabled) {
if (rangeHead != -1 && rangeTail != -1) {
editTextRangeText("");
}
if (!shift) resetTextRange();
nextChar = String.valueOf(evt.getKeyChar());
if (forceUpperCase) nextChar = nextChar.toUpperCase();
else if (forceLowerCase) nextChar = nextChar.toLowerCase();
valid = true;
if (maxLength > 0) {
if (getText().length() >= maxLength) valid =false;
}
if (valid) {
if (type == Type.DEFAULT) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
} else if (type == Type.ALPHA) {
if (validateAlpha.indexOf(nextChar) != -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
} else if (type == Type.ALPHA_NOSPACE) {
if (validateAlpha.indexOf(nextChar) != -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
} else if (type == Type.NUMERIC) {
if (validateNumeric.indexOf(nextChar) != -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
} else if (type == Type.ALPHANUMERIC) {
if (validateAlpha.indexOf(nextChar) != -1 || validateNumeric.indexOf(nextChar) != -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
} else if (type == Type.ALPHANUMERIC_NOSPACE) {
if (validateAlphaNoSpace.indexOf(nextChar) != -1 || validateNumeric.indexOf(nextChar) != -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
} else if (type == Type.EXCLUDE_SPECIAL) {
if (validateSpecChar.indexOf(nextChar) == -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
} else if (type == Type.EXCLUDE_CUSTOM) {
if (validateCustom.indexOf(nextChar) == -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
} else if (type == Type.INCLUDE_CUSTOM) {
if (validateCustom.indexOf(nextChar) != -1) {
textFieldText.add(caretIndex, nextChar);
caretIndex++;
}
}
}
if (!shift) {
if (caretIndex < textFieldText.size()) setTextRangeStart(caretIndex);
else setTextRangeStart(textFieldText.size());
}
}
}
}
this.updateText(getVisibleText());
if (shift && (evt.getKeyCode() == KeyInput.KEY_LEFT || evt.getKeyCode() == KeyInput.KEY_RIGHT)) setTextRangeEnd(caretIndex);
centerTextVertically();
controlKeyPressHook(evt, getText());
evt.setConsumed();
}
/**
* An overridable hook for the onKeyPress event of the TextField
* @param evt KeyInputEvent
* @param text String
*/
public void controlKeyPressHook(KeyInputEvent evt, String text) { }
@Override
public void onKeyRelease(KeyInputEvent evt) {
if (evt.getKeyCode() == KeyInput.KEY_LCONTROL || evt.getKeyCode() == KeyInput.KEY_RCONTROL) {
ctrl = false;
} else if (evt.getKeyCode() == KeyInput.KEY_LSHIFT || evt.getKeyCode() == KeyInput.KEY_RSHIFT) {
shift = false;
} else if (evt.getKeyCode() == KeyInput.KEY_LMENU || evt.getKeyCode() == KeyInput.KEY_RMENU) {
alt = false;
} else if (evt.getKeyCode() == KeyInput.KEY_LMETA || evt.getKeyCode() == KeyInput.KEY_RMETA) {
meta = false;
}
evt.setConsumed();
}
/**
* Internal use - NEVER USE THIS!!
*/
protected void getTextFieldText() {
String ret = "";
int index = 0;
for (String s : textFieldText) {
ret += s;
index++;
}
finalText = ret;
}
/**
* This method now forwards to setText. Feel free to use setText directly.
* @param text String The text to set for the TextField
*/
@Deprecated
public void setTextFieldText(String text) {
setText(text);
}
@Override
public void setText(String s) {
caretIndex = 0;
textFieldText.clear();
for (int i = 0; i < s.length(); i++) {
textFieldText.add(caretIndex, String.valueOf(s.charAt(i)));
caretIndex++;
}
this.updateText(getVisibleText());
setCaretPositionToEnd();
centerTextVertically();
}
@Override
public final void setFontSize(float fontSize) {
this.fontSize = fontSize;
// widthTest = new BitmapText(font, false);
// widthTest.setBox(null);
// widthTest.setSize(getFontSize());
// widthTest.setText(testString);
if (textElement != null) {
textElement.setSize(fontSize);
}
}
@Override
public String getText() {
String ret = "";
int index = 0;
for (String s : textFieldText) {
ret += s;
index++;
}
return ret;
}
/**
* Returns the visible portion of the TextField's text
* @return String
*/
protected String getVisibleText() {
getTextFieldText();
widthTest = new BitmapText(font, false);
widthTest.setBox(null);
widthTest.setSize(getFontSize());
int index1 = 0, index2;
widthTest.setText(finalText);
if (head == -1 || tail == -1 || widthTest.getLineWidth() < getWidth()) {
head = 0;
tail = finalText.length();
if (head != tail && head != -1 && tail != -1)
visibleText = finalText.substring(head, tail);
else
visibleText = "";
} else if (caretIndex < head) {
head = caretIndex;
index2 = caretIndex; //finalText.length()-1;
if (index2 == caretIndex && caretIndex != textFieldText.size()) {
index2 = caretIndex+1;
widthTest.setText(finalText.substring(caretIndex, index2));
while(widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) {
if (index2 == textFieldText.size())
break;
widthTest.setText(finalText.substring(caretIndex, index2+1));
if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) {
index2++;
}
}
}
if (index2 != textFieldText.size()) index2++;
tail = index2;
if (head != tail && head != -1 && tail != -1)
visibleText = finalText.substring(head, tail);
else
visibleText = "";
} else if (caretIndex > tail) {
tail = caretIndex;
index2 = caretIndex; //finalText.length()-1;
if (index2 == caretIndex && caretIndex != 0) {
index2 = caretIndex-1;
widthTest.setText(finalText.substring(index2, caretIndex));
while(widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) {
if (index2 == 0)
break;
widthTest.setText(finalText.substring(index2-1, caretIndex));
if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) {
index2
}
}
}
head = index2;
if (head != tail && head != -1 && tail != -1)
visibleText = finalText.substring(head, caretIndex);
else
visibleText = "";
} else {
index2 = tail; //finalText.length()-1;
if (index2 > finalText.length())
index2 = finalText.length();
if (tail != head) {
widthTest.setText(finalText.substring(head, index2));
if (widthTest.getLineWidth() > getWidth()-(getTextPadding()*2)) {
while(widthTest.getLineWidth() > getWidth()-(getTextPadding()*2)) {
if (index2 == head)
break;
widthTest.setText(finalText.substring(head, index2-1));
if (widthTest.getLineWidth() > getWidth()-(getTextPadding()*2)) {
index2
}
}
} else if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) {
while(widthTest.getLineWidth() < getWidth()-(getTextPadding()*2) && index2 < finalText.length()) {
if (index2 == head)
break;
widthTest.setText(finalText.substring(head, index2+1));
if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) {
index2++;
}
}
}
}
tail = index2;
if (head != tail && head != -1 && tail != -1)
visibleText = finalText.substring(head, tail);
else
visibleText = "";
}
String testString = "";
widthTest.setText(".");
float fixWidth = widthTest.getLineWidth();
boolean useFix = false;
if (!finalText.equals("")) {
try {
testString = finalText.substring(head, caretIndex);
if (testString.charAt(testString.length()-1) == ' ') {
testString += ".";
useFix = true;
}
} catch (Exception ex) { }
}
widthTest.setText(testString);
float nextCaretX = widthTest.getLineWidth();
if (useFix) nextCaretX -= fixWidth;
caretX = nextCaretX; //widthTest.getLineWidth();
setCaretPosition(getAbsoluteX()+caretX);
return visibleText;
}
private void setCaretPositionToIndex() {
widthTest.setText(".");
float fixWidth = widthTest.getLineWidth();
boolean useFix = false;
if (!finalText.equals("")) {
String testString = finalText.substring(head, caretIndex);
try {
if (testString.charAt(testString.length()-1) == ' ') {
testString += ".";
useFix = true;
}
} catch (Exception ex) { }
widthTest.setText(testString);
float nextCaretX = widthTest.getLineWidth();
if (useFix) nextCaretX -= fixWidth;
caretX = nextCaretX; //widthTest.getLineWidth();
setCaretPosition(getAbsoluteX()+caretX);
}
}
/**
* For internal use - do not call this method
* @param caretX float
*/
protected void setCaretPosition(float caretX) {
if (textElement != null) {
if (hasTabFocus) {
caret.getMaterial().setFloat("CaretX", caretX+getTextPadding());
caret.getMaterial().setFloat("LastUpdate", app.getTimer().getTimeInSeconds());
}
}
}
/**
* For internal use - do not call this method
* @param x float
*/
private void setCaretPositionByX(float x) {
int index1 = visibleText.length();
if (visibleText.length() > 0) {
widthTest.setSize(getFontSize());
widthTest.setText(visibleText.substring(0, index1));
while(caret.getAbsoluteX()+widthTest.getLineWidth() > (x+getTextPadding())) {
index1
widthTest.setText(visibleText.substring(0, index1));
}
caretX = widthTest.getLineWidth();
}
caretIndex = head+index1;
setCaretPosition(getAbsoluteX()+caretX);
if (!shift) {
resetTextRange();
setTextRangeStart(caretIndex);
} else {
setTextRangeEnd(caretIndex);
}
}
private void setCaretPositionByXNoRange(float x) {
int index1 = visibleText.length();
if (visibleText.length() > 0) {
String testString = "";
widthTest.setText(".");
float fixWidth = widthTest.getLineWidth();
boolean useFix = false;
widthTest.setSize(getFontSize());
widthTest.setText(visibleText.substring(0, index1));
while(caret.getAbsoluteX()+widthTest.getLineWidth() > (x+getTextPadding())) {
if (index1 > 0) {
index1
testString = visibleText.substring(0, index1);
widthTest.setText(testString);
} else {
break;
}
}
try {
testString = finalText.substring(head, caretIndex);
if (testString.charAt(testString.length()-1) == ' ') {
testString += ".";
useFix = true;
}
} catch (Exception ex) { }
widthTest.setText(testString);
float nextCaretX = widthTest.getLineWidth();
if (useFix) nextCaretX -= fixWidth;
caretX = nextCaretX;
}
caretIndex = head+index1;
setCaretPosition(getAbsoluteX()+caretX);
}
/**
* Sets the caret position to the end of the TextField's text
*/
public void setCaretPositionToEnd() {
int index1 = visibleText.length();
if (visibleText.length() > 0) {
widthTest.setText(visibleText.substring(0, index1));
caretX = widthTest.getLineWidth();
}
caretIndex = head+index1;
setCaretPosition(getAbsoluteX()+caretX);
resetTextRange();
}
private void pasteTextInto() {
String text = screen.getClipboardText();
editTextRangeText(text);
}
/**
* Sets the ColorRGBA value used for text & caret
* @param fontColor ColorRGBA
*/
public final void setTextFieldFontColor(ColorRGBA fontColor) {
setFontColor(fontColor);
caretMat.setColor("Color", fontColor);
}
/**
* Enables/disables the TextField
* @param isEnabled boolean
*/
public void setIsEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
/**
* Returns if the TextField is currently enabled/disabled
* @return boolean
*/
public boolean getIsEnabled() {
return this.isEnabled;
}
/**
* Enables/disables the use of the Copy text feature
* @param copy boolean
*/
public void setAllowCopy(boolean copy) {
this.copy = copy;
}
/**
* Returns if the Copy feature is enabled/disabled
* @return copy
*/
public boolean getAllowCopy() {
return this.copy;
}
/**
* Eanbles/disables use of the Paste text feature
* @param paste boolean
*/
public void setAllowPaste(boolean paste) {
this.paste = paste;
}
/**
* Returns if the Paste feature is enabled/disabled
* @return paste
*/
public boolean getAllowPaste() {
return this.paste;
}
/**
* Enables/disables both the Copy and Paste feature
* @param copyAndPaste boolean
*/
public void setAllowCopyAndPaste(boolean copyAndPaste) {
this.copy = copyAndPaste;
this.paste = copyAndPaste;
}
/**
* Forces all text input to uppercase
* @param forceUpperCase boolean
*/
public void setForceUpperCase(boolean forceUpperCase) {
this.forceUpperCase = forceUpperCase;
this.forceLowerCase = false;
}
/**
* Returns if the TextField is set to force uppercase
* @return boolean
*/
public boolean getForceUpperCase() {
return this.forceUpperCase;
}
/**
* Forces all text input to lowercase
* @return boolean
*/
public void setForceLowerCase(boolean forceLowerCase) {
this.forceLowerCase = forceLowerCase;
this.forceUpperCase = false;
}
/**
* Returns if the TextField is set to force lowercase
* @return boolean
*/
public boolean getForceLowerCase() {
return this.forceLowerCase;
}
/**
* Set the maximum character limit for the TextField. 0 = unlimited
* @param maxLength int
*/
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
/**
* Returns the maximum limit of character allowed for this TextField
* @return int
*/
public int getMaxLength() {
return this.maxLength;
}
@Override
public void setTabFocus() {
hasTabFocus = true;
setTextRangeStart(caretIndex);
if (isEnabled)
caret.getMaterial().setBoolean("HasTabFocus", true);
screen.setKeyboardElement(this);
controlTextFieldSetTabFocusHook();
Effect effect = getEffect(Effect.EffectEvent.TabFocus);
if (effect != null) {
effect.setColor(ColorRGBA.DarkGray);
screen.getEffectManager().applyEffect(effect);
}
if (isEnabled && !this.controls.contains(this)) {
addControl(this);
// System.out.println(getUID() + " : Is now receiving updates.");
}
}
@Override
public void resetTabFocus() {
hasTabFocus = false;
shift = false;
ctrl = false;
alt = false;
caret.getMaterial().setBoolean("HasTabFocus", false);
screen.setKeyboardElement(null);
controlTextFieldResetTabFocusHook();
Effect effect = getEffect(Effect.EffectEvent.LoseTabFocus);
if (effect != null) {
effect.setColor(ColorRGBA.White);
screen.getEffectManager().applyEffect(effect);
}
if (isEnabled && this.controls.contains(this)) {
removeControl(this);
// System.out.println(getUID() + " : Is no longer receiving updates.");
}
}
/**
* Overridable hook for receive tab focus event
*/
public void controlTextFieldSetTabFocusHook() { }
/**
* Overridable hook for lose tab focus event
*/
public void controlTextFieldResetTabFocusHook() { }
@Override
public void onGetFocus(MouseMotionEvent evt) {
if (getIsEnabled()) screen.setCursor(Screen.CursorType.TEXT);
setHasFocus(true);
}
@Override
public void onLoseFocus(MouseMotionEvent evt) {
if (getIsEnabled()) screen.setCursor(Screen.CursorType.POINTER);
setHasFocus(false);
}
public final void updateText(String text) {
this.text = text;
if (textElement == null) {
textElement = new BitmapText(font, false);
textElement.setBox(new Rectangle(0,0,getDimensions().x,getDimensions().y));
centerTextVertically();
}
textElement.setLineWrapMode(textWrap);
textElement.setAlignment(textAlign);
textElement.setVerticalAlignment(textVAlign);
textElement.setSize(fontSize);
textElement.setColor(fontColor);
textElement.setText(text);
updateTextElement();
if (textElement.getParent() == null) {
this.attachChild(textElement);
// textElement.move(0,0,getNextZOrder());
}
centerTextVertically();
}
private void centerTextVertically() {
float height = BitmapTextUtil.getTextLineHeight(this, testString);
float nextY = height-FastMath.floor(getHeight());
nextY /= 2;
nextY = (float)FastMath.ceil(nextY)+1;
setTextPosition(getTextPosition().x, -nextY);
}
@Override
public void onMouseLeftPressed(MouseButtonEvent evt) {
if (this.isEnabled) {
float time = screen.getApplication().getTimer().getTimeInSeconds();
if (time-compareClick > .2f) resetClickCounter();
compareClick = time;
isPressed = true;
clickCount++;
switch (clickCount) {
case 1:
firstClick = time;
resetTextRange();
setCaretPositionByXNoRange(evt.getX());
if (caretIndex >= 0)
this.setTextRangeStart(caretIndex);
else
this.setTextRangeStart(0);
break;
case 2:
secondClick = time;
firstClickDiff = time-firstClick;
if (firstClickDiff <= 0.2f) {
doubleClick = true;
} else {
resetClickCounter();
}
break;
case 3:
secondClickDiff = time-secondClick;
if (secondClickDiff <= 0.2f) {
tripleClick = true;
}
resetClickCounter();
break;
default:
resetClickCounter();
}
}
}
private void resetClickCounter() {
clickCount = 0;
firstClick = 0;
secondClick = 0;
firstClickDiff = 0;
secondClickDiff = 0;
}
@Override
public void onMouseLeftReleased(MouseButtonEvent evt) {
if (isEnabled) {
if (isPressed) {
isPressed = false;
if (doubleClick) {
selectTextRangeDoubleClick();
doubleClick = false;
} else if (tripleClick) {
selectTextRangeTripleClick();
tripleClick = false;
} else {
setCaretPositionByXNoRange(evt.getX());
if (caretIndex >= 0)
this.setTextRangeEnd(caretIndex);
else
this.setTextRangeEnd(0);
}
}
}
}
@Override
public void onMouseRightPressed(MouseButtonEvent evt) { }
@Override
public void onMouseRightReleased(MouseButtonEvent evt) { }
private void stillPressedInterval() {
if (screen.getMouseXY().x > getAbsoluteWidth() && caretIndex < finalText.length())
caretIndex++;
else if (screen.getMouseXY().x < getAbsoluteX() && caretIndex > 0)
caretIndex
updateText(getVisibleText());
setCaretPositionByXNoRange(screen.getMouseXY().x);
if (caretIndex >= 0)
this.setTextRangeEnd(caretIndex);
else
this.setTextRangeEnd(0);
}
// Text Range methods
/**
* Sets the current text range to all text within the TextField
*/
public void selectTextRangeAll() {
setTextRangeStart(0);
setTextRangeEnd(finalText.length());
caretIndex = finalText.length();
getVisibleText();
}
/**
* Resets the current text range
*/
public void selectTextRangeNone() {
this.resetTextRange();
}
/**
* Sets the current text range to the first instance of the provided string, if found
* @param s The String to search for
*/
public void selectTextRangeBySubstring(String s) {
int head = finalText.indexOf(s);
if (head != -1) {
setTextRangeStart(head);
int tail = head+s.length();
setTextRangeEnd(tail);
caretIndex = tail;
getVisibleText();
}
}
/**
* Sets the selected text range to head-tail or tail-head depending on the provided indexes.
* Selects nothing if either of the provided indexes are out of range
* @param head The start or end index of the desired text range
* @param tail The end or start index of the desired text range
*/
public void selectTextRangeByIndex(int head, int tail) {
int nHead = head;
int nTail = tail;
if (head > tail) {
nHead = tail;
nTail = head;
}
if (nHead < 0) nHead = 0;
if (nTail > finalText.length()) nTail = finalText.length();
this.setTextRangeStart(nHead);
this.setTextRangeEnd(nTail);
caretIndex = nTail;
getVisibleText();
}
private void selectTextRangeDoubleClick() {
if (!finalText.equals("")) {
int end;
if (finalText.substring(caretIndex, finalText.length()).indexOf(' ') != -1)
end = caretIndex+finalText.substring(caretIndex, finalText.length()).indexOf(' ');
else
end = caretIndex+finalText.substring(caretIndex, finalText.length()).length();
int start = finalText.substring(0,caretIndex).lastIndexOf(' ')+1;
if (start == -1) start = 0;
setTextRangeStart(start);
// System.out.println(caretIndex + " : " + start + " : " + end);
caretIndex = end;
updateText(getVisibleText());
setTextRangeEnd(end);
}
}
private void selectTextRangeTripleClick() {
if (!finalText.equals("")) {
caretIndex = finalText.length();
updateText(getVisibleText());
setTextRangeStart(0);
setTextRangeEnd(finalText.length());
}
}
private void setTextRangeStart(int head) {
if (!visibleText.equals("")) {
rangeHead = head;
}
}
private void setTextRangeEnd(int tail) {
if (!visibleText.equals("") && rangeHead != -1) {
widthTest.setSize(getFontSize());
widthTest.setText(".");
float diff = widthTest.getLineWidth();
float rangeX;
if (rangeHead-this.head <= 0) {
widthTest.setText("");
rangeX = widthTest.getLineWidth();
} else if(rangeHead-this.head < visibleText.length()) {
widthTest.setText(visibleText.substring(0, rangeHead-this.head));
float width = widthTest.getLineWidth();
if (widthTest.getText().length() > 0) {
if (widthTest.getText().charAt(widthTest.getText().length()-1) == ' ') {
widthTest.setText(widthTest.getText() + ".");
width = widthTest.getLineWidth()-diff;
}
}
rangeX = width;
} else {
widthTest.setText(visibleText);
rangeX = widthTest.getLineWidth();
}
if (rangeHead >= this.head)
rangeX = getAbsoluteX()+rangeX+getTextPadding();
else
rangeX = getTextPadding();
rangeTail = tail;
if (tail-this.head <= 0)
widthTest.setText("");
else if (tail-this.head < visibleText.length())
widthTest.setText(visibleText.substring(0, tail-this.head));
else
widthTest.setText(visibleText);
textRangeText = (rangeHead < rangeTail) ? finalText.substring(rangeHead, rangeTail) : finalText.substring(rangeTail, rangeHead);
// System.out.println(textRangeText);
float rangeW = getTextPadding();
if (rangeTail <= this.tail) {
float width = widthTest.getLineWidth();
if (widthTest.getText().length() > 0) {
if (widthTest.getText().charAt(widthTest.getText().length()-1) == ' ') {
widthTest.setText(widthTest.getText() + ".");
width = widthTest.getLineWidth()-diff;
}
}
rangeW = getAbsoluteX()+width+getTextPadding();
}
if (rangeHead > rangeTail) {
caret.getMaterial().setFloat("TextRangeStart", rangeW);
caret.getMaterial().setFloat("TextRangeEnd", rangeX);
} else {
caret.getMaterial().setFloat("TextRangeStart", rangeX);
caret.getMaterial().setFloat("TextRangeEnd", rangeW);
}
caret.getMaterial().setBoolean("ShowTextRange", true);
}
}
private void resetTextRange() {
textRangeText = "";
rangeHead = -1;
rangeTail = -1;
caret.getMaterial().setFloat("TextRangeStart", 0);
caret.getMaterial().setFloat("TextRangeEnd", 0);
caret.getMaterial().setBoolean("ShowTextRange", false);
}
private void editTextRangeText(String insertText) {
int head, tail;
if (rangeHead != -1 && rangeTail != -1) {
head = rangeHead;
tail = rangeTail;
if (head < 0) head = 0;
else if (head > finalText.length()) head = finalText.length();
if (tail < 0) tail = 0;
else if (tail > finalText.length()) tail = finalText.length();
resetTextRange();
} else {
head = caretIndex-1;
if (head == -1)
head = 0;
tail = caretIndex;
}
String newText;
int tempIndex;
if (tail > head) {
newText = finalText.substring(0,head) + insertText + finalText.substring(tail, finalText.length());
tempIndex = head+insertText.length();
} else {
newText = finalText.substring(0,tail) + insertText + finalText.substring(head, finalText.length());
tempIndex = tail+insertText.length();
}
try { newText = newText.replace("\r", ""); }
catch (Exception ex) { }
try { newText = newText.replace("\n", ""); }
catch (Exception ex) { }
if (this.type != Type.DEFAULT) {
String grabBag = "";
switch (type) {
case EXCLUDE_CUSTOM:
grabBag = validateCustom;
break;
case EXCLUDE_SPECIAL:
grabBag = validateSpecChar;
break;
case ALPHA:
grabBag = validateAlpha;
break;
case ALPHA_NOSPACE:
grabBag = validateAlphaNoSpace;
break;
case NUMERIC:
grabBag = validateNumeric;
break;
case ALPHANUMERIC:
grabBag = validateAlpha + validateNumeric;
break;
case ALPHANUMERIC_NOSPACE:
grabBag = validateAlphaNoSpace + validateNumeric;
break;
}
if (this.type == Type.EXCLUDE_CUSTOM || this.type == Type.EXCLUDE_SPECIAL) {
for (int i = 0; i < grabBag.length(); i++) {
try {
String ret = newText.replace(String.valueOf(grabBag.charAt(i)), "");
if (ret != null)
newText = ret;
} catch (Exception ex) { }
}
} else {
String ret = newText;
for (int i = 0; i < newText.length(); i++) {
try {
int index = grabBag.indexOf(String.valueOf(newText.charAt(i)));
if (index == -1) {
String temp = ret.replace(String.valueOf(String.valueOf(newText.charAt(i))), "");
if (temp != null)
ret = temp;
}
} catch (Exception ex) { }
}
if (!ret.equals(""))
newText = ret;
}
tempIndex = newText.length();
}
if (maxLength != 0 && newText.length() > maxLength) {
newText = newText.substring(0, maxLength);
tempIndex = maxLength;
}
int testIndex = (head > tail) ? tail : head;
setText(newText);
// if (text.length() > 0)
caretIndex = testIndex;
// else
// caretIndex = 0;
}
// Control methods
@Override
public Control cloneForSpatial(Spatial spatial) {
return this;
}
@Override
public void setSpatial(Spatial spatial) { }
@Override
public void update(float tpf) {
if (isPressed) {
stillPressedInterval();
}
}
@Override
public void render(RenderManager rm, ViewPort vp) { }
}
|
package de.danielnaber.languagetool.rules.patterns;
import java.util.ArrayList;
import java.util.List;
import de.danielnaber.languagetool.AnalyzedSentence;
import de.danielnaber.languagetool.AnalyzedToken;
import de.danielnaber.languagetool.AnalyzedTokenReadings;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.rules.Rule;
import de.danielnaber.languagetool.rules.RuleMatch;
import de.danielnaber.languagetool.tools.StringTools;
/**
* A Rule that describes a language error as a simple pattern of words or of part-of-speech
* tags.
*
* @author Daniel Naber
*/
public class PatternRule extends Rule {
private String id;
private Language[] language;
private String description;
private String message;
private int startPositionCorrection = 0;
private int endPositionCorrection = 0;
private boolean caseSensitive = false;
private boolean regExp = false;
private List<Element> patternElements;
PatternRule(String id, Language language, List<Element> elements, String description, String message) {
if (id == null)
throw new NullPointerException("id cannot be null");
if (language == null)
throw new NullPointerException("language cannot be null");
if (elements == null)
throw new NullPointerException("elements cannot be null");
if (description == null)
throw new NullPointerException("description cannot be null");
this.id = id;
this.language = new Language[] { language };
//this.pattern = pattern;
this.description = description;
this.message = message;
this.patternElements = new ArrayList<Element>(elements); // copy elements
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public String getMessage() {
return message;
}
public Language[] getLanguages() {
return language;
}
public String toString() {
return id + ":" + patternElements + ":" + description;
}
public boolean getCaseSensitive() {
return caseSensitive;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
public boolean getregExpSetting() {
return regExp;
}
public void setregExpSetting(boolean regExp) {
this.regExp = regExp;
}
public int getStartPositionCorrection() {
return startPositionCorrection;
}
public void setStartPositionCorrection(int startPositionCorrection) {
this.startPositionCorrection = startPositionCorrection;
}
public int getEndPositionCorrection() {
return endPositionCorrection;
}
public void setEndPositionCorrection(int endPositionCorrection) {
this.endPositionCorrection = endPositionCorrection;
}
public RuleMatch[] match(AnalyzedSentence text) {
List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>();
AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace();
int tokenPos = 0;
int prevSkipNext = 0;
int skipNext = 0;
int matchPos = 0;
int skipShift = 0;
int firstMatchToken = -1;
int lastMatchToken = -1;
for (int i = 0; i < tokens.length; i++) {
boolean allElementsMatch = true;
int matchingTokens = 0;
for (int k = 0; k < patternElements.size(); k++) {
Element elem = patternElements.get(k);
skipNext = elem.getSkipNext();
int nextPos = tokenPos + k + skipShift;
if (nextPos >= tokens.length) {
allElementsMatch = false;
break;
}
boolean skipMatch = false;
if (prevSkipNext + nextPos >= tokens.length || prevSkipNext < 0) { //SENT_END?
prevSkipNext = tokens.length - (nextPos + 1);
}
for (int m = nextPos; m <= nextPos+prevSkipNext; m++) {
boolean Match = false;
for (int l = 0; l < tokens[m].getReadingsLength(); l++) {
AnalyzedToken matchToken = tokens[m].getAnalyzedToken(l);
// Logical OR (cannot be AND):
if (!elem.match(matchToken)) {
Match = Match || false;
} else {
Match = true;
matchPos = m;
skipShift = matchPos - nextPos;
}
skipMatch = skipMatch || Match;
}
if (skipMatch) {
break;
}
}
allElementsMatch = skipMatch;
if (skipMatch) {
prevSkipNext = skipNext;
} else {
prevSkipNext = 0;
}
if (!allElementsMatch) {
break;
} else {
matchingTokens++;
lastMatchToken = matchPos; //nextPos;
if (firstMatchToken == -1)
firstMatchToken = matchPos; //nextPos;
}
}
if (allElementsMatch) {
String errMessage = message;
//TODO: implement skipping tokens while marking error tokens
// replace back references like \1 in message:
for (int j = 0; j < matchingTokens; j++) {
errMessage = errMessage.replaceAll("\\\\" + (j + 1), tokens[firstMatchToken + j]
.getToken());
}
boolean startsWithUppercase = StringTools.startsWithUppercase(tokens[firstMatchToken
+ startPositionCorrection].toString());
RuleMatch ruleMatch = new RuleMatch(this, tokens[firstMatchToken + startPositionCorrection]
.getStartPos(), tokens[lastMatchToken + endPositionCorrection].getStartPos()
+ tokens[lastMatchToken + endPositionCorrection].getToken().length(), errMessage,
startsWithUppercase);
ruleMatches.add(ruleMatch);
} else {
firstMatchToken = -1;
lastMatchToken = -1;
}
tokenPos++;
}
return (RuleMatch[]) ruleMatches.toArray(new RuleMatch[0]);
}
public void reset() {
// nothing
}
}
|
package ucar.nc2.iosp.uf;
import ucar.unidata.io.RandomAccessFile;
import ucar.nc2.iosp.cinrad.Cinrad2Record;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.*;
public class UFheader {
ucar.unidata.io.RandomAccessFile raf;
ucar.nc2.NetcdfFile ncfile;
static final boolean littleEndianData = true;
String dataFormat = "UNIVERSALFORMAT"; // temp setting
Ray firstRay = null;
HashMap variableGroup;
private int max_radials = 0;
private int min_radials = Integer.MAX_VALUE;
public boolean isValidFile(ucar.unidata.io.RandomAccessFile raf){
try
{
raf.seek(0);
raf.order(RandomAccessFile.BIG_ENDIAN);
byte [] b6 = new byte[6];
byte [] b4 = new byte[4];
raf.read(b6, 0, 6);
String ufStr = new String(b6, 4, 2);
if(!ufStr.equals("UF"))
return false;
//if ufStr is UF, then a further checking apply
raf.seek(0);
raf.read(b4, 0, 4);
int rsize = bytesToInt(b4, false);
byte [] buffer = new byte[rsize];
long offset = raf.getFilePointer();
raf.read(buffer, 0, rsize);
raf.read(b4, 0, 4);
int endPoint = bytesToInt(b4, false);
if(endPoint != rsize) {
return false;
}
ByteBuffer bos = ByteBuffer.wrap(buffer);
firstRay = new Ray(bos, rsize, offset);
}
catch ( IOException e )
{
return( false );
}
return true;
}
void read(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile ncfile ) throws IOException {
this.raf = raf;
this.ncfile = ncfile;
variableGroup = new HashMap();
raf.seek(0);
raf.order(RandomAccessFile.BIG_ENDIAN);
int rayNumber = 0;
/* get bad data flag from universal header */
while (!raf.isAtEndOfFile()) {
byte [] b4 = new byte[4];
raf.read(b4, 0, 4);
int rsize = bytesToInt(b4, false);
byte [] buffer = new byte[rsize];
long offset = raf.getFilePointer();
raf.read(buffer, 0, rsize);
raf.read(b4, 0, 4);
int endPoint = bytesToInt(b4, false);
if(endPoint != rsize || rsize == 0) {
// System.out.println("Herr " +velocityList.size());
continue;
}
ByteBuffer bos = ByteBuffer.wrap(buffer);
Ray r = new Ray(bos, rsize, offset);
if(firstRay == null) firstRay = r;
rayNumber ++;
HashMap rayMap = r.field_header_map;
Set kSet = rayMap.keySet();
for(Iterator it = kSet.iterator(); it.hasNext();) {
String ab = (String)it.next();
ArrayList group = (ArrayList) variableGroup.get(ab);
if (null == group) {
group = new ArrayList();
variableGroup.put(ab, group);
}
group.add(r);
}
// System.out.println("Ray Number = " + rayNumber);
}
Set vSet = variableGroup.keySet();
for(Iterator it = vSet.iterator(); it.hasNext();) {
String key = (String)it.next();
ArrayList group = (ArrayList) variableGroup.get(key);
ArrayList sgroup = sortScans(key, group);
//variableGroup.remove(key);
variableGroup.put(key, sgroup);
}
//System.out.println("Herr " +velocityList.size());
//return;
}
private ArrayList sortScans(String name, List rays) {
// now group by elevation_num
HashMap groupHash = new HashMap(600);
for (int i = 0; i < rays.size(); i++) {
Ray r = (Ray) rays.get(i);
Integer groupNo = new Integer(r.uf_header2.sweepNumber); //.elevation);
ArrayList group = (ArrayList) groupHash.get(groupNo);
if (null == group) {
group = new ArrayList();
groupHash.put(groupNo, group);
}
group.add(r);
}
// sort the groups by elevation_num
ArrayList groups = new ArrayList(groupHash.values());
Collections.sort(groups, new GroupComparator());
for (int i = 0; i < groups.size(); i++) {
ArrayList group = (ArrayList) groups.get(i);
max_radials = Math.max(max_radials, group.size());
min_radials = Math.min(min_radials, group.size());
}
return groups;
}
public float getMeanElevation(String key, int eNum){
ArrayList gp = (ArrayList)getGroup(key);
float meanEle = getMeanElevation(gp);
return meanEle;
}
public float getMeanElevation(ArrayList<Ray> gList){
float sum = 0;
int size = 0;
Iterator it = gList.iterator();
while(it.hasNext()){
Ray r = (Ray)it.next();
sum += r.getElevation();
size++;
}
return sum/size;
}
public List getGroup(String key){
return (ArrayList)variableGroup.get(key);
}
public int getMaxRadials() {
return max_radials;
}
public String getDataFormat() {
return dataFormat;
}
public Date getStartDate() {
return firstRay.getDate();
}
public Date getEndDate() {
return firstRay.getDate();
}
public float getHorizontalBeamWidth(String ab){
return firstRay.getHorizontalBeamWidth(ab);
}
public String getStationId(){
return firstRay.uf_header2.siteName;
}
public float getStationLatitude(){
return firstRay.getLatitude();
}
public float getStationLongitude(){
return firstRay.getLongtitude();
}
public float getStationElevation() {
return firstRay.getElevation();
}
public short getMissingData() {
return firstRay.getMissingData();
}
private class GroupComparator implements Comparator {
public int compare(Object o1, Object o2) {
List group1 = (List) o1;
List group2 = (List) o2;
Ray ray1 = (Ray) group1.get(0);
Ray ray2 = (Ray) group2.get(0);
//if (record1.elevation_num != record2.elevation_num)
return (ray1.uf_header2.elevation - ray2.uf_header2.elevation < 13 ? 0 : 1);
//return record1.cut - record2.cut;
}
}
protected short getShort(byte[] bytes, int offset) {
int ndx0 = offset + (littleEndianData ? 1 : 0);
int ndx1 = offset + (littleEndianData ? 0 : 1);
// careful that we only allow sign extension on the highest order byte
return (short)(bytes[ndx0] << 8 | (bytes[ndx1] & 0xff));
}
public static int bytesToShort(byte a, byte b, boolean swapBytes) {
// again, high order bit is expressed left into 32-bit form
if (swapBytes) {
return (a & 0xff) + ((int)b << 8);
} else {
return ((int)a << 8) + (b & 0xff);
}
}
public static int bytesToInt(byte [] bytes, boolean swapBytes) {
byte a = bytes[0];
byte b = bytes[1];
byte c = bytes[2];
byte d = bytes[3];
if (swapBytes) {
return ((a & 0xff) ) +
((b & 0xff) << 8 ) +
((c & 0xff) << 16 ) +
((d & 0xff) << 24);
} else {
return ((a & 0xff) << 24 ) +
((b & 0xff) << 16 ) +
((c & 0xff) << 8 ) +
((d & 0xff) );
}
}
}
|
package script.memodb.data;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
public class MDataFile<T extends MData> {
public static final int MDATAFILE_MAXSIZE_CHUNK = 1024 * 1024 * 1024;
public static final int MDATAFILE_MAXSIZE_INDEX = 256 * 1024 * 1024;
public static final int MDATAFILE_MAXSIZE_KEYS = 1024 * 1024 * 1024;
// public static final int MDATAFILE_MAXSIZE_CHUNK = 11 * 1024 * 1024;
// public static final int MDATAFILE_MAXSIZE_INDEX = 11 * 1024 * 1024;
// public static final int MDATAFILE_MAXSIZE_KEYS = 11 * 1024 * 1024;
MemoryMappedFile memFile;
/**
* Reserved size for a mdatafile.
*/
static final int MDATAFILE_RESERVED = 256;
static final int RESERVED_CURSORADDRESS = 0;
int offset;
public static final int STATUS_STANDBY = 0;
public static final int STATUS_OPENNING = 1;
public static final int STATUS_OPENED = 5;
public static final int STATUS_CLEANFRAGMENT = 10;
public static final int STATUS_CLOSED = 100;
AtomicInteger status = new AtomicInteger(STATUS_STANDBY);
String path;
int length;
public MDataFile(String path, int length) {
this.path = path;
this.length = length;
}
public synchronized void open() throws IOException {
if(status.compareAndSet(STATUS_STANDBY, STATUS_OPENED)) {
try {
openFile();
} catch (Throwable e) {
e.printStackTrace();
status.set(STATUS_CLOSED);
throw new IOException(this.getClass().getSimpleName() + " open " + path + " size " + length + " failed, " + e.getMessage(), e);
}
}
}
void openFile() throws Exception {
memFile = new MemoryMappedFile(path, length);
//read reserved parameters for a mdatafile.
offset = memFile.getIntVolatile(RESERVED_CURSORADDRESS);
if(offset == 0) {
offset = MDATAFILE_RESERVED;
memFile.putIntVolatile(RESERVED_CURSORADDRESS, offset);
}
}
void check() throws IOException {
if(status.get() != STATUS_OPENED)
throw new IOException("Path " + path + " hasn't been openned yet, status " + status.get());
}
/**
* returns
* public static final int ACQUIREADD_SUCCESSFULLY = 1;
* public static final int ACQUIREADD_FAILED = -1;
* public static final int ACQUIREADD_NOTENOUGHSPACE = -2;
*
* @param mdata
* @return
* @throws IOException
*/
public int add(T mdata) throws IOException {
check();
int pos = acquireAdd(mdata);
if(pos >= 0) {
mdata.persistent(memFile, pos);
return ACQUIREADD_SUCCESSFULLY;
}
return pos;
}
public static final int ACQUIREADD_SUCCESSFULLY = 1;
public static final int ACQUIREADD_FAILED = -1;
public static final int ACQUIREADD_NOTENOUGHSPACE = -2;
private synchronized int acquireAdd(T mdata) throws IOException {
int pos;
int dataLength = mdata.dataLength();
int nextOffset = offset + dataLength;
if(!memFile.isEnough(offset, dataLength)) {
return ACQUIREADD_NOTENOUGHSPACE;//Not enough space for this file.
}
boolean acquired = memFile.compareAndSwapInt(RESERVED_CURSORADDRESS, offset, nextOffset);
if(acquired) {
pos = offset;
offset = nextOffset;
memFile.putByte(pos, MData.VERSION_UPDATING);
memFile.putInt(pos + MData.OFFSET_VERSION, dataLength);
// memFile.putIntVolatile(RESERVED_CURSORADDRESS, offset);
return pos;
}
return ACQUIREADD_FAILED;
}
public void read(int pos, T mdata) throws IOException {
check();
int start = MDATAFILE_RESERVED;
for(int i = 0; i < pos; i++) {
int length = MData.readDataLength(memFile, start);
start += length;
}
mdata.resurrect(memFile, start);
}
public void readAll(int limit, T mdata) throws IOException {
check();
int start = MDATAFILE_RESERVED;
for(int i = 0; i < limit; i++) {
mdata.resurrect(memFile, start);
int length = MData.readDataLength(memFile, start);
start += length;
}
}
}
|
package tools;
import static org.junit.Assert.*;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.Map.Entry;
/**
*
* @author cmantas
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CSARParserTest {
public CSARParserTest() {
}
@Ignore
@org.junit.Test
public void test_01_showCase(){
try {
//create a Parser instance
Parser tc = new CSARParser("example.csar");
//application name and version
System.out.println("Application: "+tc.getAppName()+" v"+tc.getAppVersion());
//iterate through modules
for(String module: tc.getModules()){
System.out.println("\t"+module);
//module dependecies
System.out.println("\t\tdepends on: "+tc.getModuleDependencies(module));
//iterate through components
for(String component: tc.getModuleComponents(module)){
System.out.println("\t\t"+component);
//component dependencies
System.out.println("\t\t\tdepends on: "+tc.getComponentDependencies(component));
//component properties
for(Entry prop: tc.getComponentProperties(component).entrySet()){
System.out.println("\t\t\t"+prop.getKey()+": "+prop.getValue());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
fail("failed the showcase");
}
}
@org.junit.Test
@Ignore
public void test_99_nonexisting_csar() {
try{
CSARParser tc = new CSARParser("asdffasdgpkoljasdf");
}
catch (Exception e){
return;}
fail("Did not catch innexistent file");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.